forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownlevelExtensions.cs
More file actions
617 lines (549 loc) · 21.1 KB
/
Copy pathDownlevelExtensions.cs
File metadata and controls
617 lines (549 loc) · 21.1 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using System.Buffers;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System
{
internal static class DownlevelArgumentNullExceptionExtensions
{
extension(ArgumentNullException)
{
public static void ThrowIfNull(object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
{
if (argument is null)
{
throw new ArgumentNullException(paramName);
}
}
}
}
internal static class DownlevelObjectDisposedExceptionExtensions
{
extension(ObjectDisposedException)
{
public static void ThrowIf(bool condition, object instance)
{
if (condition)
{
throw new ObjectDisposedException(instance?.GetType().FullName);
}
}
}
}
internal static class DownlevelArgumentExceptionExtensions
{
extension(ArgumentException)
{
public static void ThrowIfNullOrWhiteSpace(string? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
{
if (argument is null)
{
throw new ArgumentNullException(paramName);
}
if (string.IsNullOrWhiteSpace(argument))
{
throw new ArgumentException("The value cannot be an empty string or composed entirely of whitespace.", paramName);
}
}
}
}
internal static class DownlevelDateTimeExtensions
{
extension(DateTime)
{
public static DateTime UnixEpoch => new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
}
internal static class DownlevelDateTimeOffsetExtensions
{
extension(DateTimeOffset)
{
public static DateTimeOffset UnixEpoch => new(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
}
}
internal static class DownlevelIntExtensions
{
extension(int)
{
public static bool TryParse(ReadOnlySpan<byte> utf8Text, NumberStyles style, IFormatProvider? provider, out int result)
{
if (style == NumberStyles.None)
{
return TryParseNonNegativeInt32(utf8Text, out result);
}
return int.TryParse(Encoding.UTF8.GetString(utf8Text.ToArray()), style, provider, out result);
}
}
private static bool TryParseNonNegativeInt32(ReadOnlySpan<byte> utf8Text, out int result)
{
if (utf8Text.IsEmpty)
{
result = 0;
return false;
}
var value = 0;
foreach (var c in utf8Text)
{
var digit = c - (byte)'0';
if ((uint)digit > 9)
{
result = 0;
return false;
}
if (value > (int.MaxValue - digit) / 10)
{
result = 0;
return false;
}
value = (value * 10) + digit;
}
result = value;
return true;
}
}
internal static class DownlevelOperatingSystemExtensions
{
extension(OperatingSystem)
{
public static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
public static bool IsMacOS() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
}
}
internal static class DownlevelDisposableExtensions
{
extension(IDisposable disposable)
{
public ValueTask DisposeAsync()
{
disposable.Dispose();
return default;
}
}
}
}
namespace System.Collections.Generic
{
internal static class DownlevelKeyValuePairExtensions
{
extension<TKey, TValue>(KeyValuePair<TKey, TValue> pair)
{
public void Deconstruct(out TKey key, out TValue value)
{
key = pair.Key;
value = pair.Value;
}
}
}
}
namespace System.Diagnostics
{
internal static class DownlevelStopwatchExtensions
{
extension(Stopwatch)
{
public static TimeSpan GetElapsedTime(long startingTimestamp) =>
GetElapsedTime(startingTimestamp, Stopwatch.GetTimestamp());
public static TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp)
{
var elapsedTicks = endingTimestamp - startingTimestamp;
return TimeSpan.FromTicks((long)(elapsedTicks * ((double)TimeSpan.TicksPerSecond / Stopwatch.Frequency)));
}
}
}
internal static class DownlevelProcessExtensions
{
extension(Process process)
{
public void Kill(bool entireProcessTree)
{
if (entireProcessTree)
{
if (OperatingSystem.IsWindows())
{
using var taskKill = Process.Start(new ProcessStartInfo
{
FileName = "taskkill.exe",
Arguments = string.Format(CultureInfo.InvariantCulture, "/PID {0} /T /F", process.Id),
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
});
if (taskKill is not null &&
taskKill.WaitForExit(milliseconds: 30_000) &&
(taskKill.ExitCode == 0 || process.HasExited))
{
return;
}
}
else
{
KillDescendantProcesses(process.Id);
}
}
if (!process.HasExited)
{
process.Kill();
}
}
public Task WaitForExitAsync(Threading.CancellationToken cancellationToken = default)
{
if (process.HasExited)
{
return Task.CompletedTask;
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
var completion = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler handler = (_, _) => completion.TrySetResult(null);
process.EnableRaisingEvents = true;
process.Exited += handler;
if (process.HasExited)
{
completion.TrySetResult(null);
}
var cancellationRegistration = cancellationToken.CanBeCanceled
? cancellationToken.Register(static state => ((TaskCompletionSource<object?>)state!).TrySetCanceled(), completion)
: default;
return WaitForExitAsyncCore(process, completion.Task, handler, cancellationRegistration);
}
}
private static async Task WaitForExitAsyncCore(
Process process,
Task waitTask,
EventHandler handler,
Threading.CancellationTokenRegistration cancellationRegistration)
{
using var _ = cancellationRegistration;
try
{
await waitTask.ConfigureAwait(false);
}
finally
{
process.Exited -= handler;
}
}
private static void KillDescendantProcesses(int parentProcessId)
{
foreach (var childProcessId in GetChildProcessIds(parentProcessId))
{
KillDescendantProcesses(childProcessId);
try
{
using var childProcess = Process.GetProcessById(childProcessId);
if (!childProcess.HasExited)
{
childProcess.Kill();
}
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or Win32Exception or PlatformNotSupportedException)
{
IgnoreBestEffortProcessException(ex);
}
}
}
private static List<int> GetChildProcessIds(int parentProcessId)
{
var childProcessIds = new List<int>();
try
{
using var pgrep = Process.Start(new ProcessStartInfo
{
FileName = "pgrep",
Arguments = string.Format(CultureInfo.InvariantCulture, "-P {0}", parentProcessId),
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
});
if (pgrep is null)
{
return childProcessIds;
}
var output = pgrep.StandardOutput.ReadToEnd();
if (!pgrep.WaitForExit(milliseconds: 5_000))
{
pgrep.Kill();
return childProcessIds;
}
childProcessIds.AddRange(
output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
.Select(static line =>
{
var success = int.TryParse(line, NumberStyles.None, CultureInfo.InvariantCulture, out var childProcessId);
return (success, childProcessId);
})
.Where(static result => result.success)
.Select(static result => result.childProcessId));
}
catch (Exception ex) when (ex is ObjectDisposedException or InvalidOperationException or Win32Exception or PlatformNotSupportedException)
{
IgnoreBestEffortProcessException(ex);
}
return childProcessIds;
}
private static void IgnoreBestEffortProcessException(Exception exception) =>
Debug.WriteLine(exception.ToString());
}
}
namespace System.IO
{
internal static class DownlevelStreamExtensions
{
extension(Stream stream)
{
public ValueTask<int> ReadAsync(Memory<byte> buffer, Threading.CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> segment))
{
return new ValueTask<int>(stream.ReadAsync(segment.Array!, segment.Offset, segment.Count, cancellationToken));
}
return ReadAsyncSlow(stream, buffer, cancellationToken);
}
public ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, Threading.CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> segment))
{
return new ValueTask(stream.WriteAsync(segment.Array!, segment.Offset, segment.Count, cancellationToken));
}
return WriteAsyncSlow(stream, buffer, cancellationToken);
}
public async ValueTask ReadExactlyAsync(Memory<byte> buffer, Threading.CancellationToken cancellationToken = default)
{
var totalRead = 0;
while (totalRead < buffer.Length)
{
var bytesRead = await stream.ReadAsync(buffer.Slice(totalRead), cancellationToken).ConfigureAwait(false);
if (bytesRead <= 0)
{
throw new EndOfStreamException();
}
totalRead += bytesRead;
}
}
}
private static async ValueTask<int> ReadAsyncSlow(Stream stream, Memory<byte> buffer, Threading.CancellationToken cancellationToken)
{
var rented = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
var bytesRead = await stream.ReadAsync(rented, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
rented.AsMemory(0, bytesRead).CopyTo(buffer);
return bytesRead;
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
}
private static async ValueTask WriteAsyncSlow(Stream stream, ReadOnlyMemory<byte> buffer, Threading.CancellationToken cancellationToken)
{
var rented = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
buffer.CopyTo(rented);
await stream.WriteAsync(rented, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
}
}
internal static class DownlevelTextReaderExtensions
{
extension(TextReader reader)
{
public Task<string?> ReadLineAsync(Threading.CancellationToken cancellationToken)
{
var task = reader.ReadLineAsync();
return cancellationToken.CanBeCanceled
? WaitAsync(task, cancellationToken)
: task;
}
}
private static async Task<T> WaitAsync<T>(Task<T> task, Threading.CancellationToken cancellationToken)
{
if (task.IsCompleted || !cancellationToken.CanBeCanceled)
{
return await task.ConfigureAwait(false);
}
var cancellationTask = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
using var registration = cancellationToken.Register(static state => ((TaskCompletionSource<object?>)state!).TrySetCanceled(), cancellationTask);
if (await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false) != task)
{
throw new OperationCanceledException(cancellationToken);
}
return await task.ConfigureAwait(false);
}
}
}
namespace System.Net.Sockets
{
internal static class DownlevelSocketExtensions
{
extension(Socket socket)
{
public Task ConnectAsync(string host, int port, Threading.CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
var completion = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
var connectState = new SocketConnectState(socket, completion);
try
{
socket.BeginConnect(
host,
port,
static asyncResult =>
{
var connectState = (SocketConnectState)asyncResult.AsyncState!;
try
{
connectState.Socket.EndConnect(asyncResult);
connectState.Completion.TrySetResult(null);
}
catch (SocketException ex)
{
connectState.Completion.TrySetException(ex);
}
catch (ObjectDisposedException ex)
{
connectState.Completion.TrySetException(ex);
}
catch (InvalidOperationException ex)
{
connectState.Completion.TrySetException(ex);
}
catch (Exception ex) when (!IsFatal(ex))
{
connectState.Completion.TrySetException(ex);
}
},
connectState);
}
catch (SocketException ex)
{
completion.TrySetException(ex);
}
catch (ObjectDisposedException ex)
{
completion.TrySetException(ex);
}
catch (InvalidOperationException ex)
{
completion.TrySetException(ex);
}
catch (Exception ex) when (!IsFatal(ex))
{
completion.TrySetException(ex);
}
return cancellationToken.CanBeCanceled
? WaitAsync(completion.Task, socket.Dispose, cancellationToken)
: completion.Task;
}
}
private static async Task WaitAsync(Task task, Action cancellationAction, Threading.CancellationToken cancellationToken)
{
if (task.IsCompleted)
{
await task.ConfigureAwait(false);
return;
}
var cancellationTask = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
using var registration = cancellationToken.Register(
static state =>
{
var cancellationState = (CancellationState)state!;
cancellationState.CancellationAction();
cancellationState.Completion.TrySetCanceled();
},
new CancellationState(cancellationTask, cancellationAction));
if (await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false) != task)
{
throw new OperationCanceledException(cancellationToken);
}
await task.ConfigureAwait(false);
}
private static bool IsFatal(Exception exception) =>
exception is OutOfMemoryException or StackOverflowException or AccessViolationException or AppDomainUnloadedException;
private sealed record CancellationState(TaskCompletionSource<object?> Completion, Action CancellationAction);
private sealed record SocketConnectState(Socket Socket, TaskCompletionSource<object?> Completion);
}
}
namespace System.Runtime.ExceptionServices
{
internal static class DownlevelExceptionDispatchInfoExtensions
{
extension(ExceptionDispatchInfo)
{
public static void Throw(Exception exception)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
}
}
namespace System.Runtime.InteropServices
{
internal static class DownlevelRuntimeInformationExtensions
{
extension(RuntimeInformation)
{
public static string RuntimeIdentifier
{
get
{
var os = OperatingSystem.IsWindows() ? "win" :
OperatingSystem.IsLinux() ? "linux" :
OperatingSystem.IsMacOS() ? "osx" :
RuntimeInformation.OSDescription.ToLowerInvariant().Replace(' ', '-');
var arch = RuntimeInformation.OSArchitecture switch
{
Architecture.X64 => "x64",
Architecture.X86 => "x86",
Architecture.Arm => "arm",
Architecture.Arm64 => "arm64",
_ => RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant(),
};
return $"{os}-{arch}";
}
}
}
}
}
namespace System.Threading
{
internal static class DownlevelCancellationTokenRegistrationExtensions
{
extension(CancellationTokenRegistration registration)
{
public ValueTask DisposeAsync()
{
registration.Dispose();
return default;
}
}
}
}
namespace System.Threading.Tasks
{
internal static class DownlevelValueTaskExtensions
{
extension(ValueTask)
{
public static ValueTask<T> FromResult<T>(T result) => new(result);
}
}
}