@blaxel/core 0.2.85-preview.159 → 0.2.86-preview.161

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.
@@ -1,6 +1,74 @@
1
+ import { settings } from "./settings.js";
1
2
  import { refH2SessionForActiveRequest } from "./h2ref.js";
2
3
  const MIN_H2_SESSION_MAX_LISTENERS = 64;
3
4
  const sessionsWithListenerBudget = new WeakSet();
5
+ /**
6
+ * Per-domain async semaphore that bounds the number of in-flight HTTP/2
7
+ * requests against a single edge domain (one H2 session). The cap is keyed
8
+ * by domain so throttling one sandbox's uploads never blocks requests to an
9
+ * unrelated sandbox served by a different edge.
10
+ *
11
+ * When `settings.maxConcurrentH2Requests` is `0`/unset the gate is a no-op
12
+ * (current default behavior: unlimited concurrency).
13
+ */
14
+ // Safety timeout for a held slot. A request that never resolves (no response,
15
+ // no error, no abort) would otherwise hold its slot forever and starve every
16
+ // queued request for the same domain. After this window we release the slot
17
+ // and let the underlying request continue or reject on its own; we never
18
+ // cancel the in-flight request here, we only stop it from blocking the queue.
19
+ // Kept deliberately conservative (well above any realistic part-upload time)
20
+ // so it does not interfere with legitimately slow but healthy requests.
21
+ const H2_SLOT_TIMEOUT_MS = 120_000;
22
+ const h2GatesByDomain = new Map();
23
+ function getH2Gate(domain) {
24
+ let gate = h2GatesByDomain.get(domain);
25
+ if (!gate) {
26
+ gate = { active: 0, queue: [] };
27
+ h2GatesByDomain.set(domain, gate);
28
+ }
29
+ return gate;
30
+ }
31
+ /**
32
+ * Acquire an in-flight slot for `domain`. Resolves with a release function
33
+ * that is idempotent and FIFO-fair: releasing wakes the longest-waiting
34
+ * queued caller for the same domain. A safety timer also releases the slot
35
+ * if the caller never does, preventing per-domain starvation.
36
+ */
37
+ async function acquireH2Slot(domain) {
38
+ const max = settings.maxConcurrentH2Requests; // 0/undefined = unlimited
39
+ if (!max || max <= 0)
40
+ return () => { };
41
+ const gate = getH2Gate(domain);
42
+ while (gate.active >= max) {
43
+ await new Promise((resolve) => gate.queue.push(resolve));
44
+ }
45
+ gate.active++;
46
+ let released = false;
47
+ // Holder so `release` can clear the safety timer that is created after it.
48
+ const timer = {};
49
+ const release = () => {
50
+ if (released)
51
+ return;
52
+ released = true;
53
+ if (timer.handle !== undefined)
54
+ clearTimeout(timer.handle);
55
+ gate.active--;
56
+ const next = gate.queue.shift();
57
+ if (next) {
58
+ next();
59
+ }
60
+ else if (gate.active === 0 && gate.queue.length === 0) {
61
+ // No active requests and nothing waiting: drop the empty gate so the
62
+ // Map does not grow unbounded across many short-lived domains.
63
+ h2GatesByDomain.delete(domain);
64
+ }
65
+ };
66
+ timer.handle = setTimeout(release, H2_SLOT_TIMEOUT_MS);
67
+ // unref() so a pending safety timer never keeps the process alive. Guarded
68
+ // because not every runtime's timer handle exposes unref().
69
+ timer.handle.unref?.();
70
+ return release;
71
+ }
4
72
  /**
5
73
  * Creates a fetch()-compatible function that sends requests over an existing
6
74
  * HTTP/2 session. Falls back to globalThis.fetch() only when the session is
@@ -26,11 +94,40 @@ export function createH2Fetch(session) {
26
94
  */
27
95
  export function createPoolBackedH2Fetch(pool, domain) {
28
96
  return async (input) => {
97
+ const rel = await acquireH2Slot(domain);
98
+ try {
99
+ const session = await pool.get(domain);
100
+ if (session) {
101
+ let h2RequestCreated = false;
102
+ try {
103
+ return await _h2Request(session, input, {
104
+ onH2RequestCreated: () => {
105
+ h2RequestCreated = true;
106
+ },
107
+ });
108
+ }
109
+ catch (err) {
110
+ if (h2RequestCreated) {
111
+ pool.evictSession(domain, session);
112
+ }
113
+ throw err;
114
+ }
115
+ }
116
+ return await globalThis.fetch(input);
117
+ }
118
+ finally {
119
+ rel();
120
+ }
121
+ };
122
+ }
123
+ export async function h2RequestDirectFromPool(pool, domain, url, init) {
124
+ const rel = await acquireH2Slot(domain);
125
+ try {
29
126
  const session = await pool.get(domain);
30
127
  if (session) {
31
128
  let h2RequestCreated = false;
32
129
  try {
33
- return await _h2Request(session, input, {
130
+ return await h2RequestDirectInternal(session, url, init, {
34
131
  onH2RequestCreated: () => {
35
132
  h2RequestCreated = true;
36
133
  },
@@ -43,28 +140,11 @@ export function createPoolBackedH2Fetch(pool, domain) {
43
140
  throw err;
44
141
  }
45
142
  }
46
- return globalThis.fetch(input);
47
- };
48
- }
49
- export async function h2RequestDirectFromPool(pool, domain, url, init) {
50
- const session = await pool.get(domain);
51
- if (session) {
52
- let h2RequestCreated = false;
53
- try {
54
- return await h2RequestDirectInternal(session, url, init, {
55
- onH2RequestCreated: () => {
56
- h2RequestCreated = true;
57
- },
58
- });
59
- }
60
- catch (err) {
61
- if (h2RequestCreated) {
62
- pool.evictSession(domain, session);
63
- }
64
- throw err;
65
- }
143
+ return await globalThis.fetch(url, init);
144
+ }
145
+ finally {
146
+ rel();
66
147
  }
67
- return globalThis.fetch(url, init);
68
148
  }
69
149
  /**
70
150
  * Low-level H2 request that takes raw URL + init, skipping Request construction.
@@ -5,8 +5,8 @@ import { authentication } from "../authentication/index.js";
5
5
  import { env } from "../common/env.js";
6
6
  import { fs, os, path } from "../common/node.js";
7
7
  // Build info - these placeholders are replaced at build time by build:replace-imports
8
- const BUILD_VERSION = "0.2.85-preview.159";
9
- const BUILD_COMMIT = "a9c088b49239125f1b129fbc95d1887556112a33";
8
+ const BUILD_VERSION = "0.2.86-preview.161";
9
+ const BUILD_COMMIT = "a5bdac720290868983bb67563ff7068c1cf8c67f";
10
10
  const BUILD_SENTRY_DSN = "https://fd5e60e1c9820e1eef5ccebb84a07127@o4508714045276160.ingest.us.sentry.io/4510465864564736";
11
11
  const BLAXEL_API_VERSION = "2026-04-16";
12
12
  // Cache for config.yaml tracking value
@@ -226,6 +226,32 @@ class Settings {
226
226
  }
227
227
  return isDenoRuntime();
228
228
  }
229
+ get maxConcurrentH2Requests() {
230
+ if (typeof this.config.maxConcurrentH2Requests === "number") {
231
+ return this.config.maxConcurrentH2Requests;
232
+ }
233
+ const value = env.BL_MAX_H2_INFLIGHT;
234
+ if (value) {
235
+ const parsed = parseInt(value, 10);
236
+ if (!Number.isNaN(parsed)) {
237
+ return parsed;
238
+ }
239
+ }
240
+ return 0;
241
+ }
242
+ get fsPartRetries() {
243
+ if (typeof this.config.fsPartRetries === "number") {
244
+ return this.config.fsPartRetries;
245
+ }
246
+ const value = env.BL_FS_PART_RETRIES;
247
+ if (value) {
248
+ const parsed = parseInt(value, 10);
249
+ if (!Number.isNaN(parsed)) {
250
+ return parsed;
251
+ }
252
+ }
253
+ return 0;
254
+ }
229
255
  async authenticate() {
230
256
  await this.credentials.authenticate();
231
257
  }
@@ -6,6 +6,94 @@ import { deleteFilesystemByPath, deleteFilesystemMultipartByUploadIdAbort, getFi
6
6
  const MULTIPART_THRESHOLD = 5 * 1024 * 1024; // 5MB
7
7
  const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB per part
8
8
  const MAX_PARALLEL_UPLOADS = 3; // Number of parallel part uploads
9
+ // Base backoff between part-upload retries, in milliseconds. Grows linearly
10
+ // per attempt and is jittered to avoid synchronized retries (thundering herd)
11
+ // when several parallel parts fail against the same edge at the same time.
12
+ const RETRY_BASE_DELAY_MS = 200;
13
+ // Markers that, when present anywhere in the error chain, are unambiguous
14
+ // signals of a transient HTTP/2 stream reset or connection drop. These are
15
+ // protocol/transport level codes, not application payloads, so substring
16
+ // matching them does not over-match a server-sent error body. Each entry is
17
+ // matched case-sensitively against the error message and its cause.
18
+ //
19
+ // Deliberately excluded: bare "INTERNAL_ERROR" and "fetch failed". Both are
20
+ // too generic on their own (an application 500 body or any failed fetch would
21
+ // match), so we only treat them as transient when paired with a transport
22
+ // error code on the cause (see isTransientUploadError).
23
+ const TRANSIENT_RESET_MARKERS = [
24
+ "ENHANCE_YOUR_CALM", // H2 flow-control backpressure reset
25
+ "NGHTTP2_INTERNAL_ERROR", // H2 internal stream error (qualified form)
26
+ "ERR_HTTP2", // node http2 error code family
27
+ "GOAWAY", // peer is draining the connection
28
+ "HTTP/2 session closed before response", // thrown by our own h2 transport
29
+ "HTTP/2 session sent GOAWAY before response",
30
+ ];
31
+ // Node-level error codes (from `error.code` / `error.cause.code`) that mean
32
+ // the connection itself dropped mid-flight and the request never completed.
33
+ // These are safe to retry for an idempotent part upload.
34
+ const TRANSIENT_ERROR_CODES = new Set([
35
+ "ECONNRESET",
36
+ "ECONNREFUSED",
37
+ "ETIMEDOUT",
38
+ "EPIPE",
39
+ "ERR_HTTP2_STREAM_ERROR",
40
+ "ERR_HTTP2_GOAWAY_SESSION",
41
+ "ERR_HTTP2_SESSION_ERROR",
42
+ ]);
43
+ function collectErrorText(error) {
44
+ const messages = [];
45
+ const codes = [];
46
+ // Walk the error -> cause chain (bounded) so a transport error wrapped by a
47
+ // higher-level "fetch failed" is still classified correctly.
48
+ let current = error;
49
+ for (let depth = 0; depth < 5 && current && typeof current === "object"; depth++) {
50
+ const node = current;
51
+ if (typeof node.message === "string")
52
+ messages.push(node.message);
53
+ if (typeof node.code === "string")
54
+ codes.push(node.code);
55
+ current = node.cause;
56
+ }
57
+ return { messages, codes };
58
+ }
59
+ function isTransientUploadError(error) {
60
+ if (!error || typeof error !== "object") {
61
+ return false;
62
+ }
63
+ const { messages, codes } = collectErrorText(error);
64
+ // 1. An explicit transient transport error code anywhere in the chain.
65
+ if (codes.some((code) => TRANSIENT_ERROR_CODES.has(code))) {
66
+ return true;
67
+ }
68
+ // 2. An unambiguous protocol-level reset marker in any message.
69
+ if (messages.some((text) => TRANSIENT_RESET_MARKERS.some((marker) => text.includes(marker)))) {
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ function nextRetryDelayMs(attempt) {
75
+ // Linear backoff (200ms, 400ms, ...) plus up to one extra base delay of
76
+ // random jitter so concurrent part retries do not all fire on the same tick.
77
+ const base = RETRY_BASE_DELAY_MS * attempt;
78
+ const jitter = Math.floor(Math.random() * RETRY_BASE_DELAY_MS);
79
+ return base + jitter;
80
+ }
81
+ async function retryOnTransient(fn) {
82
+ const retries = settings.fsPartRetries; // 0 = off (current default behavior)
83
+ let attempt = 0;
84
+ for (;;) {
85
+ try {
86
+ return await fn();
87
+ }
88
+ catch (error) {
89
+ attempt++;
90
+ if (retries <= 0 || attempt > retries || !isTransientUploadError(error)) {
91
+ throw error;
92
+ }
93
+ await new Promise((resolve) => setTimeout(resolve, nextRetryDelayMs(attempt)));
94
+ }
95
+ }
96
+ }
9
97
  export class SandboxFileSystem extends SandboxAction {
10
98
  process;
11
99
  constructor(sandbox, process) {
@@ -423,7 +511,7 @@ export class SandboxFileSystem extends SandboxAction {
423
511
  const start = (partNumber - 1) * CHUNK_SIZE;
424
512
  const end = Math.min(start + CHUNK_SIZE, size);
425
513
  const chunk = blob.slice(start, end);
426
- batch.push(this.uploadPart(uploadId, partNumber, chunk));
514
+ batch.push(retryOnTransient(() => this.uploadPart(uploadId, partNumber, chunk)));
427
515
  }
428
516
  // Wait for batch to complete
429
517
  const batchResults = await Promise.all(batch);