Skip to content

Commit e500304

Browse files
committed
Reuse API tokens for liveness checks
1 parent 662d899 commit e500304

3 files changed

Lines changed: 60 additions & 31 deletions

File tree

‎src/detect.ts‎

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { VersionExeName, VersionPreference } from './enums';
44
import { executeCommand, resolveDevProxyExecutable } from './utils/shell';
55
import * as vscode from 'vscode';
66
import * as logger from './logger';
7+
import { DevProxyApiClient } from './services/api-client';
78

89
let lastKnownRunningState: boolean | undefined;
910

@@ -87,32 +88,15 @@ export const getOutdatedVersion = async (devProxyExe: string): Promise<string> =
8788
};
8889

8990
export const isDevProxyRunning = async (devProxyExe: string): Promise<boolean> => {
90-
try {
91-
// Get the API port from configuration
92-
const configuration = vscode.workspace.getConfiguration('dev-proxy-toolkit');
93-
const apiPort = configuration.get('apiPort') as number;
94-
95-
// Try to connect to the Dev Proxy API on the configured port
96-
const response = await fetch(`http://127.0.0.1:${apiPort}/proxy`, {
97-
method: 'GET',
98-
signal: AbortSignal.timeout(2000), // 2 second timeout
99-
});
100-
101-
// If we get any response (even an error), Dev Proxy is running
102-
const running = response.status >= 200 && response.status < 500;
103-
if (running !== lastKnownRunningState) {
104-
logger.info('Dev Proxy running state changed', { running, status: response.status });
105-
lastKnownRunningState = running;
106-
}
107-
return running;
108-
} catch (error) {
109-
// If the request fails (connection refused, timeout, etc.), Dev Proxy is not running
110-
if (lastKnownRunningState !== false) {
111-
logger.info('Dev Proxy is not running');
112-
lastKnownRunningState = false;
113-
}
114-
return false;
91+
const configuration = vscode.workspace.getConfiguration('dev-proxy-toolkit');
92+
const apiPort = configuration.get('apiPort') as number;
93+
const running = await DevProxyApiClient.forInstance(devProxyExe, apiPort).isRunning();
94+
95+
if (running !== lastKnownRunningState) {
96+
logger.info('Dev Proxy running state changed', { running });
97+
lastKnownRunningState = running;
11598
}
99+
return running;
116100
};
117101

118102
export const getDevProxyExe = (versionPreference: VersionPreference) => {

‎src/services/api-client.ts‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import * as vscode from 'vscode';
2-
import { getDevProxyExe } from '../detect';
3-
import { VersionPreference } from '../enums';
2+
import { VersionExeName, VersionPreference } from '../enums';
43
import * as logger from '../logger';
54
import { executeFile } from '../utils/shell';
65

@@ -80,6 +79,7 @@ export async function getDevProxyApiToken(
8079
* - POST /proxy/mockrequest - Raise a mock request
8180
*/
8281
export class DevProxyApiClient {
82+
private static readonly instances = new Map<string, DevProxyApiClient>();
8383
private readonly baseUrl: string;
8484
private readonly timeout: number;
8585
private readonly tokenProvider?: ApiTokenProvider;
@@ -98,20 +98,32 @@ export class DevProxyApiClient {
9898
const config = vscode.workspace.getConfiguration('dev-proxy-toolkit');
9999
const port = config.get<number>('apiPort', 8897);
100100
const versionPreference = config.get('version') as VersionPreference;
101-
const devProxyExe = getDevProxyExe(versionPreference);
102-
return new DevProxyApiClient(port, 5000, () => getDevProxyApiToken(devProxyExe, port));
101+
const devProxyExe = versionPreference === VersionPreference.Stable
102+
? VersionExeName.Stable
103+
: VersionExeName.Beta;
104+
return DevProxyApiClient.forInstance(devProxyExe, port);
105+
}
106+
107+
static forInstance(devProxyExe: string, port: number): DevProxyApiClient {
108+
const key = `${devProxyExe}:${port}`;
109+
let client = DevProxyApiClient.instances.get(key);
110+
if (!client) {
111+
client = new DevProxyApiClient(port, 5000, () => getDevProxyApiToken(devProxyExe, port));
112+
DevProxyApiClient.instances.set(key, client);
113+
}
114+
return client;
103115
}
104116

105117
/**
106118
* Check if Dev Proxy is running by attempting to connect to the API.
107119
*/
108120
async isRunning(): Promise<boolean> {
109121
try {
110-
const response = await fetch(`${this.baseUrl}/proxy`, {
122+
const response = await this.request('/proxy', {
111123
method: 'GET',
112124
signal: AbortSignal.timeout(2000),
113125
});
114-
return response.status >= 200 && response.status < 500;
126+
return response.status >= 200 && response.status < 500 && response.status !== 401;
115127
} catch (error) {
116128
logger.debug('Dev Proxy API unreachable', error);
117129
return false;

‎src/test/api-client.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,32 @@ suite('DevProxyApiClient', () => {
5959
assert.strictEqual(result, true);
6060
});
6161

62+
test('should authenticate once and reuse the token for liveness checks', async () => {
63+
const tokenProvider = sinon.stub().resolves('a'.repeat(64));
64+
const authenticatedClient = new DevProxyApiClient(8897, 5000, tokenProvider);
65+
fetchStub.onFirstCall().resolves(new Response(null, { status: 401 }));
66+
fetchStub.onSecondCall().resolves(new Response(null, { status: 200 }));
67+
fetchStub.onThirdCall().resolves(new Response(null, { status: 200 }));
68+
69+
assert.strictEqual(await authenticatedClient.isRunning(), true);
70+
assert.strictEqual(await authenticatedClient.isRunning(), true);
71+
72+
assert.strictEqual(tokenProvider.calledOnce, true);
73+
assert.strictEqual(fetchStub.callCount, 3);
74+
const retryHeaders = new Headers(fetchStub.secondCall.args[1].headers);
75+
const cachedHeaders = new Headers(fetchStub.thirdCall.args[1].headers);
76+
assert.strictEqual(retryHeaders.get('Authorization'), `Bearer ${'a'.repeat(64)}`);
77+
assert.strictEqual(cachedHeaders.get('Authorization'), `Bearer ${'a'.repeat(64)}`);
78+
});
79+
80+
test('should return false when authentication is unavailable', async () => {
81+
fetchStub.resolves(new Response(null, { status: 401 }));
82+
83+
const result = await client.isRunning();
84+
85+
assert.strictEqual(result, false);
86+
});
87+
6288
test('should return false when proxy responds with 5xx', async () => {
6389
fetchStub.resolves(new Response(null, { status: 500 }));
6490

@@ -212,6 +238,13 @@ suite('DevProxyApiClient', () => {
212238
const configClient = DevProxyApiClient.fromConfiguration();
213239
assert.ok(configClient instanceof DevProxyApiClient);
214240
});
241+
242+
test('should reuse the client for the same executable and API port', () => {
243+
const firstClient = DevProxyApiClient.forInstance('devproxy-test', 8899);
244+
const secondClient = DevProxyApiClient.forInstance('devproxy-test', 8899);
245+
246+
assert.strictEqual(secondClient, firstClient);
247+
});
215248
});
216249

217250
suite('getDevProxyApiToken', () => {

0 commit comments

Comments
 (0)