| 1 | using System.Security.Cryptography; |
| 2 | using Zipelo.Core; |
| 3 | using Zipelo.Runtime; |
| 4 | using Zipelo.SecurityTests; |
| 5 | |
| 6 | namespace Zipelo.RuntimeTests; |
| 7 | |
| 8 | internal sealed partial class ExtractionTests |
| 9 | { |
| 10 | private async Task FolderConcurrentPublish() |
| 11 | { |
| 12 | RequireFolderImplementation(); |
| 13 | var area = await NewArea(); |
| 14 | RequireFolderDestination(area.Root); |
| 15 | var external = Path.Combine(sandbox, "folder-external-" + Guid.NewGuid().ToString("N")); |
| 16 | Directory.CreateDirectory(external); |
| 17 | var externalFile = Path.Combine(external, "keep.txt"); |
| 18 | var externalBytes = "출력 부모 밖의 보존 표식"u8.ToArray(); |
| 19 | await File.WriteAllBytesAsync(externalFile, externalBytes); |
| 20 | var inputs = new[] { await ExtractArea(area), await Extract("cumulative.zip") }; |
| 21 | foreach (var input in inputs) { Successful(input); } |
| 22 | var destination = Path.Combine(area.Root, "result"); |
| 23 | var start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 24 | using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); |
| 25 | |
| 26 | async Task<ZipPublicationResult> Attempt(int index) |
| 27 | { |
| 28 | await start.Task; |
| 29 | return await NewFolderPublisher.PublishAsync(inputs[index], destination, cancellation.Token); |
| 30 | } |
| 31 | |
| 32 | // 두 요청을 같은 시작 장벽에서 풀되 네이티브 호출의 정확한 겹침을 보장하지는 않음. |
| 33 | var attempts = new[] { Attempt(0), Attempt(1) }; |
| 34 | start.SetResult(); |
| 35 | var results = await Task.WhenAll(attempts); |
| 36 | await Preserved(area, "source.zip", "sentinel.txt", "result"); |
| 37 | ExactChildren(external, "keep.txt"); |
| 38 | var afterExternal = await File.ReadAllBytesAsync(externalFile); |
| 39 | Check.That(externalBytes.SequenceEqual(afterExternal), "출력 부모 밖의 기존 파일을 변경함"); |
| 40 | Check.Equal(1, results.Count(result => result.Published)); |
| 41 | var winner = Array.FindIndex(results, result => result.Published); |
| 42 | Check.Equal(ArchiveError.None, results[winner].Error); |
| 43 | Check.That(!results[winner].CleanupFailed && results[winner].TemporaryFileName is null, |
| 44 | "동시 게시 성공 뒤 임시 결과나 정리 실패가 남음"); |
| 45 | PublicationFailure(results[1 - winner], ArchiveError.OutputConflict); |
| 46 | await VerifyPublishedTree(destination, Successful(inputs[winner])); |
| 47 | } |
| 48 | |
| 49 | private static async Task VerifyPublishedTree(string directory, IReadOnlyList<ZipExtractedEntry> items) |
| 50 | { |
| 51 | Check.That((File.GetAttributes(directory) & FileAttributes.ReparsePoint) == 0, |
| 52 | "게시 루트가 링크로 바뀜"); |
| 53 | var expected = new Dictionary<string, bool>(StringComparer.Ordinal); |
| 54 | foreach (var item in items) |
| 55 | { |
| 56 | var segments = item.Entry.Name.Split('/'); |
| 57 | for (var index = 0; index < segments.Length; index++) |
| 58 | { |
| 59 | expected[string.Join('/', segments.Take(index + 1))] = |
| 60 | index < segments.Length - 1 || item.Entry.Kind == EntryKind.Directory; |
| 61 | } |
| 62 | } |
| 63 | var actual = new Dictionary<string, bool>(StringComparer.Ordinal); |
| 64 | var pending = new Queue<(string Path, string Prefix)>(); |
| 65 | pending.Enqueue((directory, "")); |
| 66 | while (pending.TryDequeue(out var parent)) |
| 67 | { |
| 68 | foreach (var path in Directory.GetFileSystemEntries(parent.Path)) |
| 69 | { |
| 70 | var attributes = File.GetAttributes(path); |
| 71 | Check.That((attributes & FileAttributes.ReparsePoint) == 0, "게시 결과에 외부 링크가 포함됨"); |
| 72 | var name = Path.GetFileName(path); |
| 73 | var relative = parent.Prefix.Length == 0 ? name : parent.Prefix + "/" + name; |
| 74 | var folder = (attributes & FileAttributes.Directory) != 0; |
| 75 | Check.That(expected.TryGetValue(relative, out var expectedFolder) && expectedFolder == folder, |
| 76 | "다른 게시 작업의 내용이나 예상하지 않은 항목이 섞임"); |
| 77 | actual.Add(relative, folder); |
| 78 | if (folder) { pending.Enqueue((path, relative)); } |
| 79 | } |
| 80 | } |
| 81 | Check.Equal(expected.Count, actual.Count); |
| 82 | foreach (var item in items.Where(item => item.Entry.Kind == EntryKind.File)) |
| 83 | { |
| 84 | var path = Path.Combine(directory, item.Entry.Name.Replace('/', Path.DirectorySeparatorChar)); |
| 85 | var bytes = await File.ReadAllBytesAsync(path); |
| 86 | Check.Equal(item.Content.Length, bytes.Length); |
| 87 | Check.That(SHA256.HashData(item.Content).SequenceEqual(SHA256.HashData(bytes)), |
| 88 | "동시 게시 승자의 파일 해시가 다름"); |
| 89 | } |
| 90 | } |
| 91 | } |