team-ljyzipelo

공개
210줄8.2 KB
1using System.Buffers.Binary;
2
3namespace Zipelo.Runtime.Streaming;
4
5// v1 실행 경로와 연결되지 않은 명시적 v2 전송 계층임.
6public sealed class WorkerStreamChannel : IDisposable
7{
8 public const int HeaderBytes = 64;
9 public const int MaxChunkBytes = 64 * 1024;
10 public const ushort Version = 2;
11 private const uint Magic = 0x3250495A;
12
13 private readonly Stream stream;
14 private readonly WorkerStreamDirection direction;
15 private readonly WorkerStreamValidator validator;
16 private readonly CancellationTokenSource deadline;
17 private int busy;
18 private bool disposed;
19
20 public WorkerStreamChannel(
21 Stream stream,
22 WorkerStreamDirection direction,
23 Guid jobId,
24 WorkerStreamLimits? limits = null)
25 {
26 ArgumentNullException.ThrowIfNull(stream);
27 if (direction is not (WorkerStreamDirection.Read or WorkerStreamDirection.Write))
28 {
29 throw new ArgumentOutOfRangeException(nameof(direction));
30 }
31 if (direction == WorkerStreamDirection.Read ? !stream.CanRead : !stream.CanWrite)
32 {
33 throw new ArgumentException("스트림 방향이 맞지 않음.", nameof(stream));
34 }
35 var actualLimits = limits ?? new WorkerStreamLimits();
36 validator = new WorkerStreamValidator(jobId, actualLimits);
37 deadline = new CancellationTokenSource(actualLimits.MaxDuration);
38 this.stream = stream;
39 this.direction = direction;
40 }
41
42 public WorkerStreamPhase Phase => validator.Phase;
43 public WorkerStreamTerminalStatus? TerminalStatus => validator.TerminalStatus;
44 public long TotalDataBytes => validator.TotalDataBytes;
45 public long TotalWireBytes => validator.TotalWireBytes;
46 public int FramesAccepted => validator.FramesAccepted;
47
48 public async ValueTask<WorkerStreamFrame?> ReadAsync(CancellationToken token = default)
49 {
50 Enter(WorkerStreamDirection.Read);
51 try
52 {
53 if (validator.Phase == WorkerStreamPhase.InputCompleted) { return null; }
54 if (validator.Phase == WorkerStreamPhase.Faulted)
55 {
56 throw new WorkerStreamException(WorkerStreamError.Faulted);
57 }
58
59 using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, deadline.Token);
60 var operationToken = linked.Token;
61 operationToken.ThrowIfCancellationRequested();
62
63 var bytes = new byte[HeaderBytes];
64 var first = await stream.ReadAsync(bytes.AsMemory(0, 1), operationToken).ConfigureAwait(false);
65 if (first == 0)
66 {
67 validator.CompleteInput(operationToken);
68 return null;
69 }
70 if (validator.Phase == WorkerStreamPhase.Terminal)
71 {
72 throw new WorkerStreamException(WorkerStreamError.TrailingData);
73 }
74 await stream.ReadExactlyAsync(bytes.AsMemory(1), operationToken).ConfigureAwait(false);
75 var header = Decode(bytes);
76 validator.ValidateHeader(header, operationToken);
77
78 // 검증된 청크 길이만 할당하며 항목 선언 길이로 할당하지 않음.
79 var payload = new byte[header.PayloadLength];
80 await stream.ReadExactlyAsync(payload, operationToken).ConfigureAwait(false);
81 validator.Accept(header, payload, operationToken);
82 return new WorkerStreamFrame(header, payload);
83 }
84 catch (EndOfStreamException)
85 {
86 validator.Abort();
87 throw new WorkerStreamException(WorkerStreamError.Truncated);
88 }
89 catch (OperationCanceledException) when (deadline.IsCancellationRequested && !token.IsCancellationRequested)
90 {
91 validator.Abort();
92 throw new WorkerStreamException(WorkerStreamError.BudgetExceeded);
93 }
94 catch
95 {
96 validator.Abort();
97 throw;
98 }
99 finally
100 {
101 Volatile.Write(ref busy, 0);
102 }
103 }
104
105 public async ValueTask WriteAsync(
106 WorkerStreamHeader header,
107 ReadOnlyMemory<byte> payload,
108 CancellationToken token = default)
109 {
110 Enter(WorkerStreamDirection.Write);
111 try
112 {
113 using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, deadline.Token);
114 var operationToken = linked.Token;
115 validator.ValidateHeader(header, operationToken);
116 if (payload.Length != header.PayloadLength)
117 {
118 throw new WorkerStreamException(WorkerStreamError.InvalidLength);
119 }
120
121 // 비동기 쓰기 중 호출자가 원본 메모리를 바꿀 수 없도록 작은 청크만 복사함.
122 var snapshot = payload.ToArray();
123 validator.Accept(header, snapshot, operationToken);
124 var bytes = Encode(header);
125 await stream.WriteAsync(bytes, operationToken).ConfigureAwait(false);
126 await stream.WriteAsync(snapshot, operationToken).ConfigureAwait(false);
127 await stream.FlushAsync(operationToken).ConfigureAwait(false);
128 operationToken.ThrowIfCancellationRequested();
129 }
130 catch (OperationCanceledException) when (deadline.IsCancellationRequested && !token.IsCancellationRequested)
131 {
132 validator.Abort();
133 throw new WorkerStreamException(WorkerStreamError.BudgetExceeded);
134 }
135 catch
136 {
137 validator.Abort();
138 throw;
139 }
140 finally
141 {
142 Volatile.Write(ref busy, 0);
143 }
144 }
145
146 public void Dispose()
147 {
148 if (Interlocked.CompareExchange(ref busy, 1, 0) != 0)
149 {
150 throw new InvalidOperationException("진행 중인 호출을 취소하고 기다린 뒤 해제해야 함.");
151 }
152 try
153 {
154 if (disposed) { return; }
155 disposed = true;
156 deadline.Dispose();
157 // 스트림 수명과 프로세스 종료는 호출자가 관리함.
158 }
159 finally
160 {
161 Volatile.Write(ref busy, 0);
162 }
163 }
164
165 private void Enter(WorkerStreamDirection expected)
166 {
167 if (Interlocked.CompareExchange(ref busy, 1, 0) != 0)
168 {
169 throw new InvalidOperationException("동시 채널 호출은 지원하지 않음.");
170 }
171 if (disposed || direction != expected)
172 {
173 Volatile.Write(ref busy, 0);
174 if (disposed) { throw new ObjectDisposedException(nameof(WorkerStreamChannel)); }
175 throw new InvalidOperationException("채널 방향이 맞지 않음.");
176 }
177 }
178
179 private static WorkerStreamHeader Decode(ReadOnlySpan<byte> bytes)
180 {
181 if (BinaryPrimitives.ReadUInt32LittleEndian(bytes) != Magic ||
182 BinaryPrimitives.ReadUInt16LittleEndian(bytes[4..]) != Version ||
183 BinaryPrimitives.ReadUInt32LittleEndian(bytes[12..]) != 0 ||
184 BinaryPrimitives.ReadUInt64LittleEndian(bytes[56..]) != 0)
185 {
186 throw new WorkerStreamException(WorkerStreamError.InvalidHeader);
187 }
188 var length = BinaryPrimitives.ReadUInt32LittleEndian(bytes[8..]);
189 if (length > MaxChunkBytes) { throw new WorkerStreamException(WorkerStreamError.InvalidLength); }
190 return new WorkerStreamHeader(
191 (WorkerStreamFrameKind)BinaryPrimitives.ReadUInt16LittleEndian(bytes[6..]),
192 new Guid(bytes.Slice(16, 16)),
193 new Guid(bytes.Slice(32, 16)),
194 BinaryPrimitives.ReadUInt64LittleEndian(bytes[48..]),
195 (int)length);
196 }
197
198 private static byte[] Encode(WorkerStreamHeader header)
199 {
200 var bytes = new byte[HeaderBytes];
201 BinaryPrimitives.WriteUInt32LittleEndian(bytes, Magic);
202 BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(4), Version);
203 BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(6), (ushort)header.Kind);
204 BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(8), (uint)header.PayloadLength);
205 header.JobId.TryWriteBytes(bytes.AsSpan(16, 16));
206 header.ItemId.TryWriteBytes(bytes.AsSpan(32, 16));
207 BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(48), header.Sequence);
208 return bytes;
209 }
210}