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

InspectorClient.cs « DebuggerTestSuite « wasm « sdks - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 84b9414d9c6c96211d4889c680c159652392a5e3 (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
using System;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

using System.Threading;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace WebAssembly.Net.Debugging {
	internal class InspectorClient : DevToolsClient {
		List<(int, TaskCompletionSource<Result>)> pending_cmds = new List<(int, TaskCompletionSource<Result>)> ();
		Func<string, JObject, CancellationToken, Task> onEvent;
		int next_cmd_id;

		public InspectorClient (ILogger logger) : base(logger) {}

		Task HandleMessage (string msg, CancellationToken token)
		{
			var res = JObject.Parse (msg);
			if (res ["id"] == null)
				DumpProtocol (string.Format("Event method: {0} params: {1}", res ["method"], res ["params"]));
			else
				DumpProtocol (string.Format ("Response id: {0} res: {1}", res ["id"], res));

			if (res ["id"] == null)
				return onEvent (res ["method"].Value<string> (), res ["params"] as JObject, token);
			var id = res ["id"].Value<int> ();
			var idx = pending_cmds.FindIndex (e => e.Item1 == id);
			var item = pending_cmds [idx];
			pending_cmds.RemoveAt (idx);
			item.Item2.SetResult (Result.FromJson (res));
			return null;
		}

		public async Task Connect(
			Uri uri,
			Func<string, JObject, CancellationToken, Task> onEvent,
			Func<CancellationToken, Task> send,
			CancellationToken token) {

			this.onEvent = onEvent;
			await ConnectWithMainLoops (uri, HandleMessage, send, token);
		}

		public Task<Result> SendCommand (string method, JObject args, CancellationToken token)
		{
			int id = ++next_cmd_id;
			if (args == null)
				args = new JObject ();

			var o = JObject.FromObject (new {
				id = id,
				method = method,
				@params = args
			});

			var tcs = new TaskCompletionSource<Result> ();
			pending_cmds.Add ((id, tcs));

			var str = o.ToString ();
			//Log ("protocol", $"SendCommand: id: {id} method: {method} params: {args}");

			var bytes = Encoding.UTF8.GetBytes (str);
			Send (bytes, token);
			return tcs.Task;
		}

		protected virtual void DumpProtocol (string msg){
			// Console.WriteLine (msg);
			//XXX make logging not stupid
		}
	}
}