Compare commits
19
Commits
v2.2.0
...
67d6814c4b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67d6814c4b
|
||
|
|
cdb682f484
|
||
|
|
d26f1a94ef
|
||
|
|
7e66aaff9f
|
||
|
|
b509335f72
|
||
|
|
d12f8344e2
|
||
|
|
c26267e8c4
|
||
|
|
8f1adc8f1e
|
||
|
|
82e496d7ed
|
||
|
|
422cf9a48b
|
||
|
|
0030f5b794
|
||
|
|
1bfb99d4c3 | ||
|
|
ec87b0bde3 | ||
|
|
b111c5f437 | ||
|
|
7cfa6bf8e3 | ||
|
|
65a1553612 | ||
|
|
c39314acbc | ||
|
|
81ab5c09cb | ||
|
|
3be3503cb2 |
No files matched your search
@@ -0,0 +1,123 @@
|
|||||||
|
name: Publish NuGet packages
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
env:
|
||||||
|
NUGET_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||||
|
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: '1'
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||||
|
LD_LIBRARY_PATH: /opt/dotnet-libs/usr/lib/x86_64-linux-gnu
|
||||||
|
SSL_CERT_FILE: /opt/ca-certificates.crt
|
||||||
|
steps:
|
||||||
|
- name: Fetch exact tagged source
|
||||||
|
env:
|
||||||
|
GITEA_REF: ${{ gitea.ref }}
|
||||||
|
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tag="${GITEA_REF#refs/tags/}"
|
||||||
|
case "$tag" in
|
||||||
|
v[0-9]*) ;;
|
||||||
|
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/${GITEA_REPOSITORY}/archive/${tag}.tar.gz"
|
||||||
|
node --input-type=module <<'NODE'
|
||||||
|
import { writeFile } from 'node:fs/promises';
|
||||||
|
|
||||||
|
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||||
|
NODE
|
||||||
|
mkdir release
|
||||||
|
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||||
|
rm -f release.tar.gz
|
||||||
|
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||||
|
|
||||||
|
- name: Install .NET 8 SDK
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
node --input-type=module <<'NODE'
|
||||||
|
import { writeFile } from 'node:fs/promises';
|
||||||
|
import { rootCertificates } from 'node:tls';
|
||||||
|
|
||||||
|
await writeFile('/opt/ca-certificates.crt', rootCertificates.join('\n'));
|
||||||
|
|
||||||
|
const metadataResponse = await fetch('https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/8.0/releases.json');
|
||||||
|
if (!metadataResponse.ok) throw new Error(`Release metadata download failed: ${metadataResponse.status}`);
|
||||||
|
const metadata = await metadataResponse.json();
|
||||||
|
const sdkVersion = metadata['latest-sdk'];
|
||||||
|
const release = metadata.releases.find(item => item.sdk?.version === sdkVersion);
|
||||||
|
const file = release?.sdk?.files?.find(item => item.rid === 'linux-x64' && item.name.endsWith('.tar.gz'));
|
||||||
|
if (!file) throw new Error(`Linux x64 SDK archive not found for ${sdkVersion}`);
|
||||||
|
const archiveResponse = await fetch(file.url);
|
||||||
|
if (!archiveResponse.ok) throw new Error(`SDK download failed: ${archiveResponse.status}`);
|
||||||
|
await writeFile('/tmp/dotnet-sdk.tar.gz', new Uint8Array(await archiveResponse.arrayBuffer()));
|
||||||
|
|
||||||
|
const poolUrl = 'https://deb.debian.org/debian-security/pool/updates/main/o/openssl/';
|
||||||
|
const poolResponse = await fetch(poolUrl);
|
||||||
|
if (!poolResponse.ok) throw new Error(`OpenSSL package index download failed: ${poolResponse.status}`);
|
||||||
|
const poolIndex = await poolResponse.text();
|
||||||
|
const packages = [...poolIndex.matchAll(/href="(libssl3_[^"]+_amd64\.deb)"/g)].map(match => match[1]).sort();
|
||||||
|
const packageName = packages.at(-1);
|
||||||
|
if (!packageName) throw new Error('Debian libssl3 package was not found');
|
||||||
|
const packageResponse = await fetch(poolUrl + packageName);
|
||||||
|
if (!packageResponse.ok) throw new Error(`OpenSSL package download failed: ${packageResponse.status}`);
|
||||||
|
await writeFile('/tmp/libssl3.deb', new Uint8Array(await packageResponse.arrayBuffer()));
|
||||||
|
NODE
|
||||||
|
mkdir -p /opt/dotnet
|
||||||
|
tar -xzf /tmp/dotnet-sdk.tar.gz -C /opt/dotnet
|
||||||
|
mkdir -p /opt/dotnet-libs
|
||||||
|
dpkg-deb -x /tmp/libssl3.deb /opt/dotnet-libs
|
||||||
|
rm -f /tmp/dotnet-sdk.tar.gz
|
||||||
|
rm -f /tmp/libssl3.deb
|
||||||
|
/opt/dotnet/dotnet --info
|
||||||
|
|
||||||
|
- name: Validate, pack and publish
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
: "${NUGET_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||||
|
export PATH="/opt/dotnet:$PATH"
|
||||||
|
cd release
|
||||||
|
tag="$(cat .shrink-sdk-release-tag)"
|
||||||
|
projects=()
|
||||||
|
if [[ -d DotNet~ ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find DotNet~ -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
if [[ -d Godot~ ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find Godot~ -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
if [[ "${#projects[@]}" -eq 0 ]]; then
|
||||||
|
while IFS= read -r -d '' project; do projects+=("$project"); done < <(find . -maxdepth 1 -type f -name '*.csproj' -print0)
|
||||||
|
fi
|
||||||
|
test "${#projects[@]}" -gt 0
|
||||||
|
if [[ -f package.json ]]; then
|
||||||
|
version="$(node -p "require('./package.json').version")"
|
||||||
|
else
|
||||||
|
version="$(dotnet msbuild "${projects[0]}" -getProperty:Version -nologo)"
|
||||||
|
fi
|
||||||
|
test "$tag" = "v$version"
|
||||||
|
mkdir -p packages
|
||||||
|
for project in "${projects[@]}"; do
|
||||||
|
dotnet restore "$project" --configfile NuGet.Config
|
||||||
|
dotnet pack "$project" --configuration Release --no-restore --output "$PWD/packages" --include-symbols --include-source
|
||||||
|
done
|
||||||
|
find packages -maxdepth 1 -name '*.nupkg' -type f | grep -q .
|
||||||
|
dotnet nuget push 'packages/*.nupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||||
|
if compgen -G 'packages/*.snupkg' > /dev/null; then
|
||||||
|
dotnet nuget push 'packages/*.snupkg' --api-key "$NUGET_AUTH_TOKEN" --source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --skip-duplicate
|
||||||
|
fi
|
||||||
@@ -15,22 +15,39 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
NODE_AUTH_TOKEN: ${{ secrets.SHRINKSDK_PACKAGE_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Fetch tagged revision
|
- name: Fetch exact tagged release archive
|
||||||
|
env:
|
||||||
|
GITEA_REF: ${{ gitea.ref }}
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
ref="${{ gitea.sha }}"
|
tag="${GITEA_REF#refs/tags/}"
|
||||||
test -n "$ref"
|
case "$tag" in
|
||||||
git init .
|
v[0-9]*) ;;
|
||||||
git remote add origin "https://git.crash.work/ShrinkSDK/ShrinkDataSaver.git"
|
*) echo "Expected a version tag ref, got: $GITEA_REF" >&2; exit 1 ;;
|
||||||
git fetch --depth=1 origin "$ref"
|
esac
|
||||||
git checkout --detach FETCH_HEAD
|
export SHRINKSDK_ARCHIVE_URL="https://git.crash.work/ShrinkSDK/ShrinkDataSaver/archive/${tag}.tar.gz"
|
||||||
|
node --input-type=module <<'NODE'
|
||||||
|
import { writeFile } from 'node:fs/promises';
|
||||||
|
|
||||||
|
const response = await fetch(process.env.SHRINKSDK_ARCHIVE_URL);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Release archive download failed: ${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await writeFile('release.tar.gz', new Uint8Array(await response.arrayBuffer()));
|
||||||
|
NODE
|
||||||
|
mkdir release
|
||||||
|
tar -xzf release.tar.gz --strip-components=1 -C release
|
||||||
|
rm -f release.tar.gz
|
||||||
|
printf '%s' "$tag" > release/.shrink-sdk-release-tag
|
||||||
|
|
||||||
- name: Validate immutable release version
|
- name: Validate immutable release version
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
tag="$(git describe --exact-match --tags HEAD)"
|
cd release
|
||||||
|
tag="$(cat .shrink-sdk-release-tag)"
|
||||||
version="$(node -p "require('./package.json').version")"
|
version="$(node -p "require('./package.json').version")"
|
||||||
test "$tag" = "v$version"
|
test "$tag" = "v$version"
|
||||||
npm pack --dry-run
|
npm pack --dry-run
|
||||||
@@ -40,6 +57,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
: "${NODE_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
: "${NODE_AUTH_TOKEN:?SHRINKSDK_PACKAGE_TOKEN is required}"
|
||||||
|
cd release
|
||||||
npmrc="$HOME/.npmrc"
|
npmrc="$HOME/.npmrc"
|
||||||
cleanup() { rm -f "$npmrc"; }
|
cleanup() { rm -f "$npmrc"; }
|
||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
|
|||||||
@@ -26,12 +26,17 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
|
machine_id_file="/root/.local/share/unity3d/Unity/.machine-id"
|
||||||
|
if test -s "$machine_id_file"; then
|
||||||
|
cat "$machine_id_file" > /etc/machine-id
|
||||||
|
echo "Unity machine identity restored"
|
||||||
|
fi
|
||||||
|
git config --global url."https://ghfast.top/https://github.com/".insteadOf "https://github.com/"
|
||||||
unity_bin="$(command -v unity-editor || command -v unity || command -v Unity || true)"
|
unity_bin="$(command -v unity-editor || command -v unity || command -v Unity || true)"
|
||||||
test -n "$unity_bin"
|
test -n "$unity_bin"
|
||||||
"$unity_bin" \
|
"$unity_bin" \
|
||||||
-batchmode \
|
-batchmode \
|
||||||
-nographics \
|
-nographics \
|
||||||
-quit \
|
|
||||||
-projectPath "$PWD/Development~/UnityProject" \
|
-projectPath "$PWD/Development~/UnityProject" \
|
||||||
-runTests \
|
-runTests \
|
||||||
-testPlatform EditMode \
|
-testPlatform EditMode \
|
||||||
|
|||||||
@@ -8,3 +8,11 @@
|
|||||||
/Tools~/**/[Oo]bj/
|
/Tools~/**/[Oo]bj/
|
||||||
*.user
|
*.user
|
||||||
*.DotSettings.user
|
*.DotSettings.user
|
||||||
|
/DotNet~/**/[Bb]in/
|
||||||
|
/DotNet~/**/[Oo]bj/
|
||||||
|
/Godot~/**/[Bb]in/
|
||||||
|
/Godot~/**/[Oo]bj/
|
||||||
|
/artifacts/
|
||||||
|
/packages/
|
||||||
|
!DotNet~/**/*.csproj
|
||||||
|
!Godot~/**/*.csproj
|
||||||
@@ -6,3 +6,9 @@ Tools~/
|
|||||||
*.sln
|
*.sln
|
||||||
*.user
|
*.user
|
||||||
*.DotSettings.user
|
*.DotSettings.user
|
||||||
|
DotNet~/
|
||||||
|
Godot~/
|
||||||
|
NuGet.Config
|
||||||
|
Directory.Build.props
|
||||||
|
NuGet.Config.meta
|
||||||
|
Directory.Build.props.meta
|
||||||
@@ -2,6 +2,25 @@
|
|||||||
|
|
||||||
本文件记录 `ShrinkDataSaver` 在当前工作区中的包内变更。
|
本文件记录 `ShrinkDataSaver` 在当前工作区中的包内变更。
|
||||||
|
|
||||||
|
## [2.5.0] - 2026-11-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `LocalStorageProvider` 新增 `LocalStorageCommitStrategy`;`RenameOnly` 通过宿主注入的覆盖移动委托提交,适用于不支持原子替换的沙箱文件系统。
|
||||||
|
- `ShrinkDataSaverPlatform.Initialize(IStorageProvider, ...)` 与两套 `ShrinkDataSaverRuntimeConfig.Storage` 支持宿主注入存储实现。
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `RenameOnly` 保留 `.bak1` / `.bak2` 两级备份,并在读取或下一次写入前从备份恢复中断的提交;孤立临时文件不会被当成完整存档。
|
||||||
|
- `DeleteAsync` 会同时清理主文件、两级备份和临时文件。
|
||||||
|
|
||||||
|
## [2.2.2] - 2026-08-28
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `ShrinkDataSaverSettings` 优先从 `GameAssets/Runtime/Data/ShrinkSDK/ShrinkDataSaverSettings` 加载,并保留旧根路径回退。
|
||||||
|
- 新增 `ShrinkSDK/存档/创建设置`,统一在标准资源目录创建配置。
|
||||||
|
|
||||||
## [2.2.0] - 2026-05-18
|
## [2.2.0] - 2026-05-18
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -10,6 +10,10 @@
|
|||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"com.unity.test-framework": "1.1.33",
|
"com.unity.test-framework": "1.1.33",
|
||||||
"com.cneicy.shrink-datasaver": "file:../../.."
|
"com.cneicy.shrink-datasaver": "file:../../..",
|
||||||
}
|
"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b"
|
||||||
|
},
|
||||||
|
"testables": [
|
||||||
|
"com.cneicy.shrink-datasaver"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
|
||||||
|
<Authors>ShrinkSDK</Authors>
|
||||||
|
<Company>ShrinkSDK</Company>
|
||||||
|
<RepositoryUrl>https://git.crash.work/ShrinkSDK</RepositoryUrl>
|
||||||
|
<IncludeSymbols>true</IncludeSymbols>
|
||||||
|
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 5e806df0724397542b78a8347188b8bd
|
||||||
|
DefaultImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
|
using System.IO;
|
||||||
|
using Cysharp.Threading.Tasks;
|
||||||
|
using ShrinkSDK.Runtime;
|
||||||
|
|
||||||
|
namespace ShrinkDataSaver;
|
||||||
|
|
||||||
|
public sealed class ShrinkDataSaverRuntimeConfig
|
||||||
|
{
|
||||||
|
public string? RootPath { get; set; }
|
||||||
|
public string SaveFileExtension { get; set; } = ".sav";
|
||||||
|
public string SettingsFileName { get; set; } = "settings.json";
|
||||||
|
public int CurrentSaveVersion { get; set; } = 1;
|
||||||
|
public int MaxSlots { get; set; } = 3;
|
||||||
|
public float SettingsWriteDebounceSeconds { get; set; } = 0.35f;
|
||||||
|
public bool DontDestroyOnLoadDriver { get; set; }
|
||||||
|
public IStorageProvider? Storage { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ShrinkDataSaverRuntime
|
||||||
|
{
|
||||||
|
public static bool IsInitialized { get; private set; }
|
||||||
|
|
||||||
|
public static void Initialize(ShrinkDataSaverRuntimeConfig? config = null)
|
||||||
|
{
|
||||||
|
if (IsInitialized) return;
|
||||||
|
config ??= new ShrinkDataSaverRuntimeConfig();
|
||||||
|
var root = string.IsNullOrWhiteSpace(config.RootPath)
|
||||||
|
? ShrinkRuntimeServices.Paths.PersistentDataPath
|
||||||
|
: config.RootPath!;
|
||||||
|
Directory.CreateDirectory(root);
|
||||||
|
var storage = config.Storage ?? new LocalStorageProvider(root);
|
||||||
|
ShrinkDataSaverPlatform.SettingsWriteDebounceSeconds = config.SettingsWriteDebounceSeconds;
|
||||||
|
ShrinkDataSaverPlatform.MaxSlots = config.MaxSlots;
|
||||||
|
ShrinkSettings.Initialize(storage, Path.Combine(root, config.SettingsFileName));
|
||||||
|
ShrinkSave.Initialize(storage, Path.Combine(root, "saves"), config.SaveFileExtension,
|
||||||
|
config.CurrentSaveVersion);
|
||||||
|
ShrinkSettings.LoadAsync().Forget();
|
||||||
|
IsInitialized = true;
|
||||||
|
ShrinkRuntimeServices.Logger.Log(ShrinkLogLevel.Information,
|
||||||
|
$"[ShrinkDataSaver] Runtime initialized. Root: {root}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netstandard2.1</TargetFramework>
|
||||||
|
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||||
|
<AssemblyName>ShrinkDataSaver.Runtime</AssemblyName>
|
||||||
|
<RootNamespace>ShrinkDataSaver</RootNamespace>
|
||||||
|
<PackageId>ShrinkSDK.DataSaver</PackageId>
|
||||||
|
<Version>2.5.0</Version>
|
||||||
|
<Description>ShrinkSDK engine-neutral versioned save and settings runtime.</Description>
|
||||||
|
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Runtime\ShrinkDataSaverRuntime.cs" />
|
||||||
|
<Compile Include="..\Runtime\AssemblyInfo.cs" />
|
||||||
|
<Compile Include="..\Runtime\DataSerializer.cs" />
|
||||||
|
<Compile Include="..\Runtime\IStorageProvider.cs" />
|
||||||
|
<Compile Include="..\Runtime\LocalStorageProvider.cs" />
|
||||||
|
<Compile Include="..\Runtime\MigrationChain.cs" />
|
||||||
|
<Compile Include="..\Runtime\SaveEncryptor.cs" />
|
||||||
|
<Compile Include="..\Runtime\SaveTypes.cs" />
|
||||||
|
<Compile Include="..\Runtime\ShrinkDataSaverPlatform.cs" />
|
||||||
|
<Compile Include="..\Runtime\ShrinkSave.cs" />
|
||||||
|
<Compile Include="..\Runtime\ShrinkSettings.cs" />
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="UniTask" Version="2.5.10" />
|
||||||
|
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#if UNITY_EDITOR
|
||||||
|
using UnityEditor;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace ShrinkDataSaver.Editor
|
||||||
|
{
|
||||||
|
public static class ShrinkDataSaverSettingsMenu
|
||||||
|
{
|
||||||
|
private const string SettingsDirectory =
|
||||||
|
"Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK";
|
||||||
|
private const string SettingsAssetPath =
|
||||||
|
SettingsDirectory + "/ShrinkDataSaverSettings.asset";
|
||||||
|
|
||||||
|
[MenuItem("ShrinkSDK/存档/创建设置")]
|
||||||
|
public static void CreateSettingsAsset()
|
||||||
|
{
|
||||||
|
EnsureFolder(SettingsDirectory);
|
||||||
|
|
||||||
|
var existing = AssetDatabase.LoadAssetAtPath<ShrinkDataSaverSettings>(SettingsAssetPath);
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
Selection.activeObject = existing;
|
||||||
|
EditorGUIUtility.PingObject(existing);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var asset = ScriptableObject.CreateInstance<ShrinkDataSaverSettings>();
|
||||||
|
AssetDatabase.CreateAsset(asset, SettingsAssetPath);
|
||||||
|
AssetDatabase.SaveAssets();
|
||||||
|
Selection.activeObject = asset;
|
||||||
|
EditorGUIUtility.PingObject(asset);
|
||||||
|
Debug.Log("[ShrinkDataSaver] 已创建 ShrinkDataSaverSettings.asset");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void EnsureFolder(string path)
|
||||||
|
{
|
||||||
|
var segments = path.Split('/');
|
||||||
|
var current = segments[0];
|
||||||
|
for (var i = 1; i < segments.Length; i++)
|
||||||
|
{
|
||||||
|
var next = current + "/" + segments[i];
|
||||||
|
if (!AssetDatabase.IsValidFolder(next))
|
||||||
|
AssetDatabase.CreateFolder(current, segments[i]);
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: fcd9a64a8a5541eba481189d9c887c5c
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<packageSources>
|
||||||
|
<clear />
|
||||||
|
<add key="ShrinkSDK" value="https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json" />
|
||||||
|
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||||
|
</packageSources>
|
||||||
|
</configuration>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 8d396317cc7d3294683c90786f2b3289
|
||||||
|
PluginImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
iconMap: {}
|
||||||
|
executionOrder: {}
|
||||||
|
defineConstraints: []
|
||||||
|
isPreloaded: 0
|
||||||
|
isOverridable: 0
|
||||||
|
isExplicitlyReferenced: 0
|
||||||
|
validateReferences: 1
|
||||||
|
platformData:
|
||||||
|
- first:
|
||||||
|
Any:
|
||||||
|
second:
|
||||||
|
enabled: 0
|
||||||
|
settings: {}
|
||||||
|
- first:
|
||||||
|
Editor: Editor
|
||||||
|
second:
|
||||||
|
enabled: 0
|
||||||
|
settings:
|
||||||
|
DefaultValueInitialized: true
|
||||||
|
- first:
|
||||||
|
Windows Store Apps: WindowsStoreApps
|
||||||
|
second:
|
||||||
|
enabled: 1
|
||||||
|
settings: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
# ShrinkDataSaver
|
# ShrinkDataSaver
|
||||||
|
|
||||||
一个为 Unity C# 项目设计的模块化存档与设置管理系统。支持多存档槽、链式版本迁移、可选 AES-256 加密、关键模块保护、跨模块只读查询,以及完整的事件驱动架构。
|
一个可用于 Unity、Godot 和普通 .NET 宿主的模块化存档与设置管理系统。支持多存档槽、链式版本迁移、可选 AES-256 加密、关键模块保护、跨模块只读查询,以及完整的事件驱动架构。
|
||||||
|
|
||||||
|
Godot 和普通 .NET 项目安装 `ShrinkSDK.DataSaver`;可打包源码位于 `DotNet~`,持久化路径与生命周期由宿主平台服务注入。
|
||||||
|
|
||||||
## ✨ 特性概览
|
## ✨ 特性概览
|
||||||
|
|
||||||
@@ -17,6 +19,7 @@
|
|||||||
| ⚙️ **Settings 系统** | 独立于存档的键值对设置,防抖写入,本地持久化 |
|
| ⚙️ **Settings 系统** | 独立于存档的键值对设置,防抖写入,本地持久化 |
|
||||||
| 🧷 **最近游玩槽位** | 自动记录最近一次成功进入的槽位,可用于“继续游戏” |
|
| 🧷 **最近游玩槽位** | 自动记录最近一次成功进入的槽位,可用于“继续游戏” |
|
||||||
| 🛠️ **双副本备份** | 主文件原子替换,自动保留 `.bak1` / `.bak2` 双副本轮换 |
|
| 🛠️ **双副本备份** | 主文件原子替换,自动保留 `.bak1` / `.bak2` 双副本轮换 |
|
||||||
|
| 📦 **可注入存储** | 宿主可传入自定义 `IStorageProvider`,或选择 `RenameOnly` 提交策略 |
|
||||||
| ☁️ **云存档兼容** | 每槽单文件 `.sav`,模块级 `EnableCloudSync` 开关 |
|
| ☁️ **云存档兼容** | 每槽单文件 `.sav`,模块级 `EnableCloudSync` 开关 |
|
||||||
| 🔗 **EventBus 集成** | 可选接入 ShrinkEventBus,所有事件自动桥接到事件总线 |
|
| 🔗 **EventBus 集成** | 可选接入 ShrinkEventBus,所有事件自动桥接到事件总线 |
|
||||||
| 🖥️ **Editor 工具** | 中文可视化调试窗口,实时查看/操作设置与存档 |
|
| 🖥️ **Editor 工具** | 中文可视化调试窗口,实时查看/操作设置与存档 |
|
||||||
@@ -50,9 +53,11 @@ https://git.crash.work/ShrinkSDK/ShrinkDataSaver.git
|
|||||||
|
|
||||||
### 第一步:创建配置资产
|
### 第一步:创建配置资产
|
||||||
|
|
||||||
菜单 `Assets` → `Create` → `ShrinkDataSaver` → `Settings`。
|
菜单 `ShrinkSDK` → `存档` → `创建设置`。
|
||||||
|
|
||||||
配置文件可放置在项目**任意目录**下,编辑器会通过 `AssetDatabase` 自动搜索。也可放在 `Resources/` 下供运行时加载,或在 Bootstrap 组件上手动指定。
|
菜单会创建 `Assets/Resources/GameAssets/Runtime/Data/ShrinkSDK/ShrinkDataSaverSettings.asset`。
|
||||||
|
运行时优先从该路径加载,并保留旧的 `Assets/Resources/ShrinkDataSaverSettings.asset`
|
||||||
|
回退;也可以在 Bootstrap 组件上手动指定。
|
||||||
|
|
||||||
> ⚠️ 未找到配置文件时,控制台会输出警告并使用默认配置。
|
> ⚠️ 未找到配置文件时,控制台会输出警告并使用默认配置。
|
||||||
|
|
||||||
@@ -71,6 +76,16 @@ Bootstrap 会自动 `DontDestroyOnLoad`,并在应用退出 / 移动端切后
|
|||||||
- 如果项目接入了 `ShrinkApp`,则可由宿主统一调用 `ShrinkDataSaverRuntime.Initialize(...)`
|
- 如果项目接入了 `ShrinkApp`,则可由宿主统一调用 `ShrinkDataSaverRuntime.Initialize(...)`
|
||||||
- 宿主已接管时,旧 bootstrap 会自动幂等退出,不重复初始化
|
- 宿主已接管时,旧 bootstrap 会自动幂等退出,不重复初始化
|
||||||
|
|
||||||
|
Godot 或其他 .NET 8 宿主可以注入自己的存储实现,并显式提供覆盖重命名操作。共享 netstandard2.1 库不绑定平台原生 API;缺少该操作时 `RenameOnly` 构造会失败。Godot 也可直接使用 `ShrinkGodotStorage.CreateRenameOnly(rootPath)`:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var storage = new LocalStorageProvider(rootPath, LocalStorageCommitStrategy.RenameOnly,
|
||||||
|
(source, destination) => File.Move(source, destination, overwrite: true));
|
||||||
|
ShrinkDataSaverPlatform.Initialize(storage, rootPath);
|
||||||
|
```
|
||||||
|
|
||||||
|
`ShrinkDataSaverRuntimeConfig.Storage`(Unity 与 .NET 两套运行时配置均提供)和 `ShrinkDataSaverAppModuleConfig` 也支持传入自定义存储。`RenameOnly` 适合不支持原子替换的沙箱文件系统;它仍保留 `.bak1` / `.bak2`,并会在读取或下一次写入前恢复中断的提交。
|
||||||
|
|
||||||
### 第三步:注册存档模块
|
### 第三步:注册存档模块
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
@@ -525,7 +540,7 @@ await ShrinkSave.LoadSlotAsync(slotIndex, key);
|
|||||||
|
|
||||||
- **模块注册顺序无关**:`SaveSlotAsync` 序列化所有已注册模块,`LoadSlotAsync` 分发到对应模块,缺失的模块会跳过但不会导致加载失败。
|
- **模块注册顺序无关**:`SaveSlotAsync` 序列化所有已注册模块,`LoadSlotAsync` 分发到对应模块,缺失的模块会跳过但不会导致加载失败。
|
||||||
- **宿主接管兼容**:如果项目接入了 `ShrinkApp`,推荐通过 `ShrinkDataSaver.Integration.App` 让宿主统一初始化,而不是继续依赖场景 bootstrap。
|
- **宿主接管兼容**:如果项目接入了 `ShrinkApp`,推荐通过 `ShrinkDataSaver.Integration.App` 让宿主统一初始化,而不是继续依赖场景 bootstrap。
|
||||||
- **写入原子性**:`LocalStorageProvider` 先异步写入 `.tmp` 临时文件,再通过原子替换提交主文件,并自动轮换 `.bak1` / `.bak2` 两份备份。
|
- **写入原子性**:`LocalStorageProvider` 先异步写入 `.tmp` 临时文件,再按 `FileReplace` 或 `RenameOnly` 策略提交主文件,并自动轮换 `.bak1` / `.bak2` 两份备份。
|
||||||
- **读取恢复**:`ShrinkSave` 与 `ShrinkSettings` 读取主文件失败时,会自动回退到 `.bak1`、`.bak2`,并在成功后修复主文件。
|
- **读取恢复**:`ShrinkSave` 与 `ShrinkSettings` 读取主文件失败时,会自动回退到 `.bak1`、`.bak2`,并在成功后修复主文件。
|
||||||
- **Settings 防抖**:`Set()` 调用后不立刻写磁盘,在 300ms(可配置)内连续调用只触发一次写入。退出时强制跳过防抖直接写入。
|
- **Settings 防抖**:`Set()` 调用后不立刻写磁盘,在 300ms(可配置)内连续调用只触发一次写入。退出时强制跳过防抖直接写入。
|
||||||
- **加密密钥管理**:框架不存储密钥。密钥丢失则对应存档无法解密,建议在 UI 层给玩家明确提示。
|
- **加密密钥管理**:框架不存储密钥。密钥丢失则对应存档无法解密,建议在 UI 层给玩家明确提示。
|
||||||
@@ -538,3 +553,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 -->
|
||||||
+171
-48
@@ -3,11 +3,17 @@ using System.Collections.Concurrent;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Cysharp.Threading.Tasks;
|
using Cysharp.Threading.Tasks;
|
||||||
using UnityEngine;
|
|
||||||
|
|
||||||
namespace ShrinkDataSaver
|
namespace ShrinkDataSaver
|
||||||
{
|
{
|
||||||
|
public enum LocalStorageCommitStrategy
|
||||||
|
{
|
||||||
|
FileReplace = 0,
|
||||||
|
RenameOnly = 1
|
||||||
|
}
|
||||||
|
|
||||||
public class LocalStorageProvider : IStorageProvider
|
public class LocalStorageProvider : IStorageProvider
|
||||||
{
|
{
|
||||||
private const string BackupPrimarySuffix = ".bak1";
|
private const string BackupPrimarySuffix = ".bak1";
|
||||||
@@ -18,12 +24,37 @@ namespace ShrinkDataSaver
|
|||||||
new(StringComparer.OrdinalIgnoreCase);
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
private readonly string _rootPath;
|
private readonly string _rootPath;
|
||||||
|
private readonly LocalStorageCommitStrategy _commitStrategy;
|
||||||
|
private readonly Action<string, string> _overwriteMove;
|
||||||
|
|
||||||
public LocalStorageProvider(string rootPath = null)
|
public LocalStorageProvider(string rootPath = null)
|
||||||
|
: this(rootPath, LocalStorageCommitStrategy.FileReplace)
|
||||||
{
|
{
|
||||||
_rootPath = rootPath ?? Application.persistentDataPath;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public LocalStorageProvider(string rootPath, LocalStorageCommitStrategy commitStrategy)
|
||||||
|
: this(rootPath, commitStrategy, null)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalStorageProvider(string rootPath, LocalStorageCommitStrategy commitStrategy,
|
||||||
|
Action<string, string> overwriteMove)
|
||||||
|
{
|
||||||
|
if (!Enum.IsDefined(typeof(LocalStorageCommitStrategy), commitStrategy))
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(commitStrategy));
|
||||||
|
if (commitStrategy == LocalStorageCommitStrategy.RenameOnly && overwriteMove == null)
|
||||||
|
throw new ArgumentException("RenameOnly requires an overwrite-rename implementation.", nameof(overwriteMove));
|
||||||
|
_overwriteMove = overwriteMove;
|
||||||
|
_rootPath = rootPath ?? ShrinkDataSaverPlatform.Paths?.PersistentDataPath
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
?? UnityEngine.Application.persistentDataPath
|
||||||
|
#endif
|
||||||
|
?? throw new InvalidOperationException("ShrinkDataSaver persistent path is not configured.");
|
||||||
|
_commitStrategy = commitStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalStorageCommitStrategy CommitStrategy => _commitStrategy;
|
||||||
|
|
||||||
private string Resolve(string path) =>
|
private string Resolve(string path) =>
|
||||||
Path.IsPathRooted(path) ? path : Path.Combine(_rootPath, path);
|
Path.IsPathRooted(path) ? path : Path.Combine(_rootPath, path);
|
||||||
|
|
||||||
@@ -33,50 +64,28 @@ namespace ShrinkDataSaver
|
|||||||
var dir = Path.GetDirectoryName(fullPath);
|
var dir = Path.GetDirectoryName(fullPath);
|
||||||
if (!string.IsNullOrEmpty(dir))
|
if (!string.IsNullOrEmpty(dir))
|
||||||
{
|
{
|
||||||
await UniTask.RunOnThreadPool(() => Directory.CreateDirectory(dir), cancellationToken: ct);
|
await Task.Run(() => Directory.CreateDirectory(dir), ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
var tempPath = fullPath + TempWriteSuffix;
|
|
||||||
var backupPath = fullPath + BackupPrimarySuffix;
|
|
||||||
var secondaryBackupPath = fullPath + BackupSecondarySuffix;
|
|
||||||
var pathLock = GetPathLock(fullPath);
|
var pathLock = GetPathLock(fullPath);
|
||||||
|
|
||||||
await pathLock.WaitAsync(ct);
|
await pathLock.WaitAsync(ct);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await WriteFileBytesAsync(tempPath, data, ct);
|
await Task.Run(() => RecoverInterruptedWrite(fullPath), CancellationToken.None);
|
||||||
await UniTask.RunOnThreadPool(() =>
|
ct.ThrowIfCancellationRequested();
|
||||||
{
|
|
||||||
if (File.Exists(fullPath))
|
|
||||||
{
|
|
||||||
if (File.Exists(secondaryBackupPath))
|
|
||||||
{
|
|
||||||
File.Delete(secondaryBackupPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (File.Exists(backupPath))
|
var tempPath = fullPath + TempWriteSuffix;
|
||||||
{
|
try
|
||||||
File.Move(backupPath, secondaryBackupPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
File.Replace(tempPath, fullPath, backupPath, true);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
File.Move(tempPath, fullPath);
|
|
||||||
}
|
|
||||||
}, cancellationToken: ct);
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
await UniTask.RunOnThreadPool(() =>
|
|
||||||
{
|
{
|
||||||
if (File.Exists(tempPath))
|
await WriteFileBytesAsync(tempPath, data, ct);
|
||||||
{
|
ct.ThrowIfCancellationRequested();
|
||||||
File.Delete(tempPath);
|
await Task.Run(() => Commit(tempPath, fullPath), CancellationToken.None);
|
||||||
}
|
}
|
||||||
}, cancellationToken: CancellationToken.None);
|
catch
|
||||||
throw;
|
{
|
||||||
|
await Task.Run(() => TryDelete(tempPath), CancellationToken.None);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -91,6 +100,7 @@ namespace ShrinkDataSaver
|
|||||||
await pathLock.WaitAsync(ct);
|
await pathLock.WaitAsync(ct);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
await Task.Run(() => RecoverInterruptedWrite(fullPath), CancellationToken.None);
|
||||||
if (!File.Exists(fullPath))
|
if (!File.Exists(fullPath))
|
||||||
{
|
{
|
||||||
throw new FileNotFoundException($"ShrinkDataSaver: file not found: {fullPath}");
|
throw new FileNotFoundException($"ShrinkDataSaver: file not found: {fullPath}");
|
||||||
@@ -104,8 +114,23 @@ namespace ShrinkDataSaver
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public UniTask<bool> ExistsAsync(string path, CancellationToken ct = default) =>
|
public async UniTask<bool> ExistsAsync(string path, CancellationToken ct = default) =>
|
||||||
UniTask.RunOnThreadPool(() => File.Exists(Resolve(path)), cancellationToken: ct);
|
await ExistsCoreAsync(Resolve(path), ct);
|
||||||
|
|
||||||
|
private async UniTask<bool> ExistsCoreAsync(string fullPath, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var pathLock = GetPathLock(fullPath);
|
||||||
|
await pathLock.WaitAsync(ct);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Run(() => RecoverInterruptedWrite(fullPath), CancellationToken.None);
|
||||||
|
return File.Exists(fullPath);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pathLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async UniTask DeleteAsync(string path, CancellationToken ct = default)
|
public async UniTask DeleteAsync(string path, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
@@ -114,13 +139,13 @@ namespace ShrinkDataSaver
|
|||||||
await pathLock.WaitAsync(ct);
|
await pathLock.WaitAsync(ct);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await UniTask.RunOnThreadPool(() =>
|
await Task.Run(() =>
|
||||||
{
|
{
|
||||||
if (File.Exists(fullPath))
|
File.Delete(fullPath + TempWriteSuffix);
|
||||||
{
|
File.Delete(fullPath + BackupPrimarySuffix);
|
||||||
File.Delete(fullPath);
|
File.Delete(fullPath + BackupSecondarySuffix);
|
||||||
}
|
File.Delete(fullPath);
|
||||||
}, cancellationToken: ct);
|
}, ct);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -130,7 +155,7 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
public async UniTask<string[]> ListAsync(string prefix = "", CancellationToken ct = default)
|
public async UniTask<string[]> ListAsync(string prefix = "", CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
return await UniTask.RunOnThreadPool(() =>
|
return await Task.Run(() =>
|
||||||
{
|
{
|
||||||
var dir = string.IsNullOrEmpty(prefix) ? _rootPath : Path.Combine(_rootPath, prefix);
|
var dir = string.IsNullOrEmpty(prefix) ? _rootPath : Path.Combine(_rootPath, prefix);
|
||||||
if (!Directory.Exists(dir))
|
if (!Directory.Exists(dir))
|
||||||
@@ -141,7 +166,105 @@ namespace ShrinkDataSaver
|
|||||||
return Directory.GetFiles(dir)
|
return Directory.GetFiles(dir)
|
||||||
.Select(f => Path.GetRelativePath(_rootPath, f))
|
.Select(f => Path.GetRelativePath(_rootPath, f))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
}, cancellationToken: ct);
|
}, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Commit(string tempPath, string fullPath)
|
||||||
|
{
|
||||||
|
if (_commitStrategy == LocalStorageCommitStrategy.RenameOnly)
|
||||||
|
CommitRenameOnly(tempPath, fullPath);
|
||||||
|
else
|
||||||
|
CommitFileReplace(tempPath, fullPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CommitFileReplace(string tempPath, string fullPath)
|
||||||
|
{
|
||||||
|
var backupPath = fullPath + BackupPrimarySuffix;
|
||||||
|
var secondaryBackupPath = fullPath + BackupSecondarySuffix;
|
||||||
|
if (!File.Exists(fullPath))
|
||||||
|
{
|
||||||
|
File.Move(tempPath, fullPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(secondaryBackupPath))
|
||||||
|
{
|
||||||
|
File.Delete(secondaryBackupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(backupPath))
|
||||||
|
{
|
||||||
|
File.Move(backupPath, secondaryBackupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
File.Replace(tempPath, fullPath, backupPath, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CommitRenameOnly(string tempPath, string fullPath)
|
||||||
|
{
|
||||||
|
var backupPath = fullPath + BackupPrimarySuffix;
|
||||||
|
var secondaryBackupPath = fullPath + BackupSecondarySuffix;
|
||||||
|
if (File.Exists(fullPath))
|
||||||
|
{
|
||||||
|
if (File.Exists(backupPath))
|
||||||
|
{
|
||||||
|
if (File.Exists(secondaryBackupPath))
|
||||||
|
{
|
||||||
|
File.Delete(secondaryBackupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveFileReplacing(backupPath, secondaryBackupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveFileReplacing(fullPath, backupPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveFileReplacing(tempPath, fullPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RecoverInterruptedWrite(string fullPath)
|
||||||
|
{
|
||||||
|
if (_commitStrategy != LocalStorageCommitStrategy.RenameOnly)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var tempPath = fullPath + TempWriteSuffix;
|
||||||
|
var primaryBackupPath = fullPath + BackupPrimarySuffix;
|
||||||
|
var secondaryBackupPath = fullPath + BackupSecondarySuffix;
|
||||||
|
if (!File.Exists(fullPath))
|
||||||
|
{
|
||||||
|
if (File.Exists(primaryBackupPath))
|
||||||
|
{
|
||||||
|
MoveFileReplacing(primaryBackupPath, fullPath);
|
||||||
|
}
|
||||||
|
else if (File.Exists(secondaryBackupPath))
|
||||||
|
{
|
||||||
|
MoveFileReplacing(secondaryBackupPath, fullPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(tempPath))
|
||||||
|
{
|
||||||
|
TryDelete(tempPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MoveFileReplacing(string source, string destination) => _overwriteMove(source, destination);
|
||||||
|
|
||||||
|
private static void TryDelete(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
File.Delete(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static SemaphoreSlim GetPathLock(string fullPath)
|
private static SemaphoreSlim GetPathLock(string fullPath)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using UnityEngine;
|
|
||||||
|
|
||||||
namespace ShrinkDataSaver
|
namespace ShrinkDataSaver
|
||||||
{
|
{
|
||||||
@@ -33,7 +32,7 @@ namespace ShrinkDataSaver
|
|||||||
{
|
{
|
||||||
if (!Migrations.TryGetValue(version, out var migration))
|
if (!Migrations.TryGetValue(version, out var migration))
|
||||||
{
|
{
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 未找到 v{version} → v{version + 1} 的迁移逻辑,数据可能不完整。");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 未找到 v{version} → v{version + 1} 的迁移逻辑,数据可能不完整。");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,11 +41,11 @@ namespace ShrinkDataSaver
|
|||||||
var fromV = version;
|
var fromV = version;
|
||||||
data = migration.Migrate(data) ?? data;
|
data = migration.Migrate(data) ?? data;
|
||||||
version = migration.ToVersion;
|
version = migration.ToVersion;
|
||||||
Debug.Log($"[ShrinkDataSaver] 存档已迁移 v{fromV} → v{version}");
|
ShrinkDataSaverPlatform.Info($"[ShrinkDataSaver] 存档已迁移 v{fromV} → v{version}");
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
Debug.LogError(
|
ShrinkDataSaverPlatform.Error(
|
||||||
$"[ShrinkDataSaver] 迁移 v{version} → v{migration.ToVersion} 失败: {e.Message},已回滚至 v{currentVersion}");
|
$"[ShrinkDataSaver] 迁移 v{version} → v{migration.ToVersion} 失败: {e.Message},已回滚至 v{currentVersion}");
|
||||||
return (backup, currentVersion);
|
return (backup, currentVersion);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,11 +59,28 @@ 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
|
||||||
public UnityEngine.Texture2D Screenshot = null;
|
public UnityEngine.Texture2D Screenshot = null;
|
||||||
|
#else
|
||||||
|
public byte[] Screenshot;
|
||||||
|
#endif
|
||||||
public bool Encrypt = false;
|
public bool Encrypt = false;
|
||||||
public string EncryptionKey = null;
|
public string EncryptionKey = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
"rootNamespace": "ShrinkDataSaver",
|
"rootNamespace": "ShrinkDataSaver",
|
||||||
"references": [
|
"references": [
|
||||||
"UniTask",
|
"UniTask",
|
||||||
"Newtonsoft.Json"
|
"Newtonsoft.Json",
|
||||||
|
"ShrinkRuntime.Abstractions"
|
||||||
],
|
],
|
||||||
"optionalUnityReferences": [],
|
"optionalUnityReferences": [],
|
||||||
"includePlatforms": [],
|
"includePlatforms": [],
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#nullable enable
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using ShrinkSDK.Runtime;
|
||||||
|
|
||||||
|
namespace ShrinkDataSaver
|
||||||
|
{
|
||||||
|
public static class ShrinkDataSaverPlatform
|
||||||
|
{
|
||||||
|
public static IShrinkLogger? Logger { get; private set; }
|
||||||
|
public static IShrinkClock? Clock { get; private set; }
|
||||||
|
public static IShrinkPathProvider? Paths { get; private set; }
|
||||||
|
public static IShrinkScreenshotProvider? Screenshots { get; private set; }
|
||||||
|
public static float SettingsWriteDebounceSeconds { get; set; } = 0.5f;
|
||||||
|
public static int MaxSlots { get; set; }
|
||||||
|
|
||||||
|
public static void Configure(IShrinkPathProvider paths, IShrinkClock clock,
|
||||||
|
IShrinkLogger? logger = null, IShrinkScreenshotProvider? screenshots = null)
|
||||||
|
{
|
||||||
|
Paths = paths ?? throw new ArgumentNullException(nameof(paths));
|
||||||
|
Clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||||
|
Logger = logger;
|
||||||
|
Screenshots = screenshots;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Initialize(string? rootPath = null, string saveFileExtension = ".json",
|
||||||
|
string settingsFileName = "settings.json", int currentSaveVersion = 1)
|
||||||
|
{
|
||||||
|
rootPath ??= Paths?.PersistentDataPath;
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
rootPath ??= UnityEngine.Application.persistentDataPath;
|
||||||
|
#endif
|
||||||
|
if (string.IsNullOrWhiteSpace(rootPath))
|
||||||
|
throw new InvalidOperationException("ShrinkDataSaver platform paths are not configured.");
|
||||||
|
var storage = new LocalStorageProvider(rootPath);
|
||||||
|
Initialize(storage, rootPath, saveFileExtension, settingsFileName, currentSaveVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Initialize(IStorageProvider storage, string? rootPath = null,
|
||||||
|
string saveFileExtension = ".json", string settingsFileName = "settings.json",
|
||||||
|
int currentSaveVersion = 1)
|
||||||
|
{
|
||||||
|
if (storage == null)
|
||||||
|
throw new ArgumentNullException(nameof(storage));
|
||||||
|
|
||||||
|
rootPath ??= Paths?.PersistentDataPath;
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
rootPath ??= UnityEngine.Application.persistentDataPath;
|
||||||
|
#endif
|
||||||
|
var settingsPath = string.IsNullOrWhiteSpace(rootPath)
|
||||||
|
? settingsFileName
|
||||||
|
: System.IO.Path.Combine(rootPath, settingsFileName);
|
||||||
|
var savesDir = string.IsNullOrWhiteSpace(rootPath)
|
||||||
|
? "saves"
|
||||||
|
: System.IO.Path.Combine(rootPath, "saves");
|
||||||
|
ShrinkSettings.Initialize(storage, settingsPath);
|
||||||
|
ShrinkSave.Initialize(storage, savesDir, saveFileExtension, currentSaveVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static double TimeSeconds
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Clock != null) return Clock.UnscaledTimeSeconds;
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
return UnityEngine.Time.realtimeSinceStartupAsDouble;
|
||||||
|
#else
|
||||||
|
return 0d;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Info(string message)
|
||||||
|
{
|
||||||
|
if (Logger != null) Logger.Log(ShrinkLogLevel.Information, message);
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
else UnityEngine.Debug.Log(message);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Warning(string message)
|
||||||
|
{
|
||||||
|
if (Logger != null) Logger.Log(ShrinkLogLevel.Warning, message);
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
else UnityEngine.Debug.LogWarning(message);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Error(string message)
|
||||||
|
{
|
||||||
|
if (Logger != null) Logger.Log(ShrinkLogLevel.Error, message);
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
else UnityEngine.Debug.LogError(message);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Exception(Exception exception)
|
||||||
|
{
|
||||||
|
if (Logger != null) Logger.Log(ShrinkLogLevel.Error, exception.Message, exception);
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
|
else UnityEngine.Debug.LogException(exception);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: eab4e1dc3c9ba874896f3ec4f39a7ab7
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -11,6 +11,7 @@ namespace ShrinkDataSaver
|
|||||||
public ShrinkDataSaverSettings? SettingsOverride { get; set; }
|
public ShrinkDataSaverSettings? SettingsOverride { get; set; }
|
||||||
public int CurrentSaveVersion { get; set; } = 1;
|
public int CurrentSaveVersion { get; set; } = 1;
|
||||||
public bool DontDestroyOnLoadDriver { get; set; } = true;
|
public bool DontDestroyOnLoadDriver { get; set; } = true;
|
||||||
|
public IStorageProvider? Storage { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ShrinkDataSaverRuntime
|
public static class ShrinkDataSaverRuntime
|
||||||
@@ -36,7 +37,10 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
var savesDir = Path.Combine(rootPath, "saves");
|
var savesDir = Path.Combine(rootPath, "saves");
|
||||||
var settingsPath = Path.Combine(rootPath, cfg.settingsFileName);
|
var settingsPath = Path.Combine(rootPath, cfg.settingsFileName);
|
||||||
var storage = new LocalStorageProvider(rootPath);
|
var storage = config.Storage ?? new LocalStorageProvider(rootPath);
|
||||||
|
|
||||||
|
ShrinkDataSaverPlatform.SettingsWriteDebounceSeconds = cfg.settingsWriteDebounceSeconds;
|
||||||
|
ShrinkDataSaverPlatform.MaxSlots = cfg.maxSlots;
|
||||||
|
|
||||||
ShrinkSettings.Initialize(storage, settingsPath);
|
ShrinkSettings.Initialize(storage, settingsPath);
|
||||||
ShrinkSave.Initialize(storage, savesDir, cfg.saveFileExtension, config.CurrentSaveVersion);
|
ShrinkSave.Initialize(storage, savesDir, cfg.saveFileExtension, config.CurrentSaveVersion);
|
||||||
|
|||||||
@@ -2,9 +2,13 @@
|
|||||||
|
|
||||||
namespace ShrinkDataSaver
|
namespace ShrinkDataSaver
|
||||||
{
|
{
|
||||||
[CreateAssetMenu(fileName = "ShrinkDataSaverSettings", menuName = "ShrinkDataSaver/Settings")]
|
[CreateAssetMenu(fileName = "ShrinkDataSaverSettings", menuName = "ShrinkSDK/存档/存档设置")]
|
||||||
public class ShrinkDataSaverSettings : ScriptableObject
|
public class ShrinkDataSaverSettings : ScriptableObject
|
||||||
{
|
{
|
||||||
|
public const string PreferredResourcesPath =
|
||||||
|
"GameAssets/Runtime/Data/ShrinkSDK/ShrinkDataSaverSettings";
|
||||||
|
public const string LegacyResourcesPath = "ShrinkDataSaverSettings";
|
||||||
|
|
||||||
private static ShrinkDataSaverSettings _instance;
|
private static ShrinkDataSaverSettings _instance;
|
||||||
|
|
||||||
public static ShrinkDataSaverSettings Instance
|
public static ShrinkDataSaverSettings Instance
|
||||||
@@ -13,7 +17,9 @@ namespace ShrinkDataSaver
|
|||||||
{
|
{
|
||||||
if (_instance) return _instance;
|
if (_instance) return _instance;
|
||||||
|
|
||||||
_instance = Resources.Load<ShrinkDataSaverSettings>("ShrinkDataSaverSettings");
|
_instance = Resources.Load<ShrinkDataSaverSettings>(PreferredResourcesPath);
|
||||||
|
if (!_instance)
|
||||||
|
_instance = Resources.Load<ShrinkDataSaverSettings>(LegacyResourcesPath);
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
if (!_instance)
|
if (!_instance)
|
||||||
@@ -41,6 +47,11 @@ namespace ShrinkDataSaver
|
|||||||
internal set => _instance = value;
|
internal set => _instance = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static void ResetCachedInstance()
|
||||||
|
{
|
||||||
|
_instance = null;
|
||||||
|
}
|
||||||
|
|
||||||
[Header("Storage")]
|
[Header("Storage")]
|
||||||
public string customSavePath = "";
|
public string customSavePath = "";
|
||||||
|
|
||||||
|
|||||||
+72
-28
@@ -1,10 +1,14 @@
|
|||||||
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;
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
#endif
|
||||||
|
|
||||||
namespace ShrinkDataSaver
|
namespace ShrinkDataSaver
|
||||||
{
|
{
|
||||||
@@ -141,7 +145,7 @@ namespace ShrinkDataSaver
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 读取元数据失败 slot_{slotIndex}: {e.Message}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 读取元数据失败 slot_{slotIndex}: {e.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,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 });
|
||||||
@@ -196,11 +208,15 @@ namespace ShrinkDataSaver
|
|||||||
SaveVersion = _currentSaveVersion,
|
SaveVersion = _currentSaveVersion,
|
||||||
LastModified = timestamp,
|
LastModified = timestamp,
|
||||||
PlaytimeSeconds = GetCurrentPlaytime(),
|
PlaytimeSeconds = GetCurrentPlaytime(),
|
||||||
IsEncrypted = options.Encrypt
|
IsEncrypted = encrypt
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
if (options.Screenshot || options.CaptureScreenshot)
|
if (options.Screenshot || options.CaptureScreenshot)
|
||||||
|
#else
|
||||||
|
if (options.Screenshot != null || options.CaptureScreenshot)
|
||||||
|
#endif
|
||||||
{
|
{
|
||||||
packet.Meta.ScreenshotBase64 = await CaptureScreenshotAsync(options, ct);
|
packet.Meta.ScreenshotBase64 = await CaptureScreenshotAsync(options, ct);
|
||||||
}
|
}
|
||||||
@@ -223,28 +239,39 @@ namespace ShrinkDataSaver
|
|||||||
throw new InvalidOperationException($"关键模块 '{module.Key}' 序列化失败: {e.Message}", e);
|
throw new InvalidOperationException($"关键模块 '{module.Key}' 序列化失败: {e.Message}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
Debug.LogError($"[ShrinkDataSaver] 模块 '{module.Key}' 序列化失败(已跳过): {e.Message}");
|
ShrinkDataSaverPlatform.Error($"[ShrinkDataSaver] 模块 '{module.Key}' 序列化失败(已跳过): {e.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
{
|
{
|
||||||
@@ -252,7 +279,7 @@ namespace ShrinkDataSaver
|
|||||||
ModuleNames = moduleNames.ToArray(),
|
ModuleNames = moduleNames.ToArray(),
|
||||||
Timestamp = timestamp
|
Timestamp = timestamp
|
||||||
});
|
});
|
||||||
Debug.Log($"[ShrinkDataSaver] 槽位 {slotIndex} 已保存。({moduleNames.Count} 个模块)");
|
ShrinkDataSaverPlatform.Info($"[ShrinkDataSaver] 槽位 {slotIndex} 已保存。({moduleNames.Count} 个模块)");
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
@@ -265,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();
|
||||||
@@ -293,13 +322,13 @@ namespace ShrinkDataSaver
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
Debug.LogError($"[ShrinkDataSaver] 反序列化模块 '{module.Key}' 失败: {e.Message}");
|
ShrinkDataSaverPlatform.Error($"[ShrinkDataSaver] 反序列化模块 '{module.Key}' 失败: {e.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_loadedSlot = slotIndex;
|
_loadedSlot = slotIndex;
|
||||||
_storedPlaytime = packet.Meta.PlaytimeSeconds;
|
_storedPlaytime = packet.Meta.PlaytimeSeconds;
|
||||||
_sessionStart = Time.realtimeSinceStartup;
|
_sessionStart = (float)ShrinkDataSaverPlatform.TimeSeconds;
|
||||||
await PersistRecentSlotIndexAsync(slotIndex, ct);
|
await PersistRecentSlotIndexAsync(slotIndex, ct);
|
||||||
|
|
||||||
OnLoadCompleted?.Invoke(new LoadCompletedEventArgs
|
OnLoadCompleted?.Invoke(new LoadCompletedEventArgs
|
||||||
@@ -309,7 +338,7 @@ namespace ShrinkDataSaver
|
|||||||
Version = packet.Meta.SaveVersion,
|
Version = packet.Meta.SaveVersion,
|
||||||
Timestamp = timestamp
|
Timestamp = timestamp
|
||||||
});
|
});
|
||||||
Debug.Log($"[ShrinkDataSaver] 槽位 {slotIndex} 已加载。(v{packet.Meta.SaveVersion}, {moduleNames.Count} 个模块)");
|
ShrinkDataSaverPlatform.Info($"[ShrinkDataSaver] 槽位 {slotIndex} 已加载。(v{packet.Meta.SaveVersion}, {moduleNames.Count} 个模块)");
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
@@ -344,7 +373,7 @@ namespace ShrinkDataSaver
|
|||||||
}
|
}
|
||||||
|
|
||||||
OnDeleteCompleted?.Invoke(new SlotDeletedEventArgs { SlotIndex = slotIndex });
|
OnDeleteCompleted?.Invoke(new SlotDeletedEventArgs { SlotIndex = slotIndex });
|
||||||
Debug.Log($"[ShrinkDataSaver] 槽位 {slotIndex} 已删除。");
|
ShrinkDataSaverPlatform.Info($"[ShrinkDataSaver] 槽位 {slotIndex} 已删除。");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static float GetMinAutoSaveInterval()
|
public static float GetMinAutoSaveInterval()
|
||||||
@@ -355,7 +384,7 @@ namespace ShrinkDataSaver
|
|||||||
{
|
{
|
||||||
if (cfg.AutoSaveIntervalSeconds > 0f)
|
if (cfg.AutoSaveIntervalSeconds > 0f)
|
||||||
{
|
{
|
||||||
min = Mathf.Min(min, cfg.AutoSaveIntervalSeconds);
|
min = Math.Min(min, cfg.AutoSaveIntervalSeconds);
|
||||||
hasAny = true;
|
hasAny = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -406,7 +435,11 @@ namespace ShrinkDataSaver
|
|||||||
throw new ArgumentOutOfRangeException(nameof(slotIndex), "槽位索引不能为负数。");
|
throw new ArgumentOutOfRangeException(nameof(slotIndex), "槽位索引不能为负数。");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
var max = ShrinkDataSaverSettings.Instance.maxSlots;
|
var max = ShrinkDataSaverSettings.Instance.maxSlots;
|
||||||
|
#else
|
||||||
|
var max = ShrinkDataSaverPlatform.MaxSlots;
|
||||||
|
#endif
|
||||||
if (max > 0 && slotIndex >= max)
|
if (max > 0 && slotIndex >= max)
|
||||||
{
|
{
|
||||||
throw new ArgumentOutOfRangeException(nameof(slotIndex), $"超出最大槽位数 ({max})。");
|
throw new ArgumentOutOfRangeException(nameof(slotIndex), $"超出最大槽位数 ({max})。");
|
||||||
@@ -529,7 +562,7 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 槽位 {slotIndex} 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 槽位 {slotIndex} 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
||||||
await _storage.WriteAsync(primaryPath, bytes, ct);
|
await _storage.WriteAsync(primaryPath, bytes, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,7 +571,7 @@ namespace ShrinkDataSaver
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
lastError = ex;
|
lastError = ex;
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 读取槽位副本失败:{candidatePath} / {ex.Message}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 读取槽位副本失败:{candidatePath} / {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -612,7 +645,7 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 槽位 {slotIndex} 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 槽位 {slotIndex} 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
||||||
await _storage.WriteAsync(primaryPath, bytes, ct);
|
await _storage.WriteAsync(primaryPath, bytes, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -621,7 +654,7 @@ namespace ShrinkDataSaver
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
lastError = ex;
|
lastError = ex;
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 加载槽位副本失败:{candidatePath} / {ex.Message}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 加载槽位副本失败:{candidatePath} / {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -633,10 +666,11 @@ namespace ShrinkDataSaver
|
|||||||
throw new FileNotFoundException($"槽位 {slotIndex} 不存在。");
|
throw new FileNotFoundException($"槽位 {slotIndex} 不存在。");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static float GetCurrentPlaytime() => _loadedSlot < 0 ? 0f : _storedPlaytime + (Time.realtimeSinceStartup - _sessionStart);
|
private static float GetCurrentPlaytime() => _loadedSlot < 0 ? 0f : _storedPlaytime + ((float)ShrinkDataSaverPlatform.TimeSeconds - _sessionStart);
|
||||||
|
|
||||||
private static async UniTask<string> CaptureScreenshotAsync(SaveOptions options, CancellationToken ct)
|
private static async UniTask<string> CaptureScreenshotAsync(SaveOptions options, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
#if UNITY_5_3_OR_NEWER
|
||||||
var tex = options.Screenshot;
|
var tex = options.Screenshot;
|
||||||
if (!tex && options.CaptureScreenshot)
|
if (!tex && options.CaptureScreenshot)
|
||||||
{
|
{
|
||||||
@@ -668,6 +702,16 @@ namespace ShrinkDataSaver
|
|||||||
}
|
}
|
||||||
|
|
||||||
return Convert.ToBase64String(tex.EncodeToJPG(75));
|
return Convert.ToBase64String(tex.EncodeToJPG(75));
|
||||||
|
#else
|
||||||
|
var pngBytes = options.Screenshot;
|
||||||
|
if (pngBytes == null && options.CaptureScreenshot)
|
||||||
|
{
|
||||||
|
var provider = ShrinkDataSaverPlatform.Screenshots ??
|
||||||
|
throw new InvalidOperationException("Screenshot capture was requested but no platform provider is configured.");
|
||||||
|
pngBytes = await provider.CapturePngAsync(ct);
|
||||||
|
}
|
||||||
|
return pngBytes == null ? string.Empty : Convert.ToBase64String(pngBytes);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Cysharp.Threading.Tasks;
|
using Cysharp.Threading.Tasks;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using UnityEngine;
|
|
||||||
|
|
||||||
namespace ShrinkDataSaver
|
namespace ShrinkDataSaver
|
||||||
{
|
{
|
||||||
@@ -112,7 +112,7 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
if (_watchers.TryGetValue(key, out var list))
|
if (_watchers.TryGetValue(key, out var list))
|
||||||
foreach (var cb in list)
|
foreach (var cb in list)
|
||||||
try { cb(value); } catch (Exception e) { Debug.LogException(e); }
|
try { cb(value); } catch (Exception e) { ShrinkDataSaverPlatform.Exception(e); }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async UniTaskVoid ScheduleWrite()
|
private static async UniTaskVoid ScheduleWrite()
|
||||||
@@ -123,12 +123,12 @@ namespace ShrinkDataSaver
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var delay = (int)(ShrinkDataSaverSettings.Instance.settingsWriteDebounceSeconds * 1000);
|
var delay = (int)(ShrinkDataSaverPlatform.SettingsWriteDebounceSeconds * 1000);
|
||||||
await UniTask.Delay(delay, cancellationToken: token);
|
await Task.Delay(delay, token);
|
||||||
await SaveAsync(token);
|
await SaveAsync(token);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) { }
|
catch (OperationCanceledException) { }
|
||||||
catch (Exception e) { Debug.LogException(e); }
|
catch (Exception e) { ShrinkDataSaverPlatform.Exception(e); }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async UniTask<SettingsData> TryLoadWithFallbackAsync(CancellationToken ct)
|
private static async UniTask<SettingsData> TryLoadWithFallbackAsync(CancellationToken ct)
|
||||||
@@ -149,7 +149,7 @@ namespace ShrinkDataSaver
|
|||||||
var loaded = DataSerializer.Deserialize<SettingsData>(bytes) ?? new SettingsData();
|
var loaded = DataSerializer.Deserialize<SettingsData>(bytes) ?? new SettingsData();
|
||||||
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
if (!string.Equals(candidatePath, primaryPath, StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] Settings 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] Settings 主文件损坏或缺失,已从备份恢复:{candidatePath}");
|
||||||
await _storage.WriteAsync(primaryPath, bytes, ct);
|
await _storage.WriteAsync(primaryPath, bytes, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,13 +158,13 @@ namespace ShrinkDataSaver
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
lastError = ex;
|
lastError = ex;
|
||||||
Debug.LogWarning($"[ShrinkDataSaver] 读取 Settings 副本失败:{candidatePath} / {ex.Message}");
|
ShrinkDataSaverPlatform.Warning($"[ShrinkDataSaver] 读取 Settings 副本失败:{candidatePath} / {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lastError != null)
|
if (lastError != null)
|
||||||
{
|
{
|
||||||
Debug.LogWarning("[ShrinkDataSaver] 所有 Settings 副本均不可用,已回退为空设置。");
|
ShrinkDataSaverPlatform.Warning("[ShrinkDataSaver] 所有 Settings 副本均不可用,已回退为空设置。");
|
||||||
}
|
}
|
||||||
|
|
||||||
return new SettingsData();
|
return new SettingsData();
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Cysharp.Threading.Tasks;
|
||||||
|
using NUnit.Framework;
|
||||||
|
using UnityEngine.TestTools;
|
||||||
|
|
||||||
|
namespace ShrinkDataSaver.Tests
|
||||||
|
{
|
||||||
|
[TestFixture]
|
||||||
|
public class LocalStorageProviderStrategyTests
|
||||||
|
{
|
||||||
|
private string _rootPath;
|
||||||
|
|
||||||
|
[SetUp]
|
||||||
|
public void SetUp()
|
||||||
|
{
|
||||||
|
_rootPath = Path.Combine(Path.GetTempPath(), $"ShrinkDataSaverStrategyTests_{Guid.NewGuid():N}");
|
||||||
|
Directory.CreateDirectory(_rootPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TearDown]
|
||||||
|
public void TearDown()
|
||||||
|
{
|
||||||
|
if (Directory.Exists(_rootPath))
|
||||||
|
{
|
||||||
|
Directory.Delete(_rootPath, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void DefaultConstructor_UsesFileReplace()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(LocalStorageCommitStrategy.FileReplace,
|
||||||
|
new LocalStorageProvider(_rootPath).CommitStrategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_RotatesTwoBackups() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
await WriteAsync(provider, "three");
|
||||||
|
|
||||||
|
Assert.AreEqual("three", await ReadAsync(provider, "save.dat"));
|
||||||
|
Assert.AreEqual("two", await ReadAsync(provider, "save.dat.bak1"));
|
||||||
|
Assert.AreEqual("one", await ReadAsync(provider, "save.dat.bak2"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_RecoversPrimaryFromBak1_WhenPrimaryMissing() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
var primaryBackup = primary + ".bak1";
|
||||||
|
File.Delete(primaryBackup);
|
||||||
|
File.Move(primary, primaryBackup);
|
||||||
|
|
||||||
|
Assert.IsTrue(await provider.ExistsAsync("save.dat"));
|
||||||
|
Assert.AreEqual("two", await ReadAsync(provider, "save.dat"));
|
||||||
|
Assert.IsTrue(File.Exists(primary));
|
||||||
|
Assert.IsFalse(File.Exists(primaryBackup));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_RecoversPrimaryFromBak2_WhenBak1Missing() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
await WriteAsync(provider, "three");
|
||||||
|
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.Delete(primary);
|
||||||
|
File.Delete(primary + ".bak1");
|
||||||
|
|
||||||
|
Assert.AreEqual("one", await ReadAsync(provider, "save.dat"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_DeletesStaleTempBeforeWrite() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.WriteAllText(primary + ".tmp", "stale", Encoding.UTF8);
|
||||||
|
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".tmp"));
|
||||||
|
Assert.AreEqual("two", await ReadAsync(provider, "save.dat"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_PreservesSecondGeneration_WhenBak1Missing() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
await WriteAsync(provider, "three");
|
||||||
|
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.Delete(primary + ".bak1");
|
||||||
|
|
||||||
|
await WriteAsync(provider, "four");
|
||||||
|
|
||||||
|
Assert.AreEqual("four", await ReadAsync(provider, "save.dat"));
|
||||||
|
Assert.AreEqual("three", await ReadAsync(provider, "save.dat.bak1"));
|
||||||
|
Assert.AreEqual("one", await ReadAsync(provider, "save.dat.bak2"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_DoesNotPromoteOrphanTemp() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.WriteAllText(primary + ".tmp", "partial", new UTF8Encoding(false));
|
||||||
|
|
||||||
|
Assert.IsFalse(await provider.ExistsAsync("save.dat"));
|
||||||
|
Assert.IsFalse(File.Exists(primary));
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".tmp"));
|
||||||
|
|
||||||
|
var readFailed = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await ReadAsync(provider, "save.dat");
|
||||||
|
}
|
||||||
|
catch (FileNotFoundException)
|
||||||
|
{
|
||||||
|
readFailed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(readFailed);
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator RenameOnly_PrefersBackupOverPartialTemp() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.Delete(primary);
|
||||||
|
File.WriteAllText(primary + ".tmp", "partial", new UTF8Encoding(false));
|
||||||
|
|
||||||
|
Assert.IsTrue(await provider.ExistsAsync("save.dat"));
|
||||||
|
Assert.AreEqual("one", await ReadAsync(provider, "save.dat"));
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".tmp"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator FileReplace_DoesNotApplyRenameOnlyRecovery() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.Delete(primary);
|
||||||
|
File.WriteAllText(primary + ".tmp", "partial", new UTF8Encoding(false));
|
||||||
|
|
||||||
|
Assert.IsFalse(await provider.ExistsAsync("save.dat"));
|
||||||
|
Assert.IsTrue(File.Exists(primary + ".bak1"));
|
||||||
|
Assert.IsTrue(File.Exists(primary + ".tmp"));
|
||||||
|
|
||||||
|
var readFailed = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await ReadAsync(provider, "save.dat");
|
||||||
|
}
|
||||||
|
catch (FileNotFoundException)
|
||||||
|
{
|
||||||
|
readFailed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(readFailed);
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator DeleteAsync_RemovesBackupsAndTemp() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var provider = new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly, TestMove);
|
||||||
|
await WriteAsync(provider, "one");
|
||||||
|
await WriteAsync(provider, "two");
|
||||||
|
var primary = Path.Combine(_rootPath, "save.dat");
|
||||||
|
File.WriteAllText(primary + ".tmp", "stale", Encoding.UTF8);
|
||||||
|
|
||||||
|
await provider.DeleteAsync("save.dat");
|
||||||
|
|
||||||
|
Assert.IsFalse(File.Exists(primary));
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".bak1"));
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".bak2"));
|
||||||
|
Assert.IsFalse(File.Exists(primary + ".tmp"));
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator PlatformInitialize_UsesInjectedStorage() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
var storage = new MockStorageProvider();
|
||||||
|
ShrinkSettings.ResetForTesting();
|
||||||
|
ShrinkDataSaverPlatform.Initialize(storage, "runtime-root");
|
||||||
|
ShrinkSettings.Set("injected", 7);
|
||||||
|
await ShrinkSettings.SaveAsync();
|
||||||
|
|
||||||
|
Assert.IsTrue(await storage.ExistsAsync("runtime-root/settings.json"));
|
||||||
|
var bytes = await storage.ReadAsync("runtime-root/settings.json");
|
||||||
|
StringAssert.Contains("\"injected\"", Encoding.UTF8.GetString(bytes));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Tests the shared rotation contract; Godot integration tests exercise actual overwrite rename.
|
||||||
|
private static void TestMove(string source, string destination)
|
||||||
|
{
|
||||||
|
if (File.Exists(destination)) File.Delete(destination);
|
||||||
|
File.Move(source, destination);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public void RenameOnly_RequiresOverwriteCapability() => Assert.Throws<ArgumentException>(() =>
|
||||||
|
new LocalStorageProvider(_rootPath, LocalStorageCommitStrategy.RenameOnly));
|
||||||
|
|
||||||
|
private static async UniTask WriteAsync(IStorageProvider provider, string value)
|
||||||
|
{
|
||||||
|
await provider.WriteAsync("save.dat", Encoding.UTF8.GetBytes(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async UniTask<string> ReadAsync(IStorageProvider provider, string path)
|
||||||
|
{
|
||||||
|
var bytes = await provider.ReadAsync(path);
|
||||||
|
return Encoding.UTF8.GetString(bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: f087803def7c483eab1449e4f5dce096
|
||||||
|
MonoImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading;
|
||||||
using Cysharp.Threading.Tasks;
|
using Cysharp.Threading.Tasks;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
@@ -199,6 +201,48 @@ namespace ShrinkDataSaver.Tests
|
|||||||
CollectionAssert.AreEqual(backupBytes, repairedPrimary);
|
CollectionAssert.AreEqual(backupBytes, repairedPrimary);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator LoadAsync_FallsBackToSecondaryBackup_WhenPrimaryAndFirstBackupCorrupted() =>
|
||||||
|
UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
ShrinkSettings.Set("lang", "zh_cn");
|
||||||
|
await ShrinkSettings.SaveAsync();
|
||||||
|
|
||||||
|
var backupBytes = await _storage.ReadAsync("settings.json");
|
||||||
|
await _storage.WriteAsync("settings.json.bak2", backupBytes);
|
||||||
|
await _storage.WriteAsync("settings.json.bak1", System.Text.Encoding.UTF8.GetBytes("{ broken"));
|
||||||
|
await _storage.WriteAsync("settings.json", System.Text.Encoding.UTF8.GetBytes("{ broken"));
|
||||||
|
|
||||||
|
ShrinkSettings.ResetForTesting();
|
||||||
|
ShrinkSettings.Initialize(_storage, "settings.json");
|
||||||
|
|
||||||
|
await ShrinkSettings.LoadAsync();
|
||||||
|
|
||||||
|
Assert.AreEqual("zh_cn", ShrinkSettings.Get<string>("lang"));
|
||||||
|
var repairedPrimary = await _storage.ReadAsync("settings.json");
|
||||||
|
CollectionAssert.AreEqual(backupBytes, repairedPrimary);
|
||||||
|
});
|
||||||
|
|
||||||
|
[UnityTest]
|
||||||
|
public IEnumerator SaveAsync_PropagatesStorageFailure() => UniTask.ToCoroutine(async () =>
|
||||||
|
{
|
||||||
|
ShrinkSettings.ResetForTesting();
|
||||||
|
ShrinkSettings.Initialize(new FailingStorageProvider(), "settings.json");
|
||||||
|
ShrinkSettings.Set("lang", "zh_cn");
|
||||||
|
|
||||||
|
var failed = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await ShrinkSettings.SaveAsync();
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
failed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(failed);
|
||||||
|
});
|
||||||
|
|
||||||
// ── Overwrite ──
|
// ── Overwrite ──
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
@@ -208,5 +252,23 @@ namespace ShrinkDataSaver.Tests
|
|||||||
ShrinkSettings.Set("key", "second");
|
ShrinkSettings.Set("key", "second");
|
||||||
Assert.AreEqual("second", ShrinkSettings.Get<string>("key"));
|
Assert.AreEqual("second", ShrinkSettings.Get<string>("key"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed class FailingStorageProvider : IStorageProvider
|
||||||
|
{
|
||||||
|
public UniTask WriteAsync(string path, byte[] data, CancellationToken ct = default) =>
|
||||||
|
throw new IOException("write failed");
|
||||||
|
|
||||||
|
public UniTask<byte[]> ReadAsync(string path, CancellationToken ct = default) =>
|
||||||
|
throw new FileNotFoundException(path);
|
||||||
|
|
||||||
|
public UniTask<bool> ExistsAsync(string path, CancellationToken ct = default) =>
|
||||||
|
UniTask.FromResult(false);
|
||||||
|
|
||||||
|
public UniTask DeleteAsync(string path, CancellationToken ct = default) =>
|
||||||
|
UniTask.CompletedTask;
|
||||||
|
|
||||||
|
public UniTask<string[]> ListAsync(string prefix = "", CancellationToken ct = default) =>
|
||||||
|
UniTask.FromResult(System.Array.Empty<string>());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "com.cneicy.shrink-datasaver",
|
"name": "com.cneicy.shrink-datasaver",
|
||||||
"version": "2.2.0",
|
"version": "2.5.0",
|
||||||
"displayName": "ShrinkDataSaver",
|
"displayName": "ShrinkDataSaver",
|
||||||
"description": "模块化 Unity 存档与设置管理系统,支持多槽位、链式版本迁移、AES-256 加密、关键模块保护、跨模块查询与事件驱动架构。",
|
"description": "模块化 Unity 存档与设置管理系统,支持多槽位、链式版本迁移、AES-256 加密、关键模块保护、跨模块查询与事件驱动架构。",
|
||||||
"unity": "2022.3",
|
"unity": "2022.3",
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
"com.unity.nuget.newtonsoft-json": "3.2.1",
|
"com.unity.nuget.newtonsoft-json": "3.2.1",
|
||||||
"com.cysharp.unitask": "2.5.0",
|
"com.cysharp.unitask": "2.5.0",
|
||||||
"com.unity.modules.imageconversion": "1.0.0",
|
"com.unity.modules.imageconversion": "1.0.0",
|
||||||
"com.unity.modules.screencapture": "1.0.0"
|
"com.unity.modules.screencapture": "1.0.0",
|
||||||
|
"com.cneicy.shrink-runtime-abstractions": "0.2.0"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"save",
|
"save",
|
||||||
|
|||||||
Reference in new issue
Block a user