team-ljyzipelo

공개
209줄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 using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, deadline.Token);
54 var operationToken = linked.Token;
55 operationToken.ThrowIfCancellationRequested();
56 if (validator.Phase == WorkerStreamPhase.InputCompleted) { return null; }
57 if (validator.Phase == WorkerStreamPhase.Faulted)
58 {
59 throw new WorkerStreamException(WorkerStreamError.Faulted);
60 }
61
62 var bytes = new byte[HeaderBytes];
63 var first = await stream.ReadAsync(bytes.AsMemory(0, 1), operationToken).ConfigureAwait(false);
64 if (first == 0)
65 {
66 validator.CompleteInput(operationToken);
67 return null;
68 }
69 if (validator.Phase == WorkerStreamPhase.Terminal)
70 {
71 throw new WorkerStreamException(WorkerStreamError.TrailingData);
72 }
73 await stream.ReadExactlyAsync(bytes.AsMemory(1), operationToken).ConfigureAwait(false);
74 var header = Decode(bytes);
75 validator.ValidateHeader(header, operationToken);
76
77 // 검증된 청크 길이만 할당하며 항목 선언 길이로 할당하지 않음.
78 var payload = new byte[header.PayloadLength];
79 await stream.ReadExactlyAsync(payload, operationToken).ConfigureAwait(false);
80 validator.Accept(header, payload, operationToken);
81 return new WorkerStreamFrame(header, payload);
82 }
83 catch (EndOfStreamException)
84 {
85 validator.Abort();
86 throw new WorkerStreamException(WorkerStreamError.Truncated);
87 }
88 catch (OperationCanceledException) when (deadline.IsCancellationRequested && !token.IsCancellationRequested)
89 {
90 validator.Abort();
91 throw new WorkerStreamException(WorkerStreamError.BudgetExceeded);
92 }
93 catch
94 {
95 validator.Abort();
96 throw;
97 }
98 finally
99 {
100 Volatile.Write(ref busy, 0);
101 }
102 }
103
104 public async ValueTask WriteAsync(
105 WorkerStreamHeader header,
106 ReadOnlyMemory<byte> payload,
107 CancellationToken token = default)
108 {
109 Enter(WorkerStreamDirection.Write);
110 try
111 {
112 using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, deadline.Token);
113 var operationToken = linked.Token;
114 validator.ValidateHeader(header, operationToken);
115 if (payload.Length != header.PayloadLength)
116 {
117 throw new WorkerStreamException(WorkerStreamError.InvalidLength);
118 }
119
120 // 비동기 쓰기 중 호출자가 원본 메모리를 바꿀 수 없도록 작은 청크만 복사함.
121 var snapshot = payload.ToArray();
122 validator.Accept(header, snapshot, operationToken);
123 var bytes = Encode(header);
124 await stream.WriteAsync(bytes, operationToken).ConfigureAwait(false);
125 await stream.WriteAsync(snapshot, operationToken).ConfigureAwait(false);
126 await stream.FlushAsync(operationToken).ConfigureAwait(false);
127 operationToken.ThrowIfCancellationRequested();
128 }
129 catch (OperationCanceledException) when (deadline.IsCancellationRequested && !token.IsCancellationRequested)
130 {
131 validator.Abort();
132 throw new WorkerStreamException(WorkerStreamError.BudgetExceeded);
133 }
134 catch
135 {
136 validator.Abort();
137 throw;
138 }
139 finally
140 {
141 Volatile.Write(ref busy, 0);
142 }
143 }
144
145 public void Dispose()
146 {
147 if (Interlocked.CompareExchange(ref busy, 1, 0) != 0)
148 {
149 throw new InvalidOperationException("진행 중인 호출을 취소하고 기다린 뒤 해제해야 함.");
150 }
151 try
152 {
153 if (disposed) { return; }
154 disposed = true;
155 deadline.Dispose();
156 // 스트림 수명과 프로세스 종료는 호출자가 관리함.
157 }
158 finally
159 {
160 Volatile.Write(ref busy, 0);
161 }
162 }
163
164 private void Enter(WorkerStreamDirection expected)
165 {
166 if (Interlocked.CompareExchange(ref busy, 1, 0) != 0)
167 {
168 throw new InvalidOperationException("동시 채널 호출은 지원하지 않음.");
169 }
170 if (disposed || direction != expected)
171 {
172 Volatile.Write(ref busy, 0);
173 if (disposed) { throw new ObjectDisposedException(nameof(WorkerStreamChannel)); }
174 throw new InvalidOperationException("채널 방향이 맞지 않음.");
175 }
176 }
177
178 private static WorkerStreamHeader Decode(ReadOnlySpan<byte> bytes)
179 {
180 if (BinaryPrimitives.ReadUInt32LittleEndian(bytes) != Magic ||
181 BinaryPrimitives.ReadUInt16LittleEndian(bytes[4..]) != Version ||
182 BinaryPrimitives.ReadUInt32LittleEndian(bytes[12..]) != 0 ||
183 BinaryPrimitives.ReadUInt64LittleEndian(bytes[56..]) != 0)
184 {
185 throw new WorkerStreamException(WorkerStreamError.InvalidHeader);
186 }
187 var length = BinaryPrimitives.ReadUInt32LittleEndian(bytes[8..]);
188 if (length > MaxChunkBytes) { throw new WorkerStreamException(WorkerStreamError.InvalidLength); }
189 return new WorkerStreamHeader(
190 (WorkerStreamFrameKind)BinaryPrimitives.ReadUInt16LittleEndian(bytes[6..]),
191 new Guid(bytes.Slice(16, 16)),
192 new Guid(bytes.Slice(32, 16)),
193 BinaryPrimitives.ReadUInt64LittleEndian(bytes[48..]),
194 (int)length);
195 }
196
197 private static byte[] Encode(WorkerStreamHeader header)
198 {
199 var bytes = new byte[HeaderBytes];
200 BinaryPrimitives.WriteUInt32LittleEndian(bytes, Magic);
201 BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(4), Version);
202 BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(6), (ushort)header.Kind);
203 BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(8), (uint)header.PayloadLength);
204 header.JobId.TryWriteBytes(bytes.AsSpan(16, 16));
205 header.ItemId.TryWriteBytes(bytes.AsSpan(32, 16));
206 BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(48), header.Sequence);
207 return bytes;
208 }
209}