Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestHarnessStartup.cs « BrowserDebugHost « wasm « sdks - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6ae4ba32b764c65e747dd54e906f8ac82374738a (plain)
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
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace WebAssembly.Net.Debugging {
	public class TestHarnessStartup {
		static Regex parseConnection = new Regex (@"listening on (ws?s://[^\s]*)");
		public TestHarnessStartup (IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; set; }

		// This method gets called by the runtime. Use this method to add services to the container.
		// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
		public void ConfigureServices (IServiceCollection services)
		{
			services.AddRouting ()
				.Configure<TestHarnessOptions> (Configuration);
		}

		async Task SendNodeVersion (HttpContext context)
		{
			Console.WriteLine ("hello chrome! json/version");
			var resp_obj = new JObject ();
			resp_obj ["Browser"] = "node.js/v9.11.1";
			resp_obj ["Protocol-Version"] = "1.1";

			var response = resp_obj.ToString ();
			await context.Response.WriteAsync (response, new CancellationTokenSource ().Token);
		}

		async Task SendNodeList (HttpContext context)
		{
			Console.WriteLine ("hello chrome! json/list");
			try {
				var response = new JArray (JObject.FromObject (new {
					description = "node.js instance",
					devtoolsFrontendUrl = "chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:9300/91d87807-8a81-4f49-878c-a5604103b0a4",
					faviconUrl = "https://nodejs.org/static/favicon.ico",
					id = "91d87807-8a81-4f49-878c-a5604103b0a4",
					title = "foo.js",
					type = "node",
					webSocketDebuggerUrl = "ws://localhost:9300/91d87807-8a81-4f49-878c-a5604103b0a4"
				})).ToString ();

				Console.WriteLine ($"sending: {response}");
				await context.Response.WriteAsync (response, new CancellationTokenSource ().Token);
			} catch (Exception e) { Console.WriteLine (e); }
		}

		public async Task LaunchAndServe (ProcessStartInfo psi, HttpContext context, Func<string, Task<string>> extract_conn_url)
		{

			if (!context.WebSockets.IsWebSocketRequest) {
				context.Response.StatusCode = 400;
				return;
			}

			var tcs = new TaskCompletionSource<string> ();

			var proc = Process.Start (psi);
			try {
				proc.ErrorDataReceived += (sender, e) => {
					var str = e.Data;
					Console.WriteLine ($"stderr: {str}");

					if (tcs.Task.IsCompleted)
						return;

					var match = parseConnection.Match (str);
					if (match.Success) {
						tcs.TrySetResult (match.Groups[1].Captures[0].Value);
					}
				};

				proc.OutputDataReceived += (sender, e) => {
					Console.WriteLine ($"stdout: {e.Data}");
				};

				proc.BeginErrorReadLine ();
				proc.BeginOutputReadLine ();

				if (await Task.WhenAny (tcs.Task, Task.Delay (5000)) != tcs.Task) {
					Console.WriteLine ("Didnt get the con string after 5s.");
					throw new Exception ("node.js timedout");
				}
				var line = await tcs.Task;
				var con_str = extract_conn_url != null ? await extract_conn_url (line) : line;

				Console.WriteLine ($"launching proxy for {con_str}");

				using var loggerFactory = LoggerFactory.Create(
					builder => builder.AddConsole().AddFilter(null, LogLevel.Information));
				var proxy = new DebuggerProxy (loggerFactory);
				var browserUri = new Uri (con_str);
				var ideSocket = await context.WebSockets.AcceptWebSocketAsync ();

				await proxy.Run (browserUri, ideSocket);
				Console.WriteLine("Proxy done");
			} catch (Exception e) {
				Console.WriteLine ("got exception {0}", e);
			} finally {
				proc.CancelErrorRead ();
				proc.CancelOutputRead ();
				proc.Kill ();
				proc.WaitForExit ();
				proc.Close ();
			}
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure (IApplicationBuilder app, IOptionsMonitor<TestHarnessOptions> optionsAccessor, IWebHostEnvironment env)
		{
			app.UseWebSockets ();
			app.UseStaticFiles ();

			TestHarnessOptions options = optionsAccessor.CurrentValue;

			var provider = new FileExtensionContentTypeProvider();
			provider.Mappings [".wasm"] = "application/wasm";

			app.UseStaticFiles (new StaticFileOptions {
				FileProvider = new PhysicalFileProvider (options.AppPath),
				ServeUnknownFileTypes = true, //Cuz .wasm is not a known file type :cry:
				RequestPath = "",
				ContentTypeProvider = provider
			});

			var devToolsUrl = options.DevToolsUrl;
			app.UseRouter (router => {
				router.MapGet ("launch-chrome-and-connect", async context => {
					Console.WriteLine ("New test request");
					try {
						var client = new HttpClient ();
						var psi = new ProcessStartInfo ();

						psi.Arguments = $"--headless --disable-gpu --lang=en-US --incognito --remote-debugging-port={devToolsUrl.Port} http://{TestHarnessProxy.Endpoint.Authority}/{options.PagePath}";
						psi.UseShellExecute = false;
						psi.FileName = options.ChromePath;
						psi.RedirectStandardError = true;
						psi.RedirectStandardOutput = true;


						await LaunchAndServe (psi, context, async (str) => {
							var start = DateTime.Now;
							JArray obj = null;

							while (true) {
								// Unfortunately it does look like we have to wait
								// for a bit after getting the response but before
								// making the list request.  We get an empty result
								// if we make the request too soon.
								await Task.Delay (100);

								var res = await client.GetStringAsync (new Uri (new Uri (str), "/json/list"));
								Console.WriteLine ("res is {0}", res);

								if (!String.IsNullOrEmpty (res)) {
									// Sometimes we seem to get an empty array `[ ]`
									obj = JArray.Parse (res);
									if (obj != null && obj.Count >= 1)
										break;
								}

								var elapsed = DateTime.Now - start;
								if (elapsed.Milliseconds > 5000) {
									Console.WriteLine ($"Unable to get DevTools /json/list response in {elapsed.Seconds} seconds, stopping");
									return null;
								}
							}

							var wsURl = obj[0]? ["webSocketDebuggerUrl"]?.Value<string> ();
							Console.WriteLine (">>> {0}", wsURl);

							return wsURl;
						});
					} catch (Exception ex) {
						Console.WriteLine ($"launch-chrome-and-connect failed with {ex.ToString ()}");
					}
				});
			});

			if (options.NodeApp != null) {
				Console.WriteLine($"Doing the nodejs: {options.NodeApp}");
				var nodeFullPath = Path.GetFullPath (options.NodeApp);
				Console.WriteLine (nodeFullPath);
				var psi = new ProcessStartInfo ();

				psi.UseShellExecute = false;
				psi.RedirectStandardError = true;
				psi.RedirectStandardOutput = true;

				psi.Arguments = $"--inspect-brk=localhost:0 {nodeFullPath}";
				psi.FileName = "node";

				app.UseRouter (router => {
					//Inspector API for using chrome devtools directly
					router.MapGet ("json", SendNodeList);
					router.MapGet ("json/list", SendNodeList);
					router.MapGet ("json/version", SendNodeVersion);
					router.MapGet ("launch-done-and-connect", async context => {
						await LaunchAndServe (psi, context, null);
					});
				});
			}
		}
	}
}