-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathcoderApi.ts
More file actions
835 lines (755 loc) · 23.3 KB
/
Copy pathcoderApi.ts
File metadata and controls
835 lines (755 loc) · 23.3 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
import {
isAxiosError,
type AxiosHeaders,
type AxiosInstance,
type AxiosResponseHeaders,
type AxiosResponseTransformer,
} from "axios";
import { Api } from "coder/site/src/api/api";
import * as vscode from "vscode";
import {
CONFIG_CHANGE_DEBOUNCE_MS,
watchConfigurationChanges,
} from "../configWatcher";
import { sessionId } from "../core/sessionId";
import { ClientCertificateError } from "../error/clientCertificateError";
import { toError } from "../error/errorUtils";
import { ServerCertificateError } from "../error/serverCertificateError";
import { getHeaders } from "../headers";
import { EventStreamLogger } from "../logging/eventStreamLogger";
import {
createRequestMeta,
logError,
logRequest,
logResponse,
} from "../logging/httpLogger";
import { HttpRequestsTelemetry } from "../logging/httpRequestsTelemetry";
import {
type RequestConfigWithMeta,
type HttpClientLogLevel,
} from "../logging/types";
import { sizeOf } from "../logging/utils";
import { AuthConfigTracker } from "../settings/authConfig";
import { getHeaderCommand } from "../settings/headers";
import { readHttpClientLogLevel } from "../settings/logger";
import {
NOOP_TELEMETRY_REPORTER,
type TelemetryReporter,
} from "../telemetry/reporter";
import { HttpStatusCode, WebSocketCloseCode } from "../websocket/codes";
import {
OneWayWebSocket,
type OneWayWebSocketInit,
} from "../websocket/oneWayWebSocket";
import {
ConnectionState,
ReconnectingWebSocket,
type ReconnectingWebSocketOptions,
type SocketFactory,
} from "../websocket/reconnectingWebSocket";
import { SseConnection } from "../websocket/sseConnection";
import { handshakeStatus } from "../websocket/utils";
import { getRefreshCommand, refreshCertificates } from "./certificateRefresh";
import {
parseApiResponse,
VALIDATED_RESPONSES,
type ValidatedMethods,
} from "./responseValidation";
import { createHttpAgent } from "./utils";
import type {
GetInboxNotificationResponse,
ProvisionerJob,
ProvisionerJobLog,
ServerSentEvent,
Workspace,
WorkspaceAgent,
WorkspaceAgentLog,
WorkspaceBuild,
} from "coder/site/src/api/typesGenerated";
import type { ClientOptions } from "ws";
import type { ConnectionStateReason } from "../instrumentation/websocket";
import type { Logger } from "../logging/logger";
import type {
CloseEvent,
ErrorEvent,
UnidirectionalStream,
} from "../websocket/eventStreamConnection";
const coderSessionTokenHeader = "Coder-Session-Token";
/** W3C baggage header used to propagate the session ID to the server. */
const BAGGAGE_HEADER = "baggage";
const SESSION_ID_BAGGAGE_KEY = "client_session_id";
const SESSION_ID_BAGGAGE = `${SESSION_ID_BAGGAGE_KEY}=${sessionId}`;
/**
* Default timeout for REST requests, so requests hung on half-open TCP
* connections (e.g. after system sleep) don't stall pollers forever.
* Streaming responses are only bounded until response headers arrive;
* axios never aborts an in-flight stream body.
*/
export const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
/**
* Configuration settings that affect WebSocket connections.
* Changes to these settings will trigger WebSocket reconnection.
*/
const webSocketConfigSettings = [
"coder.headerCommand",
"coder.insecure",
"coder.tlsCertFile",
"coder.tlsKeyFile",
"coder.tlsCaFile",
"coder.tlsAltHost",
"http.proxy",
"http.proxySupport",
"coder.proxyBypass",
"http.noProxy",
"http.proxyAuthorization",
"http.proxyStrictSSL",
] as const;
/**
* Unified API class that includes both REST API methods from the base Api class
* and WebSocket methods for real-time functionality.
*/
export class CoderApi extends Api implements vscode.Disposable {
private readonly reconnectingSockets = new Set<
ReconnectingWebSocket<never>
>();
private readonly configWatcher: vscode.Disposable;
private constructor(
private readonly output: Logger,
private readonly telemetry: TelemetryReporter,
private readonly httpRequestsTelemetry: HttpRequestsTelemetry,
private readonly authConfigTracker: AuthConfigTracker,
private readonly onConnectionFailure?: (
reason: ConnectionStateReason,
route: string,
) => void,
) {
super();
wrapWithValidation(this);
this.configWatcher = this.watchConfigChanges();
}
/**
* Create a new CoderApi instance with the provided configuration.
* Automatically sets up logging interceptors, certificate handling,
* HTTP request telemetry, and WebSocket connection telemetry. All
* telemetry routes through the single reporter passed in (defaults to
* NOOP_TELEMETRY_REPORTER for throwaway clients). The session ID is
* attached to every request via the `baggage` header so the server can
* correlate requests with the session's logs and telemetry.
*/
static create(
baseUrl: string,
token: string | undefined,
output: Logger,
telemetry: TelemetryReporter = NOOP_TELEMETRY_REPORTER,
onConnectionFailure?: (
reason: ConnectionStateReason,
route: string,
) => void,
): CoderApi {
const httpRequestsTelemetry = new HttpRequestsTelemetry(telemetry);
const authConfigTracker = new AuthConfigTracker();
const client = new CoderApi(
output,
telemetry,
httpRequestsTelemetry,
authConfigTracker,
onConnectionFailure,
);
client.getAxiosInstance().defaults.timeout = DEFAULT_REQUEST_TIMEOUT_MS;
client.getAxiosInstance().defaults.headers.common[BAGGAGE_HEADER] =
SESSION_ID_BAGGAGE;
client.setCredentials(baseUrl, token);
setupInterceptors(client, output, httpRequestsTelemetry, authConfigTracker);
return client;
}
getHost(): string | undefined {
return this.getAxiosInstance().defaults.baseURL;
}
/**
* Reimplemented because the SDK version polls inside a voided IIFE that
* swallows errors, hanging callers forever if a poll throws (e.g. on
* failed response validation).
*/
override waitForBuild = async (
build: WorkspaceBuild,
): Promise<ProvisionerJob | undefined> => {
while (true) {
const { job } = await this.getWorkspaceBuildByNumber(
build.workspace_owner_name,
build.workspace_name,
build.build_number,
);
if (job.status === "failed") {
throw new Error(`Build ${build.build_number} failed`);
}
if (job.status === "succeeded" || job.status === "canceled") {
return job;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
};
hasAuthConfigChangedSince(version: number | undefined): boolean {
return this.authConfigTracker.hasChangedSince(version);
}
/**
* Set both host and token together. Useful for login/logout/switch to
* avoid triggering multiple reconnection events.
*/
setCredentials = (
host: string | undefined,
token: string | undefined,
): void => {
const currentHost = this.getHost();
const currentToken = this.getSessionToken();
// We cannot use the super.setHost/setSessionToken methods because they are shadowed here
const defaults = this.getAxiosInstance().defaults;
defaults.baseURL = host;
defaults.headers.common[coderSessionTokenHeader] = token;
const hostChanged = (currentHost || "") !== (host || "");
const tokenChanged = (currentToken || "") !== (token || "");
if (hostChanged || tokenChanged) {
for (const socket of this.reconnectingSockets) {
if (host) {
socket.reconnect();
} else {
socket.disconnect(WebSocketCloseCode.NORMAL, "Host cleared");
}
}
}
};
override setSessionToken = (token: string): void => {
this.setCredentials(this.getHost(), token);
};
override setHost = (host: string | undefined): void => {
this.setCredentials(host, this.getSessionToken());
};
/**
* Permanently dispose all WebSocket connections.
* This clears handlers and prevents reconnection.
*/
dispose(): void {
this.configWatcher.dispose();
this.authConfigTracker.dispose();
this.httpRequestsTelemetry.dispose();
for (const socket of this.reconnectingSockets) {
socket.close();
}
this.reconnectingSockets.clear();
}
/**
* Watch for configuration changes that affect WebSocket connections.
* Only reconnects DISCONNECTED sockets since they require an explicit reconnect() call.
* Other states will pick up settings naturally.
*/
private watchConfigChanges(): vscode.Disposable {
const settings = webSocketConfigSettings.map((setting) => ({
setting,
getValue: () => vscode.workspace.getConfiguration().get(setting),
}));
return watchConfigurationChanges(
settings,
() => {
const socketsToReconnect = [...this.reconnectingSockets].filter(
(socket) => socket.state === ConnectionState.DISCONNECTED,
);
if (socketsToReconnect.length) {
this.output.debug(
`Configuration changed, ${socketsToReconnect.length}/${this.reconnectingSockets.size} socket(s) in DISCONNECTED state`,
);
for (const socket of socketsToReconnect) {
this.output.debug(`Reconnecting WebSocket: ${socket.url}`);
socket.reconnect();
}
}
},
{ debounceMs: CONFIG_CHANGE_DEBOUNCE_MS },
);
}
watchInboxNotifications = async (
watchTemplates: string[],
watchTargets: string[],
options?: ClientOptions,
) => {
const apiRoute = "/api/v2/notifications/inbox/watch";
return this.createReconnectingSocket(apiRoute, () =>
this.createOneWayWebSocket<GetInboxNotificationResponse>({
apiRoute,
searchParams: {
format: "plaintext",
templates: watchTemplates.join(","),
targets: watchTargets.join(","),
},
options,
}),
);
};
watchWorkspace = async (workspace: Workspace, options?: ClientOptions) => {
const apiRoute = `/api/v2/workspaces/${workspace.id}/watch-ws`;
return this.createReconnectingSocket(apiRoute, () =>
this.createStreamWithSseFallback({
apiRoute,
fallbackApiRoute: `/api/v2/workspaces/${workspace.id}/watch`,
options,
}),
);
};
watchAgentMetadata = async (
agentId: WorkspaceAgent["id"],
options?: ClientOptions,
) => {
const apiRoute = `/api/v2/workspaceagents/${agentId}/watch-metadata-ws`;
return this.createReconnectingSocket(apiRoute, () =>
this.createStreamWithSseFallback({
apiRoute,
fallbackApiRoute: `/api/v2/workspaceagents/${agentId}/watch-metadata`,
options,
}),
);
};
watchBuildLogsByBuildId = async (
buildId: string,
logs: ProvisionerJobLog[],
options?: ClientOptions,
) => {
return this.watchLogs<ProvisionerJobLog>(
`/api/v2/workspacebuilds/${buildId}/logs`,
logs,
options,
);
};
watchWorkspaceAgentLogs = async (
agentId: string,
logs: WorkspaceAgentLog[],
options?: ClientOptions,
) => {
return this.watchLogs<WorkspaceAgentLog[]>(
`/api/v2/workspaceagents/${agentId}/logs`,
logs,
options,
);
};
private async watchLogs<TData>(
apiRoute: string,
logs: Array<{ id: number }>,
options?: ClientOptions,
) {
const searchParams = new URLSearchParams({ follow: "true" });
const lastLog = logs.at(-1);
if (lastLog) {
searchParams.append("after", lastLog.id.toString());
}
return this.createOneWayWebSocket<TData>({
apiRoute,
searchParams,
options,
});
}
private async createOneWayWebSocket<TData>(
configs: Omit<OneWayWebSocketInit, "location">,
): Promise<OneWayWebSocket<TData>> {
const baseUrlRaw = this.getAxiosInstance().defaults.baseURL;
if (!baseUrlRaw) {
throw new Error("No base URL set on REST client");
}
const token = this.getAxiosInstance().defaults.headers.common[
coderSessionTokenHeader
] as string | undefined;
const headersFromCommand = await getHeaders(
baseUrlRaw,
getHeaderCommand(vscode.workspace.getConfiguration()),
this.output,
);
const httpAgent = await createHttpAgent(
vscode.workspace.getConfiguration(),
);
/**
* Similar to the REST client, we want to prioritize headers in this order (highest to lowest):
* 1. Headers from the header command
* 2. Any headers passed directly to this function
* 3. Coder session token from the Api client (if set)
*/
const headers = {
...(token ? { [coderSessionTokenHeader]: token } : {}),
...configs.options?.headers,
...headersFromCommand,
[BAGGAGE_HEADER]: SESSION_ID_BAGGAGE,
};
const baseUrl = new URL(baseUrlRaw);
const ws = new OneWayWebSocket<TData>({
location: baseUrl,
...configs,
options: {
...configs.options,
agent: httpAgent,
followRedirects: true,
headers,
},
});
this.attachStreamLogger(ws);
// Wait for connection to open before returning
return await this.waitForOpen(ws);
}
private attachStreamLogger<TData>(
connection: UnidirectionalStream<TData>,
): void {
const url = new URL(connection.url);
const logger = new EventStreamLogger(
this.output,
url.pathname + url.search,
url.protocol.startsWith("http") ? "SSE" : "WS",
);
logger.logConnecting();
connection.addEventListener("open", () => logger.logOpen());
connection.addEventListener("close", (event: CloseEvent) =>
logger.logClose(event.code, event.reason),
);
connection.addEventListener("error", (event: ErrorEvent) =>
logger.logError(event.error, event.message),
);
connection.addEventListener("message", (event) =>
logger.logMessage(event.sourceEvent.data),
);
}
/**
* Create a WebSocket connection with SSE fallback on 404.
*
* Tries WS first, falls back to SSE on 404.
*
* Note: The fallback on SSE ignores all passed client options except the headers.
*/
private async createStreamWithSseFallback(
configs: Omit<OneWayWebSocketInit, "location"> & {
fallbackApiRoute: string;
},
): Promise<UnidirectionalStream<ServerSentEvent>> {
const { fallbackApiRoute, ...socketConfigs } = configs;
try {
// createOneWayWebSocket already waits for open
return await this.createOneWayWebSocket<ServerSentEvent>(socketConfigs);
} catch (error) {
if (this.is404Error(error)) {
this.output.warn(
`WebSocket failed (${socketConfigs.apiRoute}), using SSE fallback: ${fallbackApiRoute}`,
);
const sse = this.createSseConnection(
fallbackApiRoute,
socketConfigs.searchParams,
socketConfigs.options?.headers,
);
return await this.waitForOpen(sse);
}
throw error;
}
}
/**
* Create an SSE connection without waiting for connection.
*/
private createSseConnection(
apiRoute: string,
searchParams?: Record<string, string> | URLSearchParams,
optionsHeaders?: Record<string, string>,
): SseConnection {
const baseUrlRaw = this.getAxiosInstance().defaults.baseURL;
if (!baseUrlRaw) {
throw new Error("No base URL set on REST client");
}
const url = new URL(baseUrlRaw);
const sse = new SseConnection({
location: url,
apiRoute,
searchParams,
axiosInstance: this.getAxiosInstance(),
optionsHeaders,
logger: this.output,
});
this.attachStreamLogger(sse);
return sse;
}
/**
* Wait for a connection to open. Rejects on error.
* Preserves the specific connection type (e.g., OneWayWebSocket, SseConnection).
*/
private waitForOpen<T extends UnidirectionalStream<unknown>>(
connection: T,
): Promise<T> {
return new Promise((resolve, reject) => {
const cleanup = () => {
connection.removeEventListener("open", handleOpen);
connection.removeEventListener("error", handleError);
};
const handleOpen = () => {
cleanup();
resolve(connection);
};
const handleError = (event: ErrorEvent) => {
cleanup();
connection.close();
const error = toError(
event.error,
event.message || "WebSocket connection error",
);
reject(error);
};
connection.addEventListener("open", handleOpen);
connection.addEventListener("error", handleError);
});
}
/**
* Check if an error is a 404 Not Found error.
*/
private is404Error(error: unknown): boolean {
return handshakeStatus(error) === HttpStatusCode.NOT_FOUND;
}
/**
* Create a ReconnectingWebSocket and track it for lifecycle management.
*/
private async createReconnectingSocket<TData>(
apiRoute: string,
socketFactory: SocketFactory<TData>,
): Promise<ReconnectingWebSocket<TData>> {
const options: ReconnectingWebSocketOptions = {
route: apiRoute,
onCertificateRefreshNeeded: async () => {
const refreshCommand = getRefreshCommand();
if (!refreshCommand) {
return false;
}
return refreshCertificates(refreshCommand, this.output);
},
onConnectionFailure: this.onConnectionFailure,
telemetry: this.telemetry,
};
const reconnectingSocket = await ReconnectingWebSocket.create<TData>(
socketFactory,
this.output,
options,
() => this.reconnectingSockets.delete(reconnectingSocket),
);
this.reconnectingSockets.add(reconnectingSocket);
return reconnectingSocket;
}
}
function setupInterceptors(
client: CoderApi,
output: Logger,
httpRequestsTelemetry: HttpRequestsTelemetry,
authConfigTracker: AuthConfigTracker,
): void {
addRequestInterceptors(
client.getAxiosInstance(),
output,
httpRequestsTelemetry,
);
client.getAxiosInstance().interceptors.request.use(async (config) => {
// Snapshot the version up front so it matches the config we're about
// to read, not whatever it bumps to during the awaits below.
config.authConfigVersion = authConfigTracker.version;
// Drop headers from the prior header-command run so stale keys can't
// leak through if the command output changed between attempts.
for (const key of config.headerCommandKeys ?? []) {
config.headers.delete(key);
}
const baseUrl = client.getAxiosInstance().defaults.baseURL;
const headers = await getHeaders(
baseUrl,
getHeaderCommand(vscode.workspace.getConfiguration()),
output,
);
const retrying =
config._retryAttempted === true ||
config._authConfigRetryAttempted === true;
for (const [key, value] of Object.entries(headers)) {
// On retry, don't let stale command output overwrite the session
// token retryRequest just wrote.
if (
retrying &&
key.toLowerCase() === coderSessionTokenHeader.toLowerCase()
) {
continue;
}
config.headers[key] = value;
}
// Don't track the session token: cleanup must never touch it.
config.headerCommandKeys = Object.keys(headers).filter(
(k) => k.toLowerCase() !== coderSessionTokenHeader.toLowerCase(),
);
// VS Code overrides the agent by default; set `http.proxySupport` to
// `on` or `off` to keep ours.
const agent = await createHttpAgent(vscode.workspace.getConfiguration());
config.httpsAgent = agent;
config.httpAgent = agent;
config.proxy = false;
return config;
});
// Cert-refresh retries re-enter the chain, so each attempt is recorded.
client.getAxiosInstance().interceptors.response.use(
(r) => r,
async (err: unknown) => {
const retryResponse = await tryRefreshClientCertificate(
err,
client.getAxiosInstance(),
output,
);
if (retryResponse) {
return retryResponse;
}
// Handle other certificate errors.
const baseUrl = client.getAxiosInstance().defaults.baseURL;
if (baseUrl) {
throw await ServerCertificateError.maybeWrap(err, baseUrl, output);
}
throw err;
},
);
}
function addRequestInterceptors(
client: AxiosInstance,
logger: Logger,
httpRequestsTelemetry: HttpRequestsTelemetry,
) {
client.interceptors.request.use(
(config) => {
const configWithMeta = config as RequestConfigWithMeta;
configWithMeta.metadata = createRequestMeta();
config.transformRequest = [
...wrapRequestTransform(
config.transformRequest ?? client.defaults.transformRequest ?? [],
configWithMeta,
),
(data: unknown) => {
// Log after setting the raw request size
logRequest(logger, configWithMeta, getLogLevel());
return data;
},
];
config.transformResponse = wrapResponseTransform(
config.transformResponse ?? client.defaults.transformResponse ?? [],
configWithMeta,
);
return config;
},
(error: unknown) => {
logError(logger, error, getLogLevel());
throw error;
},
);
client.interceptors.response.use(
(response) => {
httpRequestsTelemetry.recordResponse(response);
logResponse(logger, response, getLogLevel());
return response;
},
(error: unknown) => {
httpRequestsTelemetry.recordError(error);
logError(logger, error, getLogLevel());
throw error;
},
);
}
/**
* Attempts to refresh client certificates and retry the request if the error
* is a refreshable client certificate error.
*
* @returns The retry response if refresh succeeds, or undefined if the error
* is not a client certificate error (caller should handle).
* @throws {ClientCertificateError} If this is a client certificate error.
*/
async function tryRefreshClientCertificate(
err: unknown,
axiosInstance: AxiosInstance,
output: Logger,
): Promise<unknown> {
const certError = ClientCertificateError.fromError(err);
if (!certError) {
return undefined;
}
const refreshCommand = getRefreshCommand();
if (
!certError.isRefreshable ||
!refreshCommand ||
!isAxiosError(err) ||
!err.config
) {
throw certError;
}
// _certRetried is per-request (Axios creates fresh config per request).
if (err.config._certRetried) {
throw certError;
}
err.config._certRetried = true;
output.info(
`Client certificate error (alert ${certError.alertCode}), attempting refresh...`,
);
const success = await refreshCertificates(refreshCommand, output);
if (!success) {
throw certError;
}
// Create new agent with refreshed certificates.
const agent = await createHttpAgent(vscode.workspace.getConfiguration());
err.config.httpsAgent = agent;
err.config.httpAgent = agent;
// Retry the request.
output.info("Retrying request with refreshed certificates...");
return axiosInstance.request(err.config);
}
function wrapRequestTransform(
transformer: AxiosResponseTransformer | AxiosResponseTransformer[],
config: RequestConfigWithMeta,
): AxiosResponseTransformer[] {
return [
(data: unknown, headers: AxiosHeaders) => {
const transformerArray = Array.isArray(transformer)
? transformer
: [transformer];
// Transform the request first then get the size (measure what's sent over the wire)
const result = transformerArray.reduce(
(d, fn) => fn.call(config, d, headers),
data,
);
config.rawRequestSize = getSize(config.headers, result);
return result;
},
];
}
function wrapResponseTransform(
transformer: AxiosResponseTransformer | AxiosResponseTransformer[],
config: RequestConfigWithMeta,
): AxiosResponseTransformer[] {
return [
(data: unknown, headers: AxiosResponseHeaders, status?: number) => {
// Get the size before transforming the response (measure what's sent over the wire)
config.rawResponseSize = getSize(headers, data);
const transformerArray = Array.isArray(transformer)
? transformer
: [transformer];
return transformerArray.reduce(
(d, fn) => fn.call(config, d, headers, status),
data,
);
},
];
}
/**
* Validate the fields the extension reads on each response, since the SDK
* casts bodies to the generated types with no runtime check. The methods
* are instance arrow properties, so wrapping is by reassignment;
* `override` fields would depend on declaration order.
*/
function wrapWithValidation(api: CoderApi): void {
const methods: ValidatedMethods = api;
for (const [name, schema] of VALIDATED_RESPONSES) {
const method = methods[name];
methods[name] = async (...args) =>
parseApiResponse(schema, await method(...args), name, api.getHost());
}
}
function getSize(headers: AxiosHeaders, data: unknown): number | undefined {
const contentLength = headers["content-length"] as unknown;
if (typeof contentLength === "string") {
return Number.parseInt(contentLength, 10);
}
return sizeOf(data);
}
function getLogLevel(): HttpClientLogLevel {
return readHttpClientLogLevel(vscode.workspace.getConfiguration());
}