team-ljyzipelo

공개
123줄5.4 KB
1using System.Runtime.InteropServices;
2using Microsoft.Win32.SafeHandles;
3using Zipelo.Core;
4
5namespace Zipelo.Runtime;
6
7public sealed record ZipPublicationResult(bool Published, ArchiveError Error, bool CleanupFailed,
8 string? TemporaryFileName = null)
9{
10 public int? PosixError { get; init; }
11 public int? CleanupPosixError { get; init; }
12 public PublicationNativeFailure? NativeFailure { get; init; }
13 public PublicationNativeFailure? CleanupNativeFailure { get; init; }
14}
15
16// 경로와 OS 오류 메시지 없이 고정 API 이름과 숫자 코드만 전달함.
17public sealed record PublicationNativeFailure(string Operation, uint Win32Error, int? NtStatus = null);
18
19internal sealed class PublicationNativeException(ArchiveError code, PublicationNativeFailure failure)
20 : Exception(code.ToString())
21{
22 internal ArchiveError Code { get; } = code;
23 internal PublicationNativeFailure Failure { get; } = failure;
24}
25
26public static class NewZipPublisher
27{
28 // 구현 대상 여부임. OS별 실행 검증 완료나 대상 파일시스템 지원을 뜻하지 않음.
29 public static bool IsSupportedPlatform => RuntimeInformation.ProcessArchitecture == Architecture.X64 &&
30 (OperatingSystem.IsWindows() || OperatingSystem.IsLinux());
31
32 public static async Task<ZipPublicationResult> PublishAsync(ZipWorkerResult result,
33 string destinationPath, CancellationToken token)
34 {
35 PendingPublication? pending = null;
36 var published = false;
37 var error = ArchiveError.None;
38 var cleanupFailed = false;
39 string? temporaryFileName = null;
40 PublicationNativeFailure? nativeFailure = null;
41 PublicationNativeFailure? cleanupNativeFailure = null;
42 try
43 {
44 token.ThrowIfCancellationRequested();
45 if (!IsSupportedPlatform) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
46 var bytes = result.CreatedZip;
47 if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None ||
48 bytes is null || bytes.Length == 0)
49 {
50 throw new ArchiveException(ArchiveError.UnsupportedOperation);
51 }
52 if (bytes.Length > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
53 if (!Path.IsPathFullyQualified(destinationPath)) { throw new ArchiveException(ArchiveError.UnsafePath); }
54 var fullPath = Path.GetFullPath(destinationPath);
55 if (OperatingSystem.IsLinux())
56 {
57 _ = OutputPathPolicy.Validate(fullPath[1..], FileNamePolicy.Linux);
58 }
59 var parent = Path.GetDirectoryName(fullPath);
60 var leaf = Path.GetFileName(fullPath);
61 if (parent is null || OutputPathPolicy.Validate(leaf, OutputPathPolicy.CurrentPolicy).Count != 1)
62 {
63 throw new ArchiveException(ArchiveError.UnsafePath);
64 }
65 // 호출자가 생성물 배열을 이후 변경해도 쓰는 내용이 달라지지 않도록 복사함.
66 var snapshot = bytes.ToArray();
67 pending = OperatingSystem.IsWindows() ? WindowsPublication.Create(parent) : LinuxPublication.Create(parent);
68 for (var offset = 0; offset < snapshot.Length; offset += 65536)
69 {
70 token.ThrowIfCancellationRequested();
71 var count = Math.Min(65536, snapshot.Length - offset);
72 await RandomAccess.WriteAsync(pending.Handle, snapshot.AsMemory(offset, count), offset, token)
73 .ConfigureAwait(false);
74 }
75 RandomAccess.FlushToDisk(pending.Handle);
76 token.ThrowIfCancellationRequested();
77 pending.Publish(leaf);
78 // 게시 성공 이후의 늦은 취소는 이미 존재하는 새 파일을 취소 결과로 바꾸지 않음.
79 published = true;
80 }
81 catch (OperationCanceledException) when (token.IsCancellationRequested) { error = ArchiveError.Cancelled; }
82 catch (PublicationNativeException failure)
83 {
84 error = failure.Code;
85 nativeFailure = failure.Failure;
86 }
87 catch (ArchiveException failure) { error = failure.Code; }
88 catch (ArgumentException) { error = ArchiveError.UnsafePath; }
89 catch { error = ArchiveError.OutputUnavailable; }
90 finally
91 {
92 if (pending is not null)
93 {
94 if (!published)
95 {
96 try { cleanupFailed = !pending.Abort(); }
97 catch { cleanupFailed = true; }
98 if (cleanupFailed)
99 {
100 temporaryFileName = pending.TemporaryFileName;
101 cleanupNativeFailure = pending.CleanupNativeFailure;
102 }
103 }
104 pending.Dispose();
105 }
106 }
107 return new(published, error, cleanupFailed, temporaryFileName)
108 {
109 NativeFailure = nativeFailure,
110 CleanupNativeFailure = cleanupNativeFailure
111 };
112 }
113}
114
115internal abstract class PendingPublication : IDisposable
116{
117 internal abstract SafeFileHandle Handle { get; }
118 internal virtual string? TemporaryFileName => null;
119 internal virtual PublicationNativeFailure? CleanupNativeFailure => null;
120 internal abstract void Publish(string leaf);
121 internal abstract bool Abort();
122 public abstract void Dispose();
123}