-
Notifications
You must be signed in to change notification settings - Fork 352
Expand file tree
/
Copy pathgitlab-client-pool.ts
More file actions
321 lines (279 loc) · 9.44 KB
/
Copy pathgitlab-client-pool.ts
File metadata and controls
321 lines (279 loc) · 9.44 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
import fs from "node:fs";
import http from "node:http";
import type { AgentConnectOpts } from "agent-base";
import { SocksProxyAgent } from "socks-proxy-agent";
import { Agent, Dispatcher, ProxyAgent, buildConnector } from "undici";
/**
* Checks if a URL should bypass the proxy based on NO_PROXY patterns.
* Supports:
* - Exact hostname matches (e.g., "localhost", "gitlab.example.com")
* - Domain suffix matches (e.g., ".example.com" matches "gitlab.example.com")
* - IP addresses (e.g., "127.0.0.1", "192.168.1.1")
* - Wildcard "*" to bypass all proxies
* - Port-specific matches (e.g., "example.com:8080")
*
* @param url The URL to check
* @param noProxy Comma-separated list of patterns from NO_PROXY
* @returns true if the URL should bypass the proxy, false otherwise
*/
function shouldBypassProxy(url: string, noProxy: string | undefined): boolean {
if (!noProxy) {
return false;
}
let hostname: string;
let port: string;
let protocol: string;
try {
const parsedUrl = new URL(url);
hostname = parsedUrl.hostname.toLowerCase();
protocol = parsedUrl.protocol;
port = parsedUrl.port || (protocol === "https:" ? "443" : "80");
} catch {
return false;
}
const patterns = noProxy
.split(",")
.map(p => p.trim().toLowerCase())
.filter(p => p.length > 0);
for (const pattern of patterns) {
if (pattern === "*") {
return true;
}
const [patternHost, patternPort] = pattern.split(":");
if (patternPort && port !== patternPort) {
continue;
}
if (patternHost.startsWith(".")) {
const suffix = patternHost.substring(1);
if (hostname === suffix || hostname.endsWith("." + suffix)) {
return true;
}
} else if (hostname === patternHost) {
return true;
}
}
return false;
}
type TlsConnectOptions = {
rejectUnauthorized?: boolean;
ca?: Buffer;
};
class ProtocolDispatcher extends Dispatcher {
constructor(
private readonly httpDirect: Dispatcher,
private readonly httpsDirect: Dispatcher,
private readonly httpProxyDispatcher: Dispatcher,
private readonly httpsProxyDispatcher: Dispatcher,
private readonly noProxy: string | undefined
) {
super();
}
dispatcherForOrigin(originText: string): Dispatcher {
const useHttps = originText.startsWith("https:");
const bypass = shouldBypassProxy(originText, this.noProxy);
if (bypass) {
return useHttps ? this.httpsDirect : this.httpDirect;
}
return useHttps ? this.httpsProxyDispatcher : this.httpProxyDispatcher;
}
override dispatch(
options: Dispatcher.DispatchOptions,
handler: Dispatcher.DispatchHandlers
): boolean {
const origin = options.origin;
const originText = origin instanceof URL ? origin.href : String(origin ?? "");
return this.dispatcherForOrigin(originText).dispatch(options, handler);
}
}
function createSocksConnect(proxyUrl: string, tls: TlsConnectOptions): buildConnector.connector {
const socksAgent = new SocksProxyAgent(proxyUrl);
return (options, callback) => {
const port = Number(options.port);
const host = options.hostname;
const dummyReq = http.request({
hostname: "127.0.0.1",
port: 9,
path: "/",
method: "HEAD",
agent: false,
});
dummyReq.on("error", () => undefined);
dummyReq.destroy();
const connectThroughSocks = (connectOpts: AgentConnectOpts) => {
void socksAgent
.connect(dummyReq, connectOpts)
.then(socket => {
callback(null, socket);
})
.catch((error: unknown) => {
const err = error instanceof Error ? error : new Error("SOCKS connect failed");
callback(err, null);
});
};
if (options.protocol === "https:") {
connectThroughSocks({
secureEndpoint: true,
host,
port,
servername: options.servername,
rejectUnauthorized: tls.rejectUnauthorized,
ca: tls.ca,
});
return;
}
connectThroughSocks({
secureEndpoint: false,
host,
port,
});
};
}
function createDispatcher(proxyUrl: string | undefined, tls: TlsConnectOptions): Dispatcher {
const hasTls = tls.rejectUnauthorized === false || tls.ca !== undefined;
if (proxyUrl?.startsWith("socks")) {
return new Agent({ connect: createSocksConnect(proxyUrl, tls) });
}
if (proxyUrl) {
if (hasTls) {
return new ProxyAgent({ uri: proxyUrl, requestTls: tls });
}
return new ProxyAgent(proxyUrl);
}
if (hasTls) {
return new Agent({ connect: tls });
}
return new Agent();
}
export interface GitLabClientPoolOptions {
apiUrls?: string[];
httpProxy?: string;
httpsProxy?: string;
noProxy?: string;
rejectUnauthorized?: boolean;
caCertPath?: string;
poolMaxSize?: number;
}
export interface ClientDispatchers {
httpDispatcher: Dispatcher;
httpsDispatcher: Dispatcher;
dispatcher: Dispatcher;
}
/**
* Manages a pool of undici dispatchers for different GitLab API URLs.
* This allows the server to efficiently handle requests to multiple GitLab instances
* by reusing dispatchers and their underlying TCP connections.
*/
export class GitLabClientPool {
private clients: Map<string, ClientDispatchers> = new Map();
private options: GitLabClientPoolOptions;
constructor(options: GitLabClientPoolOptions) {
this.options = options;
}
private createDispatchersForUrl(apiUrl: string): ClientDispatchers {
const { httpProxy, httpsProxy, noProxy, rejectUnauthorized, caCertPath } = this.options;
const tls: TlsConnectOptions = {};
if (rejectUnauthorized === false) {
tls.rejectUnauthorized = false;
} else if (caCertPath) {
try {
tls.ca = fs.readFileSync(caCertPath);
} catch (error) {
console.error(`Failed to read CA certificate from ${caCertPath}:`, error);
throw new Error(`Failed to read CA certificate: ${caCertPath}`);
}
}
const httpDirect = createDispatcher(undefined, tls);
const httpsDirect = createDispatcher(undefined, tls);
const httpProxyDispatcher = createDispatcher(httpProxy, tls);
const httpsProxyDispatcher = createDispatcher(httpsProxy, tls);
const bypassProxy = shouldBypassProxy(apiUrl, noProxy);
return {
httpDispatcher: bypassProxy ? httpDirect : httpProxyDispatcher,
httpsDispatcher: bypassProxy ? httpsDirect : httpsProxyDispatcher,
dispatcher: new ProtocolDispatcher(
httpDirect,
httpsDirect,
httpProxyDispatcher,
httpsProxyDispatcher,
noProxy
),
};
}
/**
* Retrieves the protocol-specific dispatcher for a given API URL.
* Used by NO_PROXY tests to distinguish Agent vs ProxyAgent.
*/
public getOrCreateAgentForUrl(apiUrl: string): Dispatcher {
const dispatchers = this.getOrCreateDispatchersForUrl(apiUrl);
const url = new URL(apiUrl);
return url.protocol === "https:" ? dispatchers.httpsDispatcher : dispatchers.httpDispatcher;
}
/**
* Returns a dispatcher that picks HTTP vs HTTPS based on the request origin.
* Needed when a self-hosted GitLab redirects between HTTP and HTTPS.
*/
public getDispatcherForUrl(apiUrl: string): Dispatcher {
return this.getOrCreateDispatchersForUrl(apiUrl).dispatcher;
}
/**
* Which inner dispatcher would handle `originUrl` after following a redirect
* from `apiUrl`. Used to verify NO_PROXY is re-evaluated per origin.
*/
public getDispatcherForOrigin(apiUrl: string, originUrl: string): Dispatcher {
const dispatcher = this.getOrCreateDispatchersForUrl(apiUrl).dispatcher;
if (dispatcher instanceof ProtocolDispatcher) {
return dispatcher.dispatcherForOrigin(originUrl);
}
return dispatcher;
}
private getOrCreateDispatchersForUrl(apiUrl: string): ClientDispatchers {
const url = new URL(apiUrl);
const apiIndex = url.pathname.lastIndexOf("/api/v4");
const basePath =
apiIndex === -1 ? url.pathname : url.pathname.substring(0, apiIndex + "/api/v4".length);
const baseUrl = `${url.protocol}//${url.host}${basePath}`;
if (!this.clients.has(baseUrl)) {
if (this.options.poolMaxSize !== undefined && this.clients.size >= this.options.poolMaxSize) {
throw new Error(
`Server capacity reached: Connection pool is full (max ${this.options.poolMaxSize} instances). Please try again later.`
);
}
this.clients.set(baseUrl, this.createDispatchersForUrl(baseUrl));
}
const dispatchers = this.clients.get(baseUrl);
if (!dispatchers) {
throw new Error(`Failed to create or get client for URL: ${baseUrl}`);
}
return dispatchers;
}
public getClient(apiUrl: string): ClientDispatchers | undefined {
return this.clients.get(apiUrl);
}
public getDefaultClient(): ClientDispatchers {
const defaultUrl = this.options.apiUrls?.[0];
if (!defaultUrl) {
throw new Error("No default API URL configured.");
}
if (!this.clients.has(defaultUrl)) {
this.clients.set(defaultUrl, this.createDispatchersForUrl(defaultUrl));
}
const client = this.clients.get(defaultUrl);
if (!client) {
throw new Error("No default API URL configured.");
}
return client;
}
public closeAll(): void {
for (const [, dispatchers] of this.clients) {
void dispatchers.httpDispatcher.destroy();
void dispatchers.httpsDispatcher.destroy();
}
this.clients.clear();
}
public getStats(): { size: number; maxSize: number } {
return {
size: this.clients.size,
maxSize: this.options.poolMaxSize ?? 0,
};
}
}