aisop/src/SopHelper.CrossPlatform.Engine/Training/RecipePackage.cs

440 lines
26 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 配方包读写:把配方定义与标准 SOP 视频打包成单个 zip(.bwsrecipe),跨工位迁移时按清单校验后再落位。
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Training;
/// <summary>
/// 配方包(<c>.bwsrecipe</c>,zip 容器)的导出、检查与导入。
/// </summary>
/// <remarks>
/// 包内布局固定为 <c>package.json</c>(清单)、<c>recipe/&lt;名&gt;.yaml</c>(配方定义)和 <c>stand/&lt;文件&gt;</c>(标准 SOP 视频及其时长缓存)。
/// 清单最后写入,作为整包的完成标记:导出中断时包内没有清单,导入会直接拒绝,不会落成半个配方。
/// 导入先进入 <c>recipes/&lt;名&gt;.importing-&lt;guid&gt;</c> 暂存目录,逐文件校验大小与 SHA-256,全部通过后整目录一次移动到位,
/// 使失败路径不残留半成品配方。覆盖导入复用 <see cref="RecipeWorkspace.Delete"/> 把旧配方整目录归档,现场可回退。
/// 包只带工艺定义与标准视频,不带运行图片、录像及已移除功能遗留的数据集/模型,避免把工位历史数据搬来搬去。
/// </remarks>
public static class RecipePackage
{
/// <summary>配方包扩展名。</summary>
public const string Extension = ".bwsrecipe";
/// <summary>包标识,写入清单 <c>format</c>,用于拒绝随手压出来的 zip。</summary>
public const string FormatId = "bws.recipe";
/// <summary>当前程序支持的清单格式版本;更高的版本要求升级程序。</summary>
public const int FormatVersion = 1;
private const string ManifestEntry = "package.json";
private const string RecipeEntryRoot = "recipe";
private const string StandEntryRoot = "stand";
private const string StandDirectory = "sop_stand";
// 上限用于挡住构造出来的 zip 炸弹:清单声明体积与解压时实测字节都要过限,二者取严。
private const int MaxEntryCount = 4096;
private const long MaxTotalBytes = 4L * 1024 * 1024 * 1024;
private static readonly JsonSerializerOptions ManifestJson = new()
{
PropertyNameCaseInsensitive = true,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
/// <summary>清单里的单个文件条目;<paramref name="Path"/> 使用包内相对路径和 <c>/</c> 分隔。</summary>
public sealed record PackageFile(
[property: JsonPropertyName("path")] string Path,
[property: JsonPropertyName("bytes")] long Bytes,
[property: JsonPropertyName("sha256")] string Sha256);
/// <summary>配方包清单。</summary>
public sealed record PackageManifest(
[property: JsonPropertyName("format")] string Format,
[property: JsonPropertyName("version")] int Version,
[property: JsonPropertyName("recipeName")] string RecipeName,
[property: JsonPropertyName("exportedAt")] DateTimeOffset ExportedAt,
[property: JsonPropertyName("applicationVersion")] string ApplicationVersion,
[property: JsonPropertyName("notes")] List<string> Notes,
[property: JsonPropertyName("files")] List<PackageFile> Files);
/// <summary>导入前读出的包摘要;界面用它确认配方名、体积和提醒后再落盘。</summary>
public sealed record PackageInfo(
string RecipeName,
DateTimeOffset? ExportedAt,
string? ApplicationVersion,
int FileCount,
long TotalBytes,
bool HasStandardVideo,
IReadOnlyList<string> Warnings);
/// <summary>导出结果。</summary>
public sealed record ExportResult(string Path, string RecipeName, int FileCount, long TotalBytes, IReadOnlyList<string> Warnings);
/// <summary>导入结果;<paramref name="ArchivedPath"/> 是被覆盖旧配方的归档位置。</summary>
public sealed record ImportResult(string Name, bool Overwrote, string? ArchivedPath, IReadOnlyList<string> Warnings);
/// <summary>把配方定义和标准 SOP 视频导出为单个配方包文件。</summary>
/// <remarks>
/// 参数约束:<paramref name="name"/> 是已存在的配方名;<paramref name="destination"/> 是目标文件路径,缺扩展名时补 <see cref="Extension"/>。
/// 返回包路径、包内文件数和字节数。副作用:写出(并覆盖)目标文件;不修改配方目录内的任何文件。
/// 异常:配方不存在、目录不可写或磁盘写入失败时抛出对应 IO 异常。
/// </remarks>
public static ExportResult Export(RecipeWorkspace workspace, string name, string destination)
{
var directory = workspace.DirectoryFor(name);
var configPath = workspace.ConfigPath(name);
if (!File.Exists(configPath)) throw new FileNotFoundException("配方不存在,无法导出", configPath);
// 读文件再导出:内存里正在编辑的对象不参与打包,避免把未保存的半成品写进包。
var config = SopConfigLoader.Load(configPath);
config.Sop.Name = name;
var notes = new List<string>();
NormalizeCompletionDirectories(config, directory, notes);
// 配方 YAML 先落到临时文件,保证包内格式与程序保存的一致(含兼容迁移),再与标准视频一起压入。
var stagedConfig = Path.Combine(Path.GetTempPath(), "bws-recipe-export-" + Guid.NewGuid().ToString("N") + ".yaml");
try
{
SopConfigLoader.Save(config, stagedConfig);
var entries = new List<(string Entry, string Source)> { ($"{RecipeEntryRoot}/{name}.yaml", stagedConfig) };
// 未录制标准 SOP 的配方只有 YAML 也照样成包;导入时的“缺视频”提醒由 Inspect 给出。
var standDirectory = Path.Combine(directory, StandDirectory);
if (Directory.Exists(standDirectory))
foreach (var file in Directory.EnumerateFiles(standDirectory).OrderBy(Path.GetFileName, StringComparer.Ordinal))
entries.Add(($"{StandEntryRoot}/{Path.GetFileName(file)}", file));
var target = DestinationPath(destination);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
var sizes = entries.ToDictionary(entry => entry.Entry, entry => new FileInfo(entry.Source).Length);
// 导出期的处理说明写进清单 notes:导入方(通常是另一台工位)也能看到“哪个步骤的完成图目录被改写/清空”。
var manifest = new PackageManifest(FormatId, FormatVersion, name, DateTimeOffset.UtcNow,
typeof(RecipePackage).Assembly.GetName().Version?.ToString() ?? "0.0", notes,
entries.Select(entry => new PackageFile(entry.Entry, sizes[entry.Entry], Sha256File(entry.Source))).ToList());
// 先写临时包再原子替换:中断只留下 .tmp,不会把上一次的包改成半份。
var temporary = target + ".tmp";
try
{
using (var stream = File.Create(temporary))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
foreach (var (entry, source) in entries)
archive.CreateEntryFromFile(source, entry, CompressionLevel.Optimal);
// 清单最后写入:完成标记缺席时导入直接拒绝。
WriteManifest(archive, manifest);
}
File.Move(temporary, target, overwrite: true);
}
catch
{
TryDelete(temporary);
throw;
}
return new ExportResult(target, name, entries.Count, sizes.Values.Sum(), notes);
}
finally { TryDelete(stagedConfig); }
}
/// <summary>读取并校验配方包,返回摘要与提醒,不写任何配方文件。</summary>
/// <remarks>
/// 校验顺序:清单存在且格式/版本受支持 → 包内路径安全且与清单逐条一致(缺失、大小不符都算损坏)→ 配方 YAML 可解析。
/// 返回的 <c>Warnings</c> 含配方自身校验提醒和“包内无标准 SOP 视频”等提示,界面需要在导入前展示。
/// 异常:文件不存在、不是 BWS 配方包、清单损坏、清单与包内容不一致、配方名非法或 YAML 无法解析。
/// </remarks>
public static PackageInfo Inspect(string packagePath)
{
packagePath = Path.GetFullPath(packagePath);
if (!File.Exists(packagePath)) throw new FileNotFoundException("配方包不存在", packagePath);
using var archive = ZipFile.OpenRead(packagePath);
var manifest = ReadManifest(archive);
// 导出端记录的处理说明(完成图目录改写等)在导入端原样重现,两边看同一份说明。
var warnings = new List<string>(manifest.Notes ?? []);
var stagedConfig = Path.Combine(Path.GetTempPath(), "bws-recipe-inspect-" + Guid.NewGuid().ToString("N") + ".yaml");
try
{
var recipeEntry = manifest.Files.Single(file => GetEntryRoot(file.Path) == RecipeEntryRoot);
using (var source = archive.GetEntry(recipeEntry.Path)!.Open())
using (var target = File.Create(stagedConfig)) source.CopyTo(target);
// 走同一套解析与校验:包里的配方若缺步骤、缺区域,导入前就能在界面上看到提醒。
warnings.AddRange(SopConfigLoader.Load(stagedConfig).Warnings);
}
finally { TryDelete(stagedConfig); }
var hasVideo = manifest.Files.Any(file => GetEntryRoot(file.Path) == StandEntryRoot);
if (!hasVideo) warnings.Add("配方包内没有标准 SOP 视频,导入后需要在“SOP流程视频”页重新录制。");
return new PackageInfo(manifest.RecipeName, manifest.ExportedAt, manifest.ApplicationVersion,
manifest.Files.Count, manifest.Files.Sum(file => file.Bytes), hasVideo, warnings);
}
/// <summary>把配方包导入工作区,返回落位后的配方名。</summary>
/// <remarks>
/// 执行顺序:校验包与目标名 → 目标已存在时按 <paramref name="overwrite"/> 决定归档旧配方或拒绝 →
/// 解压到同目录下的 <c>&lt;名&gt;.importing-&lt;guid&gt;</c> 暂存目录并逐文件校验 SHA-256 与体积 → 改写 <c>sop.name</c> 为目标名 →
/// 整目录一次移动到位。解压中途失败只清理暂存目录,活动配方目录保持原状;已归档旧配方的位置在返回值中给出。
/// 副作用:新增 <c>recipes/&lt;targetName&gt;/</c>;覆盖时旧目录移入 <c>workspace/deleted-recipes/&lt;targetName&gt;/</c>。
/// 异常:包损坏、清单外多文件、包含越界路径、目标名非法、目标已存在且未选择覆盖,以及磁盘写入失败。
/// 该方法不改配方选择、已应用配方和运行状态,调用方负责刷新列表;导入的新配方不会被自动应用。
/// </remarks>
public static ImportResult Import(RecipeWorkspace workspace, string packagePath, string targetName, bool overwrite)
{
targetName = targetName.Trim();
if (RecipeWorkspace.GetNameError(targetName) is { } nameError) throw new ArgumentException("目标配方名不可用:" + nameError, nameof(targetName));
var info = Inspect(packagePath);
var targetDirectory = workspace.DirectoryFor(targetName);
var existing = File.Exists(workspace.ConfigPath(targetName));
// 同名但缺配置文件的散目录不能静默吞掉,交回现场处理,避免误删不是配方的数据。
if (Directory.Exists(targetDirectory) && !existing)
throw new IOException($"目标目录已存在且不是有效配方,请先手动处理:{targetDirectory}");
string? archived = null;
if (existing)
{
if (!overwrite) throw new IOException($"配方“{targetName}”已存在,请选择覆盖导入或改用其他名称");
archived = workspace.Delete(targetName);
}
var warnings = new List<string>(info.Warnings);
if (archived is not null) warnings.Add($"旧配方已归档,可从中找回:{archived}");
var staging = targetDirectory + ".importing-" + Guid.NewGuid().ToString("N");
if (!RecipeWorkspace.IsWithin(staging, workspace.RecipesDirectory)) throw new IOException("导入临时目录超出配方目录");
Directory.CreateDirectory(staging);
try
{
PackageManifest manifest;
using (var archive = ZipFile.OpenRead(Path.GetFullPath(packagePath)))
{
manifest = ReadManifest(archive);
var declared = manifest.Files.Select(file => file.Path).ToHashSet(StringComparer.Ordinal);
// 清单外的条目一律拒绝:手工塞进 zip 的文件不能顺带落进配方目录(清单自身除外)。
if (archive.Entries.Any(entry => entry.FullName.Length > 0 && !entry.FullName.EndsWith('/') && entry.FullName != ManifestEntry && !declared.Contains(entry.FullName)))
throw new InvalidDataException("配方包含清单之外的文件,已拒绝导入");
foreach (var file in manifest.Files) Extract(archive, file, staging);
}
var stagedRecipe = Path.Combine(staging, manifest.RecipeName + ".yaml");
var targetConfig = Path.Combine(staging, targetName + ".yaml");
var config = SopConfigLoader.Load(stagedRecipe);
// 包内配方名与目标名可以不同(改名导入),sop.name 必须与目录名一致,否则列表与文件名对不上。
config.Sop.Name = targetName;
SopConfigLoader.Save(config, targetConfig);
if (!string.Equals(stagedRecipe, targetConfig, StringComparison.Ordinal)) File.Delete(stagedRecipe);
// 整目录一次移动:目标名在移动瞬间才出现,界面列表不会看到解压到一半的配方。
Directory.Move(staging, targetDirectory);
staging = "";
return new ImportResult(targetName, existing, archived, warnings);
}
finally
{
if (staging.Length > 0 && Directory.Exists(staging)) Directory.Delete(staging, true);
}
}
/// <summary>为改名导入挑选可用配方名:原名可用则原名,否则追加 <c>-2</c>、<c>-3</c>…</summary>
public static string SuggestName(RecipeWorkspace workspace, string baseName)
{
if (RecipeWorkspace.GetNameError(baseName) is { } error) throw new ArgumentException("配方名不可用:" + error, nameof(baseName));
if (!File.Exists(workspace.ConfigPath(baseName))) return baseName;
for (var index = 2; index <= 999; index++)
{
var candidate = $"{baseName}-{index}";
// 追加后缀可能撑破文件名长度限制,此时直接改日期后缀,不再继续变长。
if (RecipeWorkspace.GetNameError(candidate) is not null) break;
if (!File.Exists(workspace.ConfigPath(candidate))) return candidate;
}
var fallback = $"{baseName}-{DateTime.Now:yyyyMMdd-HHmmss}";
if (RecipeWorkspace.GetNameError(fallback) is not null)
throw new IOException($"配方“{baseName}”的同名变体已用满,请缩短名称后导入");
return fallback;
}
/// <summary>目标路径补扩展名:无扩展名时补 <see cref="Extension"/>,已有扩展名(含 <c>.zip</c>)保留。</summary>
public static string DestinationPath(string destination)
{
destination = Path.GetFullPath(destination);
return Path.HasExtension(destination) ? destination : destination + Extension;
}
private static void WriteManifest(ZipArchive archive, PackageManifest manifest)
{
var entry = archive.CreateEntry(ManifestEntry, CompressionLevel.Optimal);
using var stream = entry.Open();
JsonSerializer.Serialize(stream, manifest, ManifestJson);
}
/// <summary>
/// 把步骤的完成图目录改成相对配方目录的路径。
/// </summary>
/// <remarks>
/// 运行期按 <c>Path.GetFullPath(目录, 配方目录)</c> 解析,相对路径换机器后仍指向配方自己。
/// 配方目录之外的绝对路径导入到别的工位只会写到不相干的位置,因此清空并提醒改用配方默认目录:
/// 不猜测现场意图,也不把工位本地路径写进可传递的包里。
/// </remarks>
private static void NormalizeCompletionDirectories(SopConfig config, string recipeDirectory, List<string> warnings)
{
foreach (var step in config.Sop.Steps)
{
var value = step.CompletionImageDirectory?.Trim() ?? "";
if (value.Length == 0 || !Path.IsPathRooted(value)) continue;
var full = Path.GetFullPath(value, recipeDirectory);
if (RecipeWorkspace.IsWithin(full, recipeDirectory))
{
step.CompletionImageDirectory = Path.GetRelativePath(recipeDirectory, full).Replace('\\', '/');
continue;
}
step.CompletionImageDirectory = "";
warnings.Add($"步骤 {step.Id}({step.Name})的完成图目录在配方目录之外({full}),导入后改用配方默认目录,请在编辑器确认。");
}
}
/// <summary>解析并校验清单:格式标识、版本、配方名、条目路径安全、大小与包内容逐条一致。</summary>
private static PackageManifest ReadManifest(ZipArchive archive)
{
var entry = archive.GetEntry(ManifestEntry)
?? throw new InvalidDataException("文件缺少 package.json,不是本程序导出的配方包");
PackageManifest? manifest;
try
{
using var stream = entry.Open();
manifest = JsonSerializer.Deserialize<PackageManifest>(stream, ManifestJson);
}
catch (JsonException error) { throw new InvalidDataException("配方包清单无法解析:" + error.Message); }
if (manifest is null) throw new InvalidDataException("配方包清单为空");
if (!string.Equals(manifest.Format, FormatId, StringComparison.Ordinal))
throw new InvalidDataException($"这不是 BWS 配方包(包标识:{manifest.Format})");
if (manifest.Version < 1) throw new InvalidDataException("配方包清单版本无效");
if (manifest.Version > FormatVersion)
throw new InvalidDataException($"配方包由更新版本程序导出(格式版本 {manifest.Version},当前支持 {FormatVersion}),请升级程序后导入");
if (RecipeWorkspace.GetNameError(manifest.RecipeName) is { } recipeNameError)
throw new InvalidDataException("配方包中的配方名不可用:" + recipeNameError);
if (manifest.Files is null || manifest.Files.Count == 0) throw new InvalidDataException("配方包没有文件");
if (manifest.Files.Count > MaxEntryCount) throw new InvalidDataException($"配方包文件过多({manifest.Files.Count})");
if (manifest.Notes is { Count: > 200 }) throw new InvalidDataException("配方包说明条目过多");
long total = 0;
var paths = new HashSet<string>(StringComparer.Ordinal);
var recipeFiles = 0;
foreach (var file in manifest.Files)
{
if (!IsSafeEntryPath(file.Path, out var root)) throw new InvalidDataException("配方包内路径不安全:" + file.Path);
if (root == RecipeEntryRoot)
{
recipeFiles++;
// 配方文件必须正好是 <配方名>.yaml:导入改名靠它定位,多余的配方文件一律拒绝。
if (file.Path != $"{RecipeEntryRoot}/{manifest.RecipeName}.yaml")
throw new InvalidDataException("配方包内的配方文件名与配方名不一致:" + file.Path);
}
if (!paths.Add(file.Path)) throw new InvalidDataException("配方包清单包含重复文件:" + file.Path);
if (file.Bytes < 0 || file.Bytes > MaxTotalBytes || !IsSha256(file.Sha256))
throw new InvalidDataException("配方包清单字段无效:" + file.Path);
total += file.Bytes;
if (total > MaxTotalBytes) throw new InvalidDataException($"配方包解压体积过大({total} 字节)");
var zipEntry = archive.GetEntry(file.Path) ?? throw new InvalidDataException($"配方包文件缺失:{file.Path}");
if (zipEntry.Length != file.Bytes) throw new InvalidDataException($"配方包与清单大小不一致:{file.Path}");
}
if (paths.Contains(ManifestEntry)) throw new InvalidDataException("配方包清单把 package.json 列为数据文件");
if (recipeFiles != 1) throw new InvalidDataException("配方包应恰好包含一个配方文件");
return manifest;
}
/// <summary>校验包内条目路径:只允许 <c>recipe/&lt;文件&gt;</c> 与 <c>stand/&lt;文件&gt;</c> 两层,禁止绝对路径、盘符、反斜杠和 <c>..</c>。</summary>
private static bool IsSafeEntryPath(string path, out string root)
{
root = "";
if (path.Length == 0 || path.Contains('\\') || path.Contains(':') || Path.IsPathRooted(path)) return false;
var segments = path.Split('/');
if (segments.Length != 2) return false;
if (segments[0] is not (RecipeEntryRoot or StandEntryRoot)) return false;
var leaf = segments[1];
if (leaf.Length == 0 || leaf is "." or ".." || leaf.Trim('.')!.Length == 0) return false;
if (leaf.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) return false;
root = segments[0];
return true;
}
private static string GetEntryRoot(string path)
{
var index = path.IndexOf('/');
return index < 0 ? path : path[..index];
}
/// <summary>解压单个条目到暂存目录,同时实测字节数与散列,超限或不符立即中止。</summary>
/// <remarks>
/// 不能只信清单声明的大小:压缩条目声明 1 KB、解压后 1 GB 是典型 zip 炸弹,因此用计数流边读边比。
/// 散列逐条比对,任一条不符即判定包被改动(拷贝中断、手工改包都可能触发),整次导入不写入配方目录。
/// </remarks>
private static void Extract(ZipArchive archive, PackageFile file, string staging)
{
var relative = GetEntryRoot(file.Path) == RecipeEntryRoot
? Path.GetFileName(file.Path)
: Path.Combine(StandDirectory, Path.GetFileName(file.Path));
var destination = Path.GetFullPath(Path.Combine(staging, relative));
if (!RecipeWorkspace.IsWithin(destination, staging))
throw new InvalidDataException("配方包内路径越界:" + file.Path);
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
using var source = archive.GetEntry(file.Path)!.Open();
using var hashing = new HashCountingStream(source);
using var target = File.Create(destination);
hashing.CopyTo(target);
target.Flush();
if (hashing.Bytes != file.Bytes)
throw new InvalidDataException($"配方包文件解压大小与清单不符:{file.Path}({hashing.Bytes}/{file.Bytes})");
if (hashing.Bytes > MaxTotalBytes) throw new InvalidDataException("配方包解压体积过大");
if (!string.Equals(Convert.ToHexString(hashing.Hash).ToLowerInvariant(), file.Sha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"配方包文件与清单散列不符,包已损坏或被修改:{file.Path}");
}
private static string Sha256File(string path)
{
using var stream = File.OpenRead(path);
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
}
private static bool IsSha256(string value)
{
if (value.Length != 64) return false;
return value.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F');
}
private static void TryDelete(string path)
{
try { if (File.Exists(path)) File.Delete(path); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
}
/// <summary>转发读取并累计散列与字节数的只读流;解压时同步校验,不必把整个条目读进内存。</summary>
private sealed class HashCountingStream(Stream inner) : Stream
{
private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
public long Bytes { get; private set; }
/// <summary>已读取数据的散列;流读取结束后取一次,实现内部用 GetHashAndReset,重复取值会得到空散列。</summary>
public byte[] Hash => _hash.GetHashAndReset();
public override int Read(byte[] buffer, int offset, int count)
{
var read = inner.Read(buffer, offset, count);
if (read > 0) { _hash.AppendData(buffer, offset, read); Bytes += read; }
return read;
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => Bytes; set => throw new NotSupportedException(); }
protected override void Dispose(bool disposing)
{
if (disposing) { _hash.Dispose(); inner.Dispose(); }
base.Dispose(disposing);
}
}
}