-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
WriteAsync.cs
375 lines (325 loc) · 15.8 KB
/
WriteAsync.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
{
public abstract class FileStream_AsyncWrites : FileSystemTest
{
private Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count) =>
WriteAsync(stream, buffer, offset, count, CancellationToken.None);
protected abstract Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken);
[Fact]
public void WriteAsyncDisposedThrows()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
fs.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
// even for noop WriteAsync
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 0)));
// out of bounds checking happens first
Assert.Throws<ArgumentOutOfRangeException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2)));
}
}
[Fact]
public void ReadOnlyThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{ }
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
Assert.Throws<NotSupportedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
fs.Dispose();
// Disposed checking happens first
Assert.Throws<ObjectDisposedException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, 1)));
// out of bounds checking happens first
Assert.Throws<ArgumentOutOfRangeException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2)));
}
}
[Fact]
public async Task NoopWriteAsyncsSucceed()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
// note that these do not succeed synchronously even though they do nothing.
await WriteAsync(fs, new byte[0], 0, 0);
await WriteAsync(fs, new byte[1], 0, 0);
// even though offset is out of bounds of buffer, this is still allowed
// for the last element
await WriteAsync(fs, new byte[1], 1, 0);
await WriteAsync(fs, new byte[2], 1, 0);
Assert.Equal(0, fs.Length);
Assert.Equal(0, fs.Position);
}
}
[Fact]
public void WriteAsyncBufferedCompletesSynchronously()
{
using (FileStream fs = new FileStream(
GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete,
TestBuffer.Length * 2, useAsync: true))
{
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[TestBuffer.Length], 0, TestBuffer.Length));
}
}
[Fact]
public async Task SimpleWriteAsync()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
await WriteAsync(fs, TestBuffer, 0, TestBuffer.Length);
Assert.Equal(TestBuffer.Length, fs.Length);
Assert.Equal(TestBuffer.Length, fs.Position);
fs.Position = 0;
byte[] buffer = new byte[TestBuffer.Length];
Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(TestBuffer, buffer);
}
}
[Fact]
public async Task WriteAsyncCancelledFile()
{
const int writeSize = 1024 * 1024;
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
{
byte[] buffer = new byte[writeSize];
CancellationTokenSource cts = new CancellationTokenSource();
Task writeTask = WriteAsync(fs, buffer, 0, buffer.Length, cts.Token);
cts.Cancel();
try
{
await writeTask;
}
catch (OperationCanceledException oce)
{
// Ideally we'd be doing an Assert.Throws<OperationCanceledException>
// but since cancellation is a race condition we accept either outcome
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
}
[Fact]
public async Task WriteAsyncInternalBufferOverflow()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write, FileShare.None, 3, useAsync: true))
{
// Fill buffer; should trigger flush of full buffer, no additional I/O
await WriteAsync(fs, TestBuffer, 0, 3);
Assert.True(fs.Length == 3);
// Add to next buffer
await WriteAsync(fs, TestBuffer, 0, 1);
Assert.True(fs.Length == 4);
// Complete that buffer; should trigger flush of full buffer, no additional I/O
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 6);
// Add to next buffer
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 8);
// Overflow buffer with amount that could fit in a buffer; should trigger a flush, with additional I/O
await WriteAsync(fs, TestBuffer, 0, 2);
Assert.True(fs.Length == 10);
// Overflow buffer with amount that couldn't fit in a buffer; shouldn't be anything to flush, just an additional I/O
await WriteAsync(fs, TestBuffer, 0, 4);
Assert.True(fs.Length == 14);
}
}
public static IEnumerable<object[]> MemberData_FileStreamAsyncWriting()
{
foreach (bool useAsync in new[] { true, false })
{
if (useAsync && !OperatingSystem.IsWindows())
{
// We don't have a special async I/O implementation in FileStream on Unix.
continue;
}
foreach (bool preSize in new[] { true, false })
{
foreach (bool cancelable in new[] { true, false })
{
yield return new object[] { useAsync, preSize, false, cancelable, 0x1000, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x1, 0x1, 1000 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x2, 0x100, 100 };
yield return new object[] { useAsync, preSize, false, cancelable, 0x4000, 0x10, 100 };
yield return new object[] { useAsync, preSize, true, cancelable, 0x1000, 99999, 10 };
}
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] // Browser PNSE: Cannot wait on monitors
public Task ManyConcurrentWriteAsyncs()
{
// For inner loop, just test one case
return ManyConcurrentWriteAsyncs_OuterLoop(
useAsync: OperatingSystem.IsWindows(),
presize: false,
exposeHandle: false,
cancelable: true,
bufferSize: 4096,
writeSize: 1024,
numWrites: 10);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[MemberData(nameof(MemberData_FileStreamAsyncWriting))]
[OuterLoop] // many combinations: we test just one in inner loop and the rest outer
public async Task ManyConcurrentWriteAsyncs_OuterLoop(
bool useAsync, bool presize, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites)
{
long totalLength = writeSize * numWrites;
var expectedData = new byte[totalLength];
new Random(42).NextBytes(expectedData);
CancellationToken cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None;
string path = GetTestFilePath();
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
if (presize)
{
fs.SetLength(totalLength);
}
if (exposeHandle)
{
_ = fs.SafeFileHandle;
}
Task[] writes = new Task[numWrites];
for (int i = 0; i < numWrites; i++)
{
writes[i] = WriteAsync(fs, expectedData, i * writeSize, writeSize, cancellationToken);
Assert.Null(writes[i].Exception);
if (useAsync)
{
Assert.Equal((i + 1) * writeSize, fs.Position);
}
}
await Task.WhenAll(writes);
}
byte[] actualData = File.ReadAllBytes(path);
Assert.Equal(expectedData.Length, actualData.Length);
if (useAsync)
{
Assert.Equal<byte>(expectedData, actualData);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task BufferCorrectlyMaintainedWhenReadAndWrite(bool useAsync)
{
string path = GetTestFilePath();
File.WriteAllBytes(path, TestBuffer);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 2, useAsync))
{
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
await WriteAsync(fs, TestBuffer, 0, TestBuffer.Length);
fs.Position = 0;
Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
for (int i = 0; i < TestBuffer.Length; i++)
{
Assert.Equal(TestBuffer[i], await ReadByteAsync(fs));
}
}
}
private static async Task<byte> ReadByteAsync(FileStream fs)
{
byte[] oneByte = new byte[1];
Assert.Equal(1, await fs.ReadAsync(oneByte, 0, 1));
return oneByte[0];
}
[Fact, OuterLoop]
public async Task WriteAsyncMiniStress()
{
TimeSpan testRunTime = TimeSpan.FromSeconds(10);
const int MaximumWriteSize = 16 * 1024;
const int NormalWriteSize = 4 * 1024;
Random rand = new Random();
DateTime testStartTime = DateTime.UtcNow;
// Generate data to write (NOTE: Randomizing this is important as some file systems may optimize writing 0s)
byte[] dataToWrite = new byte[MaximumWriteSize];
rand.NextBytes(dataToWrite);
string writeFileName = GetTestFilePath();
do
{
int totalBytesWritten = 0;
using (var stream = new FileStream(writeFileName, FileMode.Create, FileAccess.Write))
{
do
{
// 20%: random write size
int bytesToWrite = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumWriteSize) : NormalWriteSize);
if (rand.NextDouble() < 0.1)
{
// 10%: Sync write
stream.Write(dataToWrite, 0, bytesToWrite);
}
else
{
// 90%: Async write
await WriteAsync(stream, dataToWrite, 0, bytesToWrite);
}
totalBytesWritten += bytesToWrite;
// Cap written bytes at 10 million to avoid writing too much to disk
} while (totalBytesWritten < 10_000_000);
}
} while (DateTime.UtcNow - testStartTime <= testRunTime);
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/34583", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public class FileStream_WriteAsync_AsyncWrites : FileStream_AsyncWrites
{
protected override Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
stream.WriteAsync(buffer, offset, count, cancellationToken);
[Fact]
public void CancelledTokenFastPath()
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
CancellationToken cancelledToken = cts.Token;
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
// before read only check
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
fs.Dispose();
// before disposed check
FSAssert.IsCancelled(WriteAsync(fs, new byte[1], 0, 1, cancelledToken), cancelledToken);
// out of bounds checking happens first
Assert.Throws<ArgumentOutOfRangeException>(() =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[2], 1, 2, cancelledToken)));
// count is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], 0, -1, cancelledToken)));
// offset is checked prior
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, new byte[1], -1, -1, cancelledToken)));
// buffer is checked first
AssertExtensions.Throws<ArgumentNullException>("buffer", () =>
FSAssert.CompletesSynchronously(WriteAsync(fs, null, -1, -1, cancelledToken)));
}
}
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/34583", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public class FileStream_BeginEndWrite_AsyncWrites : FileStream_AsyncWrites
{
protected override Task WriteAsync(FileStream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
Task.Factory.FromAsync(
(callback, state) => stream.BeginWrite(buffer, offset, count, callback, state),
iar => stream.EndWrite(iar),
null);
}
}