@blaxel/core 0.2.87-preview.174 → 0.2.87-preview.175

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.
Files changed (37) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/common/h2fetch.js +54 -17
  3. package/dist/cjs/common/settings.js +29 -3
  4. package/dist/cjs/common/transient-retry.js +145 -0
  5. package/dist/cjs/sandbox/drive/drive.js +11 -6
  6. package/dist/cjs/sandbox/filesystem/filesystem.js +126 -158
  7. package/dist/cjs/sandbox/process/process.js +29 -16
  8. package/dist/cjs/types/common/h2fetch.d.ts +7 -0
  9. package/dist/cjs/types/common/settings.d.ts +22 -2
  10. package/dist/cjs/types/common/transient-retry.d.ts +30 -0
  11. package/dist/cjs/types/sandbox/filesystem/filesystem.d.ts +3 -0
  12. package/dist/cjs-browser/.tsbuildinfo +1 -1
  13. package/dist/cjs-browser/common/h2fetch.js +1 -0
  14. package/dist/cjs-browser/common/settings.js +29 -3
  15. package/dist/cjs-browser/common/transient-retry.js +145 -0
  16. package/dist/cjs-browser/sandbox/drive/drive.js +11 -6
  17. package/dist/cjs-browser/sandbox/filesystem/filesystem.js +126 -158
  18. package/dist/cjs-browser/sandbox/process/process.js +29 -16
  19. package/dist/cjs-browser/types/common/h2fetch.d.ts +7 -0
  20. package/dist/cjs-browser/types/common/settings.d.ts +22 -2
  21. package/dist/cjs-browser/types/common/transient-retry.d.ts +30 -0
  22. package/dist/cjs-browser/types/sandbox/filesystem/filesystem.d.ts +3 -0
  23. package/dist/esm/.tsbuildinfo +1 -1
  24. package/dist/esm/common/h2fetch.js +53 -17
  25. package/dist/esm/common/settings.js +29 -3
  26. package/dist/esm/common/transient-retry.js +141 -0
  27. package/dist/esm/sandbox/drive/drive.js +11 -6
  28. package/dist/esm/sandbox/filesystem/filesystem.js +124 -157
  29. package/dist/esm/sandbox/process/process.js +29 -16
  30. package/dist/esm-browser/.tsbuildinfo +1 -1
  31. package/dist/esm-browser/common/h2fetch.js +1 -0
  32. package/dist/esm-browser/common/settings.js +29 -3
  33. package/dist/esm-browser/common/transient-retry.js +141 -0
  34. package/dist/esm-browser/sandbox/drive/drive.js +11 -6
  35. package/dist/esm-browser/sandbox/filesystem/filesystem.js +124 -157
  36. package/dist/esm-browser/sandbox/process/process.js +29 -16
  37. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withUploadSlot = withUploadSlot;
3
4
  exports.createH2Fetch = createH2Fetch;
4
5
  exports.createPoolBackedH2Fetch = createPoolBackedH2Fetch;
5
6
  exports.h2RequestDirectFromPool = h2RequestDirectFromPool;
@@ -32,30 +33,31 @@ const sessionsWithListenerBudget = new WeakSet();
32
33
  // freed early (the queue could then admit one extra stream); acceptable as a
33
34
  // pure backstop, since the slot is otherwise tied to the true stream terminal.
34
35
  const H2_SLOT_TIMEOUT_MS = 1_800_000; // 30 minutes
36
+ // Global per-domain gate (the opt-in maxConcurrentH2Requests cap).
35
37
  const h2GatesByDomain = new Map();
36
- function getH2Gate(domain) {
37
- let gate = h2GatesByDomain.get(domain);
38
+ // Upload-scoped per-domain gate (the default-on multipart upload cap, ENG-2680).
39
+ // Kept separate from the global gate so it only ever throttles upload parts.
40
+ const h2UploadGatesByDomain = new Map();
41
+ function getGate(gates, domain) {
42
+ let gate = gates.get(domain);
38
43
  if (!gate) {
39
44
  gate = { active: 0, queue: [] };
40
- h2GatesByDomain.set(domain, gate);
45
+ gates.set(domain, gate);
41
46
  }
42
47
  return gate;
43
48
  }
44
49
  /**
45
- * Acquire an OPEN-STREAM slot for `domain`. Resolves with a release function
46
- * that is idempotent and FIFO-fair: releasing wakes the longest-waiting queued
47
- * caller for the same domain. The slot is held for the lifetime of an OPEN H2
48
- * stream the send path releases it on the stream terminal so the gate
49
- * bounds true concurrent streams on the one shared session, not merely requests
50
- * awaiting headers (ENG-2678). A backstop timer releases the slot if a request
51
- * neither opens a stream nor ever settles, preventing per-domain starvation;
52
- * it never aborts the underlying request (see `H2_SLOT_TIMEOUT_MS`).
50
+ * Core per-domain async semaphore, shared by the global and upload gates.
51
+ * Resolves with a release function that is idempotent and FIFO-fair: releasing
52
+ * wakes the longest-waiting queued caller for the same domain. When `max` is
53
+ * `0`/unset the gate is a no-op (unlimited). A backstop timer releases the slot
54
+ * if a holder never releases, preventing per-domain starvation; it never aborts
55
+ * the underlying request (see `H2_SLOT_TIMEOUT_MS`).
53
56
  */
54
- async function acquireH2Slot(domain) {
55
- const max = settings_js_1.settings.maxConcurrentH2Requests; // 0/undefined = unlimited
57
+ async function acquireGateSlot(gates, domain, max) {
56
58
  if (!max || max <= 0)
57
59
  return () => { };
58
- const gate = getH2Gate(domain);
60
+ const gate = getGate(gates, domain);
59
61
  while (gate.active >= max) {
60
62
  await new Promise((resolve) => gate.queue.push(resolve));
61
63
  }
@@ -75,9 +77,9 @@ async function acquireH2Slot(domain) {
75
77
  next();
76
78
  }
77
79
  else if (gate.active === 0 && gate.queue.length === 0) {
78
- // No active requests and nothing waiting: drop the empty gate so the
79
- // Map does not grow unbounded across many short-lived domains.
80
- h2GatesByDomain.delete(domain);
80
+ // No active holders and nothing waiting: drop the empty gate so the Map
81
+ // does not grow unbounded across many short-lived domains.
82
+ gates.delete(domain);
81
83
  }
82
84
  };
83
85
  timer.handle = setTimeout(release, H2_SLOT_TIMEOUT_MS);
@@ -86,6 +88,41 @@ async function acquireH2Slot(domain) {
86
88
  timer.handle.unref?.();
87
89
  return release;
88
90
  }
91
+ /**
92
+ * Acquire the global OPEN-STREAM slot for `domain` (the opt-in
93
+ * `maxConcurrentH2Requests` cap; `0`/unset = unlimited, the default). Held for
94
+ * the lifetime of an OPEN H2 stream — the send path releases it on the stream
95
+ * terminal — so the gate bounds true concurrent streams on the one shared
96
+ * session, not merely requests awaiting headers (ENG-2678).
97
+ */
98
+ function acquireH2Slot(domain) {
99
+ return acquireGateSlot(h2GatesByDomain, domain, settings_js_1.settings.maxConcurrentH2Requests);
100
+ }
101
+ /**
102
+ * Acquire an upload-scoped slot for `domain`, bounding concurrent multipart
103
+ * upload-part requests on the shared H2 connection (ENG-2680). Separate from the
104
+ * global gate so it only throttles uploads. Defaults to 2 — the measured value
105
+ * that stops concurrent large uploads tripping ENHANCE_YOUR_CALM — making it the
106
+ * one reliability mitigation on by default, scoped to the upload path.
107
+ */
108
+ function acquireUploadSlot(domain) {
109
+ return acquireGateSlot(h2UploadGatesByDomain, domain, settings_js_1.settings.maxConcurrentUploadH2Requests);
110
+ }
111
+ /**
112
+ * Run `fn` while holding an upload slot for `domain`, releasing it when `fn`
113
+ * settles (the part PUT completes or fails). Bounds concurrent in-flight upload
114
+ * parts per domain across all files sharing the connection. Used by the
115
+ * multipart upload path; a no-op wrapper when the upload cap is unset.
116
+ */
117
+ async function withUploadSlot(domain, fn) {
118
+ const release = await acquireUploadSlot(domain);
119
+ try {
120
+ return await fn();
121
+ }
122
+ finally {
123
+ release();
124
+ }
125
+ }
89
126
  /**
90
127
  * Creates a fetch()-compatible function that sends requests over an existing
91
128
  * HTTP/2 session. Falls back to globalThis.fetch() only when the session is
@@ -28,8 +28,8 @@ function missingCredentialsMessage() {
28
28
  return "No Blaxel credentials found. Set the BL_API_KEY and BL_WORKSPACE environment variables, or run `bl login`.";
29
29
  }
30
30
  // Build info - these placeholders are replaced at build time by build:replace-imports
31
- const BUILD_VERSION = "0.2.87-preview.174";
32
- const BUILD_COMMIT = "d820c0d5ab85c3e0603e16cd29198e14055869ec";
31
+ const BUILD_VERSION = "0.2.87-preview.175";
32
+ const BUILD_COMMIT = "31085636cd9c2557198ee7399e7794e945c21687";
33
33
  const BUILD_SENTRY_DSN = "https://fd5e60e1c9820e1eef5ccebb84a07127@o4508714045276160.ingest.us.sentry.io/4510465864564736";
34
34
  const BLAXEL_API_VERSION = "2026-04-16";
35
35
  // Cache for config.yaml tracking value
@@ -263,6 +263,19 @@ class Settings {
263
263
  }
264
264
  return 0;
265
265
  }
266
+ get maxConcurrentUploadH2Requests() {
267
+ if (typeof this.config.maxConcurrentUploadH2Requests === "number") {
268
+ return this.config.maxConcurrentUploadH2Requests;
269
+ }
270
+ const value = env_js_1.env.BL_MAX_UPLOAD_H2_INFLIGHT;
271
+ if (value) {
272
+ const parsed = parseInt(value, 10);
273
+ if (!Number.isNaN(parsed)) {
274
+ return parsed;
275
+ }
276
+ }
277
+ return 2;
278
+ }
266
279
  get fsPartRetries() {
267
280
  if (typeof this.config.fsPartRetries === "number") {
268
281
  return this.config.fsPartRetries;
@@ -274,7 +287,20 @@ class Settings {
274
287
  return parsed;
275
288
  }
276
289
  }
277
- return 0;
290
+ return 3;
291
+ }
292
+ get sandboxReadRetries() {
293
+ if (typeof this.config.sandboxReadRetries === "number") {
294
+ return this.config.sandboxReadRetries;
295
+ }
296
+ const value = env_js_1.env.BL_SANDBOX_READ_RETRIES;
297
+ if (value) {
298
+ const parsed = parseInt(value, 10);
299
+ if (!Number.isNaN(parsed)) {
300
+ return parsed;
301
+ }
302
+ }
303
+ return 5;
278
304
  }
279
305
  /**
280
306
  * Fail fast with a clear, actionable error when credentials are missing or
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTransientResetError = isTransientResetError;
4
+ exports.retryOnTransientReset = retryOnTransientReset;
5
+ const settings_js_1 = require("./settings.js");
6
+ // Markers that, when present anywhere in the error chain, are unambiguous
7
+ // signals of a transient HTTP/2 stream reset or connection drop. These are
8
+ // protocol/transport level codes, not application payloads, so substring
9
+ // matching them does not over-match a server-sent error body. Each entry is
10
+ // matched case-sensitively against the error message and its cause.
11
+ //
12
+ // Deliberately excluded: bare "INTERNAL_ERROR" and "fetch failed". Both are
13
+ // too generic on their own (an application 500 body or any failed fetch would
14
+ // match), so we only treat them as transient when paired with a transport
15
+ // error code on the cause (see isTransientResetError).
16
+ const TRANSIENT_RESET_MARKERS = [
17
+ "ENHANCE_YOUR_CALM", // H2 flow-control backpressure reset
18
+ "NGHTTP2_INTERNAL_ERROR", // H2 internal stream error (qualified form)
19
+ "ERR_HTTP2", // node http2 error code family
20
+ "GOAWAY", // peer is draining the connection
21
+ "HTTP/2 session closed before response", // thrown by our own h2 transport
22
+ "HTTP/2 session sent GOAWAY before response",
23
+ ];
24
+ // Node-level error codes (from `error.code` / `error.cause.code`) that mean
25
+ // the connection itself dropped mid-flight and the request never completed.
26
+ // These are safe to retry for an idempotent request.
27
+ const TRANSIENT_ERROR_CODES = new Set([
28
+ "ECONNRESET",
29
+ "ECONNREFUSED",
30
+ "ETIMEDOUT",
31
+ "EPIPE",
32
+ "ERR_HTTP2_STREAM_ERROR",
33
+ "ERR_HTTP2_GOAWAY_SESSION",
34
+ "ERR_HTTP2_SESSION_ERROR",
35
+ ]);
36
+ function collectErrorText(error) {
37
+ const messages = [];
38
+ const codes = [];
39
+ // Walk the error -> cause chain (bounded) so a transport error wrapped by a
40
+ // higher-level "fetch failed" is still classified correctly.
41
+ let current = error;
42
+ for (let depth = 0; depth < 5 && current && typeof current === "object"; depth++) {
43
+ const node = current;
44
+ if (typeof node.message === "string")
45
+ messages.push(node.message);
46
+ if (typeof node.code === "string")
47
+ codes.push(node.code);
48
+ current = node.cause;
49
+ }
50
+ return { messages, codes };
51
+ }
52
+ // True when the error chain carries a real HTTP response (a status came back
53
+ // from the server). Such an error is an APPLICATION response — never a transport
54
+ // reset — even if the server's error body text happens to contain a reset marker
55
+ // like "GOAWAY" or "ERR_HTTP2". Guarding on this stops a marker-bearing 4xx/5xx
56
+ // body from being misread as transient and retried (the over-match Codex flagged
57
+ // for the now default-on idempotent-read retry).
58
+ function hasHttpResponseStatus(error) {
59
+ let current = error;
60
+ for (let depth = 0; depth < 5 && current && typeof current === "object"; depth++) {
61
+ const node = current;
62
+ if (typeof node.status === "number")
63
+ return true;
64
+ if (node.response && typeof node.response === "object" &&
65
+ typeof node.response.status === "number") {
66
+ return true;
67
+ }
68
+ current = node.cause;
69
+ }
70
+ return false;
71
+ }
72
+ /**
73
+ * True only for transport-level resets/drops that are safe to retry on an
74
+ * IDEMPOTENT request (transient HTTP/2 stream reset, GOAWAY, or a dropped
75
+ * connection). Application errors (4xx/5xx — even when their body text contains
76
+ * a marker word) and a bare "fetch failed" with no transport code are
77
+ * deliberately NOT transient, so auto-retry never masks a real server error or
78
+ * duplicates a non-idempotent call.
79
+ *
80
+ * This is the single classifier shared by the upload-part retry (ENG-2680) and
81
+ * the idempotent sandbox-op retry (read/list/etc.), so both judge "transient"
82
+ * identically.
83
+ */
84
+ function isTransientResetError(error) {
85
+ if (!error || typeof error !== "object") {
86
+ return false;
87
+ }
88
+ // An error that carries an HTTP response is an application error, not a
89
+ // transport reset — never retry it on the strength of a marker in its body.
90
+ if (hasHttpResponseStatus(error)) {
91
+ return false;
92
+ }
93
+ const { messages, codes } = collectErrorText(error);
94
+ // 1. An explicit transient transport error code anywhere in the chain.
95
+ if (codes.some((code) => TRANSIENT_ERROR_CODES.has(code))) {
96
+ return true;
97
+ }
98
+ // 2. An unambiguous protocol-level reset marker in any message.
99
+ if (messages.some((text) => TRANSIENT_RESET_MARKERS.some((marker) => text.includes(marker)))) {
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+ const DEFAULT_BASE_DELAY_MS = 200;
105
+ const DEFAULT_MAX_DELAY_MS = 2000;
106
+ // Exponential backoff with full-jitter on top of one base delay, capped so a
107
+ // single wait never blocks unreasonably long. Exponential (rather than linear)
108
+ // gives a later attempt room to span a multi-second sandbox cold-start/standby
109
+ // wake, which is the window a first-call reset falls into, while early attempts
110
+ // stay fast for the common quick-reset case.
111
+ function backoffDelayMs(attempt, baseDelayMs, maxDelayMs) {
112
+ const exponential = baseDelayMs * Math.pow(2, attempt - 1);
113
+ const capped = Math.min(exponential, maxDelayMs);
114
+ const jitter = Math.floor(Math.random() * baseDelayMs);
115
+ return capped + jitter;
116
+ }
117
+ /**
118
+ * Run `fn`, retrying only on transient transport resets (see
119
+ * isTransientResetError) with exponential backoff. Caller owns idempotency:
120
+ * ONLY wrap idempotent operations (GET-shaped reads/lists, or an idempotent
121
+ * PUT of the same bytes) — never a non-idempotent POST such as process.exec,
122
+ * which would duplicate the side effect (ENG-2340).
123
+ *
124
+ * Defaults to `settings.sandboxReadRetries` (the higher idempotent-read budget,
125
+ * sized for a multi-second standby wake). The upload path passes
126
+ * `{ retries: settings.fsPartRetries }` to keep its own (lower) budget.
127
+ */
128
+ async function retryOnTransientReset(fn, options = {}) {
129
+ const retries = options.retries ?? settings_js_1.settings.sandboxReadRetries;
130
+ const baseDelayMs = options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
131
+ const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
132
+ let attempt = 0;
133
+ for (;;) {
134
+ try {
135
+ return await fn();
136
+ }
137
+ catch (error) {
138
+ attempt++;
139
+ if (retries <= 0 || attempt > retries || !isTransientResetError(error)) {
140
+ throw error;
141
+ }
142
+ await new Promise((resolve) => setTimeout(resolve, backoffDelayMs(attempt, baseDelayMs, maxDelayMs)));
143
+ }
144
+ }
145
+ }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SandboxDrive = void 0;
4
4
  const action_js_1 = require("../action.js");
5
+ const transient_retry_js_1 = require("../../common/transient-retry.js");
5
6
  const index_js_1 = require("../client/index.js");
6
7
  class SandboxDrive extends action_js_1.SandboxAction {
7
8
  constructor(sandbox) {
@@ -36,12 +37,16 @@ class SandboxDrive extends action_js_1.SandboxAction {
36
37
  * List all mounted drives in the sandbox
37
38
  */
38
39
  async list() {
39
- const { response, data, error } = await (0, index_js_1.getDrivesMount)(this.withClient({
40
- baseUrl: this.url,
41
- }));
42
- this.handleResponseError(response, data, error);
43
- const result = data;
44
- return result.mounts ?? [];
40
+ // Idempotent GET: self-heal a transient connection reset after sandbox resume.
41
+ // mount/unmount stay un-retried (non-idempotent POST/DELETE).
42
+ return (0, transient_retry_js_1.retryOnTransientReset)(async () => {
43
+ const { response, data, error } = await (0, index_js_1.getDrivesMount)(this.withClient({
44
+ baseUrl: this.url,
45
+ }));
46
+ this.handleResponseError(response, data, error);
47
+ const result = data;
48
+ return result.mounts ?? [];
49
+ });
45
50
  }
46
51
  }
47
52
  exports.SandboxDrive = SandboxDrive;