Skip to content

ServerWebSocket: send Blob bytes instead of "[object Blob]" - #36032

Merged
Jarred-Sumner merged 8 commits into
mainfrom
farm/9570e8b3/server-ws-send-blob
Jul 27, 2026
Merged

Jarred-Sumner merged 8 commits into
mainfrom
farm/9570e8b3/server-ws-send-blob

Conversation

@robobun

@robobun robobun commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

What

ServerWebSocket.send(blob), ws.publish(topic, blob), ws.sendBinary(blob), ws.publishBinary(topic, blob), ws.ping(blob), ws.pong(blob), and server.publish(topic, blob) now send the Blob's bytes as a binary frame, matching the client-side WebSocket.send(blob) and npm ws.

Previously:

  • send / publish fell through to ToString and shipped the literal text "[object Blob]" (return code 13), silently corrupting data.
  • sendBinary / publishBinary / ping / pong rejected Blobs with a TypeError.

So passing the same Blob to the client WebSocket.send, the server ws.send, and ws.sendBinary produced three different results.

Repro

const server = Bun.serve({
  port: 0,
  fetch: (req, s) => (s.upgrade(req) ? undefined : new Response("no")),
  websocket: { open(ws) { globalThis.sws = ws; ws.subscribe("t"); }, message() {} },
});
const c = new WebSocket(`ws://127.0.0.1:${server.port}/`);
c.binaryType = "arraybuffer";
c.onmessage = e =>
  console.log("client got:", typeof e.data === "string" ? JSON.stringify(e.data) : new Uint8Array(e.data));
c.onopen = () => {
  const blob = new Blob([new Uint8Array([1, 2, 3, 4])]);
  console.log("ws.send(blob) rc =", sws.send(blob));           // before: 13, after: 4
  console.log("server.publish rc =", server.publish("t", blob)); // before: 13, after: 4
};
// before: client got: "[object Blob]"  "[object Blob]"
// after:  client got: Uint8Array [1,2,3,4]  Uint8Array [1,2,3,4]

Cause

send() / publish() check message_value.as_array_buffer() and on miss fall straight through to message_value.to_js_string(), which is the JS ToString coercion. Blobs (and every other object) become "[object Blob]".

Fix

Insert a value.as_class_ref::<Blob>() check between the ArrayBuffer check and the string coercion at all seven sites, sending blob.shared_view() as Opcode::Binary. A shared blob_payload() helper does the detection and rejects file/S3-backed blobs (Bun.file(), Bun.s3()) with a TypeError that points at await blob.bytes(), since these send paths are synchronous and return a byte count so async I/O cannot happen there.

sendBinary / publishBinary error messages now say "Blob or BufferSource" instead of "an ArrayBufferView".

Type definitions and the websockets doc page are updated to include Blob in the unions.

Notes

Non-Blob objects passed to send / publish still coerce via ToString (e.g. ws.send(42) sends "42"). Tightening that to a TypeError the way npm ws does would be a separate behavior change.


no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/websocket/websocket-server.test.ts

ServerWebSocket.send(blob), publish(topic, blob), sendBinary(blob),
publishBinary(topic, blob), ping(blob), pong(blob), and
server.publish(topic, blob) now send the Blob's bytes as a binary
frame. Previously send/publish fell through to ToString and shipped the
text '[object Blob]' (rc=13) while sendBinary/publishBinary/ping/pong
rejected Blobs entirely, so the same Blob meant three different things
between the client WebSocket, the server send path, and sendBinary.

File- and S3-backed Blobs (Bun.file, Bun.s3) throw a TypeError naming
blob.bytes() as the workaround, since these APIs are synchronous and
return a byte count.

Fixes #5271
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 58 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5f6e371e-ddd3-4da9-ad13-a12818f8ec11

📥 Commits

Reviewing files that changed from the base of the PR and between 2e59410 and 89f6a2f.

📒 Files selected for processing (2)
  • src/runtime/server/ServerWebSocket.rs
  • test/js/bun/websocket/websocket-server.test.ts

Walkthrough

Changes

WebSocket Blob Support

Layer / File(s) Summary
Blob API contracts
packages/bun-types/serve.d.ts, docs/runtime/http/websockets.mdx
Public WebSocket send, publish, ping, and pong declarations and examples now include Blob.
Synchronous Blob extraction
src/runtime/server/ServerWebSocket.rs
Adds shared byte extraction for in-memory Blobs and rejects file-backed or S3-backed Blobs synchronously.
WebSocket transmission paths
src/runtime/server/ServerWebSocket.rs, src/runtime/server/server_body.rs
WebSocket and server publish APIs transmit Blob contents as binary payloads while preserving existing text fallback behavior.
Blob behavior validation
test/js/bun/websocket/websocket-server.test.ts
Tests Blob and File transmission, publishing, sliced and empty payloads, and file-backed Blob errors.

Possibly related PRs

  • oven-sh/bun#36001: Updates shared byte-view extraction for rope-backed Blob storage used by this support.

Suggested reviewers: jarred-sumner, alii

🚥 Pre-merge checks | ✅ 2 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements Blob WebSocket support, but linked issue #5271 is about macro circular-structure support, so the change does not satisfy it. Either link the correct issue for Blob WebSocket support or implement the macro/circular-structure feature requested by #5271.
Out of Scope Changes check ⚠️ Warning The Blob WebSocket API and test changes are unrelated to the linked macro/circular-structure issue, so they are out of scope for #5271. Remove the unrelated Blob WebSocket work from this issue, or relink the PR to the correct Blob-support issue.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the primary behavior change: Blob inputs now send bytes instead of becoming "[object Blob]".
Description check ✅ Passed The PR description covers what changed, why, and how it was validated, though it doesn't use the template's exact headings.

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the inline nits, I also checked the unbound 'a lifetime on blob_payload() — it's sound because as_class_ref::<Blob>() returns &'static Blob, so shared_view() yields a 'static slice; ensure_still_alive() after each send keeps the Blob wrapper (and its Store) live past the borrow. Also verified shared_view() applies offset/size so the Blob.slice() test case is exercising the right code path.

Extended reasoning...

The two inline findings are minor (a test-cleanup edge case and an error-message wording miss). The core change looks correct and well-tested, but it's a user-visible behavior change on the ServerWebSocket send/publish hot path that borrows Blob store bytes across an FFI send — worth a human glance rather than an auto-approve.

Comment thread test/js/bun/websocket/websocket-server.test.ts Outdated
Comment thread src/runtime/server/ServerWebSocket.rs
Comment thread src/runtime/server/ServerWebSocket.rs Outdated
Comment thread src/runtime/server/ServerWebSocket.rs Outdated
@robobun

robobun commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 9:23 PM PT - Jul 26th, 2026

✅ @autofix-ci[bot], your commit 89f6a2f63c24d13f4efe4cbee66fd3ecfc4897d2 passed in Build #83017! 🎉


🧪   To try this PR locally:

bunx bun-pr 36032

That installs a local version of the PR into your bun-36032 executable, so you can run:

bun-36032 --bun

Comment thread test/js/bun/websocket/websocket-server.test.ts Outdated
The file-level afterEach stops every server in servers[], so under
it.concurrent one sibling finishing would tear down the others'
servers mid-flush. Wrap the one fallible await in try/catch instead.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/websocket/websocket-server.test.ts`:
- Line 794: Remove the issue-reference comment adjacent to the WebSocket Blob
transmission test; leave the test logic unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6718df92-e1e3-4c34-bd33-7579ecd935a3

📥 Commits

Reviewing files that changed from the base of the PR and between 43d60f6 and 2e59410.

📒 Files selected for processing (5)
  • docs/runtime/http/websockets.mdx
  • packages/bun-types/serve.d.ts
  • src/runtime/server/ServerWebSocket.rs
  • src/runtime/server/server_body.rs
  • test/js/bun/websocket/websocket-server.test.ts

Comment thread test/js/bun/websocket/websocket-server.test.ts Outdated
Comment thread src/runtime/server/ServerWebSocket.rs

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — all prior review feedback has been addressed.

What was reviewed:

  • blob_payload() uses as_class_ref::<Blob>() + shared_view() (offset/size-aware, empty for file/S3 stores) with ensure_still_alive() after each send, matching the existing js_string.ensure_still_alive() idiom in this file.
  • All seven call sites (send/sendBinary/publish/publishBinary/ping/pong/server.publish) are covered by the three new tests, including Blob.slice, File, empty Blob, and file-backed rejection.
  • openOne() now uses local try/catch cleanup instead of the shared servers[] array, avoiding the it.concurrent × afterEach race flagged earlier.
Extended reasoning...

Overview

Adds Blob as an accepted payload type at seven ServerWebSocket send-family sites (send, sendBinary, publish, publishBinary, ping, pong, and server.publish). Previously send/publish fell through to ToString and shipped "[object Blob]"; the binary variants threw. A shared blob_payload() helper detects Blob via as_class_ref::<Blob>(), rejects file-/S3-backed stores with a TypeError pointing at await blob.bytes(), and returns shared_view(). Type defs and docs updated to include Blob in the unions.

Security risks

None. Input is a JS-heap Blob whose bytes are already in memory; no file I/O, no untrusted-length arithmetic (the slice comes straight from shared_view(), which clamps offset/size against the store length). File/S3-backed blobs are rejected before any read.

Level of scrutiny

Medium — native Rust in a hot user-facing send path, but the change is purely additive and mechanical: one new branch inserted between the existing ArrayBuffer check and the string-coercion fallthrough at each site, following the file's exact ensure_still_alive() idiom. as_class_ref returns &'static T kept live by the conservative stack scan while the JSValue is on the stack; the slice is consumed synchronously before ensure_still_alive() roots it past the send. shared_view() at webcore_types.rs:323 already handles offset/size (so blob.slice() works) and returns empty for non-bytes stores.

Other factors

This PR has been through three prior review rounds from me: (1) openOne() server-leak on early reject and the missing "Blob" in the ping/pong TypeError, (2) the servers.push() × it.concurrent × file-level afterEach race that a304bbe introduced, and (3) the "file-backed" wording not covering S3. All are resolved in the current diff (try/catch local cleanup, "string, Blob, or BufferSource", "file- or S3-backed"). CodeRabbit's stray issue-URL nit and comment-cop's long-comment nags were also addressed. The bug hunter found nothing new this run. Test coverage is comprehensive: exact return codes and received bytes asserted for Blob/Blob.slice/File/empty across all seven methods, plus the file-backed error at all seven.

@Jarred-Sumner
Jarred-Sumner merged commit c7233fb into main Jul 27, 2026
55 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/9570e8b3/server-ws-send-blob branch July 27, 2026 05:24
Jarred-Sumner pushed a commit that referenced this pull request Jul 27, 2026
## What

`ServerWebSocket.send(blob)`, `ws.publish(topic, blob)`,
`ws.sendBinary(blob)`, `ws.publishBinary(topic, blob)`, `ws.ping(blob)`,
`ws.pong(blob)`, and `server.publish(topic, blob)` now send the Blob's
bytes as a **binary** frame, matching the client-side
`WebSocket.send(blob)` and npm `ws`.

Previously:
- `send` / `publish` fell through to `ToString` and shipped the literal
text `"[object Blob]"` (return code 13), silently corrupting data.
- `sendBinary` / `publishBinary` / `ping` / `pong` rejected Blobs with a
TypeError.

So passing the same Blob to the client `WebSocket.send`, the server
`ws.send`, and `ws.sendBinary` produced three different results.

## Repro

```js
const server = Bun.serve({
  port: 0,
  fetch: (req, s) => (s.upgrade(req) ? undefined : new Response("no")),
  websocket: { open(ws) { globalThis.sws = ws; ws.subscribe("t"); }, message() {} },
});
const c = new WebSocket(`ws://127.0.0.1:${server.port}/`);
c.binaryType = "arraybuffer";
c.onmessage = e =>
  console.log("client got:", typeof e.data === "string" ? JSON.stringify(e.data) : new Uint8Array(e.data));
c.onopen = () => {
  const blob = new Blob([new Uint8Array([1, 2, 3, 4])]);
  console.log("ws.send(blob) rc =", sws.send(blob));           // before: 13, after: 4
  console.log("server.publish rc =", server.publish("t", blob)); // before: 13, after: 4
};
// before: client got: "[object Blob]"  "[object Blob]"
// after:  client got: Uint8Array [1,2,3,4]  Uint8Array [1,2,3,4]
```

## Cause

`send()` / `publish()` check `message_value.as_array_buffer()` and on
miss fall straight through to `message_value.to_js_string()`, which is
the JS `ToString` coercion. Blobs (and every other object) become
`"[object Blob]"`.

## Fix

Insert a `value.as_class_ref::<Blob>()` check between the ArrayBuffer
check and the string coercion at all seven sites, sending
`blob.shared_view()` as `Opcode::Binary`. A shared `blob_payload()`
helper does the detection and rejects file/S3-backed blobs
(`Bun.file()`, `Bun.s3()`) with a TypeError that points at `await
blob.bytes()`, since these send paths are synchronous and return a byte
count so async I/O cannot happen there.

`sendBinary` / `publishBinary` error messages now say "Blob or
BufferSource" instead of "an ArrayBufferView".

Type definitions and the websockets doc page are updated to include
`Blob` in the unions.

## Notes

Non-Blob objects passed to `send` / `publish` still coerce via
`ToString` (e.g. `ws.send(42)` sends `"42"`). Tightening that to a
TypeError the way npm `ws` does would be a separate behavior change.



<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · Platform-specific test(s) that do not
run on this machine. Deferring to CI, which covers all platforms:
test/js/bun/websocket/websocket-server.test.ts

<!-- robobun:evidence:end -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants