team-ljyzipelo

공개

작업자 스트림 프로토콜 독립 회귀 검사 추가

작성자
코노모리 카논
작성 시각
커밋
23a7d6ec0e7b40298f4e302fae774cb5edaa7cd8
부모
260428e
이 시점의 파일 보기

변경된 파일 8개

+1,056-0
추가tests/stream-protocol/ChannelTests.cs+421-0
@@ -0,0 +1,421 @@
1추가: using System.Buffers.Binary;
2추가: using Zipelo.Runtime.Streaming;
3추가:
4추가: namespace Zipelo.StreamProtocolTests;
5추가:
6추가: internal static class ChannelTests
7추가: {
8추가: private static readonly TimeSpan Guard = TimeSpan.FromSeconds(4);
9추가:
10추가: public static async Task RoundTrip(int[] sizes, int fragment = int.MaxValue)
11추가: {
12추가: var frames = Wire.JobFrames(sizes);
13추가: using var output = new ControlledStream();
14추가: using (var writer = new WorkerStreamChannel(output, WorkerStreamDirection.Write, Wire.Job))
15추가: {
16추가: foreach (var frame in frames) { await Wire.Write(writer, frame); }
17추가: Check.Equal(WorkerStreamPhase.Terminal, writer.Phase);
18추가: Check.Equal((long)sizes.Sum(), writer.TotalDataBytes);
19추가: Check.Equal(frames.Length, writer.FramesAccepted);
20추가: Check.Equal((long)output.Written.Length, writer.TotalWireBytes);
21추가: }
22추가: Check.That(output.CanWrite, "채널이 호출자 스트림을 닫음");
23추가: Check.Bytes(Wire.Join(frames.Select(Wire.Encode).ToArray()), output.Written);
24추가: using var input = new ControlledStream(output.Written) { ReadFragment = fragment };
25추가: using var reader = new WorkerStreamChannel(input, WorkerStreamDirection.Read, Wire.Job);
26추가: foreach (var expected in frames)
27추가: {
28추가: var actual = await reader.ReadAsync() ?? throw new InvalidOperationException("조기 EOF임");
29추가: Check.Equal(expected.Header, actual.Header);
30추가: Check.Bytes(expected.Payload.Span, actual.Payload.Span);
31추가: }
32추가: Check.Equal(WorkerStreamPhase.Terminal, reader.Phase);
33추가: Check.That(await reader.ReadAsync() is null, "종료 후 EOF 확인에 실패함");
34추가: Check.Equal(WorkerStreamPhase.InputCompleted, reader.Phase);
35추가: Check.Equal<WorkerStreamTerminalStatus?>(WorkerStreamTerminalStatus.Completed, reader.TerminalStatus);
36추가: var calls = input.ReadCalls;
37추가: Check.That(await reader.ReadAsync() is null, "완료된 수신을 재개함");
38추가: Check.Equal(calls, input.ReadCalls);
39추가: Check.Equal((long)sizes.Sum(), reader.TotalDataBytes);
40추가: Check.Equal((long)output.Written.Length, reader.TotalWireBytes);
41추가: Check.That(input.LargestReadRequest <= 65536, "청크 상한보다 큰 읽기를 요청함");
42추가: }
43추가:
44추가: public static async Task GoldenHeader()
45추가: {
46추가: Check.Equal(64, WorkerStreamChannel.HeaderBytes);
47추가: Check.Equal(65536, WorkerStreamChannel.MaxChunkBytes);
48추가: Check.Equal((ushort)2, WorkerStreamChannel.Version);
49추가: var expected = Convert.FromHexString(
50추가: "5A49503202000100000000000000000033221100554477668899AABBCCDDEEFF" + new string('0', 64));
51추가: using var stream = new ControlledStream();
52추가: using var writer = new WorkerStreamChannel(stream, WorkerStreamDirection.Write, Wire.Job);
53추가: await Wire.Write(writer, Wire.Begin);
54추가: Check.Bytes(expected, stream.Written);
55추가: Check.Bytes(expected, Wire.Encode(Wire.Begin));
56추가: }
57추가:
58추가: private static async Task Reject(byte[] bytes, int accepted, WorkerStreamError error, long? ceiling = null)
59추가: {
60추가: using var stream = new ControlledStream(bytes) { ReadCeiling = ceiling ?? long.MaxValue };
61추가: using var reader = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job);
62추가: for (var index = 0; index < accepted; index++)
63추가: {
64추가: Check.That(await reader.ReadAsync() is not null, "정상 접두 프레임이 거절됨");
65추가: }
66추가: var allocatedBefore = GC.GetAllocatedBytesForCurrentThread();
67추가: var rejected = reader.ReadAsync().AsTask();
68추가: Check.That(rejected.IsCompleted, "메모리 입력 검사가 예기치 않게 대기함");
69추가: await Check.Error(error, async () => { await rejected; });
70추가: var allocated = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore;
71추가: Check.That(allocated >= 0 && allocated < 1024 * 1024, "작은 오류 프레임에 1 MiB 이상 할당함");
72추가: Check.Equal(WorkerStreamPhase.Faulted, reader.Phase);
73추가: Check.Equal<WorkerStreamTerminalStatus?>(null, reader.TerminalStatus);
74추가: await Check.Error(WorkerStreamError.Faulted, async () => { await reader.ReadAsync(); });
75추가: if (ceiling is not null) { Check.Equal(ceiling.Value, stream.BytesRead); }
76추가: Check.That(stream.LargestReadRequest <= 65536, "큰 본문 읽기를 요청함");
77추가: }
78추가:
79추가: public static async Task TruncatedHeaders()
80추가: {
81추가: var bytes = Wire.Encode(Wire.Begin);
82추가: for (var cut = 0; cut < 64; cut++) { await Reject(bytes[..cut], 0, WorkerStreamError.Truncated); }
83추가: }
84추가:
85추가: public static async Task TruncatedBodies()
86추가: {
87추가: var item = Wire.Encode(Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(8), Wire.Item));
88추가: for (var cut = 0; cut < 8; cut++)
89추가: {
90추가: await Reject(Wire.Join(Wire.Encode(Wire.Begin), item[..(64 + cut)]), 1, WorkerStreamError.Truncated);
91추가: }
92추가: var frames = Wire.JobFrames(8);
93추가: var data = Wire.Encode(frames[2]);
94추가: for (var cut = 0; cut < 8; cut++)
95추가: {
96추가: await Reject(Wire.Join(Wire.Encode(frames[0]), Wire.Encode(frames[1]), data[..(64 + cut)]),
97추가: 2, WorkerStreamError.Truncated);
98추가: }
99추가: }
100추가:
101추가: public static async Task FixedFields()
102추가: {
103추가: foreach (var offset in new[] { 0, 3, 4, 5, 12, 13, 14, 15, 56, 57, 58, 59, 60, 61, 62, 63 })
104추가: {
105추가: var bytes = Wire.Encode(Wire.Begin);
106추가: bytes[offset] ^= 0x80;
107추가: await Reject(bytes, 0, WorkerStreamError.InvalidHeader, 64);
108추가: }
109추가: }
110추가:
111추가: public static async Task KindsAndLengths()
112추가: {
113추가: foreach (var kind in new ushort[] { 0, 6, ushort.MaxValue })
114추가: {
115추가: var bytes = Wire.Encode(Wire.Begin);
116추가: BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(6), kind);
117추가: await Reject(bytes, 0, WorkerStreamError.InvalidLength, 64);
118추가: }
119추가: foreach (var (kind, length) in new (ushort, uint)[]
120추가: {
121추가: (1, 1), (2, 0), (2, 7), (2, 9), (3, 0), (3, 65537),
122추가: (3, int.MaxValue), (3, uint.MaxValue), (4, 0), (4, 9), (5, 0), (5, 2)
123추가: })
124추가: {
125추가: var bytes = Wire.Encode(Wire.Begin);
126추가: BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(6), kind);
127추가: BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(8), length);
128추가: await Reject(bytes, 0, WorkerStreamError.InvalidLength, 64);
129추가: }
130추가: }
131추가:
132추가: public static async Task HugeDeclarations()
133추가: {
134추가: foreach (var length in new ulong[] { 16777217, int.MaxValue, (ulong)long.MaxValue, ulong.MaxValue })
135추가: {
136추가: var beginItem = Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(length), Wire.Item);
137추가: await Reject(Wire.Join(Wire.Encode(Wire.Begin), Wire.Encode(beginItem)), 1,
138추가: WorkerStreamError.BudgetExceeded, 136);
139추가: }
140추가: var limitedItem = Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(0), Wire.Item);
141추가: using var stream = new ControlledStream(Wire.Join(Wire.Encode(Wire.Begin), Wire.Encode(limitedItem)))
142추가: {
143추가: ReadCeiling = 128
144추가: };
145추가: using var reader = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job,
146추가: new() { MaxWireBytes = 129 });
147추가: await reader.ReadAsync();
148추가: await Check.Error(WorkerStreamError.BudgetExceeded, async () => { await reader.ReadAsync(); });
149추가: Check.Equal(128L, stream.BytesRead);
150추가: Check.Equal(WorkerStreamPhase.Faulted, reader.Phase);
151추가: }
152추가:
153추가: public static async Task EarlyEof()
154추가: {
155추가: var frames = Wire.JobFrames(1);
156추가: for (var count = 0; count < frames.Length; count++)
157추가: {
158추가: await Reject(Wire.Join(frames.Take(count).Select(Wire.Encode).ToArray()),
159추가: count, WorkerStreamError.Truncated);
160추가: }
161추가: }
162추가:
163추가: public static async Task TrailingData()
164추가: {
165추가: var frames = Wire.JobFrames();
166추가: var complete = Wire.Join(frames.Select(Wire.Encode).ToArray());
167추가: foreach (var suffix in new[] { new byte[] { 0 }, Wire.Encode(Wire.End(2)) })
168추가: {
169추가: await Reject(Wire.Join(complete, suffix), 2, WorkerStreamError.TrailingData);
170추가: }
171추가: }
172추가:
173추가: public static async Task FailedTerminals()
174추가: {
175추가: foreach (var status in new byte[] { 2, 3 })
176추가: {
177추가: var frames = new[] { Wire.Begin,
178추가: Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(10), Wire.Item), Wire.End(2, status) };
179추가: using var stream = new ControlledStream(Wire.Join(frames.Select(Wire.Encode).ToArray()));
180추가: using var reader = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job);
181추가: foreach (var unused in frames) { Check.That(await reader.ReadAsync() is not null, "조기 종료임"); }
182추가: Check.That(await reader.ReadAsync() is null, "EOF가 아님");
183추가: Check.Equal(WorkerStreamPhase.InputCompleted, reader.Phase);
184추가: Check.Equal<WorkerStreamTerminalStatus?>((WorkerStreamTerminalStatus)status, reader.TerminalStatus);
185추가: }
186추가: }
187추가:
188추가: public static async Task PreCancelled()
189추가: {
190추가: foreach (var direction in new[] { WorkerStreamDirection.Read, WorkerStreamDirection.Write })
191추가: {
192추가: using var stream = new ControlledStream();
193추가: using var channel = new WorkerStreamChannel(stream, direction, Wire.Job);
194추가: using var cancellation = new CancellationTokenSource();
195추가: cancellation.Cancel();
196추가: await Check.ThrowsAsync<OperationCanceledException>(() => direction == WorkerStreamDirection.Read
197추가: ? Read(channel, cancellation.Token) : Wire.Write(channel, Wire.Begin, cancellation.Token));
198추가: Check.Equal(0, stream.ReadCalls + stream.WriteCalls);
199추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
200추가: await Check.Error(WorkerStreamError.Faulted, () => direction == WorkerStreamDirection.Read
201추가: ? Read(channel, default) : Wire.Write(channel, Wire.Begin));
202추가: }
203추가: }
204추가:
205추가: private static async Task Read(WorkerStreamChannel channel, CancellationToken token) =>
206추가: _ = await channel.ReadAsync(token);
207추가:
208추가: public static async Task BlockedRead(bool body, bool deadline, bool resume = false)
209추가: {
210추가: var frames = Wire.JobFrames(8);
211추가: using var stream = new ControlledStream(Wire.Join(frames.Select(Wire.Encode).ToArray()));
212추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job,
213추가: new() { MaxDuration = deadline ? TimeSpan.FromMilliseconds(180) : TimeSpan.FromSeconds(10) });
214추가: await channel.ReadAsync();
215추가: await channel.ReadAsync();
216추가: stream.BlockRead = stream.ReadCalls + (body ? 3 : 1);
217추가: using var cancellation = new CancellationTokenSource();
218추가: var pending = channel.ReadAsync(cancellation.Token).AsTask();
219추가: try
220추가: {
221추가: await stream.Entered.Task.WaitAsync(Guard);
222추가: Check.That(!pending.IsCompleted, "생산자를 기다리지 않고 읽기를 완료함");
223추가: Check.Equal(2, channel.FramesAccepted);
224추가: if (resume)
225추가: {
226추가: stream.Release.TrySetResult();
227추가: var frame = await pending.WaitAsync(Guard) ?? throw new InvalidOperationException();
228추가: Check.Bytes(frames[2].Payload.Span, frame.Payload.Span);
229추가: return;
230추가: }
231추가: if (!deadline) { cancellation.Cancel(); }
232추가: if (deadline) { await Check.Error(WorkerStreamError.BudgetExceeded, async () => { await pending.WaitAsync(Guard); }); }
233추가: else { await Check.ThrowsAsync<OperationCanceledException>(async () => { await pending.WaitAsync(Guard); }); }
234추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
235추가: Check.Equal<WorkerStreamTerminalStatus?>(null, channel.TerminalStatus);
236추가: if (!deadline) { await Check.Error(WorkerStreamError.Faulted, () => Read(channel, default)); }
237추가: }
238추가: finally
239추가: {
240추가: cancellation.Cancel();
241추가: try { await pending.WaitAsync(Guard); }
242추가: catch (OperationCanceledException) { }
243추가: catch (WorkerStreamException) { }
244추가: }
245추가: }
246추가:
247추가: public static async Task BlockedWrite(string stage, bool deadline, bool resume = false)
248추가: {
249추가: using var stream = new ControlledStream();
250추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Write, Wire.Job,
251추가: new() { MaxDuration = deadline ? TimeSpan.FromMilliseconds(180) : TimeSpan.FromSeconds(10) });
252추가: await Wire.Write(channel, Wire.Begin);
253추가: await Wire.Write(channel, Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(3), Wire.Item));
254추가: if (stage == "header") { stream.BlockWrite = stream.WriteCalls + 1; }
255추가: if (stage == "body") { stream.BlockWrite = stream.WriteCalls + 2; }
256추가: if (stage == "flush") { stream.BlockFlush = stream.FlushCalls + 1; }
257추가: byte[] payload = [1, 2, 3];
258추가: var frame = Wire.Frame(WorkerStreamFrameKind.Data, 2, payload, Wire.Item);
259추가: using var cancellation = new CancellationTokenSource();
260추가: var pending = Wire.Write(channel, frame, cancellation.Token);
261추가: try
262추가: {
263추가: await stream.Entered.Task.WaitAsync(Guard);
264추가: Check.That(!pending.IsCompleted, "소비자나 Flush를 기다리지 않고 완료함");
265추가: if (resume)
266추가: {
267추가: payload.AsSpan().Fill(99);
268추가: stream.Release.TrySetResult();
269추가: await pending.WaitAsync(Guard);
270추가: Check.Bytes(new byte[] { 1, 2, 3 }, stream.Written.AsSpan(200, 3));
271추가: Check.Equal(3L, channel.TotalDataBytes);
272추가: return;
273추가: }
274추가: if (!deadline) { cancellation.Cancel(); }
275추가: if (deadline) { await Check.Error(WorkerStreamError.BudgetExceeded, () => pending.WaitAsync(Guard)); }
276추가: else { await Check.ThrowsAsync<OperationCanceledException>(() => pending.WaitAsync(Guard)); }
277추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
278추가: Check.Equal<WorkerStreamTerminalStatus?>(null, channel.TerminalStatus);
279추가: if (!deadline) { await Check.Error(WorkerStreamError.Faulted, () => Wire.Write(channel, Wire.Begin)); }
280추가: }
281추가: finally
282추가: {
283추가: cancellation.Cancel();
284추가: try { await pending.WaitAsync(Guard); }
285추가: catch (OperationCanceledException) { }
286추가: catch (WorkerStreamException) { }
287추가: }
288추가: }
289추가:
290추가: public static async Task MissingEof()
291추가: {
292추가: using var stream = new ControlledStream(Wire.Join(Wire.Encode(Wire.Begin), Wire.Encode(Wire.End(1))));
293추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job,
294추가: new() { MaxDuration = TimeSpan.FromMilliseconds(180) });
295추가: await channel.ReadAsync();
296추가: await channel.ReadAsync();
297추가: stream.BlockRead = stream.ReadCalls + 1;
298추가: await Check.Error(WorkerStreamError.BudgetExceeded, async () => { await channel.ReadAsync().AsTask().WaitAsync(Guard); });
299추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
300추가: Check.Equal<WorkerStreamTerminalStatus?>(null, channel.TerminalStatus);
301추가: }
302추가:
303추가: public static async Task FinalStatePriority()
304추가: {
305추가: foreach (var status in new byte[] { 1, 2, 3 })
306추가: {
307추가: using var stream = new ControlledStream(Wire.Join(Wire.Encode(Wire.Begin), Wire.Encode(Wire.End(1, status))));
308추가: using var reader = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job,
309추가: new() { MaxDuration = TimeSpan.FromMilliseconds(250) });
310추가: await reader.ReadAsync();
311추가: await reader.ReadAsync();
312추가: Check.That(await reader.ReadAsync() is null, "종료 EOF가 아님");
313추가: var calls = stream.ReadCalls;
314추가: using var cancelled = new CancellationTokenSource();
315추가: cancelled.Cancel();
316추가: Check.That(await reader.ReadAsync(cancelled.Token) is null, "확정 EOF를 취소가 바꿈");
317추가: await Task.Delay(400);
318추가: Check.That(await reader.ReadAsync() is null, "확정 EOF를 기한이 바꿈");
319추가: Check.Equal(WorkerStreamPhase.InputCompleted, reader.Phase);
320추가: Check.Equal<WorkerStreamTerminalStatus?>((WorkerStreamTerminalStatus)status, reader.TerminalStatus);
321추가: Check.Equal(calls, stream.ReadCalls);
322추가: }
323추가:
324추가: var bytes = Wire.Encode(Wire.Begin);
325추가: bytes[0] = 0;
326추가: using var input = new ControlledStream(bytes);
327추가: using var faulted = new WorkerStreamChannel(input, WorkerStreamDirection.Read, Wire.Job,
328추가: new() { MaxDuration = TimeSpan.FromMilliseconds(250) });
329추가: await Check.Error(WorkerStreamError.InvalidHeader, () => Read(faulted, default));
330추가: var reads = input.ReadCalls;
331추가: using var cancellation = new CancellationTokenSource();
332추가: cancellation.Cancel();
333추가: await Check.Error(WorkerStreamError.Faulted, () => Read(faulted, cancellation.Token));
334추가: await Task.Delay(400);
335추가: await Check.Error(WorkerStreamError.Faulted, () => Read(faulted, default));
336추가: Check.Equal(WorkerStreamPhase.Faulted, faulted.Phase);
337추가: Check.Equal<WorkerStreamTerminalStatus?>(null, faulted.TerminalStatus);
338추가: Check.Equal(reads, input.ReadCalls);
339추가: }
340추가:
341추가: public static async Task BetweenCallsDeadline()
342추가: {
343추가: using var stream = new ControlledStream();
344추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Write, Wire.Job,
345추가: new() { MaxDuration = TimeSpan.FromMilliseconds(40) });
346추가: await Task.Delay(100);
347추가: await Check.Error(WorkerStreamError.BudgetExceeded, () => Wire.Write(channel, Wire.Begin));
348추가: Check.Equal(0, stream.WriteCalls);
349추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
350추가: }
351추가:
352추가: public static async Task IoFailure(bool read)
353추가: {
354추가: using var stream = new ControlledStream(read ? Wire.Encode(Wire.Begin) : null)
355추가: {
356추가: FailRead = read ? 2 : -1, FailWrite = read ? -1 : 2
357추가: };
358추가: using var channel = new WorkerStreamChannel(stream,
359추가: read ? WorkerStreamDirection.Read : WorkerStreamDirection.Write, Wire.Job);
360추가: var exception = await Check.ThrowsAsync<IOException>(() => read
361추가: ? Read(channel, default) : Wire.Write(channel, Wire.Begin));
362추가: Check.That(ReferenceEquals(stream.Failure, exception), "원래 I/O 오류를 바꿈");
363추가: Check.Equal(WorkerStreamPhase.Faulted, channel.Phase);
364추가: await Check.Error(WorkerStreamError.Faulted, () => read
365추가: ? Read(channel, default) : Wire.Write(channel, Wire.Begin));
366추가: }
367추가:
368추가: public static async Task ConcurrentCalls()
369추가: {
370추가: using var stream = new ControlledStream(Wire.Encode(Wire.Begin)) { BlockRead = 1 };
371추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Read, Wire.Job);
372추가: using var cancellation = new CancellationTokenSource();
373추가: var pending = channel.ReadAsync(cancellation.Token).AsTask();
374추가: try
375추가: {
376추가: await stream.Entered.Task.WaitAsync(Guard);
377추가: await Check.ThrowsAsync<InvalidOperationException>(() => Read(channel, default));
378추가: Check.Throws<InvalidOperationException>(channel.Dispose);
379추가: Check.Equal(WorkerStreamPhase.Ready, channel.Phase);
380추가: stream.Release.TrySetResult();
381추가: Check.Equal(Wire.Begin.Header, (await pending.WaitAsync(Guard))!.Header);
382추가: }
383추가: finally
384추가: {
385추가: cancellation.Cancel();
386추가: try { await pending.WaitAsync(Guard); }
387추가: catch (OperationCanceledException) { }
388추가: }
389추가: }
390추가:
391추가: public static async Task DirectionAndLifetime()
392추가: {
393추가: using var stream = new ControlledStream();
394추가: using var channel = new WorkerStreamChannel(stream, WorkerStreamDirection.Write, Wire.Job);
395추가: await Check.ThrowsAsync<InvalidOperationException>(() => Read(channel, default));
396추가: Check.Equal(WorkerStreamPhase.Ready, channel.Phase);
397추가: await Wire.Write(channel, Wire.Begin);
398추가: channel.Dispose();
399추가: channel.Dispose();
400추가: Check.That(stream.CanWrite, "호출자 스트림을 닫음");
401추가: await Check.ThrowsAsync<ObjectDisposedException>(() => Wire.Write(channel, Wire.End(1)));
402추가: }
403추가:
404추가: public static async Task InvalidWrite()
405추가: {
406추가: foreach (var length in new[] { -1, 1, 65537, int.MaxValue })
407추가: {
408추가: using var stream = new ControlledStream();
409추가: using var writer = new WorkerStreamChannel(stream, WorkerStreamDirection.Write, Wire.Job);
410추가: var frame = Wire.Begin with { Header = Wire.Begin.Header with { PayloadLength = length } };
411추가: await Check.Error(WorkerStreamError.InvalidLength, () => Wire.Write(writer, frame));
412추가: Check.Equal(0, stream.WriteCalls);
413추가: Check.Equal(WorkerStreamPhase.Faulted, writer.Phase);
414추가: }
415추가: using var output = new ControlledStream();
416추가: using var channel = new WorkerStreamChannel(output, WorkerStreamDirection.Write, Wire.Job);
417추가: await Check.Error(WorkerStreamError.InvalidLength,
418추가: () => channel.WriteAsync(Wire.Begin.Header, new byte[] { 1 }).AsTask());
419추가: Check.Equal(0, output.WriteCalls);
420추가: }
421추가: }
추가tests/stream-protocol/ControlledStream.cs+77-0
@@ -0,0 +1,77 @@
1추가: namespace Zipelo.StreamProtocolTests;
2추가:
3추가: // 작은 메모리 입력과 취소 가능한 한 개의 장벽만 사용하는 I/O 대역임.
4추가: internal sealed class ControlledStream(byte[]? input = null) : Stream
5추가: {
6추가: private readonly MemoryStream inner = input is null ? new() : new(input, false);
7추가: public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
8추가: public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
9추가: public int ReadCalls { get; private set; }
10추가: public int WriteCalls { get; private set; }
11추가: public int FlushCalls { get; private set; }
12추가: public long BytesRead { get; private set; }
13추가: public int LargestReadRequest { get; private set; }
14추가: public int ReadFragment { get; init; } = int.MaxValue;
15추가: public int BlockRead { get; set; } = -1;
16추가: public int BlockWrite { get; set; } = -1;
17추가: public int BlockFlush { get; set; } = -1;
18추가: public int FailRead { get; set; } = -1;
19추가: public int FailWrite { get; set; } = -1;
20추가: public long ReadCeiling { get; set; } = long.MaxValue;
21추가: public IOException Failure { get; } = new("테스트 I/O 실패");
22추가: public byte[] Written => inner.ToArray();
23추가:
24추가: private async Task Wait(CancellationToken token)
25추가: {
26추가: Entered.TrySetResult();
27추가: await Release.Task.WaitAsync(token);
28추가: }
29추가:
30추가: public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken token = default)
31추가: {
32추가: ReadCalls++;
33추가: LargestReadRequest = Math.Max(LargestReadRequest, buffer.Length);
34추가: if (ReadCalls == FailRead) { throw Failure; }
35추가: if (ReadCalls == BlockRead) { await Wait(token); }
36추가: token.ThrowIfCancellationRequested();
37추가: if (buffer.Length != 0 && inner.Position >= ReadCeiling)
38추가: {
39추가: throw new InvalidOperationException("거절해야 할 본문에 접근함");
40추가: }
41추가: var count = await inner.ReadAsync(buffer[..Math.Min(buffer.Length, ReadFragment)], token);
42추가: BytesRead += count;
43추가: return count;
44추가: }
45추가:
46추가: public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default)
47추가: {
48추가: WriteCalls++;
49추가: if (WriteCalls == FailWrite) { throw Failure; }
50추가: if (WriteCalls == BlockWrite) { await Wait(token); }
51추가: await inner.WriteAsync(buffer, token);
52추가: }
53추가:
54추가: public override async Task FlushAsync(CancellationToken token)
55추가: {
56추가: FlushCalls++;
57추가: if (FlushCalls == BlockFlush) { await Wait(token); }
58추가: token.ThrowIfCancellationRequested();
59추가: }
60추가:
61추가: protected override void Dispose(bool disposing)
62추가: {
63추가: if (disposing) { inner.Dispose(); }
64추가: base.Dispose(disposing);
65추가: }
66추가:
67추가: public override bool CanRead => inner.CanRead;
68추가: public override bool CanWrite => inner.CanWrite;
69추가: public override bool CanSeek => false;
70추가: public override long Length => inner.Length;
71추가: public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
72추가: public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
73추가: public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
74추가: public override void Flush() => throw new NotSupportedException();
75추가: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
76추가: public override void SetLength(long value) => throw new NotSupportedException();
77추가: }
추가tests/stream-protocol/NuGet.Config+6-0
@@ -0,0 +1,6 @@
1추가: <?xml version="1.0" encoding="utf-8"?>
2추가: <configuration>
3추가: <packageSources>
4추가: <clear />
5추가: </packageSources>
6추가: </configuration>
추가tests/stream-protocol/Program.cs+89-0
@@ -0,0 +1,89 @@
1추가: namespace Zipelo.StreamProtocolTests;
2추가:
3추가: internal static class Program
4추가: {
5추가: private static readonly (string Name, Func<Task> Run)[] Cases =
6추가: [
7추가: ("wire.empty_job", () => ChannelTests.RoundTrip([])),
8추가: ("wire.empty_item", () => ChannelTests.RoundTrip([0])),
9추가: ("wire.one_byte", () => ChannelTests.RoundTrip([1])),
10추가: ("wire.chunk_boundaries", () => ChannelTests.RoundTrip([65535, 65536])),
11추가: ("wire.fragmented_reads", () => ChannelTests.RoundTrip([1, 7, 1024], 3)),
12추가: ("wire.golden_64_byte_header", () => ChannelTests.GoldenHeader()),
13추가: ("wire.all_header_truncations", () => ChannelTests.TruncatedHeaders()),
14추가: ("wire.metadata_and_data_truncations", () => ChannelTests.TruncatedBodies()),
15추가: ("wire.magic_version_reserved", () => ChannelTests.FixedFields()),
16추가: ("wire.kind_length_and_uint_overflow", () => ChannelTests.KindsAndLengths()),
17추가: ("wire.huge_declaration_allocation_bound", () => ChannelTests.HugeDeclarations()),
18추가: ("state.job_and_item_ids", () => ValidatorTests.Identifiers()),
19추가: ("state.sequence_duplicate_gap_overflow", () => ValidatorTests.Sequences()),
20추가: ("state.missing_and_nested_transitions", () => ValidatorTests.Transitions()),
21추가: ("state.duplicate_item_id", () => ValidatorTests.DuplicateItem()),
22추가: ("state.actual_declared_end_lengths", () => ValidatorTests.ItemLengths()),
23추가: ("state.status_and_open_item", () => ValidatorTests.TerminalStatus()),
24추가: ("state.failed_cancelled_eof", () => ChannelTests.FailedTerminals()),
25추가: ("state.eof_before_terminal", () => ChannelTests.EarlyEof()),
26추가: ("state.trailing_byte_duplicate_end", () => ChannelTests.TrailingData()),
27추가: ("state.terminal_without_eof_deadline", () => ChannelTests.MissingEof()),
28추가: ("state.final_status_over_cancel_and_deadline", () => ChannelTests.FinalStatePriority()),
29추가: ("budget.invalid_limits", () => ValidatorTests.Limits()),
30추가: ("budget.validate_header_does_not_spend", () => ValidatorTests.HeaderValidationDoesNotSpend()),
31추가: ("budget.wire_exact_and_one_short", () => ValidatorTests.WireBudget()),
32추가: ("budget.data_cumulative_16mib", () => ValidatorTests.DataBudget()),
33추가: ("budget.small_chunk_frame_count", () => ValidatorTests.FrameBudget()),
34추가: ("budget.empty_item_count", () => ValidatorTests.ItemBudget()),
35추가: ("budget.signed_and_payload_lengths", () => ValidatorTests.ArithmeticLengths()),
36추가: ("cancel.before_io", () => ChannelTests.PreCancelled()),
37추가: ("cancel.read_header", () => ChannelTests.BlockedRead(false, false)),
38추가: ("cancel.read_body", () => ChannelTests.BlockedRead(true, false)),
39추가: ("cancel.write_header", () => ChannelTests.BlockedWrite("header", false)),
40추가: ("cancel.write_body", () => ChannelTests.BlockedWrite("body", false)),
41추가: ("cancel.write_flush", () => ChannelTests.BlockedWrite("flush", false)),
42추가: ("deadline.read_wait", () => ChannelTests.BlockedRead(true, true)),
43추가: ("deadline.write_wait", () => ChannelTests.BlockedWrite("body", true)),
44추가: ("deadline.between_calls", () => ChannelTests.BetweenCallsDeadline()),
45추가: ("flow.slow_producer", () => ChannelTests.BlockedRead(true, false, true)),
46추가: ("flow.slow_consumer_snapshot", () => ChannelTests.BlockedWrite("body", false, true)),
47추가: ("flow.flush_completion", () => ChannelTests.BlockedWrite("flush", false, true)),
48추가: ("fault.read_io_and_reuse", () => ChannelTests.IoFailure(true)),
49추가: ("fault.write_io_and_reuse", () => ChannelTests.IoFailure(false)),
50추가: ("api.concurrent_call_and_dispose", () => ChannelTests.ConcurrentCalls()),
51추가: ("api.direction_stream_lifetime", () => ChannelTests.DirectionAndLifetime()),
52추가: ("api.invalid_write_before_output", () => ChannelTests.InvalidWrite()),
53추가: ];
54추가:
55추가: public static async Task<int> Main(string[] arguments)
56추가: {
57추가: if (arguments is ["--list"])
58추가: {
59추가: foreach (var item in Cases) { Console.WriteLine(item.Name); }
60추가: Console.WriteLine($"등록: {Cases.Length}");
61추가: return 0;
62추가: }
63추가: if (arguments.Length != 0) { return 2; }
64추가: var passed = 0;
65추가: var failed = 0;
66추가: foreach (var (name, run) in Cases)
67추가: {
68추가: try
69추가: {
70추가: await run().WaitAsync(TimeSpan.FromSeconds(8));
71추가: Console.WriteLine($"PASS {name}");
72추가: passed++;
73추가: }
74추가: catch (TimeoutException)
75추가: {
76추가: Console.Error.WriteLine($"FAIL {name}: 검사 제한 시간 초과");
77추가: Console.WriteLine($"등록 {Cases.Length}, 통과 {passed}, 실패 {failed + 1}, 미실행 {Cases.Length - passed - failed - 1}");
78추가: return 124;
79추가: }
80추가: catch (Exception exception)
81추가: {
82추가: Console.Error.WriteLine($"FAIL {name}: {exception.GetType().Name}: {exception.Message}");
83추가: failed++;
84추가: }
85추가: }
86추가: Console.WriteLine($"등록 {Cases.Length}, 통과 {passed}, 실패 {failed}, SKIP 0");
87추가: return failed == 0 ? 0 : 1;
88추가: }
89추가: }
추가tests/stream-protocol/TestSupport.cs+117-0
@@ -0,0 +1,117 @@
1추가: using System.Buffers.Binary;
2추가: using Zipelo.Runtime.Streaming;
3추가:
4추가: namespace Zipelo.StreamProtocolTests;
5추가:
6추가: internal static class Check
7추가: {
8추가: public static void That(bool condition, string message)
9추가: {
10추가: if (!condition) { throw new InvalidOperationException(message); }
11추가: }
12추가:
13추가: public static void Equal<T>(T expected, T actual) =>
14추가: That(EqualityComparer<T>.Default.Equals(expected, actual), $"기대값 {expected}, 실제값 {actual}");
15추가:
16추가: public static void Bytes(ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual) =>
17추가: That(expected.SequenceEqual(actual), "전송 바이트가 다름");
18추가:
19추가: public static T Throws<T>(Action run) where T : Exception
20추가: {
21추가: try { run(); }
22추가: catch (T exception) { return exception; }
23추가: throw new InvalidOperationException($"예상 예외가 없음: {typeof(T).Name}");
24추가: }
25추가:
26추가: public static async Task<T> ThrowsAsync<T>(Func<Task> run) where T : Exception
27추가: {
28추가: try { await run(); }
29추가: catch (T exception) { return exception; }
30추가: throw new InvalidOperationException($"예상 예외가 없음: {typeof(T).Name}");
31추가: }
32추가:
33추가: public static async Task Error(WorkerStreamError expected, Func<Task> run) =>
34추가: Equal(expected, (await ThrowsAsync<WorkerStreamException>(run)).Error);
35추가: }
36추가:
37추가: internal static class Wire
38추가: {
39추가: public static readonly Guid Job = new("00112233-4455-6677-8899-aabbccddeeff");
40추가: public static readonly Guid Item = new("10213243-5465-7687-98a9-bacbdcedfe0f");
41추가: public static readonly Guid OtherItem = new("20314253-6475-8697-a8b9-cadbecfd0e1f");
42추가:
43추가: public static byte[] Length(ulong value)
44추가: {
45추가: var result = new byte[8];
46추가: BinaryPrimitives.WriteUInt64LittleEndian(result, value);
47추가: return result;
48추가: }
49추가:
50추가: public static WorkerStreamFrame Frame(WorkerStreamFrameKind kind, ulong sequence,
51추가: byte[]? payload = null, Guid? item = null, Guid? job = null)
52추가: {
53추가: var bytes = payload ?? [];
54추가: return new(new(kind, job ?? Job, item ?? Guid.Empty, sequence, bytes.Length), bytes);
55추가: }
56추가:
57추가: public static WorkerStreamFrame Begin => Frame(WorkerStreamFrameKind.BeginJob, 0);
58추가: public static WorkerStreamFrame End(ulong sequence, byte status = 1) =>
59추가: Frame(WorkerStreamFrameKind.EndJob, sequence, [status]);
60추가:
61추가: // 제품 인코더를 호출하지 않는 문서 기준 바이트 픽스처임.
62추가: public static byte[] Encode(WorkerStreamHeader header, ReadOnlySpan<byte> payload)
63추가: {
64추가: var bytes = new byte[64 + payload.Length];
65추가: "ZIP2"u8.CopyTo(bytes);
66추가: BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(4), 2);
67추가: BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(6), (ushort)header.Kind);
68추가: BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(8), unchecked((uint)header.PayloadLength));
69추가: header.JobId.TryWriteBytes(bytes.AsSpan(16, 16));
70추가: header.ItemId.TryWriteBytes(bytes.AsSpan(32, 16));
71추가: BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(48), header.Sequence);
72추가: payload.CopyTo(bytes.AsSpan(64));
73추가: return bytes;
74추가: }
75추가:
76추가: public static byte[] Encode(WorkerStreamFrame frame) => Encode(frame.Header, frame.Payload.Span);
77추가:
78추가: public static byte[] Join(params byte[][] parts)
79추가: {
80추가: using var stream = new MemoryStream();
81추가: foreach (var part in parts) { stream.Write(part); }
82추가: return stream.ToArray();
83추가: }
84추가:
85추가: public static WorkerStreamFrame[] JobFrames(params int[] sizes)
86추가: {
87추가: var frames = new List<WorkerStreamFrame> { Begin };
88추가: if (sizes.Length != 0)
89추가: {
90추가: var length = (ulong)sizes.Sum();
91추가: frames.Add(Frame(WorkerStreamFrameKind.BeginItem, 1, Length(length), Item));
92추가: foreach (var size in sizes)
93추가: {
94추가: if (size == 0) { continue; }
95추가: var payload = Enumerable.Range(0, size).Select(index => (byte)(index % 251)).ToArray();
96추가: frames.Add(Frame(WorkerStreamFrameKind.Data, (ulong)frames.Count, payload, Item));
97추가: }
98추가: frames.Add(Frame(WorkerStreamFrameKind.EndItem, (ulong)frames.Count, Length(length), Item));
99추가: }
100추가: frames.Add(End((ulong)frames.Count));
101추가: return frames.ToArray();
102추가: }
103추가:
104추가: public static WorkerStreamValidator Active(ulong length = 1, WorkerStreamLimits? limits = null)
105추가: {
106추가: var validator = new WorkerStreamValidator(Job, limits);
107추가: Accept(validator, Begin);
108추가: Accept(validator, Frame(WorkerStreamFrameKind.BeginItem, 1, Length(length), Item));
109추가: return validator;
110추가: }
111추가:
112추가: public static void Accept(WorkerStreamValidator validator, WorkerStreamFrame frame) =>
113추가: validator.Accept(frame.Header, frame.Payload.Span);
114추가:
115추가: public static async Task Write(WorkerStreamChannel channel, WorkerStreamFrame frame,
116추가: CancellationToken token = default) => await channel.WriteAsync(frame.Header, frame.Payload, token);
117추가: }
추가tests/stream-protocol/ValidatorTests.cs+225-0
@@ -0,0 +1,225 @@
1추가: using Zipelo.Runtime.Streaming;
2추가:
3추가: namespace Zipelo.StreamProtocolTests;
4추가:
5추가: internal static class ValidatorTests
6추가: {
7추가: private static void Reject(WorkerStreamValidator validator, WorkerStreamFrame frame, WorkerStreamError error)
8추가: {
9추가: Check.Equal(error, Check.Throws<WorkerStreamException>(() => Wire.Accept(validator, frame)).Error);
10추가: Check.Equal(WorkerStreamPhase.Faulted, validator.Phase);
11추가: Check.Equal<WorkerStreamTerminalStatus?>(null, validator.TerminalStatus);
12추가: Check.Equal(WorkerStreamError.Faulted,
13추가: Check.Throws<WorkerStreamException>(() => Wire.Accept(validator, Wire.Begin)).Error);
14추가: }
15추가:
16추가: public static Task Identifiers()
17추가: {
18추가: var wrongJob = Wire.Begin with { Header = Wire.Begin.Header with { JobId = Wire.Item } };
19추가: Reject(new(Wire.Job), wrongJob, WorkerStreamError.IdMismatch);
20추가: Reject(new(Wire.Job), Wire.Frame(WorkerStreamFrameKind.BeginJob, 0, item: Wire.Item),
21추가: WorkerStreamError.IdMismatch);
22추가: foreach (var kind in new[] { WorkerStreamFrameKind.Data, WorkerStreamFrameKind.EndItem })
23추가: {
24추가: var payload = kind == WorkerStreamFrameKind.Data ? new byte[] { 1 } : Wire.Length(0);
25추가: Reject(Wire.Active(), Wire.Frame(kind, 2, payload, Wire.OtherItem), WorkerStreamError.IdMismatch);
26추가: }
27추가: var between = new WorkerStreamValidator(Wire.Job);
28추가: Wire.Accept(between, Wire.Begin);
29추가: Reject(between, Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(0)), WorkerStreamError.IdMismatch);
30추가: Reject(Wire.Active(), Wire.Frame(WorkerStreamFrameKind.EndJob, 2, [2], Wire.Item), WorkerStreamError.IdMismatch);
31추가: return Task.CompletedTask;
32추가: }
33추가:
34추가: public static Task Sequences()
35추가: {
36추가: foreach (var sequence in new ulong[] { 0, 1, 3, ulong.MaxValue })
37추가: {
38추가: Reject(Wire.Active(), Wire.Frame(WorkerStreamFrameKind.Data, sequence, [7], Wire.Item),
39추가: WorkerStreamError.SequenceMismatch);
40추가: }
41추가: return Task.CompletedTask;
42추가: }
43추가:
44추가: public static Task Transitions()
45추가: {
46추가: Reject(new(Wire.Job), Wire.End(0), WorkerStreamError.UnexpectedFrame);
47추가: Reject(new(Wire.Job), Wire.Frame(WorkerStreamFrameKind.BeginItem, 0, Wire.Length(0), Wire.Item),
48추가: WorkerStreamError.UnexpectedFrame);
49추가: var between = new WorkerStreamValidator(Wire.Job);
50추가: Wire.Accept(between, Wire.Begin);
51추가: Reject(between, Wire.Frame(WorkerStreamFrameKind.Data, 1, [1], Wire.Item),
52추가: WorkerStreamError.UnexpectedFrame);
53추가: Reject(Wire.Active(), Wire.Frame(WorkerStreamFrameKind.BeginItem, 2, Wire.Length(0), Wire.OtherItem),
54추가: WorkerStreamError.UnexpectedFrame);
55추가: Reject(Wire.Active(), Wire.Frame(WorkerStreamFrameKind.BeginJob, 2), WorkerStreamError.UnexpectedFrame);
56추가: return Task.CompletedTask;
57추가: }
58추가:
59추가: public static Task DuplicateItem()
60추가: {
61추가: var validator = Wire.Active(0);
62추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.EndItem, 2, Wire.Length(0), Wire.Item));
63추가: Reject(validator, Wire.Frame(WorkerStreamFrameKind.BeginItem, 3, Wire.Length(0), Wire.Item),
64추가: WorkerStreamError.IdMismatch);
65추가: return Task.CompletedTask;
66추가: }
67추가:
68추가: public static Task ItemLengths()
69추가: {
70추가: Reject(Wire.Active(1), Wire.Frame(WorkerStreamFrameKind.EndItem, 2, Wire.Length(0), Wire.Item),
71추가: WorkerStreamError.InvalidLength);
72추가: var validator = Wire.Active(1);
73추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item));
74추가: Reject(validator, Wire.Frame(WorkerStreamFrameKind.EndItem, 3, Wire.Length(ulong.MaxValue), Wire.Item),
75추가: WorkerStreamError.InvalidLength);
76추가: Reject(Wire.Active(0), Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item),
77추가: WorkerStreamError.BudgetExceeded);
78추가: return Task.CompletedTask;
79추가: }
80추가:
81추가: public static Task TerminalStatus()
82추가: {
83추가: Reject(Wire.Active(), Wire.End(2), WorkerStreamError.UnexpectedFrame);
84추가: foreach (var status in new byte[] { 0, 4, 255 })
85추가: {
86추가: Reject(Wire.Active(), Wire.End(2, status), WorkerStreamError.UnexpectedFrame);
87추가: }
88추가: foreach (var status in new byte[] { 2, 3 })
89추가: {
90추가: var validator = Wire.Active(1);
91추가: Wire.Accept(validator, Wire.End(2, status));
92추가: Check.Equal(WorkerStreamPhase.Terminal, validator.Phase);
93추가: validator.CompleteInput();
94추가: Check.Equal(WorkerStreamPhase.InputCompleted, validator.Phase);
95추가: Check.Equal<WorkerStreamTerminalStatus?>((WorkerStreamTerminalStatus)status, validator.TerminalStatus);
96추가: }
97추가: return Task.CompletedTask;
98추가: }
99추가:
100추가: public static Task Limits()
101추가: {
102추가: var defaults = new WorkerStreamLimits();
103추가: foreach (var value in new[]
104추가: {
105추가: defaults with { MaxDataBytes = -1 }, defaults with { MaxDataBytes = long.MaxValue },
106추가: defaults with { MaxWireBytes = 128 }, defaults with { MaxWireBytes = long.MaxValue },
107추가: defaults with { MaxItems = -1 }, defaults with { MaxItems = int.MaxValue },
108추가: defaults with { MaxFrames = 1 }, defaults with { MaxFrames = int.MaxValue },
109추가: defaults with { MaxDuration = TimeSpan.Zero }, defaults with { MaxDuration = TimeSpan.MaxValue }
110추가: })
111추가: {
112추가: Check.Throws<ArgumentOutOfRangeException>(() => new WorkerStreamValidator(Wire.Job, value));
113추가: }
114추가: Check.Throws<ArgumentException>(() => new WorkerStreamValidator(Guid.Empty));
115추가: var minimal = new WorkerStreamValidator(Wire.Job, defaults with
116추가: {
117추가: MaxDataBytes = 0, MaxItems = 0, MaxFrames = 2, MaxWireBytes = 129
118추가: });
119추가: Wire.Accept(minimal, Wire.Begin);
120추가: Wire.Accept(minimal, Wire.End(1));
121추가: minimal.CompleteInput();
122추가: Check.Equal(129L, minimal.TotalWireBytes);
123추가: return Task.CompletedTask;
124추가: }
125추가:
126추가: public static Task HeaderValidationDoesNotSpend()
127추가: {
128추가: var validator = new WorkerStreamValidator(Wire.Job);
129추가: validator.ValidateHeader(Wire.Begin.Header);
130추가: validator.ValidateHeader(Wire.Begin.Header);
131추가: Check.Equal(0, validator.FramesAccepted);
132추가: Check.Equal(0L, validator.TotalWireBytes);
133추가: Wire.Accept(validator, Wire.Begin);
134추가: Check.Equal(1, validator.FramesAccepted);
135추가: Check.Equal(64L, validator.TotalWireBytes);
136추가: return Task.CompletedTask;
137추가: }
138추가:
139추가: public static Task WireBudget()
140추가: {
141추가: foreach (var budget in new long[] { 129, 273 })
142추가: {
143추가: var validator = new WorkerStreamValidator(Wire.Job, new() { MaxWireBytes = budget });
144추가: Wire.Accept(validator, Wire.Begin);
145추가: if (budget == 273)
146추가: {
147추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(0), Wire.Item));
148추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.EndItem, 2, Wire.Length(0), Wire.Item));
149추가: }
150추가: Wire.Accept(validator, Wire.End((ulong)validator.FramesAccepted));
151추가: Check.Equal(budget, validator.TotalWireBytes);
152추가: }
153추가: var insufficient = new WorkerStreamValidator(Wire.Job, new() { MaxWireBytes = 272 });
154추가: Wire.Accept(insufficient, Wire.Begin);
155추가: Wire.Accept(insufficient, Wire.Frame(WorkerStreamFrameKind.BeginItem, 1, Wire.Length(0), Wire.Item));
156추가: Wire.Accept(insufficient, Wire.Frame(WorkerStreamFrameKind.EndItem, 2, Wire.Length(0), Wire.Item));
157추가: Reject(insufficient, Wire.End(3), WorkerStreamError.BudgetExceeded);
158추가: return Task.CompletedTask;
159추가: }
160추가:
161추가: public static Task DataBudget()
162추가: {
163추가: // 64 KiB 버퍼 하나를 재사용해 16 MiB 누적 경계만 검사함.
164추가: var validator = new WorkerStreamValidator(Wire.Job);
165추가: Wire.Accept(validator, Wire.Begin);
166추가: var chunk = new byte[65536];
167추가: foreach (var id in new[] { Wire.Item, Wire.OtherItem })
168추가: {
169추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.BeginItem,
170추가: (ulong)validator.FramesAccepted, Wire.Length(8 * 1024 * 1024), id));
171추가: for (var index = 0; index < 128; index++)
172추가: {
173추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.Data,
174추가: (ulong)validator.FramesAccepted, chunk, id));
175추가: }
176추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.EndItem,
177추가: (ulong)validator.FramesAccepted, Wire.Length(8 * 1024 * 1024), id));
178추가: }
179추가: Check.Equal(16L * 1024 * 1024, validator.TotalDataBytes);
180추가: Wire.Accept(validator, Wire.End((ulong)validator.FramesAccepted));
181추가: validator.CompleteInput();
182추가:
183추가: var limited = Wire.Active(1, new() { MaxDataBytes = 1 });
184추가: Wire.Accept(limited, Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item));
185추가: Wire.Accept(limited, Wire.Frame(WorkerStreamFrameKind.EndItem, 3, Wire.Length(1), Wire.Item));
186추가: Reject(limited, Wire.Frame(WorkerStreamFrameKind.BeginItem, 4, Wire.Length(1), Wire.OtherItem),
187추가: WorkerStreamError.BudgetExceeded);
188추가: return Task.CompletedTask;
189추가: }
190추가:
191추가: public static Task FrameBudget()
192추가: {
193추가: var validator = Wire.Active(2, new() { MaxFrames = 5 });
194추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item));
195추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.Data, 3, [2], Wire.Item));
196추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.EndItem, 4, Wire.Length(2), Wire.Item));
197추가: Check.Equal(5, validator.FramesAccepted);
198추가: Reject(validator, Wire.End(5), WorkerStreamError.BudgetExceeded);
199추가: return Task.CompletedTask;
200추가: }
201추가:
202추가: public static Task ItemBudget()
203추가: {
204추가: var validator = Wire.Active(0, new() { MaxItems = 1 });
205추가: Wire.Accept(validator, Wire.Frame(WorkerStreamFrameKind.EndItem, 2, Wire.Length(0), Wire.Item));
206추가: Check.Equal(1, validator.ItemsAccepted);
207추가: Reject(validator, Wire.Frame(WorkerStreamFrameKind.BeginItem, 3, Wire.Length(0), Wire.OtherItem),
208추가: WorkerStreamError.BudgetExceeded);
209추가: return Task.CompletedTask;
210추가: }
211추가:
212추가: public static Task ArithmeticLengths()
213추가: {
214추가: foreach (var length in new[] { int.MinValue, -1, 0, 65537, int.MaxValue })
215추가: {
216추가: var frame = Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item);
217추가: Reject(Wire.Active(), frame with { Header = frame.Header with { PayloadLength = length } },
218추가: WorkerStreamError.InvalidLength);
219추가: }
220추가: var validator = Wire.Active();
221추가: var mismatched = Wire.Frame(WorkerStreamFrameKind.Data, 2, [1], Wire.Item) with { Payload = new byte[2] };
222추가: Reject(validator, mismatched, WorkerStreamError.InvalidLength);
223추가: return Task.CompletedTask;
224추가: }
225추가: }
추가tests/stream-protocol/Zipelo.StreamProtocolTests.csproj+18-0
@@ -0,0 +1,18 @@
1추가: <Project Sdk="Microsoft.NET.Sdk">
2추가: <PropertyGroup>
3추가: <OutputType>Exe</OutputType>
4추가: <TargetFramework>net10.0</TargetFramework>
5추가: <Nullable>enable</Nullable>
6추가: <ImplicitUsings>enable</ImplicitUsings>
7추가: <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
8추가: <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
9추가: </PropertyGroup>
10추가: <ItemGroup>
11추가: <Compile Include="Program.cs" />
12추가: <Compile Include="TestSupport.cs" />
13추가: <Compile Include="ControlledStream.cs" />
14추가: <Compile Include="ChannelTests.cs" />
15추가: <Compile Include="ValidatorTests.cs" />
16추가: <ProjectReference Include="../../src/Zipelo.Runtime/Zipelo.Runtime.csproj" />
17추가: </ItemGroup>
18추가: </Project>
추가tests/stream-protocol/contract.json+103-0
@@ -0,0 +1,103 @@
1추가: {
2추가: "schema_version": 1,
3추가: "base_commit": "260428ec8836bf122589d995c7526468a09e190d",
4추가: "dependency": {
5추가: "pr": "https://github.com/Team-LJY/zipelo/pull/7",
6추가: "head": "6fe660aa914dec9e4d2f4c8f85e8ff3932a805a6",
7추가: "files": {
8추가: "src/Zipelo.Runtime/Streaming/WorkerStreamContract.cs": "0e8e8c21478224d6ed861e50a5ec310dce8b6af522ce3d66e4f899a926cf7a94",
9추가: "src/Zipelo.Runtime/Streaming/WorkerStreamValidator.cs": "933e93fc4d4cae7ac9e1bc0621ed0598994ff057ff0c320c7dc5f7cc59ada09a",
10추가: "src/Zipelo.Runtime/Streaming/WorkerStreamChannel.cs": "4109e345138763df3ecec0368755660b5891349567908ac7ddb996b38ca94046"
11추가: },
12추가: "original_requested_head": "1235f8e2f3bf0d505ed7e7c9dffc74332827f2bf",
13추가: "update": "종료 상태 우선순위 수정이 작업 중 추가됨. InputCompleted 재읽기와 Faulted 재읽기는 취소/만료 기한보다 먼저 확정 상태를 처리함. 새 회귀 사례는 이전 1235f8e2의 재읽기 결함을 통과로 완화하지 않음"
14추가: },
15추가: "registered_cases": [
16추가: "wire.empty_job",
17추가: "wire.empty_item",
18추가: "wire.one_byte",
19추가: "wire.chunk_boundaries",
20추가: "wire.fragmented_reads",
21추가: "wire.golden_64_byte_header",
22추가: "wire.all_header_truncations",
23추가: "wire.metadata_and_data_truncations",
24추가: "wire.magic_version_reserved",
25추가: "wire.kind_length_and_uint_overflow",
26추가: "wire.huge_declaration_allocation_bound",
27추가: "state.job_and_item_ids",
28추가: "state.sequence_duplicate_gap_overflow",
29추가: "state.missing_and_nested_transitions",
30추가: "state.duplicate_item_id",
31추가: "state.actual_declared_end_lengths",
32추가: "state.status_and_open_item",
33추가: "state.failed_cancelled_eof",
34추가: "state.eof_before_terminal",
35추가: "state.trailing_byte_duplicate_end",
36추가: "state.terminal_without_eof_deadline",
37추가: "state.final_status_over_cancel_and_deadline",
38추가: "budget.invalid_limits",
39추가: "budget.validate_header_does_not_spend",
40추가: "budget.wire_exact_and_one_short",
41추가: "budget.data_cumulative_16mib",
42추가: "budget.small_chunk_frame_count",
43추가: "budget.empty_item_count",
44추가: "budget.signed_and_payload_lengths",
45추가: "cancel.before_io",
46추가: "cancel.read_header",
47추가: "cancel.read_body",
48추가: "cancel.write_header",
49추가: "cancel.write_body",
50추가: "cancel.write_flush",
51추가: "deadline.read_wait",
52추가: "deadline.write_wait",
53추가: "deadline.between_calls",
54추가: "flow.slow_producer",
55추가: "flow.slow_consumer_snapshot",
56추가: "flow.flush_completion",
57추가: "fault.read_io_and_reuse",
58추가: "fault.write_io_and_reuse",
59추가: "api.concurrent_call_and_dispose",
60추가: "api.direction_stream_lifetime",
61추가: "api.invalid_write_before_output"
62추가: ],
63추가: "registered_count": 46,
64추가: "commands": {
65추가: "build": "dotnet build tests/stream-protocol/Zipelo.StreamProtocolTests.csproj -c Release --configfile tests/stream-protocol/NuGet.Config --artifacts-path tests/stream-protocol/.work/artifacts -o tests/stream-protocol/.work/bin -p:UseAppHost=false --disable-build-servers",
66추가: "list": "dotnet tests/stream-protocol/.work/bin/Zipelo.StreamProtocolTests.dll --list",
67추가: "run": "dotnet tests/stream-protocol/.work/bin/Zipelo.StreamProtocolTests.dll",
68추가: "self_contained": "중앙 SDK 환경에서 같은 프로젝트를 OS별 RID와 --self-contained true로 별도 tests/stream-protocol/.work 출력에 게시한 뒤 Zipelo.StreamProtocolTests 앱호스트를 무인수 실행함. Windows만 .exe를 붙임"
69추가: },
70추가: "scope": "기존 98개, PR #6, v1 실행 경로와 16 MiB 상한은 변경하지 않음. 이 프로젝트는 파일을 열거나 Worker 프로세스를 시작하지 않는 메모리 전송 계약 검사임",
71추가: "bounds": {
72추가: "header_bytes": 64,
73추가: "chunk_bytes": 65536,
74추가: "default_data_bytes": 16777216,
75추가: "default_wire_bytes": 22020096,
76추가: "large_cumulative_test": "64 KiB 배열 하나를 두 항목에서 256번 재사용함. 16 MiB 실제 파일이나 전체 결과 배열을 생성하지 않음",
77추가: "roundtrip": "최대 정상 왕복 페이로드 합계 131071바이트. 프레임 및 출력 복사는 이 작은 입력 크기로 제한됨",
78추가: "hostile_lengths": "고정 64바이트 헤더 또는 8바이트 선언만 제공함. 거절 시 본문 접근 금지와 동일 스레드의 동기 완료 호출당 1 MiB 미만 할당을 요구함. 이는 프로세스 최대 메모리/성능 측정이 아님",
79추가: "waiting": "게이트 1개와 협조적 취소를 사용함. 대기 진입 확인 4초, 사례별 8초 상한. 전체 기한 검사는 40/180/250ms 제한을 사용함. 매우 느린 검증 환경의 실패는 로그를 보고 분리해야 함"
80추가: },
81추가: "validation": {
82추가: "static": "passed: XML/JSON, 46 unique registrations, 5 explicit compile items, dependency SHA-256, golden header size, formatting and delimiter inspection; not C# compilation",
83추가: "compile": "not_run: local SDK absent",
84추가: "windows": "not_run",
85추가: "ubuntu": "not_run"
86추가: },
87추가: "limitations": [
88추가: "실제 stdin/stdout 파이프와 Worker 프로세스 통합은 PR #7 범위 밖이며 미검증",
89추가: "취소를 무시하는 Stream의 강제 중단, 디스크 게시/CRC/경로, 양방향 예산은 검증하지 않음",
90추가: "큰 실제 파일의 처리량과 최대 메모리 개선을 주장하지 않음",
91추가: "반환 프레임을 호출자가 무제한 보관하는 상황은 다루지 않음"
92추가: ],
93추가: "files": [
94추가: "tests/stream-protocol/ChannelTests.cs",
95추가: "tests/stream-protocol/ControlledStream.cs",
96추가: "tests/stream-protocol/NuGet.Config",
97추가: "tests/stream-protocol/Program.cs",
98추가: "tests/stream-protocol/TestSupport.cs",
99추가: "tests/stream-protocol/ValidatorTests.cs",
100추가: "tests/stream-protocol/Zipelo.StreamProtocolTests.csproj",
101추가: "tests/stream-protocol/contract.json"
102추가: ]
103추가: }