Rust Async Working Group
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: "Design meeting 2024-02-29: Async portability / Context reactor hook" tags: ["WG-async", "design-meeting", "minutes"] date: 2024-02-29 discussion: https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async/topic/Design.20meeting.202024-02-29 url: https://hackmd.io/9o1X1degTECn9gjEvHS-MA --- # Background on context reactor hook https://jblog.andbit.net/2022/12/28/context-reactor-hook/ https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async/topic/Context.20reactor.20hook https://github.com/jkarneges/waker-waiter/issues/1 # Discussion ## Attendance - People: TC, tmandry, yosh, Daria, Vincenzo, Justin Karneges ## Meeting roles - Minutes, driver: TC ## Are we right to specialize this to futures? yosh: This proposes passing a `Reactor` argument via the `task::Context` type down into futures internals. This makes two assumptions: 1. A reactor argument is inherently accessed from the `poll` state machine of future internals 2. This is something unique enough to futures, and so using a dedicated mechanism for futures is justfied Yosh: To the first point, I just finished writing a counter-example in the [`wasi-async-runtime`](https://docs.rs/wasi-async-runtime/latest/wasi_async_runtime/struct.Reactor.html#method.wait_for) crate. Here the `Reactor::wait_for` method creates a concrete future which must be `.await`ed, rather than needing to manage manual callbacks in poll state machines. TC: Isn't this a "turtles all the way down" sort of thing? I.e., the problem here is that something in the synchronous world needs to block to then trigger the wake up of one or more futures. How would creating yet another future that needs to be awoken help here? Yosh: What I'm trying to get at is that "obtain the reactor from the `Context` param" is too low-level, at least with our current tools. In the WASI world we're not really interested in obtaining the reactor at the level of poll state machines; we're interested in obtaining it at the level of "async/.await". Granted, there may be opportunities to use it with manual futures - but that's a matter of passing the reactor into the manual futures. TC: It's not clear to me whether, in that WASI code, you're trying to solve this same problem or whether it's a different problem. Maybe it's correct for there to be another layer for solving the problem the WASI code wants to solve here that is distinct from the problem that Justin is trying to solve. Yosh: It's definitely the same problem - but WASI has a slightly different polling model than Linux or MacOS have. This means the best way to pass the reactor down is not as an argument via the poll state machines, but as arguments to async functions. The differences are not in the intent, they're in the actual polling model. TC: What's special about WASI here, as compared to Linux, that calls for the differences in approach you mention? Yosh: The WASI polling model is entirely single-threaded, which is one difference. The second one is that it uses unique interest tokens on a per-operation basis, which differs from the `epoll` model which registers interest on a per-resource basis. This means the interest is registered in the function, rather than on the resource - which I think is what underlies the difference in how we end up exposing it. Here is a concrete example: ```rust use wasi::http::outgoing_handler::{handle, OutgoingRequest}; use wasi::http::types::{Fields, Method, Scheme}; use wasi::io::poll; fn main() { // Construct an HTTP request let fields = Fields::new(); let req = OutgoingRequest::new(fields); req.set_method(&Method::Get).unwrap(); req.set_scheme(Some(&Scheme::Https)).unwrap(); req.set_path_with_query(Some("/")).unwrap(); req.set_authority(Some("example.com")).unwrap(); // Send the request and wait for it to complete let res = handle(req, None).unwrap(); // 1. We're ready to send the request over the network let pollable = res.subscribe(); // 2. We obtain the `Pollable` from the response future poll::poll(&[&pollable]); // 3. Block until we're ready to look at the response // We're now ready to try and access the response headers. If // the request was unsuccessful we might still get an error here, // but we won't get an error that we tried to read data before the // operation was completed. let res = res.get().unwrap().unwrap().unwrap(); for (name, _) in res.headers().entries() { println!("header: {name}"); } } ``` TC: Are you proposing that doing this in the `Context` is not expressive enough for the WASI code or that it would be awkward in the implementation. Yosh: It leans more toward the awkward. TC: Are you writing up a counterproposal here? Yosh: I'm partial to the general context mechanism, as in tmandry's post. There are a number of use cases here beyond async Rust. If we could solve this problem generally, that'd be better. tmandry: The leaf future is what needs to interact with this reactor. And that's generally written in the poll style. So I'm not really understanding here. Yosh: In the WASI case, we can write the leaf futures with `async fn`. https://github.com/yoshuawuyts/wasm-http-tools/blob/main/crates/wasi-http-client/src/lib.rs#L37-L45 eholk: If we think of this as a monad, the context is the thing that's being threaded through. We want the reactor to be threaded through in this same way. The plumbing is already there. There may be other things we'd want to plumb through in this same way also, and that may help with avoiding use of TLS. --- Yosh: Here are two examples for discussion: - https://github.com/yoshuawuyts/wasm-http-tools/blob/main/crates/wasi-http-client/src/lib.rs#L37-L45 - https://docs.rs/wasi-async-runtime/latest/src/wasi_async_runtime/reactor.rs.html#65-86 Justin: I feel like this would work in the context reactor model. ## Continuing the second point from above Yosh: To the second point, Tyler wrote a post on a generalized mechanism for this in late 2022: [context and capabilities for Rust](http://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/). Examples of other things we want to pass down "contextually" mentioned by the blog post include loggers, allocators, and executors. Why would we believe that this a unique mechanism specifically for contexts would be justified - and why wouldn't we pursue the more general mechanism if we know that shares many of the issues? TC: If we had had a general context mechanism, perhaps we would have used that in the first place rather than adding a `Context` argument to `Future::poll`. Yosh: I'm not sure tbh - all futures do need to always pass a `Waker` of some kind. Contexts seem more suited for things which may not always need to be passed? But maybe I'm wrong, and it would actually have made sense to pass it via a context. eholk: It looks like the wasi-runtime still bottoms out in a `poll_fn`: https://github.com/yoshuawuyts/wasm-http-tools/blob/main/crates/wasi-async-runtime/src/reactor.rs#L70 So it seems like maybe this is structured so there's essentially just one leaf future and everything else is built around that. Yosh: You're not wrong. ## `QueryInterface` eholk: In the Windows/COM world there's [`QueryInterface`], which gives a way to let objects dynamically support an unbounded set of interfaces. I wonder if it'd make sense to apply something like that here to make things more easily extensible? It might look like: ```rust fn poll(self: Pin<&mut Self>, cx: Context) { let waiter = cx.get_service::<Waiter>().unwrap(); } ``` Unfortunately, this would almost certainly not be zero cost, so it may be unacceptable overhead for low level future mechanics. [`QueryInterface`]: https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(refiid_void) tmandry: ...there is a proposal for this, "[Provider]". [Provider]: https://github.com/rust-lang/rust/issues/96024 Justin: I do like this idea. I put this in the Context because we don't have that mechanism. Justin: The `waker_getters` mechanism is going to help here. ## Nouns tmandry: There are a lot of nouns in this proposal. Let's map them out? Justin: I tried to keep these names minimal so they don't imply too much. Executor is presenting itself as the `TopLevelPoller`. ## Type safety yosh: This erases the types we're passing around. The types are not equivalent - and we probably want to stabilize shared interfaces. How are we evaluating this? Is type-unsafety ok here? Would we prefer a type-safe interface? eholk: we might be confusing two things here: dyn traits and option. dyn traits don't give you a runtime failure. We would be introducing new optional types - and that could introduce runtime failures yes. That raises a question about graceful degradation. ## Example of how this all works Justin: [hackish tokio example](https://github.com/jkarneges/waker-waiter/blob/waker_getters/examples/tokio.rs) (The meeting ended here.)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully