Repository navigation
Conversation
Several Node compatibility gaps in net.SocketAddress and net.BlockList:
- SocketAddress rejected numeric string ports (port: "80"). Run the port
through Node's validatePort semantics so numbers and numeric strings are
accepted (coerced via ToNumber) while non-integers and out-of-range
values throw ERR_SOCKET_BAD_PORT.
- An invalid address threw with code ERR_INVALID_IP_ADDRESS. Node uses
ERR_INVALID_ADDRESS ("Invalid socket address").
- SocketAddress was not structured-cloneable (structuredClone threw
DataCloneError). Register it with the structured-clone serializer so its
value round-trips, matching Node (clone yes, storage/transfer no).
- BlockList had no toJSON/fromJSON, so JSON.stringify(blockList) yielded
"{}". Add BlockList.prototype.toJSON (the rules array) and fromJSON (the
documented v22+ round-trip that rebuilds rules from that array or its
JSON string form).
- Dropped the non-Node addrfamily accessor from SocketAddress.prototype.
|
Warning Review limit reached
Next review available in: 46 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughAdds ChangesBlockList JSON round-trip
SocketAddress port validation and structured clone
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 1:09 AM PT - Jul 7th, 2026
❌ @robobun, your commit 5721972 has some failures in 🧪 To try this PR locally: bunx bun-pr 33572That installs a local version of the PR into your bun-33572 --bun |
- Define BlockList.prototype.toJSON natively instead of patching it onto the prototype at node:net load time, so a structured-clone wrapper created in a realm that never imported net (a Worker receiving a BlockList via postMessage) still has it. fromJSON stays in JS. - validate_port's blank-string check now matches String.prototype.trim's full ECMAScript whitespace set, not just ASCII, so a Unicode-whitespace -only port string is rejected with ERR_SOCKET_BAD_PORT like Node rather than coercing to 0.
|
Thanks, both addressed in 4016876:
|
There was a problem hiding this comment.
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 `@src/runtime/node/net/BlockList.rs`:
- Around line 362-369: The doc comment on BlockList::to_json is too long and
should be reduced to at most 3 lines. Trim the `///` comment to a concise
summary of the method’s behavior, and move the extra rationale about native
implementation, cross-realm behavior, and structured-clone compatibility into
external docs instead.
🪄 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: 1c3a10ba-cb3c-4a64-b79d-a4aef1be9dc8
📒 Files selected for processing (8)
src/js/node/net.tssrc/jsc/bindings/webcore/SerializedScriptValue.cppsrc/runtime/node/net/BlockList.rssrc/runtime/socket/SocketAddress.rssrc/runtime/socket/sockets.classes.tstest/js/node/net/blocklist-gc.test.tstest/js/node/net/socketaddress.spec.tstest/js/web/workers/structuredClone-classes.test.ts
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/runtime/socket/SocketAddress.rs:540-553— nit: thisStructuredCloneWriter+bun_io::Writeimpl is now the third copy of the same ~14-line adapter overcrate::generated_classes::WriteBytesFn—BlockList.rshas a byte-equivalent one (which the doc comment even points at) andBlob.rshas a near-identical one. No correctness impact and you're following existing precedent, but it'd be a nice follow-up to move this to one shared spot (e.g. next to the generatedWriteBytesFntypedef) and import it from all three sites.Extended reasoning...
What this is
The PR adds a private
StructuredCloneWriterstruct atsrc/runtime/socket/SocketAddress.rs:540-553:struct StructuredCloneWriter { ctx: *mut core::ffi::c_void, impl_: crate::generated_classes::WriteBytesFn, } impl bun_io::Write for StructuredCloneWriter { #[inline] fn write_all(&mut self, bytes: &[u8]) -> bun_io::Result<()> { unsafe { (self.impl_)(self.ctx, bytes.as_ptr(), bytes.len() as u32) }; Ok(()) } }
This is functionally byte-for-byte identical to the existing
StructuredCloneWriterinsrc/runtime/node/net/BlockList.rs:9-25(same two fieldsctx/impl_, samebun_io::Write::write_allbody invoking the FFI callback), and near-identical to the one insrc/runtime/webcore/Blob.rs:4206. The new copy's doc comment even says "(seeBlockList)", explicitly acknowledging it's a copy. Grep confirms these are the only three occurrences insrc/.Why it's flagged
The repo's review guidance (CLAUDE.md → "Landing PRs" → "Code style & idioms") is explicit on this class of change: "Never copy a helper or constant table between modules — share or derive it" and "If your fix makes two functions byte-identical, delete one." This is a thin, generic adapter that turns the C++
CloneSerializerwrite callback (WriteBytesFn) into abun_io::Writesink; there is nothingSocketAddress-,BlockList-, orBlob-specific about it, so it belongs in one place.Step-by-step: how the third copy came to be
Blob.rsoriginally introduced aStructuredCloneWriterwrappingcrate::generated_classes::WriteBytesFnfor its structured-clone serialize hook.- When
BlockListgainedstructuredClone: { tag: 251 }, the same adapter was copy-pasted intoBlockList.rsrather than shared. - This PR adds
structuredClone: { tag: 249 }toSocketAddressand needs the samebun_io::Writesink foron_structured_clone_serialize, so it copies theBlockListversion verbatim (fields, body,#[inline], SAFETY comment shape) and points a doc comment back atBlockList.
Each step made local sense; the cumulative effect is three definitions of the same 14 lines that will drift independently the next time someone tweaks the SAFETY comment or the
u32cast.Why nothing prevents it
Each copy is a private (crate-local, non-
pub) struct in a different module, so there's no name collision and no compiler signal. The generatedWriteBytesFntypedef lives incrate::generated_classes(emitted bysrc/codegen/generate-classes.ts:2586-2588), but codegen only emits the function-pointer type, not a writer wrapper, so every consumer that wants abun_io::Writeview has to build its own — and so far every consumer has copy-pasted rather than shared.Impact
Zero correctness impact. All three copies compile to the same trivial FFI thunk; there's no behavioral divergence possible today. This is purely a maintenance concern: three places to update if the
WriteBytesFnsignature changes, and three separately-worded SAFETY comments describing the same invariant. The duplication betweenBlob.rsandBlockList.rsalso pre-exists this PR, so the PR is following an established (if imperfect) pattern rather than introducing a new one — which is why this is a nit, not a blocker.Suggested fix
Move the struct +
impl bun_io::Writenext to theWriteBytesFntypedef so everystructuredClone-enabled class can import it. Two reasonable homes:- Emit it from
src/codegen/generate-classes.tsalongside thepub type WriteBytesFn = ...lines (it's already the module every consumer importsWriteBytesFnfrom), or - A tiny hand-written
src/runtime/structured_clone.rs(or similar) that re-exportsWriteBytesFnand definespub struct StructuredCloneWriter { pub ctx: *mut c_void, pub impl_: WriteBytesFn }+ thebun_io::Writeimpl.
Then replace the three private definitions with
use crate::…::StructuredCloneWriter;. Fine as a follow-up; not worth blocking this PR on.
Address review nits: keep the BlockList.toJSON doc comment within the 3-line limit, and correct the fromJSON catch comment to state that it is deliberately more lenient than Node for hand-authored input (the toJSON round-trip never produces a semantically invalid entry).
|
Addressed the latest nits in edbd56e:
|
| struct StructuredCloneWriter { | ||
| ctx: *mut core::ffi::c_void, | ||
| impl_: crate::generated_classes::WriteBytesFn, | ||
| } | ||
|
|
||
| impl bun_io::Write for StructuredCloneWriter { | ||
| #[inline] | ||
| fn write_all(&mut self, bytes: &[u8]) -> bun_io::Result<()> { | ||
| // SAFETY: `ctx` and `impl_` are supplied together by the C++ writer; | ||
| // the callback reads exactly `len` bytes from `ptr`. | ||
| unsafe { (self.impl_)(self.ctx, bytes.as_ptr(), bytes.len() as u32) }; | ||
| Ok(()) | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 nit: this is now the third copy of StructuredCloneWriter + its bun_io::Write impl in bun_runtime (byte-identical to src/runtime/node/net/BlockList.rs:9, near-identical to src/runtime/webcore/Blob.rs:4206) — the doc comment even points at the original. Since all three reference crate::generated_classes::WriteBytesFn, consider making one pub(crate) (or moving it next to WriteBytesFn) and importing it here and in BlockList.rs. No runtime impact, fine as a follow-up.
Extended reasoning...
What the issue is
This PR adds a private StructuredCloneWriter struct plus its bun_io::Write impl at src/runtime/socket/SocketAddress.rs:562-575. The definition is byte-for-byte identical to the one already at src/runtime/node/net/BlockList.rs:9-26 (same fields ctx / impl_, same write_all body, same SAFETY comment structure), and near-identical to a third pre-existing copy at src/runtime/webcore/Blob.rs:4206 (that one adds an extra write() inherent method but has the same bun_io::Write impl). The new copy's own doc comment — /// Writer over the C++ CloneSerializer byte sink (see BlockList). — explicitly acknowledges it was copied.
Why nothing prevents sharing
All three definitions live in the same bun_runtime crate and all three reference the same type alias crate::generated_classes::WriteBytesFn. BlockList.rs already imports from crate::socket::socket_address (use crate::socket::socket_address::{SocketAddress, sockaddr};), so cross-module visibility is already established between two of the three sites. Making one copy pub(crate) and importing it at the other sites — or, more idiomatically, defining it once next to WriteBytesFn in the generated-classes support code — is a mechanical change with no behavioural risk.
Step-by-step proof
rg 'struct StructuredCloneWriter' src/yields exactly three hits:src/runtime/webcore/Blob.rs:4206,src/runtime/node/net/BlockList.rs:9, andsrc/runtime/socket/SocketAddress.rs:562(the last added by this PR).- Diffing the
BlockList.rsandSocketAddress.rsdefinitions: both declarestruct StructuredCloneWriter { ctx: *mut c_void, impl_: crate::generated_classes::WriteBytesFn }and bothimpl bun_io::Writewith an#[inline] write_allthat doesunsafe { (self.impl_)(self.ctx, bytes.as_ptr(), bytes.len() as u32) }; Ok(()). The only textual differences are in the SAFETY comment wording. - All three files use
crate::generated_classes::WriteBytesFn, confirming same-crate residency, sopub(crate)visibility on any one of them would let the other twouseit directly.
Why it matters (and why it's only a nit)
CLAUDE.md's "Landing PRs" review guidance is explicit on this pattern: "Never copy a helper or constant table between modules — share or derive it" and "The second time a multi-line block appears in your diff, extract a named helper and use it at EVERY parallel site." This PR adds the third copy, and every future .classes.ts type that gains structuredClone: {...} will be tempted to add a fourth.
That said, this is strictly nit severity. There is zero runtime impact — the struct is two pointers and a three-line unsafe callback wrapper, and all three copies compile to identical code. The two pre-existing copies (Blob.rs ↔ BlockList.rs) show the pattern was already tolerated in-tree once. Extracting a shared helper touches 3+ files and arguably exceeds the scope of a focused Node-compat PR (CLAUDE.md also cautions against "riding file-wide standardization on a focused bugfix"). This should not block merge.
Suggested fix
Either in this PR or as a follow-up: mark BlockList.rs's StructuredCloneWriter as pub(crate) and use crate::node::net::block_list::StructuredCloneWriter; here (deleting lines 562-575), or — cleaner long-term — define it once alongside WriteBytesFn in the generated-classes support module and import it in all three sites (Blob.rs, BlockList.rs, SocketAddress.rs).
|
Checked this against the reference version and the Same for |
CI statusThe diff itself is green. Across builds #69486 and #69552 the only hard failure is the 274 other lanes passed; the annotation body has no mention of This is ready for a maintainer to retry the darwin lane or merge. I won't push another retrigger. |
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-07, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main. |
What
Several Node compatibility gaps in
net.SocketAddress/net.BlockList, each breaking a concrete pattern. Verified against Node v26.3.0.new SocketAddress({ address, port: "80" }).portTHREW ERR_SOCKET_BAD_PORT80new SocketAddress({ address: "999.1.1.1" })codeERR_INVALID_IP_ADDRESSERR_INVALID_ADDRESSstructuredClone(socketAddress)THREW DataCloneErrorisSocketAddresstrueJSON.stringify(new BlockList())"{}""[]"BlockList.prototype.{toJSON,fromJSON}SocketAddress.prototypeown namesaddrfamilyCause
is_number+ integer check, so numeric strings (which real code gets from env vars, config,URL#port) were rejected.ERR_INVALID_IP_ADDRESS; Node's documented code for this API isERR_INVALID_ADDRESS(message "Invalid socket address").SocketAddresswas never registered with the structured-clone serializer, so it could not be cloned orpostMessage'd to a worker.BlockListhad no JSON round-trip, soJSON.stringifyfell back to"{}".addrfamilygetter was on the prototype.Fix
All behavior preserved where it already matched Node:
validatePortsemantics (src/runtime/socket/SocketAddress.rs): numbers and numeric strings are accepted and coerced viaToNumber; non-integers, negatives, out-of-range, whitespace-only strings, and non-numeric types throwERR_SOCKET_BAD_PORT.ptonfailures throwERR_INVALID_ADDRESS("Invalid socket address").SocketAddressis registered as a host-cloneable type (tag 249). It is an immutable value, so serialize writes its fields and each deserialize rebuilds a fresh instance. Flags match Node: cloneable, not transferable, not storable (Node'sv8.serializedoes not preserve it either).BlockList.prototype.toJSONreturns the rules array andfromJSONrebuilds rules from that array (or its JSON string form), mirroring Node's implementation and itsERR_INVALID_ARG_TYPEvalidation (src/js/node/net.ts).addrfamilyaccessor.Note: the report also suggested a static
BlockList.fromJSON; that does not exist in Node (it is a prototype method), so this adds the prototype method only.Verification
test/js/node/net/socketaddress.spec.ts: port coercion/rejection,ERR_INVALID_ADDRESS, prototype shape,structuredCloneround-trip.test/js/node/net/blocklist-gc.test.ts:toJSON/fromJSONround-trip (all rule kinds), JSON string form, malformed-entry skipping,ERR_INVALID_ARG_TYPE.test/js/web/workers/structuredClone-classes.test.ts:SocketAddressacross contexts/transfer/storage modes.All fail on the released binary and pass with this change. Node's upstream
test-socketaddress.js,test-blocklist.js,test-blocklist-clone.jsstill pass.Relationship to #33570
#33570 (also robobun) fixes a different set of faces in these same files: strict canonical address parsing (rejecting
010.1.2.3, IPv6 zone-id handling,.addresscanonicalization). The two PRs are complementary but overlap onsrc/runtime/socket/SocketAddress.rsand on switching the invalid-address error code toERR_INVALID_ADDRESS, and #33570 renamessocketaddress.spec.ts. Whichever lands first, the other will need a rebase.