๐Ÿ“ฆ hediet / vscode-rpc

๐Ÿ“„ nodeDebugger.ts ยท 169 lines
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
169import { TypedChannel, MessageStream } from "@hediet/typed-json-rpc";
import { nodeDebuggerContract } from "vscode-rpc";
import {
	OutputChannel,
	DebugConfiguration,
	debug,
	StatusBarAlignment,
} from "vscode";
import { StatusBarOptionService } from "./StatusBarOptionService";
import { Barrier } from "@hediet/std/synchronization";
import { dispatched } from "./contractTransformer";
import { Disposable } from "@hediet/std/disposable";
import { Config } from "./Config";

const dispatchedNodeDebuggerContract = dispatched(nodeDebuggerContract);

type Contract = typeof dispatchedNodeDebuggerContract;
type Server = Contract["TServerInterface"];

export class NodeDebugServer {
	private autoAttachLabels = new Set<string>();
	private readonly clients = new Set<Contract["TClientInterface"]>();
	public dispose = Disposable.fn();

	constructor(
		private readonly outputChannel: OutputChannel,
		private readonly registrarServer: TypedChannel,
		private readonly config: Config
	) {
		this.dispose.track(this.statusBarService);

		this.dispose.track(
			config.onChange.sub(() => {
				this.reloadConfig();
			})
		);
		this.reloadConfig();
	}

	private reloadConfig() {
		this.autoAttachLabels = new Set(this.config.getAutoAttachLabels());
	}

	private readonly statusBarService = new StatusBarOptionService({
		id: "nodeDebugStatusBar",
		alignment: StatusBarAlignment.Right,
		priority: 10000000,
	});

	public handleClient(channel: TypedChannel, stream: MessageStream) {
		const { client } = dispatchedNodeDebuggerContract.registerServer(
			channel,
			{
				addNodeDebugTarget: this.addNodeDebugTarget,
				removeNodeDebugTarget: this.removeNodeDebugTarget,
			}
		);
		this.clients.add(client);

		stream.onClosed.then(() => {
			this.clients.delete(client);
		});
	}

	private readonly targetIdsByClientId = new Map<string, string[]>();
	private readonly openRequestsByTargetId = new Map<string, Disposable>();

	public onClientDisconnected(clientId: string) {
		const c = this.targetIdsByClientId.get(clientId);
		if (c) {
			for (const requestId of c) {
				this.cancelRequest(requestId);
			}
			this.targetIdsByClientId.delete(clientId);
		}
	}

	private cancelRequest(targetId: string): void {
		const r = this.openRequestsByTargetId.get(targetId);
		if (!r) {
			return;
		}

		r.dispose();
		this.openRequestsByTargetId.delete(targetId);
	}

	private readonly removeNodeDebugTarget: Server["removeNodeDebugTarget"] = async ({
		targetId,
	}) => {
		this.cancelRequest(targetId);
	};

	private readonly addNodeDebugTarget: Server["addNodeDebugTarget"] = async ({
		port: debuggerPort,
		targetId,
		name,
		$sourceClientId,
	}) => {
		const b = new Barrier<{ attach: boolean }>();

		if (name && this.autoAttachLabels.has(name)) {
			b.unlock({ attach: true });
		} else {
			this.openRequestsByTargetId.set(
				targetId,
				this.statusBarService.addOptions({
					options: [
						{
							caption: `$(bug) Debug Node Process${
								name ? ` "${name}"` : ""
							}`,
							action: () => {
								b.unlock({ attach: true });
							},
						},
						{
							caption: `Continue`,
							action: () => {
								b.unlock({ attach: false });
							},
						},
					],
				})
			);
		}

		let client = this.targetIdsByClientId.get($sourceClientId);
		if (!client) {
			client = [];
			this.targetIdsByClientId.set($sourceClientId, client);
		}
		client.push(targetId);

		const { attach } = await b.onUnlocked;
		if (attach) {
			await this.launchDebugger(debuggerPort, targetId);
		} else {
			for (const client of this.clients) {
				client.onNodeDebugTargetIgnored({
					targetId,
				});
			}
		}
	};

	private async launchDebugger(debuggerPort: number, targetId: string) {
		// "type: node" does not work!
		const config: DebugConfiguration = {
			type: this.config.getDebugAdapterKey(),
			request: "attach",
			name: "Attach to process",
			port: debuggerPort,
		};

		try {
			for (const client of this.clients) {
				client.onAttachingToNodeDebugTarget({
					targetId,
				});
			}
			const result = await debug.startDebugging(undefined, config);
			this.outputChannel.appendLine(`start: ${result}`);
		} catch (ex) {
			this.outputChannel.appendLine(`ex: ${ex}`);
		}
	}
}