|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Net; |
| 7 | +using System.Reflection; |
| 8 | +using Microsoft.AspNetCore.Builder; |
| 9 | +using Microsoft.AspNetCore.Hosting; |
| 10 | +using Microsoft.AspNetCore.Hosting.Server.Features; |
| 11 | +using Microsoft.AspNetCore.Http; |
| 12 | +using Microsoft.Extensions.DependencyInjection; |
| 13 | + |
| 14 | +namespace Azure.Template.Perf |
| 15 | +{ |
| 16 | + public class InProcTestServer : IStartup, IDisposable |
| 17 | + { |
| 18 | + // Stream.CopyToAsync default buffer |
| 19 | + private const int BufferSize = 81920; |
| 20 | + |
| 21 | + private readonly RequestDelegate _app; |
| 22 | + private readonly IWebHost _host; |
| 23 | + |
| 24 | + public Uri Address => new Uri(_host.ServerFeatures.Get<IServerAddressesFeature>().Addresses.First()); |
| 25 | + |
| 26 | + public InProcTestServer(RequestDelegate app) |
| 27 | + { |
| 28 | + _app = app; |
| 29 | + _host = new WebHostBuilder() |
| 30 | + .UseKestrel(options => options.Listen(new IPEndPoint(IPAddress.Loopback, 0))) |
| 31 | + .ConfigureServices(services => { services.AddSingleton<IStartup>(this); }) |
| 32 | + .UseSetting(WebHostDefaults.ApplicationKey, typeof(InProcTestServer).GetTypeInfo().Assembly.FullName) |
| 33 | + .Build(); |
| 34 | + |
| 35 | + _host.Start(); |
| 36 | + } |
| 37 | + |
| 38 | + IServiceProvider IStartup.ConfigureServices(IServiceCollection services) |
| 39 | + { |
| 40 | + return services.BuildServiceProvider(); |
| 41 | + } |
| 42 | + |
| 43 | + void IStartup.Configure(IApplicationBuilder app) |
| 44 | + { |
| 45 | + app.Run(_app); |
| 46 | + } |
| 47 | + |
| 48 | + public void Dispose() |
| 49 | + { |
| 50 | + _host?.Dispose(); |
| 51 | + } |
| 52 | + |
| 53 | + public static InProcTestServer CreateStaticResponse(long size) |
| 54 | + { |
| 55 | + var buffer = new byte[BufferSize]; |
| 56 | + return new InProcTestServer(async context => |
| 57 | + { |
| 58 | + long left = size; |
| 59 | + while (left > 0) |
| 60 | + { |
| 61 | + var amountToWrite = (int)Math.Min(left, buffer.Length); |
| 62 | + await context.Response.Body.WriteAsync(buffer, 0, amountToWrite); |
| 63 | + left -= amountToWrite; |
| 64 | + } |
| 65 | + }); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments