Repository navigation
Give Rust APIs the IoContext of the current request #7963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bartlomieju
wants to merge
14
commits into
main
Choose a base branch
from
biwanczuk/rust-jsg-io-context
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+674
−21
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
68dddfd
Give Rust APIs the IoContext of the current request
bartlomieju 2596ce1
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-jsg-io…
bartlomieju c93f799
Fix clippy errors in the io-context test bridge
bartlomieju 0ac8d6d
Say what to change in both copies of the no-request message
bartlomieju 497ff59
Create Rust builtin modules' exports outside any request
bartlomieju 9ffcd92
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-jsg-io…
bartlomieju 0e9a43b
Run the io-context crate's unit tests
bartlomieju d137485
Merge branch 'main' into biwanczuk/rust-jsg-io-context
bartlomieju 802490c
Merge branch 'main' into biwanczuk/rust-jsg-io-context
bartlomieju 934cd23
Merge branch 'main' into biwanczuk/rust-jsg-io-context
bartlomieju 12d6f72
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-jsg-io…
bartlomieju 60e6022
Get the IoContext id and error message through the shim
bartlomieju af4b59c
Merge remote-tracking branch 'origin/biwanczuk/rust-jsg-io-context' i…
bartlomieju 2a91b05
Merge branch 'main' into biwanczuk/rust-jsg-io-context
bartlomieju File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| load("//:build/kj_test.bzl", "kj_test") | ||
| load("//:build/wd_cc_library.bzl", "wd_cc_library") | ||
| load("//:build/wd_rust_crate.bzl", "wd_rust_crate") | ||
|
|
||
| # The IoContext of the current request, for APIs implemented in Rust. A package of its own | ||
| # because //src/workerd/io depends on jsg. | ||
| wd_rust_crate( | ||
| name = "io-context", | ||
| srcs = [ | ||
| "ffi.rs", | ||
| "lib.rs", | ||
| "lib-test.rs", | ||
| ], | ||
| cxx_bridge_deps = ["//src/workerd/io"], | ||
| cxx_bridge_hdrs = ["ffi.h"], | ||
| cxx_bridge_src = "ffi.rs", | ||
| link_deps = [":ffi"], | ||
| test_deps = ["//src/rust/jsg-test"], | ||
| visibility = ["//visibility:public"], | ||
| deps = ["//src/rust/jsg"], | ||
| ) | ||
|
|
||
| wd_cc_library( | ||
| name = "ffi", | ||
| srcs = ["ffi.c++"], | ||
| hdrs = ["ffi.h"], | ||
| deps = ["//src/workerd/io"], | ||
| ) | ||
|
|
||
| # Checked by //src/rust/jsg:cpp-jsg-allowlist-test. | ||
| exports_files([ | ||
| "ffi.c++", | ||
| "ffi.h", | ||
| ]) | ||
|
|
||
| # The Rust half of io-context-test. | ||
| wd_rust_crate( | ||
| name = "io-context-test-bridge", | ||
| testonly = True, | ||
| srcs = ["test_bridge.rs"], | ||
| crate_root = "test_bridge.rs", | ||
| cxx_bridge_deps = ["//src/rust/jsg"], | ||
| cxx_bridge_hdrs = [], | ||
| cxx_bridge_src = "test_bridge.rs", | ||
| deps = [ | ||
| ":io-context", | ||
| "//src/rust/jsg", | ||
| ], | ||
| ) | ||
|
|
||
| # io-context inside a request of a real worker and in a Durable Object, and the IoContext that | ||
| # Rust builtin modules see when a request resolves them. | ||
| kj_test( | ||
| src = "io-context-test.c++", | ||
| deps = [ | ||
| ":ffi", | ||
| ":io-context-test-bridge", | ||
| "//src/rust/jsg:bridge", | ||
| "//src/workerd/tests:test-fixture", | ||
| ], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| // Copyright (c) 2026 Cloudflare, Inc. | ||
| // Licensed under the Apache 2.0 license found in the LICENSE file or at: | ||
| // https://opensource.org/licenses/Apache-2.0 | ||
|
|
||
| #include "ffi.h" | ||
|
|
||
| #include <capnp/message.h> | ||
| #include <capnp/serialize.h> | ||
|
|
||
| #include <bit> | ||
| #include <type_traits> | ||
|
|
||
| namespace workerd::io_context { | ||
|
|
||
| namespace { | ||
|
|
||
| // IoContext::Id holds only the process-unique uint64_t that Rust stores. | ||
| static_assert(sizeof(IoContext::Id) == sizeof(uint64_t)); | ||
| static_assert(std::is_trivially_copyable_v<IoContext::Id>); | ||
|
|
||
| // The current IoContext, which must be the one `id` identifies. | ||
| IoContext& currentWithId(uint64_t id) { | ||
| auto& context = KJ_REQUIRE_NONNULL(IoContext::tryCurrent(), "there is no current request"); | ||
| KJ_REQUIRE(context.getId() == std::bit_cast<IoContext::Id>(id), | ||
| "the IoContext is not the one of the current request"); | ||
| return context; | ||
| } | ||
|
|
||
| } // namespace | ||
|
|
||
| ::rust::Str io_context_no_request_message() { | ||
| return IoContext::NO_REQUEST_MESSAGE.cStr(); | ||
| } | ||
|
|
||
| kj::Maybe<uint64_t> io_context_try_current_id() { | ||
| return IoContext::tryGetCurrentId().map( | ||
| [](IoContext::Id id) { return std::bit_cast<uint64_t>(id); }); | ||
| } | ||
|
|
||
| int64_t io_context_now(uint64_t id) { | ||
| return (currentWithId(id).now() - kj::UNIX_EPOCH) / kj::NANOSECONDS; | ||
| } | ||
|
|
||
| void io_context_write_logfwdr(uint64_t id, uint32_t channel, ::rust::Slice<const uint8_t> message) { | ||
| auto& context = currentWithId(id); | ||
|
|
||
| // Rust does not align the bytes to words, so they are copied. | ||
| auto bytes = kj::arrayPtr(message.data(), message.size()); | ||
| KJ_REQUIRE(bytes.size() > 0, "the serialized message is empty"); | ||
| KJ_REQUIRE(bytes.size() % sizeof(capnp::word) == 0, | ||
| "the serialized message is not a whole number of words"); | ||
| auto words = kj::heapArray<capnp::word>(bytes.size() / sizeof(capnp::word)); | ||
| words.asBytes().copyFrom(bytes); | ||
| capnp::FlatArrayMessageReader reader(words); | ||
| KJ_REQUIRE(reader.getEnd() == words.end(), "bytes follow the serialized message"); | ||
|
|
||
| KJ_IF_SOME(outputLocks, context.waitForOutputLocksIfNecessary()) { | ||
| // In a Durable Object, the message must not leave before the storage writes that precede it | ||
| // are confirmed, as in AnalyticsEngine::writeDataPoint(). The message is copied now, so that | ||
| // an invalid one fails this call rather than the write. | ||
| auto copy = kj::heap<capnp::MallocMessageBuilder>(); | ||
| copy->getRoot<capnp::AnyPointer>().set(reader.getRoot<capnp::AnyPointer>()); | ||
| context.addWaitUntil( | ||
| outputLocks.then([weakRef = context.getWeakRef(), channel, copy = kj::mv(copy)]() mutable { | ||
| // The IoContext owns its waitUntil tasks, so it is alive while one runs. | ||
| auto& context = KJ_ASSERT_NONNULL(weakRef->tryGet()); | ||
| // IoChannelFactory::writeLogfwdr() needs the current IoContext, so the write runs in it. | ||
| return context.run([channel, copy = kj::mv(copy)](Worker::Lock&, IoContext& context) mutable { | ||
| context.writeLogfwdr(channel, [&](capnp::AnyPointer::Builder builder) { | ||
| builder.set(copy->getRoot<capnp::AnyPointer>().asReader()); | ||
| }); | ||
| }); | ||
| })); | ||
| } else { | ||
| context.writeLogfwdr(channel, [&](capnp::AnyPointer::Builder builder) { | ||
| builder.set(reader.getRoot<capnp::AnyPointer>()); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| } // namespace workerd::io_context | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // Copyright (c) 2026 Cloudflare, Inc. | ||
| // Licensed under the Apache 2.0 license found in the LICENSE file or at: | ||
| // https://opensource.org/licenses/Apache-2.0 | ||
|
|
||
| #pragma once | ||
|
|
||
| #include <workerd/io/io-context.h> | ||
|
|
||
| #include <rust/cxx.h> | ||
|
|
||
| #include <cstdint> | ||
|
|
||
| // The IoContext calls `ffi.rs` makes. Rust identifies an IoContext by its IoContext::Id, as a | ||
| // uint64_t, and holds no reference to it. Each call below that takes an `id` uses the current | ||
| // IoContext, and fails unless `id` identifies it: ids are never reused, so a stale id cannot | ||
| // reach another request's IoContext, or one that has been destroyed. | ||
| namespace workerd::io_context { | ||
|
|
||
| // The message of the error IoContext::current() throws outside a request. | ||
| ::rust::Str io_context_no_request_message(); | ||
|
|
||
| // IoContext::tryGetCurrentId(), as a uint64_t. | ||
| kj::Maybe<uint64_t> io_context_try_current_id(); | ||
|
|
||
| // IoContext::now(), in nanoseconds since the Unix epoch. | ||
| int64_t io_context_now(uint64_t id); | ||
|
|
||
| // IoContext::writeLogfwdr(), for a serialized Cap'n Proto message. In a Durable Object, the | ||
| // write waits for the output gate, as AnalyticsEngine::writeDataPoint() does. | ||
| void io_context_write_logfwdr(uint64_t id, uint32_t channel, ::rust::Slice<const uint8_t> message); | ||
|
|
||
| } // namespace workerd::io_context |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| // Copyright (c) 2026 Cloudflare, Inc. | ||
| // Licensed under the Apache 2.0 license found in the LICENSE file or at: | ||
| // https://opensource.org/licenses/Apache-2.0 | ||
|
|
||
| //! The bridge to the C++ `IoContext` calls in `ffi.h`. | ||
|
|
||
| #![expect(unsafe_code, reason = "the cxx bridge expands to unsafe FFI glue")] | ||
|
|
||
| #[cxx::bridge(namespace = "workerd::io_context")] | ||
| pub mod bridge { | ||
| unsafe extern "C++" { | ||
| include!("workerd/io/io-context/ffi.h"); | ||
|
|
||
| fn io_context_no_request_message() -> &'static str; | ||
| fn io_context_try_current_id() -> KjMaybe<u64>; | ||
| fn io_context_now(id: u64) -> Result<i64>; | ||
| fn io_context_write_logfwdr(id: u64, channel: u32, message: &[u8]) -> Result<()>; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.