@promigence/sdk 0.1.0-beta.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +14 -0
- package/README.md +54 -0
- package/dist/blake3.d.ts +10 -0
- package/dist/blake3.js +111 -0
- package/dist/bundle.d.ts +96 -0
- package/dist/bundle.js +227 -0
- package/dist/ca-guard.d.ts +1 -0
- package/dist/ca-guard.js +166 -0
- package/dist/caller.d.ts +73 -0
- package/dist/caller.js +47 -0
- package/dist/cjs/blake3.d.ts +10 -0
- package/dist/cjs/blake3.js +116 -0
- package/dist/cjs/bundle.d.ts +96 -0
- package/dist/cjs/bundle.js +242 -0
- package/dist/cjs/ca-guard.d.ts +1 -0
- package/dist/cjs/ca-guard.js +174 -0
- package/dist/cjs/caller.d.ts +73 -0
- package/dist/cjs/caller.js +57 -0
- package/dist/cjs/client.d.ts +3015 -0
- package/dist/cjs/client.js +2617 -0
- package/dist/cjs/command-errors.d.ts +41 -0
- package/dist/cjs/command-errors.js +43 -0
- package/dist/cjs/context.d.ts +119 -0
- package/dist/cjs/context.js +598 -0
- package/dist/cjs/core.d.ts +285 -0
- package/dist/cjs/core.js +290 -0
- package/dist/cjs/credstore.d.ts +90 -0
- package/dist/cjs/credstore.js +219 -0
- package/dist/cjs/dispatcher.d.ts +58 -0
- package/dist/cjs/dispatcher.js +91 -0
- package/dist/cjs/github.d.ts +158 -0
- package/dist/cjs/github.js +84 -0
- package/dist/cjs/gitlab.d.ts +104 -0
- package/dist/cjs/gitlab.js +24 -0
- package/dist/cjs/handles.d.ts +82 -0
- package/dist/cjs/handles.js +139 -0
- package/dist/cjs/hint.d.ts +1 -0
- package/dist/cjs/hint.js +10 -0
- package/dist/cjs/http2.d.ts +206 -0
- package/dist/cjs/http2.js +1932 -0
- package/dist/cjs/index.d.ts +34 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/keyed.gen.d.ts +1 -0
- package/dist/cjs/keyed.gen.js +10 -0
- package/dist/cjs/models.gen.d.ts +6162 -0
- package/dist/cjs/models.gen.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/proxy.d.ts +40 -0
- package/dist/cjs/proxy.js +257 -0
- package/dist/cjs/pty.d.ts +171 -0
- package/dist/cjs/pty.js +504 -0
- package/dist/cjs/sandbox.d.ts +537 -0
- package/dist/cjs/sandbox.js +736 -0
- package/dist/cjs/ssh.d.ts +25 -0
- package/dist/cjs/ssh.js +117 -0
- package/dist/cjs/trace.d.ts +33 -0
- package/dist/cjs/trace.js +88 -0
- package/dist/cjs/transport-worker.d.ts +1 -0
- package/dist/cjs/transport-worker.js +468 -0
- package/dist/cjs/warm.d.ts +1 -0
- package/dist/cjs/warm.js +43 -0
- package/dist/client.d.ts +3015 -0
- package/dist/client.js +2583 -0
- package/dist/command-errors.d.ts +41 -0
- package/dist/command-errors.js +36 -0
- package/dist/context.d.ts +119 -0
- package/dist/context.js +588 -0
- package/dist/core.d.ts +285 -0
- package/dist/core.js +266 -0
- package/dist/credstore.d.ts +90 -0
- package/dist/credstore.js +206 -0
- package/dist/dispatcher.d.ts +58 -0
- package/dist/dispatcher.js +86 -0
- package/dist/github.d.ts +158 -0
- package/dist/github.js +78 -0
- package/dist/gitlab.d.ts +104 -0
- package/dist/gitlab.js +20 -0
- package/dist/handles.d.ts +82 -0
- package/dist/handles.js +135 -0
- package/dist/hint.d.ts +1 -0
- package/dist/hint.js +7 -0
- package/dist/http2.d.ts +206 -0
- package/dist/http2.js +1921 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +15 -0
- package/dist/keyed.gen.d.ts +1 -0
- package/dist/keyed.gen.js +7 -0
- package/dist/models.gen.d.ts +6162 -0
- package/dist/models.gen.js +1 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +249 -0
- package/dist/pty.d.ts +171 -0
- package/dist/pty.js +496 -0
- package/dist/sandbox.d.ts +537 -0
- package/dist/sandbox.js +725 -0
- package/dist/ssh.d.ts +25 -0
- package/dist/ssh.js +114 -0
- package/dist/trace.d.ts +33 -0
- package/dist/trace.js +80 -0
- package/dist/transport-worker.d.ts +1 -0
- package/dist/transport-worker.js +466 -0
- package/dist/warm.d.ts +1 -0
- package/dist/warm.js +40 -0
- package/package.json +54 -0
|
@@ -0,0 +1,1932 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.__http2Internals = exports.Http2Transport = exports.tuning = exports.H2Response = void 0;
|
|
4
|
+
exports.http2Allowed = http2Allowed;
|
|
5
|
+
exports.warmTls = warmTls;
|
|
6
|
+
exports.parseSessions = parseSessions;
|
|
7
|
+
exports.extraOrders = extraOrders;
|
|
8
|
+
exports.lookupApiName = lookupApiName;
|
|
9
|
+
exports.warmTransport = warmTransport;
|
|
10
|
+
const http2 = require("node:http2");
|
|
11
|
+
const node_net_1 = require("node:net");
|
|
12
|
+
const tls = require("node:tls");
|
|
13
|
+
const node_worker_threads_1 = require("node:worker_threads");
|
|
14
|
+
const zlib = require("node:zlib");
|
|
15
|
+
const ca_guard_js_1 = require("./ca-guard.js");
|
|
16
|
+
const core_js_1 = require("./core.js");
|
|
17
|
+
const dispatcher_js_1 = require("./dispatcher.js");
|
|
18
|
+
const trace_js_1 = require("./trace.js");
|
|
19
|
+
const MAX_SESSIONS = 4;
|
|
20
|
+
const FIRST_SESSIONS = 2;
|
|
21
|
+
const BURST_MIN = 8;
|
|
22
|
+
const HOLD_MS = 10;
|
|
23
|
+
const LOAD_FIRST_USE_MS = 120_000;
|
|
24
|
+
const CONNECT_TIMEOUT_MS = 10_000;
|
|
25
|
+
const IDLE_CLOSE_MS = 10_000;
|
|
26
|
+
const PING_TIMEOUT_MS = 2_000;
|
|
27
|
+
const RETRY_AFTER_MS = 30_000;
|
|
28
|
+
const MAX_UNPROCESSED_RESENDS = 3;
|
|
29
|
+
const MAX_REPLAYS = 1;
|
|
30
|
+
const MAX_CONNECT_FAILURES = 3;
|
|
31
|
+
const MAX_BAD_SESSIONS = 3;
|
|
32
|
+
const MAX_STREAM_FAILURES = 5;
|
|
33
|
+
const DEFAULT_STREAM_LIMIT = 100;
|
|
34
|
+
const MAX_STREAM_LIMIT = 1_000;
|
|
35
|
+
const STREAM_WINDOW = 8 * 1024 * 1024;
|
|
36
|
+
const SESSION_WINDOW = 32 * 1024 * 1024;
|
|
37
|
+
const { NGHTTP2_CANCEL, NGHTTP2_REFUSED_STREAM, NGHTTP2_HTTP_1_1_REQUIRED } = http2.constants;
|
|
38
|
+
const FETCH_AT_LOAD = globalThis.fetch;
|
|
39
|
+
const PROXY_VARS = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"];
|
|
40
|
+
const OFF = new Set(["0", "false", "off", "no"]);
|
|
41
|
+
const NOT_IN_H2 = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade", "host", "te"]);
|
|
42
|
+
function http2Allowed(opt, env = process.env) {
|
|
43
|
+
try {
|
|
44
|
+
const envFlag = env["PROMIGENCE_HTTP2"]?.trim().toLowerCase();
|
|
45
|
+
const wanted = opt ?? (envFlag === undefined || envFlag === "" ? true : !OFF.has(envFlag));
|
|
46
|
+
if (!wanted)
|
|
47
|
+
return false;
|
|
48
|
+
if (!isNode())
|
|
49
|
+
return false;
|
|
50
|
+
if (typeof http2.connect !== "function")
|
|
51
|
+
return false;
|
|
52
|
+
if (globalThis.fetch !== FETCH_AT_LOAD)
|
|
53
|
+
return false;
|
|
54
|
+
if ((0, dispatcher_js_1.customDispatcher)())
|
|
55
|
+
return false;
|
|
56
|
+
if (PROXY_VARS.some((k) => (env[k] ?? "").trim() !== ""))
|
|
57
|
+
return false;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function isNode() {
|
|
65
|
+
const v = typeof process === "object" ? process.versions : undefined;
|
|
66
|
+
return Boolean(v?.["node"]) && !v?.["bun"] && !v?.["deno"];
|
|
67
|
+
}
|
|
68
|
+
let tlsWarmed = false;
|
|
69
|
+
function warmTls() {
|
|
70
|
+
if (tlsWarmed)
|
|
71
|
+
return;
|
|
72
|
+
tlsWarmed = true;
|
|
73
|
+
try {
|
|
74
|
+
if (isNode())
|
|
75
|
+
tls.createSecureContext();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const utf8 = new TextDecoder("utf-8");
|
|
81
|
+
class H2Response {
|
|
82
|
+
status;
|
|
83
|
+
raw;
|
|
84
|
+
bytes;
|
|
85
|
+
ok;
|
|
86
|
+
built;
|
|
87
|
+
constructor(status, raw, bytes) {
|
|
88
|
+
this.status = status;
|
|
89
|
+
this.raw = raw;
|
|
90
|
+
this.bytes = bytes;
|
|
91
|
+
this.ok = status >= 200 && status < 300;
|
|
92
|
+
}
|
|
93
|
+
replayed = false;
|
|
94
|
+
header(name) {
|
|
95
|
+
const v = this.raw[name.toLowerCase()];
|
|
96
|
+
if (v === undefined)
|
|
97
|
+
return null;
|
|
98
|
+
return Array.isArray(v) ? v.join(", ") : String(v);
|
|
99
|
+
}
|
|
100
|
+
textNow() {
|
|
101
|
+
const b = this.bytes;
|
|
102
|
+
if (b === null || b.length === 0)
|
|
103
|
+
return "";
|
|
104
|
+
return utf8.decode(b);
|
|
105
|
+
}
|
|
106
|
+
get headers() {
|
|
107
|
+
if (this.built === undefined) {
|
|
108
|
+
const h = new Headers();
|
|
109
|
+
for (const [k, v] of Object.entries(this.raw)) {
|
|
110
|
+
if (k.startsWith(":") || v === undefined)
|
|
111
|
+
continue;
|
|
112
|
+
if (Array.isArray(v))
|
|
113
|
+
for (const x of v)
|
|
114
|
+
h.append(k, x);
|
|
115
|
+
else
|
|
116
|
+
h.append(k, String(v));
|
|
117
|
+
}
|
|
118
|
+
this.built = h;
|
|
119
|
+
}
|
|
120
|
+
return this.built;
|
|
121
|
+
}
|
|
122
|
+
text() {
|
|
123
|
+
return Promise.resolve(this.textNow());
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
exports.H2Response = H2Response;
|
|
127
|
+
class OriginPool {
|
|
128
|
+
origin;
|
|
129
|
+
sessions = [];
|
|
130
|
+
connecting;
|
|
131
|
+
backgrounds = [];
|
|
132
|
+
opening;
|
|
133
|
+
holding = false;
|
|
134
|
+
parked;
|
|
135
|
+
warmed = 0;
|
|
136
|
+
off = false;
|
|
137
|
+
offReason = "";
|
|
138
|
+
suspendedUntil = 0;
|
|
139
|
+
connectFailures = 0;
|
|
140
|
+
badSessions = 0;
|
|
141
|
+
streamFailures = 0;
|
|
142
|
+
opened = 0;
|
|
143
|
+
knownLimit;
|
|
144
|
+
constructor(origin) {
|
|
145
|
+
this.origin = origin;
|
|
146
|
+
}
|
|
147
|
+
usable() {
|
|
148
|
+
return !this.off && Date.now() >= this.suspendedUntil;
|
|
149
|
+
}
|
|
150
|
+
turnOff(reason) {
|
|
151
|
+
if (!this.off) {
|
|
152
|
+
this.off = true;
|
|
153
|
+
this.offReason = reason;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
tryAcquire() {
|
|
157
|
+
if (this.holding)
|
|
158
|
+
return undefined;
|
|
159
|
+
const best = this.leastLoaded();
|
|
160
|
+
if (best === undefined)
|
|
161
|
+
return undefined;
|
|
162
|
+
if (best.gotSettings && best.active >= streamLimit(best) && this.sessions.length < MAX_SESSIONS)
|
|
163
|
+
return undefined;
|
|
164
|
+
this.begin(best);
|
|
165
|
+
return best;
|
|
166
|
+
}
|
|
167
|
+
acquire(deadline, signal) {
|
|
168
|
+
if (signal?.aborted)
|
|
169
|
+
return Promise.reject(signal.reason);
|
|
170
|
+
return new Promise((resolve, reject) => {
|
|
171
|
+
let done = false;
|
|
172
|
+
let rounds = 0;
|
|
173
|
+
let counted;
|
|
174
|
+
const settle = () => {
|
|
175
|
+
done = true;
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
if (signal !== undefined)
|
|
178
|
+
signal.removeEventListener("abort", onAbort);
|
|
179
|
+
if (counted !== undefined && !counted.released)
|
|
180
|
+
counted.waiters--;
|
|
181
|
+
counted = undefined;
|
|
182
|
+
};
|
|
183
|
+
const onAbort = () => { if (!done) {
|
|
184
|
+
settle();
|
|
185
|
+
reject(signal?.reason);
|
|
186
|
+
} };
|
|
187
|
+
const timer = setTimeout(() => { if (!done) {
|
|
188
|
+
settle();
|
|
189
|
+
reject(timeoutReason());
|
|
190
|
+
} }, Math.max(0, deadline - performance.now()));
|
|
191
|
+
timer.unref?.();
|
|
192
|
+
if (signal !== undefined)
|
|
193
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
194
|
+
const attempt = (opened) => {
|
|
195
|
+
if (done)
|
|
196
|
+
return;
|
|
197
|
+
counted = undefined;
|
|
198
|
+
try {
|
|
199
|
+
if (!this.usable()) {
|
|
200
|
+
settle();
|
|
201
|
+
resolve(null);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const ready = this.tryAcquire();
|
|
205
|
+
if (ready !== undefined) {
|
|
206
|
+
settle();
|
|
207
|
+
resolve(ready);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (opened === null || ++rounds > MAX_SESSIONS + 1) {
|
|
211
|
+
const any = this.leastLoaded();
|
|
212
|
+
if (any !== undefined)
|
|
213
|
+
this.begin(any);
|
|
214
|
+
settle();
|
|
215
|
+
resolve(any ?? null);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (!this.connecting) {
|
|
219
|
+
this.unpark();
|
|
220
|
+
const opening = this.leastLoaded() === undefined ? this.openFirst(false) : this.open();
|
|
221
|
+
this.connecting = opening.finally(() => { this.connecting = undefined; });
|
|
222
|
+
}
|
|
223
|
+
this.hold();
|
|
224
|
+
const o = this.opening;
|
|
225
|
+
if (o !== undefined && !o.released) {
|
|
226
|
+
o.waiters++;
|
|
227
|
+
counted = o;
|
|
228
|
+
}
|
|
229
|
+
this.connecting.then(attempt, () => attempt(null));
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
settle();
|
|
233
|
+
resolve(null);
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
attempt(undefined);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
leastLoaded() {
|
|
240
|
+
let best;
|
|
241
|
+
for (const e of this.sessions) {
|
|
242
|
+
if (e.retired || e.session.closed || e.session.destroyed)
|
|
243
|
+
continue;
|
|
244
|
+
if (!best || e.active < best.active)
|
|
245
|
+
best = e;
|
|
246
|
+
}
|
|
247
|
+
return best;
|
|
248
|
+
}
|
|
249
|
+
warm(firstUseMs) {
|
|
250
|
+
if (!this.usable() || this.connecting !== undefined || this.leastLoaded() !== undefined || this.parked !== undefined)
|
|
251
|
+
return;
|
|
252
|
+
const route = backgroundRoute(this.origin);
|
|
253
|
+
if (route.kind === "none") {
|
|
254
|
+
(0, trace_js_1.traceEvent)("h2:warm-none");
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (route.kind === "wait") {
|
|
258
|
+
const parked = { cancelled: false };
|
|
259
|
+
this.parked = parked;
|
|
260
|
+
(0, trace_js_1.traceEvent)("h2:warm-park");
|
|
261
|
+
onEarlyAnswer(route.early, () => {
|
|
262
|
+
if (parked.cancelled || this.parked !== parked)
|
|
263
|
+
return;
|
|
264
|
+
this.parked = undefined;
|
|
265
|
+
const next = backgroundRoute(this.origin);
|
|
266
|
+
if (next.kind === "answer")
|
|
267
|
+
this.startWarm(firstUseMs, next.answer);
|
|
268
|
+
else
|
|
269
|
+
(0, trace_js_1.traceEvent)("h2:warm-none");
|
|
270
|
+
});
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
this.startWarm(firstUseMs, route.kind === "answer" ? route.answer : undefined);
|
|
274
|
+
}
|
|
275
|
+
startWarm(firstUseMs, pre) {
|
|
276
|
+
if (!this.usable() || this.connecting !== undefined || this.leastLoaded() !== undefined)
|
|
277
|
+
return;
|
|
278
|
+
if (pre !== undefined && !busyElsewhere()) {
|
|
279
|
+
(0, trace_js_1.traceEvent)("h2:warm-idle");
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
this.warmed++;
|
|
283
|
+
(0, trace_js_1.traceEvent)("h2:warm");
|
|
284
|
+
const opening = this.openFirst(true, firstUseMs, pre).finally(() => { this.connecting = undefined; });
|
|
285
|
+
this.connecting = opening;
|
|
286
|
+
opening.catch(() => { });
|
|
287
|
+
}
|
|
288
|
+
isConnecting() { return this.connecting !== undefined; }
|
|
289
|
+
isParked() { return this.parked !== undefined; }
|
|
290
|
+
unpark() {
|
|
291
|
+
if (this.parked === undefined)
|
|
292
|
+
return;
|
|
293
|
+
this.parked.cancelled = true;
|
|
294
|
+
this.parked = undefined;
|
|
295
|
+
(0, trace_js_1.traceEvent)("h2:warm-unpark");
|
|
296
|
+
}
|
|
297
|
+
hold() {
|
|
298
|
+
for (const bg of this.backgrounds) {
|
|
299
|
+
if (bg.held)
|
|
300
|
+
continue;
|
|
301
|
+
bg.held = true;
|
|
302
|
+
safely(() => { bg.socket?.ref(); });
|
|
303
|
+
safely(() => { bg.timer?.ref?.(); });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
track() {
|
|
307
|
+
const bg = { held: false, done: false, socket: undefined, timer: undefined };
|
|
308
|
+
this.backgrounds.push(bg);
|
|
309
|
+
return bg;
|
|
310
|
+
}
|
|
311
|
+
untrack(bg) {
|
|
312
|
+
const k = this.backgrounds.indexOf(bg);
|
|
313
|
+
if (k >= 0)
|
|
314
|
+
this.backgrounds.splice(k, 1);
|
|
315
|
+
}
|
|
316
|
+
openFirst(background, firstUseMs, pre) {
|
|
317
|
+
const n = sessionsWanted();
|
|
318
|
+
const idle = firstUseMs === undefined ? {} : { firstUseMs };
|
|
319
|
+
const ownOpts = pre === undefined ? idle : { ...idle, preResolved: pre };
|
|
320
|
+
if (n <= 1) {
|
|
321
|
+
if (!background)
|
|
322
|
+
return this.open(undefined, ownOpts);
|
|
323
|
+
const bg = this.track();
|
|
324
|
+
return this.open(bg, ownOpts).finally(() => { this.untrack(bg); });
|
|
325
|
+
}
|
|
326
|
+
let resolve;
|
|
327
|
+
const handed = new Promise((r) => { resolve = r; });
|
|
328
|
+
const own = this.track();
|
|
329
|
+
const o = { waiters: 0, pending: 1, first: null, own, released: false, hold: undefined, resolve };
|
|
330
|
+
this.opening = o;
|
|
331
|
+
let started = false;
|
|
332
|
+
const observe = (answer) => {
|
|
333
|
+
if (started || o.released || !this.usable())
|
|
334
|
+
return;
|
|
335
|
+
started = true;
|
|
336
|
+
for (const order of extraOrders(answer, n)) {
|
|
337
|
+
o.pending++;
|
|
338
|
+
(0, trace_js_1.traceEvent)("h2:extra");
|
|
339
|
+
const bg = { held: false, done: false, socket: undefined, timer: undefined };
|
|
340
|
+
this.open(bg, { ...idle, answer: order }).then((e) => { this.settled(o, e, false); }, () => { this.settled(o, null, false); });
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
this.open(own, pre === undefined ? { ...idle, observe } : ownOpts).finally(() => { this.untrack(own); })
|
|
344
|
+
.then((e) => { this.settled(o, e, true); }, () => { this.settled(o, null, true); });
|
|
345
|
+
if (pre !== undefined)
|
|
346
|
+
observe(pre);
|
|
347
|
+
return handed;
|
|
348
|
+
}
|
|
349
|
+
settled(o, entry, own) {
|
|
350
|
+
o.pending--;
|
|
351
|
+
if (o.released)
|
|
352
|
+
return;
|
|
353
|
+
if (entry !== null && o.first === null)
|
|
354
|
+
o.first = entry;
|
|
355
|
+
if (o.first === null) {
|
|
356
|
+
if (own || o.pending === 0)
|
|
357
|
+
this.release(o);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (o.pending === 0) {
|
|
361
|
+
this.release(o);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (o.hold !== undefined)
|
|
365
|
+
return;
|
|
366
|
+
if (o.waiters >= exports.tuning.burstMin && exports.tuning.holdMs > 0) {
|
|
367
|
+
this.holding = true;
|
|
368
|
+
(0, trace_js_1.traceEvent)("h2:hold");
|
|
369
|
+
o.hold = setTimeout(() => { this.release(o); }, exports.tuning.holdMs);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
this.release(o);
|
|
373
|
+
}
|
|
374
|
+
release(o) {
|
|
375
|
+
if (o.released)
|
|
376
|
+
return;
|
|
377
|
+
o.released = true;
|
|
378
|
+
if (o.hold !== undefined) {
|
|
379
|
+
clearTimeout(o.hold);
|
|
380
|
+
o.hold = undefined;
|
|
381
|
+
}
|
|
382
|
+
if (this.opening === o) {
|
|
383
|
+
this.opening = undefined;
|
|
384
|
+
this.holding = false;
|
|
385
|
+
}
|
|
386
|
+
this.untrack(o.own);
|
|
387
|
+
if (!o.own.done && o.own.held) {
|
|
388
|
+
o.own.held = false;
|
|
389
|
+
safely(() => { o.own.socket?.unref(); });
|
|
390
|
+
safely(() => { o.own.timer?.unref?.(); });
|
|
391
|
+
}
|
|
392
|
+
(0, trace_js_1.traceEvent)("h2:release");
|
|
393
|
+
o.resolve(o.first);
|
|
394
|
+
}
|
|
395
|
+
async open(bg, o = {}) {
|
|
396
|
+
const growing = this.leastLoaded() !== undefined;
|
|
397
|
+
const extra = o.answer !== undefined;
|
|
398
|
+
const pre = o.preResolved;
|
|
399
|
+
let asked = { v4: false, early: false };
|
|
400
|
+
const lookup = extra ? fixedLookup(o.answer) : pre !== undefined ? fixedLookup(pre) : apiLookup(asked, o.observe);
|
|
401
|
+
let res = await tlsConnect(this.origin, bg, lookup, extra || pre !== undefined);
|
|
402
|
+
if ((pre !== undefined || asked.early) && !(res.ok && res.socket.alpnProtocol === "h2") && !givenUp(res)) {
|
|
403
|
+
if (res.ok)
|
|
404
|
+
res.socket.destroy();
|
|
405
|
+
if (pre !== undefined && (bg === undefined || !bg.held))
|
|
406
|
+
return null;
|
|
407
|
+
(0, trace_js_1.traceEvent)("dns:fallback");
|
|
408
|
+
if (bg !== undefined)
|
|
409
|
+
bg.done = false;
|
|
410
|
+
asked = { v4: false, early: false };
|
|
411
|
+
res = await tlsConnect(this.origin, bg, apiLookup(asked, undefined, undefined, false), false);
|
|
412
|
+
}
|
|
413
|
+
if (!res.ok && res.phase === "tcp" && asked.v4 && res.error?.givenUp !== true) {
|
|
414
|
+
(0, trace_js_1.traceEvent)("dns:both");
|
|
415
|
+
if (bg !== undefined)
|
|
416
|
+
bg.done = false;
|
|
417
|
+
res = await tlsConnect(this.origin, bg, apiLookup({ v4: false }, undefined, false), extra);
|
|
418
|
+
}
|
|
419
|
+
if (!res.ok) {
|
|
420
|
+
if (growing || extra)
|
|
421
|
+
return null;
|
|
422
|
+
if (o.observe !== undefined && this.leastLoaded() !== undefined)
|
|
423
|
+
return null;
|
|
424
|
+
if (bg !== undefined && !bg.held && res.phase === "tcp")
|
|
425
|
+
return null;
|
|
426
|
+
if (res.phase === "tls") {
|
|
427
|
+
this.turnOff(`TLS handshake failed: ${errCode(res.error)}`);
|
|
428
|
+
}
|
|
429
|
+
else if (++this.connectFailures >= MAX_CONNECT_FAILURES) {
|
|
430
|
+
this.turnOff(`connect failed ${this.connectFailures} times: ${errCode(res.error)}`);
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
this.suspendedUntil = Date.now() + RETRY_AFTER_MS;
|
|
434
|
+
}
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
const socket = res.socket;
|
|
438
|
+
if (socket.alpnProtocol !== "h2") {
|
|
439
|
+
socket.destroy();
|
|
440
|
+
if (!extra)
|
|
441
|
+
this.turnOff(`server chose ${socket.alpnProtocol || "no protocol"} over h2`);
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
this.connectFailures = 0;
|
|
445
|
+
let session;
|
|
446
|
+
try {
|
|
447
|
+
session = http2.connect(this.origin.origin, {
|
|
448
|
+
createConnection: () => socket,
|
|
449
|
+
settings: { enablePush: false, initialWindowSize: STREAM_WINDOW },
|
|
450
|
+
...(this.knownLimit === undefined ? {} : { peerMaxConcurrentStreams: this.knownLimit }),
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
catch (err) {
|
|
454
|
+
socket.destroy();
|
|
455
|
+
if (!extra)
|
|
456
|
+
this.turnOff(`http2.connect threw: ${errCode(err)}`);
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
const entry = {
|
|
460
|
+
session, active: 0, retired: false, goawayLast: undefined, idleTimer: undefined,
|
|
461
|
+
pinging: false, lostStreams: 0, gotSettings: false,
|
|
462
|
+
};
|
|
463
|
+
(0, trace_js_1.traceEvent)("h2:session");
|
|
464
|
+
session.on("remoteSettings", (settings) => {
|
|
465
|
+
(0, trace_js_1.traceEvent)("h2:settings");
|
|
466
|
+
entry.gotSettings = true;
|
|
467
|
+
const m = settings.maxConcurrentStreams;
|
|
468
|
+
if (typeof m === "number" && m > 0)
|
|
469
|
+
this.knownLimit = Math.min(m, MAX_STREAM_LIMIT);
|
|
470
|
+
});
|
|
471
|
+
session.on("error", () => { this.retire(entry); });
|
|
472
|
+
session.on("goaway", (_code, lastStreamId) => {
|
|
473
|
+
entry.goawayLast = Math.min(entry.goawayLast ?? lastStreamId, lastStreamId);
|
|
474
|
+
this.retire(entry);
|
|
475
|
+
});
|
|
476
|
+
session.on("close", () => { this.retire(entry); });
|
|
477
|
+
safely(() => session.setLocalWindowSize(SESSION_WINDOW));
|
|
478
|
+
session.on("frameError", () => { });
|
|
479
|
+
this.sessions.push(entry);
|
|
480
|
+
this.opened++;
|
|
481
|
+
this.markIdle(entry, o.firstUseMs);
|
|
482
|
+
return entry;
|
|
483
|
+
}
|
|
484
|
+
retire(entry) {
|
|
485
|
+
if (entry.idleTimer !== undefined) {
|
|
486
|
+
clearTimeout(entry.idleTimer);
|
|
487
|
+
entry.idleTimer = undefined;
|
|
488
|
+
}
|
|
489
|
+
if (entry.retired)
|
|
490
|
+
return;
|
|
491
|
+
entry.retired = true;
|
|
492
|
+
const i = this.sessions.indexOf(entry);
|
|
493
|
+
if (i >= 0)
|
|
494
|
+
this.sessions.splice(i, 1);
|
|
495
|
+
if (entry.active === 0)
|
|
496
|
+
safely(() => entry.session.unref());
|
|
497
|
+
}
|
|
498
|
+
begin(entry) {
|
|
499
|
+
if (entry.idleTimer !== undefined) {
|
|
500
|
+
clearTimeout(entry.idleTimer);
|
|
501
|
+
entry.idleTimer = undefined;
|
|
502
|
+
}
|
|
503
|
+
if (entry.active++ === 0)
|
|
504
|
+
safely(() => entry.session.ref());
|
|
505
|
+
}
|
|
506
|
+
end(entry) {
|
|
507
|
+
entry.active = Math.max(0, entry.active - 1);
|
|
508
|
+
if (entry.active === 0)
|
|
509
|
+
this.markIdle(entry);
|
|
510
|
+
}
|
|
511
|
+
markIdle(entry, ms = IDLE_CLOSE_MS) {
|
|
512
|
+
safely(() => entry.session.unref());
|
|
513
|
+
if (entry.retired)
|
|
514
|
+
return;
|
|
515
|
+
entry.idleTimer = setTimeout(() => {
|
|
516
|
+
entry.idleTimer = undefined;
|
|
517
|
+
if (entry.active !== 0)
|
|
518
|
+
return;
|
|
519
|
+
this.retire(entry);
|
|
520
|
+
safely(() => entry.session.close());
|
|
521
|
+
}, ms);
|
|
522
|
+
entry.idleTimer.unref?.();
|
|
523
|
+
}
|
|
524
|
+
succeeded() {
|
|
525
|
+
this.streamFailures = 0;
|
|
526
|
+
this.badSessions = 0;
|
|
527
|
+
}
|
|
528
|
+
streamFailed(entry, sessionDying) {
|
|
529
|
+
if (sessionDying) {
|
|
530
|
+
if (entry.lostStreams++ === 0 && ++this.badSessions >= MAX_BAD_SESSIONS) {
|
|
531
|
+
this.turnOff(`${this.badSessions} sessions in a row died with requests in flight`);
|
|
532
|
+
}
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (++this.streamFailures >= MAX_STREAM_FAILURES)
|
|
536
|
+
this.turnOff(`${this.streamFailures} requests in a row failed on a live session`);
|
|
537
|
+
}
|
|
538
|
+
checkAlive(entry) {
|
|
539
|
+
if (entry.pinging || entry.retired)
|
|
540
|
+
return;
|
|
541
|
+
entry.pinging = true;
|
|
542
|
+
const drop = () => {
|
|
543
|
+
if (++this.badSessions >= MAX_BAD_SESSIONS)
|
|
544
|
+
this.turnOff(`${this.badSessions} sessions in a row stopped answering`);
|
|
545
|
+
this.retire(entry);
|
|
546
|
+
safely(() => entry.session.destroy());
|
|
547
|
+
};
|
|
548
|
+
const timer = setTimeout(drop, PING_TIMEOUT_MS);
|
|
549
|
+
timer.unref?.();
|
|
550
|
+
try {
|
|
551
|
+
const sent = entry.session.ping((err) => {
|
|
552
|
+
entry.pinging = false;
|
|
553
|
+
clearTimeout(timer);
|
|
554
|
+
if (err)
|
|
555
|
+
drop();
|
|
556
|
+
});
|
|
557
|
+
if (!sent) {
|
|
558
|
+
clearTimeout(timer);
|
|
559
|
+
entry.pinging = false;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
catch {
|
|
563
|
+
clearTimeout(timer);
|
|
564
|
+
entry.pinging = false;
|
|
565
|
+
drop();
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
exports.tuning = {
|
|
570
|
+
sessions: undefined,
|
|
571
|
+
holdMs: HOLD_MS,
|
|
572
|
+
burstMin: BURST_MIN,
|
|
573
|
+
loadFirstUseMs: LOAD_FIRST_USE_MS,
|
|
574
|
+
earlyPlatform: undefined,
|
|
575
|
+
earlyServers: undefined,
|
|
576
|
+
earlyHostsFile: undefined,
|
|
577
|
+
};
|
|
578
|
+
let sessionsFromEnv;
|
|
579
|
+
function sessionsWanted() {
|
|
580
|
+
if (exports.tuning.sessions !== undefined)
|
|
581
|
+
return parseSessions(String(exports.tuning.sessions));
|
|
582
|
+
if (sessionsFromEnv === undefined) {
|
|
583
|
+
let raw;
|
|
584
|
+
try {
|
|
585
|
+
raw = process.env["PROMIGENCE_HTTP2_SESSIONS"];
|
|
586
|
+
}
|
|
587
|
+
catch {
|
|
588
|
+
raw = undefined;
|
|
589
|
+
}
|
|
590
|
+
sessionsFromEnv = parseSessions(raw);
|
|
591
|
+
}
|
|
592
|
+
return sessionsFromEnv;
|
|
593
|
+
}
|
|
594
|
+
function parseSessions(raw) {
|
|
595
|
+
const t = raw?.trim().toLowerCase() ?? "";
|
|
596
|
+
if (t === "")
|
|
597
|
+
return FIRST_SESSIONS;
|
|
598
|
+
if (OFF.has(t))
|
|
599
|
+
return 1;
|
|
600
|
+
const n = Number(t);
|
|
601
|
+
if (!Number.isInteger(n) || n < 0)
|
|
602
|
+
return FIRST_SESSIONS;
|
|
603
|
+
return Math.max(1, Math.min(MAX_SESSIONS, n));
|
|
604
|
+
}
|
|
605
|
+
function extraOrders(answer, sessions) {
|
|
606
|
+
if (sessions <= 1 || answer.length < 2)
|
|
607
|
+
return [];
|
|
608
|
+
const family = answer[0].family;
|
|
609
|
+
const seen = new Set();
|
|
610
|
+
const mine = [];
|
|
611
|
+
const other = [];
|
|
612
|
+
for (const a of answer) {
|
|
613
|
+
if (typeof a?.address !== "string" || seen.has(a.address))
|
|
614
|
+
continue;
|
|
615
|
+
seen.add(a.address);
|
|
616
|
+
(a.family === family ? mine : other).push(a);
|
|
617
|
+
}
|
|
618
|
+
const rot = (list, by) => {
|
|
619
|
+
if (list.length === 0)
|
|
620
|
+
return [];
|
|
621
|
+
const k = by % list.length;
|
|
622
|
+
return [...list.slice(k), ...list.slice(0, k)];
|
|
623
|
+
};
|
|
624
|
+
const out = [];
|
|
625
|
+
for (let i = 1; i < Math.min(sessions, mine.length); i++)
|
|
626
|
+
out.push([...rot(mine, i), ...rot(other, i)]);
|
|
627
|
+
return out;
|
|
628
|
+
}
|
|
629
|
+
function streamLimit(entry) {
|
|
630
|
+
try {
|
|
631
|
+
const m = entry.session.remoteSettings?.maxConcurrentStreams;
|
|
632
|
+
return typeof m === "number" && m > 0 ? Math.min(m, MAX_STREAM_LIMIT) : DEFAULT_STREAM_LIMIT;
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
return DEFAULT_STREAM_LIMIT;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
function safely(fn) {
|
|
639
|
+
try {
|
|
640
|
+
fn();
|
|
641
|
+
}
|
|
642
|
+
catch { }
|
|
643
|
+
}
|
|
644
|
+
function errCode(err) {
|
|
645
|
+
const e = err;
|
|
646
|
+
return e?.code ?? e?.message ?? String(err);
|
|
647
|
+
}
|
|
648
|
+
const TRANSIENT = new Set(["ECONNRESET", "ETIMEDOUT", "EPIPE", "ECONNABORTED", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN"]);
|
|
649
|
+
const IDLE_CHECK_MS = 5;
|
|
650
|
+
const onTheWire = new Set();
|
|
651
|
+
let idleCheck;
|
|
652
|
+
function activeResources() {
|
|
653
|
+
try {
|
|
654
|
+
const info = process.getActiveResourcesInfo;
|
|
655
|
+
return typeof info === "function" ? info.call(process) : undefined;
|
|
656
|
+
}
|
|
657
|
+
catch {
|
|
658
|
+
return undefined;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
function watchWire(w) {
|
|
662
|
+
onTheWire.add(w);
|
|
663
|
+
if (idleCheck !== undefined)
|
|
664
|
+
return;
|
|
665
|
+
idleCheck = setInterval(checkIdle, IDLE_CHECK_MS);
|
|
666
|
+
safely(() => { idleCheck?.unref?.(); });
|
|
667
|
+
}
|
|
668
|
+
function unwatchWire(w) {
|
|
669
|
+
if (!onTheWire.delete(w))
|
|
670
|
+
return;
|
|
671
|
+
if (onTheWire.size === 0 && idleCheck !== undefined) {
|
|
672
|
+
clearInterval(idleCheck);
|
|
673
|
+
idleCheck = undefined;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function checkIdle() {
|
|
677
|
+
const info = activeResources();
|
|
678
|
+
if (info === undefined)
|
|
679
|
+
return;
|
|
680
|
+
let connects = 0, lookups = 0, timers = 0;
|
|
681
|
+
for (const t of info) {
|
|
682
|
+
if (t === "ConnectWrap")
|
|
683
|
+
connects++;
|
|
684
|
+
else if (t === "GetAddrInfoReqWrap")
|
|
685
|
+
lookups++;
|
|
686
|
+
else if (t === "Timeout")
|
|
687
|
+
timers++;
|
|
688
|
+
else if (t !== "PipeWrap" && t !== "TTYWrap")
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
let c = 0, l = 0, t = 0;
|
|
692
|
+
for (const w of onTheWire) {
|
|
693
|
+
if (w.bg.held)
|
|
694
|
+
return;
|
|
695
|
+
if (w.tcp)
|
|
696
|
+
c++;
|
|
697
|
+
if (w.lookup)
|
|
698
|
+
l++;
|
|
699
|
+
if (w.attemptTimer)
|
|
700
|
+
t++;
|
|
701
|
+
}
|
|
702
|
+
if (connects > c || lookups > l || timers > t)
|
|
703
|
+
return;
|
|
704
|
+
for (const w of [...onTheWire])
|
|
705
|
+
safely(w.giveUp);
|
|
706
|
+
}
|
|
707
|
+
function tlsConnect(origin, bg, lookup, fixed = false) {
|
|
708
|
+
return new Promise((resolve) => {
|
|
709
|
+
const host = origin.hostname.replace(/^\[(.*)\]$/, "$1");
|
|
710
|
+
const port = origin.port ? Number(origin.port) : 443;
|
|
711
|
+
let tcpUp = false;
|
|
712
|
+
let done = false;
|
|
713
|
+
let socket;
|
|
714
|
+
const release = () => {
|
|
715
|
+
if (bg !== undefined && !bg.held && !done)
|
|
716
|
+
safely(() => { socket.unref(); });
|
|
717
|
+
};
|
|
718
|
+
let wire;
|
|
719
|
+
const finish = (r) => {
|
|
720
|
+
if (done)
|
|
721
|
+
return;
|
|
722
|
+
done = true;
|
|
723
|
+
if (bg !== undefined)
|
|
724
|
+
bg.done = true;
|
|
725
|
+
if (wire !== undefined)
|
|
726
|
+
unwatchWire(wire);
|
|
727
|
+
clearTimeout(timer);
|
|
728
|
+
socket.removeListener("error", onError);
|
|
729
|
+
if (bg !== undefined)
|
|
730
|
+
socket.removeListener("connectionAttempt", release);
|
|
731
|
+
if (!r.ok)
|
|
732
|
+
socket.destroy();
|
|
733
|
+
resolve(r);
|
|
734
|
+
};
|
|
735
|
+
const onError = (error) => {
|
|
736
|
+
const phase = tcpUp && !TRANSIENT.has(errCode(error)) ? "tls" : "tcp";
|
|
737
|
+
finish({ ok: false, phase, error });
|
|
738
|
+
};
|
|
739
|
+
const timer = setTimeout(() => {
|
|
740
|
+
finish({ ok: false, phase: "tcp", error: Object.assign(new Error("connect timed out"), { code: "ETIMEDOUT" }) });
|
|
741
|
+
}, CONNECT_TIMEOUT_MS);
|
|
742
|
+
try {
|
|
743
|
+
(0, trace_js_1.traceEvent)("tls:connect");
|
|
744
|
+
socket = tls.connect({
|
|
745
|
+
host,
|
|
746
|
+
port,
|
|
747
|
+
...((0, node_net_1.isIP)(host) ? {} : { servername: host }),
|
|
748
|
+
ALPNProtocols: ["h2", "http/1.1"],
|
|
749
|
+
checkServerIdentity: ca_guard_js_1.guardCertChain,
|
|
750
|
+
...(lookup === undefined || (0, node_net_1.isIP)(host) ? {} : { lookup }),
|
|
751
|
+
});
|
|
752
|
+
(0, trace_js_1.traceEvent)("tls:connect-returned");
|
|
753
|
+
}
|
|
754
|
+
catch (error) {
|
|
755
|
+
clearTimeout(timer);
|
|
756
|
+
resolve({ ok: false, phase: "tls", error });
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (bg !== undefined) {
|
|
760
|
+
bg.socket = socket;
|
|
761
|
+
bg.timer = timer;
|
|
762
|
+
if (!bg.held)
|
|
763
|
+
safely(() => { timer.unref?.(); });
|
|
764
|
+
release();
|
|
765
|
+
socket.on("connectionAttempt", release);
|
|
766
|
+
const w = {
|
|
767
|
+
bg, lookup: !(0, node_net_1.isIP)(host) && !fixed, tcp: false, attemptTimer: false, addresses: new Set(), attempts: 0,
|
|
768
|
+
giveUp: () => finish({ ok: false, phase: "tcp", error: Object.assign(new Error("connect given up: nothing else keeps the process alive"), { code: "ECONNABORTED", givenUp: true }) }),
|
|
769
|
+
};
|
|
770
|
+
const attemptOver = () => { w.tcp = false; w.attemptTimer = false; };
|
|
771
|
+
socket.on("lookup", (_err, ip) => { w.lookup = false; if (typeof ip === "string")
|
|
772
|
+
w.addresses.add(ip); });
|
|
773
|
+
socket.on("connectionAttempt", () => { w.tcp = true; w.attempts++; w.attemptTimer = w.addresses.size > w.attempts; });
|
|
774
|
+
socket.on("connectionAttemptFailed", attemptOver);
|
|
775
|
+
socket.on("connectionAttemptTimeout", attemptOver);
|
|
776
|
+
socket.once("connect", () => { attemptOver(); unwatchWire(w); });
|
|
777
|
+
wire = w;
|
|
778
|
+
watchWire(w);
|
|
779
|
+
}
|
|
780
|
+
socket.once("connect", () => { tcpUp = true; release(); (0, trace_js_1.traceEvent)("tcp:connected"); });
|
|
781
|
+
socket.once("secureConnect", () => { (0, trace_js_1.traceEvent)("tls:secure"); finish({ ok: true, socket }); });
|
|
782
|
+
socket.on("error", onError);
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
function nodeDns() {
|
|
786
|
+
try {
|
|
787
|
+
const get = process.getBuiltinModule;
|
|
788
|
+
return typeof get === "function" ? get("node:dns") : undefined;
|
|
789
|
+
}
|
|
790
|
+
catch {
|
|
791
|
+
return undefined;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
let familySetting;
|
|
795
|
+
function v4First() {
|
|
796
|
+
if (familySetting === undefined) {
|
|
797
|
+
let raw;
|
|
798
|
+
try {
|
|
799
|
+
raw = process.env["PROMIGENCE_DNS_FAMILY"];
|
|
800
|
+
}
|
|
801
|
+
catch {
|
|
802
|
+
raw = undefined;
|
|
803
|
+
}
|
|
804
|
+
familySetting = raw?.trim() === "0" ? 0 : 4;
|
|
805
|
+
}
|
|
806
|
+
return familySetting === 4;
|
|
807
|
+
}
|
|
808
|
+
function lookupApiName(dnsLookup, hostname, options, callback, asked, ipv4First = true) {
|
|
809
|
+
const o = options;
|
|
810
|
+
const either = o.family === undefined || o.family === 0 || o.family === "IPv4or6";
|
|
811
|
+
if (!ipv4First || !either) {
|
|
812
|
+
dnsLookup(hostname, options, callback);
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
dnsLookup(hostname, { ...options, family: 4 }, (err, address, family) => {
|
|
816
|
+
const found = err === null && (Array.isArray(address) ? address.length > 0 : typeof address === "string" && address !== "");
|
|
817
|
+
if (!found) {
|
|
818
|
+
dnsLookup(hostname, options, callback);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
asked.v4 = true;
|
|
822
|
+
callback(null, address, family);
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
function apiLookup(asked, observe, ipv4First = v4First(), earlyOk = true) {
|
|
826
|
+
if (!ipv4First && observe === undefined)
|
|
827
|
+
return undefined;
|
|
828
|
+
const dns = nodeDns();
|
|
829
|
+
if (dns === undefined)
|
|
830
|
+
return undefined;
|
|
831
|
+
return ((hostname, options, callback) => {
|
|
832
|
+
const lookup = dns.lookup;
|
|
833
|
+
const early = earlyOk && observe !== undefined && ipv4First ? earlyForRequest(hostname, options, lookup) : undefined;
|
|
834
|
+
if (early !== undefined) {
|
|
835
|
+
asked.early = true;
|
|
836
|
+
(0, trace_js_1.traceEvent)("dns:early");
|
|
837
|
+
const all = options.all === true;
|
|
838
|
+
process.nextTick(() => {
|
|
839
|
+
if (all)
|
|
840
|
+
callback(null, early);
|
|
841
|
+
else
|
|
842
|
+
callback(null, early[0].address, 4);
|
|
843
|
+
safely(() => observe(early));
|
|
844
|
+
});
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
lookupApiName(lookup, hostname, options, (err, address, family) => {
|
|
848
|
+
callback(err, address, family);
|
|
849
|
+
if (observe !== undefined && err === null && Array.isArray(address))
|
|
850
|
+
safely(() => observe(address));
|
|
851
|
+
}, asked, ipv4First);
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
const earlies = new Map();
|
|
855
|
+
const MAX_EARLIES = 4;
|
|
856
|
+
const EARLY_MAX_AGE_MS = 60_000;
|
|
857
|
+
const EARLY_TIMEOUT_MS = 2_000;
|
|
858
|
+
const LOOKUP_AT_LOAD = (() => {
|
|
859
|
+
try {
|
|
860
|
+
return nodeDns()?.lookup;
|
|
861
|
+
}
|
|
862
|
+
catch {
|
|
863
|
+
return undefined;
|
|
864
|
+
}
|
|
865
|
+
})();
|
|
866
|
+
function lookupReplaced() {
|
|
867
|
+
try {
|
|
868
|
+
const d = nodeDns();
|
|
869
|
+
return d !== undefined && d.lookup !== LOOKUP_AT_LOAD;
|
|
870
|
+
}
|
|
871
|
+
catch {
|
|
872
|
+
return true;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
const EARLY_WORKER = `
|
|
876
|
+
const { workerData } = require("node:worker_threads");
|
|
877
|
+
const { isIPv4 } = require("node:net");
|
|
878
|
+
const { port, host, timeoutMs, servers, hostsFile } = workerData;
|
|
879
|
+
const done = (m) => { try { port.postMessage(m); } catch {} try { port.close(); } catch {} };
|
|
880
|
+
try {
|
|
881
|
+
let named = false;
|
|
882
|
+
const v4 = [];
|
|
883
|
+
try {
|
|
884
|
+
for (const line of require("node:fs").readFileSync(hostsFile || "/etc/hosts", "utf8").split("\\n")) {
|
|
885
|
+
const f = line.replace(/#.*/, "").trim().split(/\\s+/);
|
|
886
|
+
if (f.length < 2 || !f.slice(1).some((n) => n.toLowerCase() === host)) continue;
|
|
887
|
+
named = true;
|
|
888
|
+
if (isIPv4(f[0]) && !v4.includes(f[0])) v4.push(f[0]);
|
|
889
|
+
}
|
|
890
|
+
} catch {}
|
|
891
|
+
if (named) done(v4.length > 0 ? { host, addrs: v4, ttl: 60, at: Date.now() } : { host, none: "hosts" });
|
|
892
|
+
else {
|
|
893
|
+
const r = new (require("node:dns").Resolver)({ timeout: timeoutMs, tries: 1 });
|
|
894
|
+
if (Array.isArray(servers) && servers.length > 0) r.setServers(servers);
|
|
895
|
+
r.resolve4(host, { ttl: true }, (err, recs) => {
|
|
896
|
+
if (err || !Array.isArray(recs) || recs.length === 0) return done({ host, none: (err && err.code) || "empty" });
|
|
897
|
+
done({ host, addrs: recs.map((x) => x.address), ttl: Math.min(...recs.map((x) => x.ttl)), at: Date.now() });
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
} catch { done({ host, none: "error" }); }
|
|
901
|
+
`;
|
|
902
|
+
const EARLY_SEAM = Symbol.for("promigence.sdk.early-seam");
|
|
903
|
+
function earlySeam() {
|
|
904
|
+
const v = globalThis[EARLY_SEAM];
|
|
905
|
+
return v !== null && typeof v === "object" ? v : {};
|
|
906
|
+
}
|
|
907
|
+
function earlyPlatform() {
|
|
908
|
+
const seam = earlySeam().platform;
|
|
909
|
+
return (exports.tuning.earlyPlatform ?? (typeof seam === "string" ? seam : undefined) ?? process.platform) === "linux";
|
|
910
|
+
}
|
|
911
|
+
function busyElsewhere() {
|
|
912
|
+
const info = activeResources();
|
|
913
|
+
if (info === undefined)
|
|
914
|
+
return true;
|
|
915
|
+
return info.some((t) => t !== "PipeWrap" && t !== "TTYWrap" && t !== "MessagePort" && t !== "Worker");
|
|
916
|
+
}
|
|
917
|
+
function earlyLookupFor(host) {
|
|
918
|
+
const known = earlies.get(host);
|
|
919
|
+
if (known !== undefined)
|
|
920
|
+
return known;
|
|
921
|
+
if (!earlyPlatform() || earlies.size >= MAX_EARLIES)
|
|
922
|
+
return undefined;
|
|
923
|
+
try {
|
|
924
|
+
const { port1, port2 } = new node_worker_threads_1.MessageChannel();
|
|
925
|
+
port1.unref();
|
|
926
|
+
const worker = new node_worker_threads_1.Worker(EARLY_WORKER, {
|
|
927
|
+
eval: true,
|
|
928
|
+
workerData: {
|
|
929
|
+
port: port2, host, timeoutMs: EARLY_TIMEOUT_MS,
|
|
930
|
+
servers: exports.tuning.earlyServers ?? (Array.isArray(earlySeam().servers) ? earlySeam().servers : undefined),
|
|
931
|
+
hostsFile: exports.tuning.earlyHostsFile ?? (typeof earlySeam().hostsFile === "string" ? earlySeam().hostsFile : undefined),
|
|
932
|
+
},
|
|
933
|
+
transferList: [port2],
|
|
934
|
+
env: {},
|
|
935
|
+
argv: [],
|
|
936
|
+
execArgv: [],
|
|
937
|
+
});
|
|
938
|
+
worker.unref();
|
|
939
|
+
const e = { host, port: port1, state: "pending", waiters: [], listening: false };
|
|
940
|
+
worker.on("error", () => { settleEarly(e, undefined); });
|
|
941
|
+
worker.on("exit", () => { pollEarly(e); if (e.state === "pending")
|
|
942
|
+
settleEarly(e, undefined); });
|
|
943
|
+
earlies.set(host, e);
|
|
944
|
+
(0, trace_js_1.traceEvent)("dns:early-start");
|
|
945
|
+
return e;
|
|
946
|
+
}
|
|
947
|
+
catch {
|
|
948
|
+
return undefined;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
function pollEarly(e) {
|
|
952
|
+
if (e.state !== "pending")
|
|
953
|
+
return;
|
|
954
|
+
try {
|
|
955
|
+
const got = (0, node_worker_threads_1.receiveMessageOnPort)(e.port);
|
|
956
|
+
if (got !== undefined)
|
|
957
|
+
settleEarly(e, got.message);
|
|
958
|
+
}
|
|
959
|
+
catch {
|
|
960
|
+
settleEarly(e, undefined);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
function settleEarly(e, message) {
|
|
964
|
+
if (e.state !== "pending")
|
|
965
|
+
return;
|
|
966
|
+
const m = message;
|
|
967
|
+
const addrs = Array.isArray(m?.addrs) ? m.addrs.filter((a) => typeof a === "string" && (0, node_net_1.isIP)(a) === 4) : [];
|
|
968
|
+
if (m !== undefined && m.host === e.host && addrs.length > 0 && typeof m.at === "number") {
|
|
969
|
+
e.state = "answered";
|
|
970
|
+
e.answer = addrs.map((address) => ({ address, family: 4 }));
|
|
971
|
+
const ttlMs = typeof m.ttl === "number" && m.ttl >= 0 ? m.ttl * 1000 : 0;
|
|
972
|
+
e.until = m.at + Math.min(ttlMs, EARLY_MAX_AGE_MS);
|
|
973
|
+
}
|
|
974
|
+
else {
|
|
975
|
+
e.state = "none";
|
|
976
|
+
}
|
|
977
|
+
safely(() => { e.port.close(); });
|
|
978
|
+
const waiters = e.waiters.splice(0);
|
|
979
|
+
for (const w of waiters)
|
|
980
|
+
safely(w);
|
|
981
|
+
}
|
|
982
|
+
function onEarlyAnswer(e, cb) {
|
|
983
|
+
pollEarly(e);
|
|
984
|
+
if (e.state !== "pending") {
|
|
985
|
+
process.nextTick(cb);
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
e.waiters.push(cb);
|
|
989
|
+
if (e.listening)
|
|
990
|
+
return;
|
|
991
|
+
e.listening = true;
|
|
992
|
+
try {
|
|
993
|
+
e.port.on("message", (m) => { settleEarly(e, m); });
|
|
994
|
+
e.port.unref();
|
|
995
|
+
}
|
|
996
|
+
catch {
|
|
997
|
+
settleEarly(e, undefined);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
function earlyFresh(e) {
|
|
1001
|
+
pollEarly(e);
|
|
1002
|
+
if (e.state !== "answered" || e.answer === undefined || e.until === undefined || Date.now() > e.until)
|
|
1003
|
+
return undefined;
|
|
1004
|
+
return e.answer.map((a) => ({ ...a }));
|
|
1005
|
+
}
|
|
1006
|
+
function backgroundRoute(origin) {
|
|
1007
|
+
try {
|
|
1008
|
+
const host = origin.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase();
|
|
1009
|
+
if ((0, node_net_1.isIP)(host) !== 0 || !earlyPlatform() || lookupReplaced() || !v4First())
|
|
1010
|
+
return { kind: "lookup" };
|
|
1011
|
+
const e = earlyLookupFor(host);
|
|
1012
|
+
if (e === undefined)
|
|
1013
|
+
return { kind: "none" };
|
|
1014
|
+
const answer = earlyFresh(e);
|
|
1015
|
+
if (answer !== undefined)
|
|
1016
|
+
return { kind: "answer", answer };
|
|
1017
|
+
return e.state === "pending" ? { kind: "wait", early: e } : { kind: "none" };
|
|
1018
|
+
}
|
|
1019
|
+
catch {
|
|
1020
|
+
return { kind: "none" };
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
function earlyForRequest(hostname, options, lookup) {
|
|
1024
|
+
try {
|
|
1025
|
+
if (lookup !== LOOKUP_AT_LOAD)
|
|
1026
|
+
return undefined;
|
|
1027
|
+
const o = options;
|
|
1028
|
+
if (!(o.family === undefined || o.family === 0 || o.family === 4 || o.family === "IPv4or6"))
|
|
1029
|
+
return undefined;
|
|
1030
|
+
const e = earlies.get(hostname.toLowerCase());
|
|
1031
|
+
return e === undefined ? undefined : earlyFresh(e);
|
|
1032
|
+
}
|
|
1033
|
+
catch {
|
|
1034
|
+
return undefined;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
function givenUp(res) {
|
|
1038
|
+
return !res.ok && res.error?.givenUp === true;
|
|
1039
|
+
}
|
|
1040
|
+
function fixedLookup(answer) {
|
|
1041
|
+
return ((_hostname, options, callback) => {
|
|
1042
|
+
const all = options.all === true;
|
|
1043
|
+
process.nextTick(() => {
|
|
1044
|
+
if (all)
|
|
1045
|
+
callback(null, answer);
|
|
1046
|
+
else
|
|
1047
|
+
callback(null, answer[0].address, answer[0].family);
|
|
1048
|
+
});
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
function timeoutReason() {
|
|
1052
|
+
try {
|
|
1053
|
+
return new DOMException("The operation was aborted due to timeout", "TimeoutError");
|
|
1054
|
+
}
|
|
1055
|
+
catch {
|
|
1056
|
+
return Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" });
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function exchange(pool, entry, target, init, deadline) {
|
|
1060
|
+
return new Promise((resolve) => {
|
|
1061
|
+
const remaining = deadline - performance.now();
|
|
1062
|
+
if (remaining <= 0) {
|
|
1063
|
+
pool.end(entry);
|
|
1064
|
+
resolve({ kind: "aborted", reason: timeoutReason() });
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const headers = {
|
|
1068
|
+
":method": init.method,
|
|
1069
|
+
":path": target.path,
|
|
1070
|
+
":scheme": "https",
|
|
1071
|
+
":authority": target.host,
|
|
1072
|
+
};
|
|
1073
|
+
for (const k in init.headers) {
|
|
1074
|
+
const name = k.toLowerCase();
|
|
1075
|
+
if (!NOT_IN_H2.has(name))
|
|
1076
|
+
headers[name] = init.headers[k];
|
|
1077
|
+
}
|
|
1078
|
+
headers[http2.sensitiveHeaders] = ["authorization"];
|
|
1079
|
+
const body = init.body === undefined ? undefined : Buffer.from(init.body, "utf8");
|
|
1080
|
+
if (body !== undefined)
|
|
1081
|
+
headers["content-length"] = body.length;
|
|
1082
|
+
let stream;
|
|
1083
|
+
try {
|
|
1084
|
+
stream = entry.session.request(headers, { endStream: body === undefined });
|
|
1085
|
+
}
|
|
1086
|
+
catch (error) {
|
|
1087
|
+
pool.end(entry);
|
|
1088
|
+
const code = errCode(error);
|
|
1089
|
+
if (entry.session.closed || entry.session.destroyed || code === "ERR_HTTP2_GOAWAY_SESSION"
|
|
1090
|
+
|| code === "ERR_HTTP2_INVALID_SESSION" || code === "ERR_HTTP2_OUT_OF_STREAMS") {
|
|
1091
|
+
pool.retire(entry);
|
|
1092
|
+
if (code === "ERR_HTTP2_OUT_OF_STREAMS")
|
|
1093
|
+
safely(() => entry.session.close());
|
|
1094
|
+
resolve({ kind: "failed", error, processed: "no" });
|
|
1095
|
+
}
|
|
1096
|
+
else {
|
|
1097
|
+
resolve({ kind: "use-fetch" });
|
|
1098
|
+
}
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const tr = init.trace;
|
|
1102
|
+
if (tr !== undefined) {
|
|
1103
|
+
(0, trace_js_1.mark)(tr, "req");
|
|
1104
|
+
tr.via = "h2";
|
|
1105
|
+
}
|
|
1106
|
+
let status = 0;
|
|
1107
|
+
let resHeaders;
|
|
1108
|
+
let first;
|
|
1109
|
+
let chunks;
|
|
1110
|
+
let settled = false;
|
|
1111
|
+
let streamError;
|
|
1112
|
+
const signal = init.signal;
|
|
1113
|
+
const finish = (o) => {
|
|
1114
|
+
if (settled)
|
|
1115
|
+
return;
|
|
1116
|
+
settled = true;
|
|
1117
|
+
clearTimeout(timer);
|
|
1118
|
+
if (signal !== undefined)
|
|
1119
|
+
signal.removeEventListener("abort", onAbort);
|
|
1120
|
+
resolve(o);
|
|
1121
|
+
};
|
|
1122
|
+
const onTimeout = () => {
|
|
1123
|
+
if (settled)
|
|
1124
|
+
return;
|
|
1125
|
+
safely(() => stream.close(NGHTTP2_CANCEL));
|
|
1126
|
+
pool.streamFailed(entry, false);
|
|
1127
|
+
pool.checkAlive(entry);
|
|
1128
|
+
finish({ kind: "aborted", reason: timeoutReason() });
|
|
1129
|
+
};
|
|
1130
|
+
const onAbort = () => {
|
|
1131
|
+
safely(() => stream.close(NGHTTP2_CANCEL));
|
|
1132
|
+
finish({ kind: "aborted", reason: signal?.reason });
|
|
1133
|
+
};
|
|
1134
|
+
const timer = setTimeout(onTimeout, remaining);
|
|
1135
|
+
timer.unref?.();
|
|
1136
|
+
if (signal !== undefined) {
|
|
1137
|
+
if (signal.aborted)
|
|
1138
|
+
onAbort();
|
|
1139
|
+
else
|
|
1140
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1141
|
+
}
|
|
1142
|
+
stream.on("response", (h) => {
|
|
1143
|
+
resHeaders = h;
|
|
1144
|
+
status = Number(h[":status"]);
|
|
1145
|
+
if (tr !== undefined) {
|
|
1146
|
+
(0, trace_js_1.mark)(tr, "hdr");
|
|
1147
|
+
tr.status = status;
|
|
1148
|
+
const rx = h["x-promigence-rx-ns"], tx = h["x-promigence-tx-ns"];
|
|
1149
|
+
if (typeof rx === "string")
|
|
1150
|
+
tr.rx = rx;
|
|
1151
|
+
if (typeof tx === "string")
|
|
1152
|
+
tr.tx = tx;
|
|
1153
|
+
}
|
|
1154
|
+
});
|
|
1155
|
+
stream.on("data", (c) => {
|
|
1156
|
+
if (first === undefined)
|
|
1157
|
+
first = c;
|
|
1158
|
+
else
|
|
1159
|
+
(chunks ??= [first]).push(c);
|
|
1160
|
+
});
|
|
1161
|
+
stream.on("error", (err) => { streamError = err; });
|
|
1162
|
+
stream.on("end", () => {
|
|
1163
|
+
if (tr !== undefined)
|
|
1164
|
+
(0, trace_js_1.mark)(tr, "end");
|
|
1165
|
+
if (settled || status === 0)
|
|
1166
|
+
return;
|
|
1167
|
+
if (status === 421) {
|
|
1168
|
+
pool.turnOff("421 Misdirected Request");
|
|
1169
|
+
finish({ kind: "use-fetch" });
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
try {
|
|
1173
|
+
const raw = chunks !== undefined ? Buffer.concat(chunks) : (first ?? EMPTY);
|
|
1174
|
+
const response = toResponse(status, resHeaders ?? {}, raw, init.method);
|
|
1175
|
+
if (tr !== undefined)
|
|
1176
|
+
(0, trace_js_1.mark)(tr, "out");
|
|
1177
|
+
pool.succeeded();
|
|
1178
|
+
finish({ kind: "response", response });
|
|
1179
|
+
}
|
|
1180
|
+
catch (error) {
|
|
1181
|
+
finish({ kind: "failed", error, processed: "yes" });
|
|
1182
|
+
}
|
|
1183
|
+
});
|
|
1184
|
+
stream.on("close", () => {
|
|
1185
|
+
pool.end(entry);
|
|
1186
|
+
if (settled)
|
|
1187
|
+
return;
|
|
1188
|
+
if (signal?.aborted) {
|
|
1189
|
+
finish({ kind: "aborted", reason: signal.reason });
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
const rst = stream.rstCode;
|
|
1193
|
+
const sessionDying = entry.session.destroyed || entry.session.closed || entry.retired;
|
|
1194
|
+
const error = streamError ?? Object.assign(new Error(`HTTP/2 stream closed (code ${rst ?? "?"})`), { code: "ERR_HTTP2_STREAM_ERROR" });
|
|
1195
|
+
if (rst === NGHTTP2_HTTP_1_1_REQUIRED && status === 0) {
|
|
1196
|
+
pool.turnOff("server asked for HTTP/1.1");
|
|
1197
|
+
finish({ kind: "use-fetch" });
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
let processed;
|
|
1201
|
+
if (status !== 0)
|
|
1202
|
+
processed = "yes";
|
|
1203
|
+
else if (rst === NGHTTP2_REFUSED_STREAM)
|
|
1204
|
+
processed = "no";
|
|
1205
|
+
else if (stream.id === undefined)
|
|
1206
|
+
processed = "no";
|
|
1207
|
+
else if (entry.goawayLast !== undefined && stream.id > entry.goawayLast)
|
|
1208
|
+
processed = "no";
|
|
1209
|
+
else
|
|
1210
|
+
processed = "maybe";
|
|
1211
|
+
if (processed !== "no")
|
|
1212
|
+
pool.streamFailed(entry, sessionDying);
|
|
1213
|
+
finish({ kind: "failed", error, processed });
|
|
1214
|
+
});
|
|
1215
|
+
if (body !== undefined) {
|
|
1216
|
+
stream.end(body);
|
|
1217
|
+
}
|
|
1218
|
+
if (tr !== undefined)
|
|
1219
|
+
(0, trace_js_1.mark)(tr, "sub");
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
const EMPTY = Buffer.alloc(0);
|
|
1223
|
+
function toResponse(status, raw, body, method) {
|
|
1224
|
+
const nullBody = method === "HEAD" || status === 204 || status === 205 || status === 304;
|
|
1225
|
+
const enc = raw["content-encoding"];
|
|
1226
|
+
const bytes = nullBody ? null : decodeBody(body, typeof enc === "string" ? enc : null);
|
|
1227
|
+
return new H2Response(status, raw, bytes);
|
|
1228
|
+
}
|
|
1229
|
+
function decodeBody(body, encoding) {
|
|
1230
|
+
if (!encoding || body.length === 0)
|
|
1231
|
+
return body;
|
|
1232
|
+
const codings = encoding.toLowerCase().split(",").map((s) => s.trim()).filter((s) => s && s !== "identity");
|
|
1233
|
+
let out = body;
|
|
1234
|
+
for (const c of codings.reverse()) {
|
|
1235
|
+
if (c === "gzip" || c === "x-gzip")
|
|
1236
|
+
out = zlib.gunzipSync(out);
|
|
1237
|
+
else if (c === "br")
|
|
1238
|
+
out = zlib.brotliDecompressSync(out);
|
|
1239
|
+
else if (c === "deflate") {
|
|
1240
|
+
try {
|
|
1241
|
+
out = zlib.inflateSync(out);
|
|
1242
|
+
}
|
|
1243
|
+
catch {
|
|
1244
|
+
out = zlib.inflateRawSync(out);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
else
|
|
1248
|
+
return body;
|
|
1249
|
+
}
|
|
1250
|
+
return out;
|
|
1251
|
+
}
|
|
1252
|
+
const pools = new Map();
|
|
1253
|
+
function poolFor(origin) {
|
|
1254
|
+
let p = pools.get(origin);
|
|
1255
|
+
if (!p) {
|
|
1256
|
+
p = new OriginPool(new URL(origin));
|
|
1257
|
+
pools.set(origin, p);
|
|
1258
|
+
}
|
|
1259
|
+
return p;
|
|
1260
|
+
}
|
|
1261
|
+
function plainPath(url, at) {
|
|
1262
|
+
if (url.charCodeAt(at) !== 0x2f)
|
|
1263
|
+
return false;
|
|
1264
|
+
let query = false;
|
|
1265
|
+
for (let i = at + 1; i < url.length; i++) {
|
|
1266
|
+
const c = url.charCodeAt(i);
|
|
1267
|
+
if ((c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) || (c >= 0x30 && c <= 0x39))
|
|
1268
|
+
continue;
|
|
1269
|
+
if (c === 0x2f || c === 0x2d || c === 0x5f || c === 0x7e || c === 0x3d || c === 0x26)
|
|
1270
|
+
continue;
|
|
1271
|
+
if (c === 0x3f && !query && i + 1 < url.length) {
|
|
1272
|
+
query = true;
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
return false;
|
|
1276
|
+
}
|
|
1277
|
+
return true;
|
|
1278
|
+
}
|
|
1279
|
+
function targetOf(url, known, remember) {
|
|
1280
|
+
if (known !== undefined && url.startsWith(known.text) && plainPath(url, known.text.length)) {
|
|
1281
|
+
return { origin: known.origin, host: known.host, path: url.slice(known.text.length) };
|
|
1282
|
+
}
|
|
1283
|
+
const u = new URL(url);
|
|
1284
|
+
if (u.protocol !== "https:")
|
|
1285
|
+
return undefined;
|
|
1286
|
+
const path = u.pathname + u.search;
|
|
1287
|
+
const target = { origin: u.origin, host: u.host, path };
|
|
1288
|
+
if (remember !== undefined && url.startsWith("https://")) {
|
|
1289
|
+
let end = 8;
|
|
1290
|
+
while (end < url.length) {
|
|
1291
|
+
const c = url.charCodeAt(end);
|
|
1292
|
+
if (c === 0x2f || c === 0x3f || c === 0x23 || c === 0x5c)
|
|
1293
|
+
break;
|
|
1294
|
+
end++;
|
|
1295
|
+
}
|
|
1296
|
+
if (end > 8 && url.charCodeAt(end) === 0x2f)
|
|
1297
|
+
remember({ text: url.slice(0, end), origin: target.origin, host: target.host });
|
|
1298
|
+
}
|
|
1299
|
+
return target;
|
|
1300
|
+
}
|
|
1301
|
+
function fetchInit(init, deadline) {
|
|
1302
|
+
const timeout = AbortSignal.timeout(Math.max(0, Math.ceil(deadline - performance.now())));
|
|
1303
|
+
return {
|
|
1304
|
+
method: init.method,
|
|
1305
|
+
headers: init.headers,
|
|
1306
|
+
signal: init.signal === undefined ? timeout : AbortSignal.any([timeout, init.signal]),
|
|
1307
|
+
...(init.body === undefined ? {} : { body: init.body }),
|
|
1308
|
+
...(init.dispatcher === undefined ? {} : { dispatcher: init.dispatcher }),
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
function fetchFailed(cause) {
|
|
1312
|
+
return new TypeError("fetch failed", { cause });
|
|
1313
|
+
}
|
|
1314
|
+
class HandBack {
|
|
1315
|
+
resends;
|
|
1316
|
+
replays;
|
|
1317
|
+
constructor(resends, replays) {
|
|
1318
|
+
this.resends = resends;
|
|
1319
|
+
this.replays = replays;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
const UNSENT = new HandBack(0, 0);
|
|
1323
|
+
const VIA_FETCH = Symbol("via-fetch");
|
|
1324
|
+
const THREAD_GRACE_MS = 1_000;
|
|
1325
|
+
const THREAD_PHASES = ["w.got", "w.sent", "w.head", "w.end"];
|
|
1326
|
+
class TransportThread {
|
|
1327
|
+
origin;
|
|
1328
|
+
worker;
|
|
1329
|
+
port;
|
|
1330
|
+
state = "starting";
|
|
1331
|
+
sessions = 0;
|
|
1332
|
+
limit = DEFAULT_STREAM_LIMIT;
|
|
1333
|
+
everReady = false;
|
|
1334
|
+
closedReason = "";
|
|
1335
|
+
onFail;
|
|
1336
|
+
inflight = new Map();
|
|
1337
|
+
nextId = 1;
|
|
1338
|
+
listening = false;
|
|
1339
|
+
answered = 0;
|
|
1340
|
+
pace = THREAD_DEFAULTS.pace;
|
|
1341
|
+
hrOffset = Number(process.hrtime.bigint()) / 1e6 - performance.now();
|
|
1342
|
+
constructor(origin, worker, port) {
|
|
1343
|
+
this.origin = origin;
|
|
1344
|
+
this.worker = worker;
|
|
1345
|
+
this.port = port;
|
|
1346
|
+
}
|
|
1347
|
+
poll() {
|
|
1348
|
+
for (;;) {
|
|
1349
|
+
let got;
|
|
1350
|
+
try {
|
|
1351
|
+
got = (0, node_worker_threads_1.receiveMessageOnPort)(this.port);
|
|
1352
|
+
}
|
|
1353
|
+
catch {
|
|
1354
|
+
got = undefined;
|
|
1355
|
+
}
|
|
1356
|
+
if (got === undefined)
|
|
1357
|
+
break;
|
|
1358
|
+
this.onMessage(got.message);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
ready() {
|
|
1362
|
+
if (this.state !== "closed")
|
|
1363
|
+
this.poll();
|
|
1364
|
+
return this.state === "ready" && this.sessions > 0 && this.inflight.size < this.sessions * this.limit;
|
|
1365
|
+
}
|
|
1366
|
+
onMessage(m) {
|
|
1367
|
+
const msg = m;
|
|
1368
|
+
switch (msg?.t) {
|
|
1369
|
+
case "ready":
|
|
1370
|
+
if (this.state === "starting" || this.state === "ready") {
|
|
1371
|
+
const first = !this.everReady;
|
|
1372
|
+
this.state = "ready";
|
|
1373
|
+
this.everReady = true;
|
|
1374
|
+
this.sessions = msg.sessions ?? 1;
|
|
1375
|
+
if (typeof msg.limit === "number" && msg.limit > 0)
|
|
1376
|
+
this.limit = first ? msg.limit : Math.min(this.limit, msg.limit);
|
|
1377
|
+
const hr = msg.hr;
|
|
1378
|
+
if (typeof hr === "number") {
|
|
1379
|
+
const t = hr - this.hrOffset;
|
|
1380
|
+
(0, trace_js_1.traceEventAt)(`thread:session${this.sessions}`, t);
|
|
1381
|
+
if (first)
|
|
1382
|
+
(0, trace_js_1.traceEventAt)(`thread:limit${this.limit}`, t);
|
|
1383
|
+
const c = msg;
|
|
1384
|
+
if (typeof c.index === "number" && typeof c.addr === "string" && typeof c.localPort === "number")
|
|
1385
|
+
(0, trace_js_1.traceEventAt)(`thread:conn${c.index} ${c.addr} ${c.localPort}`, t);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
return;
|
|
1389
|
+
case "sessions":
|
|
1390
|
+
if (typeof msg.sessions === "number")
|
|
1391
|
+
this.sessions = msg.sessions;
|
|
1392
|
+
return;
|
|
1393
|
+
case "draining":
|
|
1394
|
+
if (this.state !== "closed" && this.state !== "draining") {
|
|
1395
|
+
this.state = "draining";
|
|
1396
|
+
if (this.closedReason === "")
|
|
1397
|
+
this.closedReason = msg.reason ?? "draining";
|
|
1398
|
+
(0, trace_js_1.traceEvent)("thread:draining");
|
|
1399
|
+
}
|
|
1400
|
+
return;
|
|
1401
|
+
case "closed":
|
|
1402
|
+
this.close(msg.reason ?? "closed");
|
|
1403
|
+
return;
|
|
1404
|
+
case "ack": {
|
|
1405
|
+
const p = this.inflight.get(msg.id ?? -1);
|
|
1406
|
+
if (p !== undefined)
|
|
1407
|
+
p.acked = true;
|
|
1408
|
+
return;
|
|
1409
|
+
}
|
|
1410
|
+
case "res":
|
|
1411
|
+
case "err":
|
|
1412
|
+
this.settle(m);
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
settle(m) {
|
|
1417
|
+
const id = m["id"];
|
|
1418
|
+
const p = this.inflight.get(id);
|
|
1419
|
+
if (p === undefined)
|
|
1420
|
+
return;
|
|
1421
|
+
this.inflight.delete(id);
|
|
1422
|
+
this.release(p);
|
|
1423
|
+
if (m["t"] === "res") {
|
|
1424
|
+
this.answered++;
|
|
1425
|
+
const body = Buffer.from(m["body"]);
|
|
1426
|
+
let res;
|
|
1427
|
+
try {
|
|
1428
|
+
res = toResponse(m["status"], (m["headers"] ?? {}), body, p.method);
|
|
1429
|
+
}
|
|
1430
|
+
catch (error) {
|
|
1431
|
+
p.reject(fetchFailed(error));
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
if (m["replayed"] === true)
|
|
1435
|
+
res.replayed = true;
|
|
1436
|
+
const tr = p.trace;
|
|
1437
|
+
if (tr !== undefined) {
|
|
1438
|
+
tr.status = res.status;
|
|
1439
|
+
const h = (m["headers"] ?? {});
|
|
1440
|
+
const rx = h["x-promigence-rx-ns"], tx = h["x-promigence-tx-ns"];
|
|
1441
|
+
if (typeof rx === "string")
|
|
1442
|
+
tr.rx = rx;
|
|
1443
|
+
if (typeof tx === "string")
|
|
1444
|
+
tr.tx = tx;
|
|
1445
|
+
if (typeof m["conn"] === "number")
|
|
1446
|
+
tr.conn = m["conn"];
|
|
1447
|
+
const w = m["w"];
|
|
1448
|
+
if (Array.isArray(w)) {
|
|
1449
|
+
for (let i = 0; i < THREAD_PHASES.length; i++)
|
|
1450
|
+
if (typeof w[i] === "number" && w[i] > 0)
|
|
1451
|
+
tr.t[THREAD_PHASES[i]] = w[i] - this.hrOffset;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
p.resolve(res);
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (m["kind"] === "timeout") {
|
|
1458
|
+
this.stopUsing("a request timed out");
|
|
1459
|
+
p.reject(timeoutReason());
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
if (m["kind"] === "back") {
|
|
1463
|
+
this.stopUsing("no session");
|
|
1464
|
+
p.resolve(new HandBack(Number(m["resends"]) || 0, Number(m["replays"]) || 0));
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
if (m["processed"] === "no") {
|
|
1468
|
+
this.stopUsing("requests refused");
|
|
1469
|
+
p.resolve(VIA_FETCH);
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
this.stopUsing("a request failed");
|
|
1473
|
+
p.reject(fetchFailed(Object.assign(new Error(String(m["message"] ?? "HTTP/2 stream error")), { code: m["code"] })));
|
|
1474
|
+
}
|
|
1475
|
+
stopUsing(reason) {
|
|
1476
|
+
if (this.state !== "starting" && this.state !== "ready")
|
|
1477
|
+
return;
|
|
1478
|
+
this.state = "draining";
|
|
1479
|
+
this.closedReason = reason;
|
|
1480
|
+
(0, trace_js_1.traceEvent)("thread:draining");
|
|
1481
|
+
try {
|
|
1482
|
+
this.port.postMessage({ t: "drain" });
|
|
1483
|
+
}
|
|
1484
|
+
catch { }
|
|
1485
|
+
}
|
|
1486
|
+
close(reason) {
|
|
1487
|
+
if (this.state === "closed")
|
|
1488
|
+
return;
|
|
1489
|
+
this.state = "closed";
|
|
1490
|
+
if (this.closedReason === "")
|
|
1491
|
+
this.closedReason = reason;
|
|
1492
|
+
(0, trace_js_1.traceEvent)("thread:closed");
|
|
1493
|
+
for (const [id, p] of [...this.inflight]) {
|
|
1494
|
+
this.inflight.delete(id);
|
|
1495
|
+
this.release(p);
|
|
1496
|
+
if (!p.acked)
|
|
1497
|
+
p.resolve(UNSENT);
|
|
1498
|
+
else if (p.replayable)
|
|
1499
|
+
p.resolve(new HandBack(0, 1));
|
|
1500
|
+
else
|
|
1501
|
+
p.reject(fetchFailed(Object.assign(new Error(`the transport thread ended: ${reason}`), { code: "ERR_HTTP2_SESSION_ERROR" })));
|
|
1502
|
+
}
|
|
1503
|
+
safely(() => { this.port.close(); });
|
|
1504
|
+
this.unref();
|
|
1505
|
+
if (!this.everReady) {
|
|
1506
|
+
const f = this.onFail;
|
|
1507
|
+
this.onFail = undefined;
|
|
1508
|
+
if (f !== undefined)
|
|
1509
|
+
safely(f);
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
ref() {
|
|
1513
|
+
if (!this.listening) {
|
|
1514
|
+
this.listening = true;
|
|
1515
|
+
this.poll();
|
|
1516
|
+
this.port.on("message", (m) => { this.onMessage(m); });
|
|
1517
|
+
}
|
|
1518
|
+
safely(() => { this.port.ref(); });
|
|
1519
|
+
safely(() => { this.worker.ref(); });
|
|
1520
|
+
}
|
|
1521
|
+
unref() {
|
|
1522
|
+
safely(() => { this.port.unref(); });
|
|
1523
|
+
safely(() => { this.worker.unref(); });
|
|
1524
|
+
}
|
|
1525
|
+
release(p) {
|
|
1526
|
+
if (p.signal !== undefined && p.onAbort !== undefined)
|
|
1527
|
+
p.signal.removeEventListener("abort", p.onAbort);
|
|
1528
|
+
if (p.backstop !== undefined)
|
|
1529
|
+
clearTimeout(p.backstop);
|
|
1530
|
+
if (this.inflight.size === 0)
|
|
1531
|
+
this.unref();
|
|
1532
|
+
}
|
|
1533
|
+
send(target, init, replayable, deadline) {
|
|
1534
|
+
const remaining = Math.ceil(deadline - performance.now());
|
|
1535
|
+
if (remaining <= 0)
|
|
1536
|
+
return Promise.reject(timeoutReason());
|
|
1537
|
+
if (init.signal?.aborted)
|
|
1538
|
+
return Promise.reject(init.signal.reason);
|
|
1539
|
+
const headers = {
|
|
1540
|
+
":method": init.method,
|
|
1541
|
+
":path": target.path,
|
|
1542
|
+
":scheme": "https",
|
|
1543
|
+
":authority": target.host,
|
|
1544
|
+
};
|
|
1545
|
+
for (const k in init.headers) {
|
|
1546
|
+
const name = k.toLowerCase();
|
|
1547
|
+
if (!NOT_IN_H2.has(name))
|
|
1548
|
+
headers[name] = init.headers[k];
|
|
1549
|
+
}
|
|
1550
|
+
if (init.body !== undefined)
|
|
1551
|
+
headers["content-length"] = Buffer.byteLength(init.body, "utf8");
|
|
1552
|
+
const id = this.nextId++;
|
|
1553
|
+
const tr = init.trace;
|
|
1554
|
+
return new Promise((resolve, reject) => {
|
|
1555
|
+
const p = { resolve, reject, method: init.method, replayable, acked: false, trace: tr };
|
|
1556
|
+
const signal = init.signal;
|
|
1557
|
+
if (signal !== undefined) {
|
|
1558
|
+
p.signal = signal;
|
|
1559
|
+
p.onAbort = () => {
|
|
1560
|
+
if (!this.inflight.has(id))
|
|
1561
|
+
return;
|
|
1562
|
+
this.inflight.delete(id);
|
|
1563
|
+
this.release(p);
|
|
1564
|
+
try {
|
|
1565
|
+
this.port.postMessage({ t: "cancel", id });
|
|
1566
|
+
}
|
|
1567
|
+
catch { }
|
|
1568
|
+
reject(signal.reason);
|
|
1569
|
+
};
|
|
1570
|
+
signal.addEventListener("abort", p.onAbort, { once: true });
|
|
1571
|
+
}
|
|
1572
|
+
p.backstop = setTimeout(() => {
|
|
1573
|
+
this.poll();
|
|
1574
|
+
if (!this.inflight.has(id))
|
|
1575
|
+
return;
|
|
1576
|
+
this.inflight.delete(id);
|
|
1577
|
+
this.release(p);
|
|
1578
|
+
try {
|
|
1579
|
+
this.port.postMessage({ t: "cancel", id });
|
|
1580
|
+
}
|
|
1581
|
+
catch { }
|
|
1582
|
+
reject(timeoutReason());
|
|
1583
|
+
this.close("no answer from the transport thread");
|
|
1584
|
+
}, remaining + THREAD_GRACE_MS);
|
|
1585
|
+
safely(() => { p.backstop?.unref?.(); });
|
|
1586
|
+
this.inflight.set(id, p);
|
|
1587
|
+
this.ref();
|
|
1588
|
+
try {
|
|
1589
|
+
const paced = this.pace === "all" || (this.pace === "creates" && init.method === "POST" && CREATE_PATH.test(target.path));
|
|
1590
|
+
this.port.postMessage({ t: "req", id, headers, sensitive: ["authorization"], body: init.body, timeoutMs: remaining, replayable, paced });
|
|
1591
|
+
}
|
|
1592
|
+
catch {
|
|
1593
|
+
this.inflight.delete(id);
|
|
1594
|
+
this.release(p);
|
|
1595
|
+
resolve(UNSENT);
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
if (tr !== undefined) {
|
|
1599
|
+
(0, trace_js_1.mark)(tr, "sub");
|
|
1600
|
+
tr.via = "thread";
|
|
1601
|
+
}
|
|
1602
|
+
});
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
let transportThread;
|
|
1606
|
+
function threadFor(origin) {
|
|
1607
|
+
const t = transportThread;
|
|
1608
|
+
if (t === undefined || t.origin !== origin)
|
|
1609
|
+
return undefined;
|
|
1610
|
+
return t.ready() && !lookupReplaced() ? t : undefined;
|
|
1611
|
+
}
|
|
1612
|
+
function ownFile() {
|
|
1613
|
+
const frame = (new Error().stack ?? "").split("\n")[1] ?? "";
|
|
1614
|
+
const m = /\((.*):\d+:\d+\)\s*$/.exec(frame) ?? /at (.*):\d+:\d+\s*$/.exec(frame);
|
|
1615
|
+
return m?.[1] ?? "";
|
|
1616
|
+
}
|
|
1617
|
+
const THREAD_DEFAULTS = { sessions: 8, gapUs: 2000, pace: "all" };
|
|
1618
|
+
const THREAD_MAX_SESSIONS = 32;
|
|
1619
|
+
const THREAD_MAX_GAP_US = 10_000;
|
|
1620
|
+
const CREATE_PATH = /\/(?:runs|sandboxes)(?:\?|$)/;
|
|
1621
|
+
function threadKnobs(env = process.env) {
|
|
1622
|
+
const read = (name, dflt, off, min, max) => {
|
|
1623
|
+
const raw = (env[name] ?? "").trim().toLowerCase();
|
|
1624
|
+
if (raw === "")
|
|
1625
|
+
return dflt;
|
|
1626
|
+
if (OFF.has(raw))
|
|
1627
|
+
return off;
|
|
1628
|
+
const n = Number(raw);
|
|
1629
|
+
return Number.isInteger(n) && n >= min ? Math.min(max, n) : dflt;
|
|
1630
|
+
};
|
|
1631
|
+
const p = (env["PROMIGENCE_HTTP2_PACE"] ?? "").trim().toLowerCase();
|
|
1632
|
+
return {
|
|
1633
|
+
sessions: read("PROMIGENCE_HTTP2_SESSIONS", THREAD_DEFAULTS.sessions, 1, 1, THREAD_MAX_SESSIONS),
|
|
1634
|
+
gapUs: read("PROMIGENCE_HTTP2_STREAM_GAP_US", THREAD_DEFAULTS.gapUs, 0, 0, THREAD_MAX_GAP_US),
|
|
1635
|
+
pace: p === "all" || p === "creates" ? p : OFF.has(p) ? "off" : THREAD_DEFAULTS.pace,
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
function startTransportThread(origin, onFail) {
|
|
1639
|
+
if (transportThread !== undefined)
|
|
1640
|
+
return;
|
|
1641
|
+
try {
|
|
1642
|
+
const here = ownFile();
|
|
1643
|
+
if (!/http2\.js$/.test(here))
|
|
1644
|
+
return;
|
|
1645
|
+
const seam = earlySeam();
|
|
1646
|
+
const knobs = threadKnobs();
|
|
1647
|
+
const file = typeof seam.transportFile === "string" ? seam.transportFile : here.replace(/http2\.js$/, "transport-worker.js");
|
|
1648
|
+
const { port1, port2 } = new node_worker_threads_1.MessageChannel();
|
|
1649
|
+
const worker = new node_worker_threads_1.Worker(file.startsWith("file:") ? new URL(file) : file, {
|
|
1650
|
+
workerData: {
|
|
1651
|
+
promigenceTransport: true, port: port2, origin: origin.origin, sessions: knobs.sessions, gapUs: knobs.gapUs,
|
|
1652
|
+
firstUseMs: exports.tuning.loadFirstUseMs, idleMs: IDLE_CLOSE_MS, connectTimeoutMs: CONNECT_TIMEOUT_MS,
|
|
1653
|
+
lookupTimeoutMs: EARLY_TIMEOUT_MS, trace: trace_js_1.TRACE_ON,
|
|
1654
|
+
servers: exports.tuning.earlyServers ?? (Array.isArray(seam.servers) ? seam.servers : undefined),
|
|
1655
|
+
hostsFile: exports.tuning.earlyHostsFile ?? (typeof seam.hostsFile === "string" ? seam.hostsFile : undefined),
|
|
1656
|
+
distrustedForTest: ca_guard_js_1.__caGuardInternals.testHashes(),
|
|
1657
|
+
},
|
|
1658
|
+
transferList: [port2],
|
|
1659
|
+
argv: [],
|
|
1660
|
+
execArgv: [],
|
|
1661
|
+
});
|
|
1662
|
+
worker.unref();
|
|
1663
|
+
port1.unref();
|
|
1664
|
+
const t = new TransportThread(origin.origin, worker, port1);
|
|
1665
|
+
t.pace = knobs.pace;
|
|
1666
|
+
t.onFail = onFail;
|
|
1667
|
+
worker.on("error", () => { t.poll(); t.close("error"); });
|
|
1668
|
+
worker.on("exit", () => { t.poll(); t.close("exit"); });
|
|
1669
|
+
transportThread = t;
|
|
1670
|
+
(0, trace_js_1.traceEvent)("thread:start");
|
|
1671
|
+
}
|
|
1672
|
+
catch {
|
|
1673
|
+
transportThread = undefined;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
const prefixes = [];
|
|
1677
|
+
const MAX_PREFIXES = 4;
|
|
1678
|
+
function knownPrefix(url) {
|
|
1679
|
+
for (let i = 0; i < prefixes.length; i++) {
|
|
1680
|
+
const p = prefixes[i];
|
|
1681
|
+
if (url.startsWith(p.text) && url.charCodeAt(p.text.length) === 0x2f)
|
|
1682
|
+
return p;
|
|
1683
|
+
}
|
|
1684
|
+
return undefined;
|
|
1685
|
+
}
|
|
1686
|
+
function remember(p) {
|
|
1687
|
+
for (let i = 0; i < prefixes.length; i++)
|
|
1688
|
+
if (prefixes[i].text === p.text)
|
|
1689
|
+
return;
|
|
1690
|
+
prefixes.unshift(p);
|
|
1691
|
+
if (prefixes.length > MAX_PREFIXES)
|
|
1692
|
+
prefixes.pop();
|
|
1693
|
+
}
|
|
1694
|
+
class Http2Transport {
|
|
1695
|
+
fallback;
|
|
1696
|
+
constructor(fallback) {
|
|
1697
|
+
this.fallback = fallback;
|
|
1698
|
+
}
|
|
1699
|
+
preconnect(url) {
|
|
1700
|
+
try {
|
|
1701
|
+
const u = new URL(url);
|
|
1702
|
+
if (u.protocol !== "https:" || (0, dispatcher_js_1.customDispatcher)())
|
|
1703
|
+
return;
|
|
1704
|
+
poolFor(u.origin).warm();
|
|
1705
|
+
}
|
|
1706
|
+
catch {
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
viaFetch(url, init, deadline) {
|
|
1710
|
+
if (init.trace !== undefined)
|
|
1711
|
+
init.trace.via = "fetch";
|
|
1712
|
+
return this.fallback(url, fetchInit(init, deadline));
|
|
1713
|
+
}
|
|
1714
|
+
async fetch(url, init, replayable) {
|
|
1715
|
+
const tr = init.trace;
|
|
1716
|
+
if (tr !== undefined)
|
|
1717
|
+
(0, trace_js_1.mark)(tr, "h2");
|
|
1718
|
+
const deadline = performance.now() + init.timeoutMs;
|
|
1719
|
+
let target;
|
|
1720
|
+
try {
|
|
1721
|
+
target = targetOf(url, knownPrefix(url), remember);
|
|
1722
|
+
}
|
|
1723
|
+
catch {
|
|
1724
|
+
return this.viaFetch(url, init, deadline);
|
|
1725
|
+
}
|
|
1726
|
+
if (target === undefined || (0, dispatcher_js_1.customDispatcher)())
|
|
1727
|
+
return this.viaFetch(url, init, deadline);
|
|
1728
|
+
let resends = 0;
|
|
1729
|
+
let replays = 0;
|
|
1730
|
+
const thread = threadFor(target.origin);
|
|
1731
|
+
if (thread !== undefined) {
|
|
1732
|
+
const out = await thread.send(target, init, replayable, deadline);
|
|
1733
|
+
if (out === VIA_FETCH)
|
|
1734
|
+
return this.viaFetch(url, init, deadline);
|
|
1735
|
+
if (!(out instanceof HandBack))
|
|
1736
|
+
return out;
|
|
1737
|
+
resends = out.resends;
|
|
1738
|
+
replays = out.replays;
|
|
1739
|
+
if (tr !== undefined)
|
|
1740
|
+
delete tr.via;
|
|
1741
|
+
}
|
|
1742
|
+
const pool = poolFor(target.origin);
|
|
1743
|
+
if (!pool.usable())
|
|
1744
|
+
return this.viaFetch(url, init, deadline);
|
|
1745
|
+
for (;;) {
|
|
1746
|
+
const entry = pool.tryAcquire() ?? await pool.acquire(deadline, init.signal);
|
|
1747
|
+
if (tr !== undefined)
|
|
1748
|
+
(0, trace_js_1.mark)(tr, "acq");
|
|
1749
|
+
if (entry === null)
|
|
1750
|
+
return this.viaFetch(url, init, deadline);
|
|
1751
|
+
let out;
|
|
1752
|
+
try {
|
|
1753
|
+
out = await exchange(pool, entry, target, init, deadline);
|
|
1754
|
+
}
|
|
1755
|
+
catch {
|
|
1756
|
+
pool.turnOff("internal error");
|
|
1757
|
+
out = { kind: "failed", error: new Error("HTTP/2 transport error"), processed: "maybe" };
|
|
1758
|
+
}
|
|
1759
|
+
switch (out.kind) {
|
|
1760
|
+
case "response":
|
|
1761
|
+
if (replays > 0)
|
|
1762
|
+
out.response.replayed = true;
|
|
1763
|
+
return out.response;
|
|
1764
|
+
case "aborted":
|
|
1765
|
+
throw out.reason;
|
|
1766
|
+
case "use-fetch":
|
|
1767
|
+
return this.viaFetch(url, init, deadline);
|
|
1768
|
+
case "failed":
|
|
1769
|
+
if (out.processed === "no") {
|
|
1770
|
+
if (++resends <= MAX_UNPROCESSED_RESENDS)
|
|
1771
|
+
continue;
|
|
1772
|
+
return this.viaFetch(url, init, deadline);
|
|
1773
|
+
}
|
|
1774
|
+
if (out.processed === "maybe" && replayable && replays++ < MAX_REPLAYS)
|
|
1775
|
+
continue;
|
|
1776
|
+
throw fetchFailed(out.error);
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
exports.Http2Transport = Http2Transport;
|
|
1782
|
+
function warmTransport() {
|
|
1783
|
+
const res = toResponse(200, { "content-type": "application/json" }, Buffer.from("{}"), "POST");
|
|
1784
|
+
res.header("server-timing");
|
|
1785
|
+
res.textNow();
|
|
1786
|
+
plainPath("https://a/b?c=d", 9);
|
|
1787
|
+
targetOf("https://a/b?c=d", undefined);
|
|
1788
|
+
const p = new Http2Transport(globalThis.fetch).fetch(undefined, undefined, false);
|
|
1789
|
+
p.catch(() => { });
|
|
1790
|
+
const none = "";
|
|
1791
|
+
exchange({ end() { } }, undefined, { origin: none, host: none, path: none }, undefined, 0).catch(() => { });
|
|
1792
|
+
}
|
|
1793
|
+
exports.__http2Internals = {
|
|
1794
|
+
pools() {
|
|
1795
|
+
return [...pools.values()].map((p) => ({
|
|
1796
|
+
origin: p.origin.origin,
|
|
1797
|
+
sessions: p.sessions.length,
|
|
1798
|
+
opened: p.opened,
|
|
1799
|
+
warmed: p.warmed,
|
|
1800
|
+
connecting: p.isConnecting(),
|
|
1801
|
+
parked: p.isParked(),
|
|
1802
|
+
off: p.off,
|
|
1803
|
+
suspended: !p.off && !p.usable(),
|
|
1804
|
+
offReason: p.offReason,
|
|
1805
|
+
active: p.sessions.reduce((a, e) => a + e.active, 0),
|
|
1806
|
+
split: p.sessions.map((e) => e.active),
|
|
1807
|
+
}));
|
|
1808
|
+
},
|
|
1809
|
+
targetOf(url, known) {
|
|
1810
|
+
let prefix;
|
|
1811
|
+
const target = targetOf(url, known, (p) => { prefix = p; });
|
|
1812
|
+
return { target, prefix };
|
|
1813
|
+
},
|
|
1814
|
+
prefixes() {
|
|
1815
|
+
return prefixes.map((p) => p.text);
|
|
1816
|
+
},
|
|
1817
|
+
reset() {
|
|
1818
|
+
for (const p of pools.values()) {
|
|
1819
|
+
for (const e of [...p.sessions]) {
|
|
1820
|
+
p.retire(e);
|
|
1821
|
+
safely(() => e.session.destroy());
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
pools.clear();
|
|
1825
|
+
},
|
|
1826
|
+
pool(origin) {
|
|
1827
|
+
return new OriginPool(new URL(origin));
|
|
1828
|
+
},
|
|
1829
|
+
thread() {
|
|
1830
|
+
const t = transportThread;
|
|
1831
|
+
if (t === undefined)
|
|
1832
|
+
return undefined;
|
|
1833
|
+
t.poll();
|
|
1834
|
+
return { state: t.state, sessions: t.sessions, limit: t.limit, answered: t.answered, everReady: t.everReady, closedReason: t.closedReason };
|
|
1835
|
+
},
|
|
1836
|
+
threadKnobs(env) {
|
|
1837
|
+
return threadKnobs(env);
|
|
1838
|
+
},
|
|
1839
|
+
crashThreadForTest() {
|
|
1840
|
+
try {
|
|
1841
|
+
transportThread?.port.postMessage({ t: "crash-for-test" });
|
|
1842
|
+
}
|
|
1843
|
+
catch { }
|
|
1844
|
+
},
|
|
1845
|
+
early: {
|
|
1846
|
+
start(host) {
|
|
1847
|
+
return earlyLookupFor(host.toLowerCase()) !== undefined;
|
|
1848
|
+
},
|
|
1849
|
+
state(host) {
|
|
1850
|
+
const e = earlies.get(host.toLowerCase());
|
|
1851
|
+
if (e === undefined)
|
|
1852
|
+
return undefined;
|
|
1853
|
+
const fresh = earlyFresh(e);
|
|
1854
|
+
return { state: e.state, ...(e.answer === undefined ? {} : { answer: e.answer }), fresh: fresh !== undefined };
|
|
1855
|
+
},
|
|
1856
|
+
hosts() {
|
|
1857
|
+
return [...earlies.keys()];
|
|
1858
|
+
},
|
|
1859
|
+
reset() {
|
|
1860
|
+
for (const e of earlies.values())
|
|
1861
|
+
safely(() => { e.port.close(); });
|
|
1862
|
+
earlies.clear();
|
|
1863
|
+
},
|
|
1864
|
+
},
|
|
1865
|
+
};
|
|
1866
|
+
const AT_LOAD = Symbol.for("promigence.sdk.connect-at-load");
|
|
1867
|
+
function isMainThread() {
|
|
1868
|
+
try {
|
|
1869
|
+
const get = process.getBuiltinModule;
|
|
1870
|
+
const wt = typeof get === "function" ? get("node:worker_threads") : undefined;
|
|
1871
|
+
return wt?.isMainThread === true;
|
|
1872
|
+
}
|
|
1873
|
+
catch {
|
|
1874
|
+
return false;
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
function connectAtLoad() {
|
|
1878
|
+
try {
|
|
1879
|
+
if (!isNode() || Number(process.versions.node.split(".")[0]) < 22)
|
|
1880
|
+
return;
|
|
1881
|
+
const off = () => OFF.has((process.env["PROMIGENCE_PRECONNECT"] ?? "").trim().toLowerCase());
|
|
1882
|
+
if (off())
|
|
1883
|
+
return;
|
|
1884
|
+
const g = globalThis;
|
|
1885
|
+
if (g[AT_LOAD] !== undefined)
|
|
1886
|
+
return;
|
|
1887
|
+
g[AT_LOAD] = true;
|
|
1888
|
+
try {
|
|
1889
|
+
if ((process.env["PROMIGENCE_API_KEY"] ?? "").trim() !== "" && isMainThread() && http2Allowed(undefined, process.env)) {
|
|
1890
|
+
const raw = process.env["PROMIGENCE_API_URL"];
|
|
1891
|
+
const url = new URL(raw ? raw : core_js_1.DEFAULT_API_URL);
|
|
1892
|
+
const host = url.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase();
|
|
1893
|
+
const threadOff = OFF.has((process.env["PROMIGENCE_TRANSPORT_THREAD"] ?? "").trim().toLowerCase());
|
|
1894
|
+
if (url.protocol === "https:" && !(0, dispatcher_js_1.customDispatcher)() && earlyPlatform() && v4First() && !threadOff && earlySeam().transportThread !== false) {
|
|
1895
|
+
startTransportThread(url, () => { if (loadTurnRan)
|
|
1896
|
+
warmAtLoad(); });
|
|
1897
|
+
}
|
|
1898
|
+
else if (url.protocol === "https:" && !(0, dispatcher_js_1.customDispatcher)() && (0, node_net_1.isIP)(host) === 0 && earlyPlatform() && v4First())
|
|
1899
|
+
earlyLookupFor(host);
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
catch {
|
|
1903
|
+
}
|
|
1904
|
+
let loadTurnRan = false;
|
|
1905
|
+
const warmAtLoad = () => {
|
|
1906
|
+
try {
|
|
1907
|
+
if (off() || (process.env["PROMIGENCE_API_KEY"] ?? "").trim() === "")
|
|
1908
|
+
return;
|
|
1909
|
+
if (!isMainThread() || !http2Allowed(undefined, process.env))
|
|
1910
|
+
return;
|
|
1911
|
+
const raw = process.env["PROMIGENCE_API_URL"];
|
|
1912
|
+
const url = new URL(raw ? raw : core_js_1.DEFAULT_API_URL);
|
|
1913
|
+
if (url.protocol !== "https:" || (0, dispatcher_js_1.customDispatcher)())
|
|
1914
|
+
return;
|
|
1915
|
+
if (transportThread !== undefined && transportThread.origin === url.origin) {
|
|
1916
|
+
transportThread.poll();
|
|
1917
|
+
if (transportThread.state !== "closed" || transportThread.everReady)
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
warmTls();
|
|
1921
|
+
poolFor(url.origin).warm(exports.tuning.loadFirstUseMs);
|
|
1922
|
+
}
|
|
1923
|
+
catch {
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
const immediate = setImmediate(() => { loadTurnRan = true; warmAtLoad(); });
|
|
1927
|
+
immediate.unref?.();
|
|
1928
|
+
}
|
|
1929
|
+
catch {
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
connectAtLoad();
|