-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcsolution-rpc-client.ts
More file actions
235 lines (206 loc) · 9.05 KB
/
csolution-rpc-client.ts
File metadata and controls
235 lines (206 loc) · 9.05 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
/*
* Copyright (C) 2026 Arm Limited
*/
import * as vscode from 'vscode';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as manifest from '../manifest';
import { ChildProcess, spawn } from 'node:child_process';
import { MessageConnection } from 'vscode-jsonrpc';
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from 'vscode-jsonrpc/node';
import { RpcMethods, RpcInterface, GetVersionResult } from './interface/rpc-interface';
import { constructor } from '../generic/constructor';
import { Optional } from '../generic/type-helper';
import { debounce } from 'lodash';
import { getCmsisPackRoot, getCmsisToolboxRoot } from '../utils/path-utils';
import { VcpkgManager } from '../vcpkg/vcpkg-manager';
import { Environment, EnvironmentManager } from '../desktop/env-manager';
import { Mutex } from 'async-mutex';
import { CommandsProvider } from '../vscode-api/commands-provider';
export * from './interface/rpc-interface';
declare module './interface/rpc-interface' {
export interface Condition {
selectedAggregate?: string; // only used in UI to keep the selection in the dropdown
}
}
export interface CsolutionService extends RpcInterface {
activate(context: Pick<vscode.ExtensionContext, 'subscriptions'>): Promise<void>;
getCsolutionBin(): string;
waitForExit(): Promise<void>;
}
class CsolutionServiceImpl extends RpcMethods implements CsolutionService {
public static readonly reloadPacksCommandId = `${manifest.PACKAGE_NAME}.reloadPacks`;
// private members and functions for client handling ---------------------------------
private child: ChildProcess | undefined;
private connection: MessageConnection | undefined;
private idxWatcher: Optional<fs.FSWatcher> = undefined;
private readonly debouncedLoadPacks = debounce(super.loadPacks.bind(this), 1000);
private csolutionBin = 'csolution';
private exitPromise: Promise<void> | undefined;
private cachedVersion: GetVersionResult = { success: false };
private readonly mutex: Mutex;
constructor(
private readonly environmentManager: EnvironmentManager,
private readonly commandsProvider: CommandsProvider,
) {
super();
this.mutex = new Mutex();
}
public async activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
this,
this.commandsProvider.registerCommand(CsolutionServiceImpl.reloadPacksCommandId, this.loadPacks, this),
);
this.loadPacks();
}
public async dispose() {
await this.shutdown();
await this.waitForExit();
}
async get<TArgs, TResponse>(remoteMethod: string, args?: TArgs): Promise<TResponse> {
const response = await this.transceive<TResponse>(remoteMethod, args);
return (response ?? {}) as TResponse;
}
public async getVersion(): Promise<GetVersionResult> {
if (!this.cachedVersion.success) {
// Query daemon version once per launched session
this.cachedVersion = await super.getVersion();
console.log('csolution version:', this.cachedVersion);
}
return this.cachedVersion;
}
public async loadPacks() {
if (this.idxWatcher === undefined) {
this.watchPackIdxFile();
}
// ensure version is cached
await this.getVersion();
return super.loadPacks();
}
public getCsolutionBin(): string {
return this.csolutionBin;
}
public async waitForExit(): Promise<void> {
return this.exitPromise ?? Promise.resolve();
}
private watchPackIdxFile() {
this.idxWatcher?.close();
const pack_idx = path.join(getCmsisPackRoot(), 'pack.idx');
let mtimeMs = fs.statSync(pack_idx)?.mtimeMs;
this.idxWatcher = fs.watch(pack_idx, eventType => {
if (eventType === 'change') {
const stat = fs.statSync(pack_idx);
if (stat?.mtimeMs !== mtimeMs) {
mtimeMs = stat.mtimeMs;
this.debouncedLoadPacks();
}
}
});
}
private async transceive<TResponse>(method: string, params?: unknown, ..._rest: unknown[]):
Promise<TResponse | undefined> {
const release = await this.mutex.acquire();
try {
if (!(this.child?.pid) && !(await this.launch())) {
return undefined;
}
console.log('csolution rpc request:', method, params ? JSON.stringify(params) : '{ }');
const start = Date.now();
let response = undefined;
try {
response = params ?
await this.connection?.sendRequest<TResponse>(method, params) :
await this.connection?.sendRequest<TResponse>(method);
} catch (error) {
response = { success: false, message: error instanceof Error ? error.message : String(error) } as TResponse;
}
console.log(`csolution rpc response took ${Date.now() - start}ms:`, response);
return response;
} finally {
release();
}
}
private onTerminate() {
this.child = undefined;
this.idxWatcher?.close();
this.idxWatcher = undefined;
this.connection?.dispose();
this.connection = undefined;
this.cachedVersion = { success: false };
}
private async launch(): Promise<boolean> {
// wait vcpkg activation to pick up environment variables
await VcpkgManager.instance.awaitActivation().catch(() => {
console.warn('VcpkgManager activation failed or timed out');
}).then(() => {
console.log('VcpkgManager activation completed');
});
// Augment environment
const augmentedEnv = this.environmentManager.augmentEnv(new Environment(process.env)).vars;
// Resolve the final path to the executable
this.csolutionBin = path.resolve(getCmsisToolboxRoot(augmentedEnv), 'bin', `csolution${process.platform === 'win32' ? '.exe' : ''}`);
if (fs.existsSync(this.csolutionBin) && fs.statSync(this.csolutionBin).isFile()) {
console.log('Running csolution rpc:', this.csolutionBin);
} else {
console.error('csolution rpc executable not found:', this.csolutionBin);
this.csolutionBin = 'csolution';
}
if (!this.child) {
// append extra args from env.CSOLUTION_ARGS only if it is defined and not empty
const args = augmentedEnv.CSOLUTION_ARGS?.split(',').map(s => s.trim()).filter(s => s) ?? [];
this.child = spawn(this.csolutionBin, ['rpc', '--content-length', ...args],
{
cwd: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? './',
env: augmentedEnv,
}
);
this.exitPromise = new Promise((resolve, reject) => {
this.child?.on('exit', (code) => {
console.warn(`csolution rpc child process exited (${code})`);
this.onTerminate();
resolve();
});
this.child?.on('error', (error) => {
console.error('csolution rpc child process error:', error);
this.onTerminate();
reject();
});
this.child?.on('disconnect', () => {
console.warn('csolution rpc child process disconnected');
this.onTerminate();
reject();
});
});
this.child.stderr?.on('data', (data) => {
console.error('csolution rpc child process stderr:', data.toString());
});
if (!this.child?.pid || !this.child.stdout || !this.child.stdin) {
console.error('csolution rpc launch failed');
throw new Error('csolution rpc launch failed');
}
console.warn('csolution rpc started pid:', this.child.pid);
// Use stdin and stdout for communication
this.connection = createMessageConnection(
new StreamMessageReader(this.child.stdout),
new StreamMessageWriter(this.child.stdin)
);
// Listen for child process close event
this.child.on('close', (code) => {
console.warn(`csolution rpc child process closed (${code})`);
this.onTerminate();
throw new Error(`csolution rpc child process closed (${code})`);
});
// Listen for rpc connection errors
this.connection.onError((error) => {
console.error('csolution rpc connection error:', error);
throw error;
});
// Start listening
this.connection.listen();
} else {
console.log('ignoring launch request, csolution rpc already running');
}
return true;
}
}
export const CsolutionService = constructor<typeof CsolutionServiceImpl, CsolutionService>(CsolutionServiceImpl);