新增配方包引擎层读写:配方定义与标准SOP视频打包为.bwsrecipe,导出写清单校验和,导入按清单逐文件校验后整目录落位,覆盖导入归档旧配方,并补充拒绝篡改包、越界路径和高版本包的冒烟测试

This commit is contained in:
tfarcraw 2026-11-23 21:26:37 +08:00
parent b7027e2e2f
commit ad652b2caa
3 changed files with 738 additions and 0 deletions

View File

@ -0,0 +1,439 @@
// 配方包读写:把配方定义与标准 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);
}
}
}

View File

@ -0,0 +1,295 @@
// 配方包冒烟:验证导出/检查/导入的往返一致性、覆盖归档与改名建议,以及篡改包、越界路径、清单外文件和体积骗局的拒绝行为。
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
internal static class Program
{
private static string Root = "";
[STAThread]
public static int Main()
{
Root = Path.Combine(Path.GetTempPath(), "recipe-package-smoke-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Root);
try
{
Run();
Console.WriteLine("RecipePackage smoke:全部检查通过");
return 0;
}
catch (Exception error)
{
Console.Error.WriteLine("FAIL: " + error.Message);
return 1;
}
finally
{
// 只清理本次测试自建目录,不触碰任何程序数据。
if (Path.GetFileName(Root).StartsWith("recipe-package-smoke-") && Directory.Exists(Root)) Directory.Delete(Root, true);
}
}
private static void Run()
{
RoundTrip();
OverwriteAndRename();
RejectedPackages();
MissingStandardVideo();
}
/// <summary>导出→检查→导入的往返:内容一致、路径改写、不残留暂存目录。</summary>
private static void RoundTrip()
{
var source = new RecipeWorkspace(Path.Combine(Root, "source"));
var target = new RecipeWorkspace(Path.Combine(Root, "target"));
const string name = "装配";
var inside = Path.Combine(source.DirectoryFor(name), "done");
var outside = Path.Combine(Root, "outside-images");
Seed(source, name, inside, outside);
// 目标路径缺扩展名时补 .bwsrecipe,现场直接按扩展名识别配方包。
var package = RecipePackage.Export(source, name, Path.Combine(Root, name)).Path;
Check(Path.GetExtension(package) == RecipePackage.Extension, "导出自动补上配方包扩展名");
Check(File.Exists(package) && !File.Exists(package + ".tmp"), "导出原子落位且不留下临时包");
Check(Directory.EnumerateFileSystemEntries(source.DirectoryFor(name)).All(entry => !Path.GetFileName(entry).Contains("export-")),
"导出不在配方目录留下临时文件");
Check(!Directory.EnumerateFiles(Root, "*.yaml").Any(), "导出不残留临时配方文件");
var info = RecipePackage.Inspect(package);
Check(info.RecipeName == name && info.FileCount == 3 && info.HasStandardVideo && info.TotalBytes > 0, "包摘要给出配方名、文件数、体积与标准视频");
Check(info.ExportedAt is not null && !string.IsNullOrWhiteSpace(info.ApplicationVersion), "包记录导出时间和导出程序版本");
Check(info.Warnings.Any(w => w.Contains("配方目录之外") && w.Contains("步骤 2")), "配方目录之外的完成图目录在导入前提醒并指出步骤");
var imported = RecipePackage.Import(target, package, name, false);
Check(imported.Name == name && !imported.Overwrote && imported.ArchivedPath is null, "首次导入不声明覆盖也没有归档");
Check(File.Exists(target.ConfigPath(name)), "导入生成配方配置文件");
Check(Directory.GetDirectories(target.RecipesDirectory).Single() == target.DirectoryFor(name), "导入不留暂存目录");
Check(Directory.GetFileSystemEntries(target.DirectoryFor(name)).Length == 2
&& Directory.Exists(Path.Combine(target.DirectoryFor(name), "done")) == false, "导入目录只包含包内文件,不创建空目录");
Check(File.ReadAllText(Path.Combine(target.DirectoryFor(name), "sop_stand", "sop.avi")) == "fake-avi"
&& File.Exists(Path.Combine(target.DirectoryFor(name), "sop_stand", "duration.json")), "标准 SOP 视频与时长时间缓存一起随包迁移");
var migrated = SopConfigLoader.Load(target.ConfigPath(name));
Check(migrated.Sop.Name == name && migrated.Sop.Steps.Count == 2 && migrated.Sop.Regions.ContainsKey("取料"), "导入保留步骤、区域和配方名");
Check(migrated.Sop.Steps[0].Description.Contains("握住物料") && migrated.Sop.Steps[1].Detection!.Method == ConditionMethod.TimeElapsed,
"步骤说明与判定方法逐字迁移,不经界面重写");
Check(migrated.Sop.Steps[0].CompletionImageDirectory == "done", "配方目录内的完成图目录改写为相对路径");
Check(migrated.Sop.Steps[1].CompletionImageDirectory.Length == 0, "配方目录之外的完成图目录被清空,不把工位本地路径带到新机器");
var reimported = RecipePackage.Export(target, name, Path.Combine(Root, "re-export")).Path;
var second = RecipePackage.Inspect(reimported);
Check(second.FileCount == 3 && second.HasStandardVideo && !second.Warnings.Any(w => w.Contains("配方目录之外")),
"导入后的配方可再次导出,完成图目录提醒不再重复出现");
}
/// <summary>覆盖导入的归档行为、改名导入和改名建议。</summary>
private static void OverwriteAndRename()
{
var source = new RecipeWorkspace(Path.Combine(Root, "source2"));
var target = new RecipeWorkspace(Path.Combine(Root, "target2"));
const string name = "装配";
Seed(source, name, Path.Combine(source.DirectoryFor(name), "done"), Path.Combine(Root, "outside2"));
var package = RecipePackage.Export(source, name, Path.Combine(Root, "pack2")).Path;
var renamed = RecipePackage.Import(target, package, "装配二", false);
Check(renamed.Name == "装配二" && File.Exists(target.ConfigPath("装配二")) && SopConfigLoader.Load(target.ConfigPath("装配二")).Sop.Name == "装配二",
"改名导入同时改写目录名、文件名和 sop.name");
Check(Directory.GetFiles(target.DirectoryFor("装配二"), "*.yaml").Single().EndsWith("装配二.yaml"), "改名导入不留下包内旧文件名");
File.WriteAllText(Path.Combine(target.DirectoryFor("装配二"), "marker.txt"), "旧现场数据");
var refused = Catch(() => RecipePackage.Import(target, package, "装配二", false));
Check(refused is IOException && refused.Message.Contains("已存在"), "同名配方未选择覆盖时拒绝导入");
Check(File.Exists(Path.Combine(target.DirectoryFor("装配二"), "marker.txt")), "被拒绝的覆盖导入不动已有配方");
var overwritten = RecipePackage.Import(target, package, "装配二", true);
Check(overwritten.Overwrote && overwritten.ArchivedPath is not null && overwritten.Warnings.Any(w => w.Contains("归档")),
"覆盖导入报告归档位置");
Check(!File.Exists(Path.Combine(target.DirectoryFor("装配二"), "marker.txt")) && File.Exists(target.ConfigPath("装配二")),
"覆盖导入用包内容替换配方目录");
Check(Directory.GetFiles(overwritten.ArchivedPath!, "marker.txt", SearchOption.AllDirectories).Length == 1, "旧配方数据完整保留在归档目录");
Check(Directory.GetDirectories(target.RecipesDirectory).Select(Path.GetFileName).SequenceEqual(new[] { "装配二" }), "覆盖导入不产生额外配方目录");
Check(RecipePackage.SuggestName(target, name) == name, "名称未被占用时建议原名");
Check(RecipePackage.SuggestName(target, "装配二") == "装配二-2", "已有同名配方时建议追加 -2");
Directory.CreateDirectory(target.DirectoryFor("装配二-2"));
File.WriteAllText(target.ConfigPath("装配二-2"), "x");
Check(RecipePackage.SuggestName(target, "装配二") == "装配二-3", "连续占用时建议下一个可用名称");
var stray = Path.Combine(target.RecipesDirectory, "散目录");
Directory.CreateDirectory(stray);
var strayError = Catch(() => RecipePackage.Import(target, package, "散目录", true));
Check(strayError is IOException && strayError.Message.Contains("不是有效配方"), "同名散目录不会被导入静默吞掉");
}
/// <summary>损坏包、非配方包、越界路径、清单外文件和高版本包全部拒绝,且不写入配方目录。</summary>
private static void RejectedPackages()
{
var source = new RecipeWorkspace(Path.Combine(Root, "source3"));
var target = new RecipeWorkspace(Path.Combine(Root, "target3"));
Seed(source, "装配", Path.Combine(source.DirectoryFor("装配"), "done"), Path.Combine(Root, "outside3"));
var package = RecipePackage.Export(source, "装配", Path.Combine(Root, "pack3")).Path;
var tampered = Tamper(package, keepLength: true);
var hashError = Catch(() => RecipePackage.Import(target, tampered, "装配", false));
Check(hashError is InvalidDataException && hashError.Message.Contains("散列"), "包内配方文件被改写后散列校验拒绝导入");
Check(!Directory.Exists(target.DirectoryFor("装配")) && !Directory.EnumerateDirectories(target.RecipesDirectory).Any(dir => dir.Contains(".importing-")),
"散列校验失败不留半成品配方目录");
var resized = Tamper(package, keepLength: false);
var sizeError = Catch(() => RecipePackage.Inspect(resized));
Check(sizeError is InvalidDataException && sizeError.Message.Contains("大小不一致"), "包内文件与清单大小不符时检查阶段就拒绝");
var extra = AddEntry(package, "extra/notes.txt", "夹带文件");
var extraError = Catch(() => RecipePackage.Import(target, extra, "装配", false));
Check(extraError is InvalidDataException && extraError.Message.Contains("清单之外"), "清单外的夹带文件拒绝导入");
var noManifest = Craft("非配方包", null, ("说明.txt", "随手压的 zip"));
Check(Catch(() => RecipePackage.Inspect(noManifest)).Message!.Contains("package.json"), "缺少清单的普通 zip 判定为非配方包");
var future = Craft("高版本包", Manifest("新装配", RecipePackage.FormatVersion + 99, ("recipe/新装配.yaml", 2, Sha("ab"))), ("recipe/新装配.yaml", "ab"));
Check(Catch(() => RecipePackage.Inspect(future)).Message!.Contains("更新版本"), "更高格式版本的包要求先升级程序");
var traversal = Craft("越界包", Manifest("越界", 1, ("../../evil.txt", 4, Sha("evil"))), ("../../evil.txt", "evil"));
var traversalError = Catch(() => RecipePackage.Inspect(traversal));
Check(traversalError is InvalidDataException && traversalError.Message.Contains("路径不安全"), "包含 .. 越界路径的包被拒绝");
Check(!File.Exists(Path.Combine(target.RecipesDirectory, "..", "..", "evil.txt")), "越界包没有写出配方目录之外的文件");
var absolute = Craft("绝对路径包", Manifest("越界", 1, ("C:/windows/evil.txt", 4, Sha("evil"))), ("C:/windows/evil.txt", "evil"));
Check(Catch(() => RecipePackage.Inspect(absolute)).Message!.Contains("路径不安全"), "包含盘符绝对路径的包被拒绝");
var nested = Craft("深层路径包", Manifest("越界", 1, ("recipe/sub/a.yaml", 2, Sha("ab"))), ("recipe/sub/a.yaml", "ab"));
Check(Catch(() => RecipePackage.Inspect(nested)).Message!.Contains("路径不安全"), "超出约定布局的深层条目被拒绝");
}
/// <summary>未录制标准 SOP 的配方也能成包,并明确提醒导入后需要重录。</summary>
private static void MissingStandardVideo()
{
var source = new RecipeWorkspace(Path.Combine(Root, "source4"));
var target = new RecipeWorkspace(Path.Combine(Root, "target4"));
Directory.CreateDirectory(source.DirectoryFor("无视频"));
var config = new SopConfig(); config.Sop.Name = "无视频";
config.Sop.Steps = [new StepDef { Id = 1, Name = "计时", Description = "步骤说明:等待两秒", Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }];
SopConfigLoader.Save(config, source.ConfigPath("无视频"));
var info = RecipePackage.Inspect(RecipePackage.Export(source, "无视频", Path.Combine(Root, "pack4")).Path);
Check(info.FileCount == 1 && !info.HasStandardVideo && info.Warnings.Any(w => w.Contains("标准 SOP 视频")), "缺标准视频的配方包明确提醒");
Check(File.Exists(target.ConfigPath("无视频")) == false && RecipePackage.Import(target, Path.Combine(Root, "pack4.bwsrecipe"), "无视频", false).Name == "无视频",
"缺标准视频的配方包仍可正常导入");
Check(SopConfigLoader.Load(target.ConfigPath("无视频")).Sop.Steps.Single().Name == "计时", "导入后的步骤内容一致");
}
/// <summary>写入用于导出的配方:配方目录内、目录外各一个完成图目录,并带标准 SOP 视频。</summary>
private static void Seed(RecipeWorkspace workspace, string name, string insideDirectory, string outsideDirectory)
{
Directory.CreateDirectory(workspace.DirectoryFor(name));
var config = new SopConfig();
config.Sop.Name = name;
config.Sop.Regions["取料"] = new RegionDef { X1 = 10, Y1 = 20, X2 = 320, Y2 = 240, Name = "取料", Description = "料盒上方" };
config.Sop.Steps =
[
new StepDef { Id = 1, Name = "取料", Description = "步骤说明:手在取料区握住物料", CompletionImageDirectory = insideDirectory, Detection = new StepCondition { Method = ConditionMethod.HandInRegion, Region = "取料" } },
new StepDef { Id = 2, Name = "放置", Description = "步骤说明:物料放入放置区并保持稳定", CompletionImageDirectory = outsideDirectory, Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 2000 } }
];
SopConfigLoader.Save(config, workspace.ConfigPath(name));
var stand = Path.Combine(workspace.DirectoryFor(name), "sop_stand");
Directory.CreateDirectory(stand);
File.WriteAllText(Path.Combine(stand, "sop.avi"), "fake-avi");
File.WriteAllText(Path.Combine(stand, "duration.json"), "{\"seconds\":3.5}");
}
/// <summary>改写包内配方文件副本:keepLength 时长度不变只命中散列校验,否则改变长度命中清单大小校验。</summary>
private static string Tamper(string package, bool keepLength)
{
var copy = Copy(package);
string text;
// Update 模式下同一条目不能重复打开,先只读取出内容,再重开写入。
using (var read = ZipFile.OpenRead(copy))
{
using var stream = read.GetEntry("recipe/装配.yaml")!.Open();
text = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
}
var replacement = keepLength ? ReplaceOneCharacter(text) : text + "\n";
using var archive = ZipFile.Open(copy, ZipArchiveMode.Update);
using var write = archive.GetEntry("recipe/装配.yaml")!.Open();
write.SetLength(0);
write.Write(Encoding.UTF8.GetBytes(replacement));
return copy;
}
private static string AddEntry(string package, string entryName, string body)
{
var copy = Copy(package);
using var archive = ZipFile.Open(copy, ZipArchiveMode.Update);
using var stream = archive.CreateEntry(entryName).Open();
stream.Write(Encoding.UTF8.GetBytes(body));
return copy;
}
private static string Copy(string package)
{
var copy = package + "." + Guid.NewGuid().ToString("N") + ".bwsrecipe";
File.Copy(package, copy);
return copy;
}
private static string ReplaceOneCharacter(string text)
{
var index = text.IndexOf('x');
return index < 0 ? text + " " : text[..index] + "y" + text[(index + 1)..];
}
/// <summary>构造任意配方的包,用于喂入损坏、越界和高版本清单。manifestJson 为空表示不写清单。</summary>
private static string Craft(string label, string? manifestJson, params (string Entry, string Body)[] entries)
{
var path = Path.Combine(Root, label + "-" + Guid.NewGuid().ToString("N") + ".bwsrecipe");
using var archive = new ZipArchive(File.Create(path), ZipArchiveMode.Create);
foreach (var (entry, body) in entries)
{
using var stream = archive.CreateEntry(entry).Open();
stream.Write(Encoding.UTF8.GetBytes(body));
}
if (manifestJson is not null)
{
using var manifest = archive.CreateEntry("package.json").Open();
manifest.Write(Encoding.UTF8.GetBytes(manifestJson));
}
return path;
}
private static string Manifest(string recipeName, int version, params (string Path, long Bytes, string Sha)[] files) =>
JsonSerializer.Serialize(new
{
format = RecipePackage.FormatId,
version,
recipeName,
exportedAt = DateTimeOffset.UtcNow,
applicationVersion = "smoke",
files = files.Select(file => new { path = file.Path, bytes = file.Bytes, sha256 = file.Sha })
});
private static string Sha(string body) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(body))).ToLowerInvariant();
private static Exception Catch(Action action)
{
try
{
action();
throw new Exception("预期失败但没有抛出");
}
catch (Exception error) when (!(error is InvalidOperationException && error.Message == "预期失败但没有抛出"))
{
return error;
}
}
private static void Check(bool value, string message)
{
if (!value) throw new Exception(message);
Console.WriteLine("PASS: " + message);
}
}

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" /></ItemGroup>
</Project>