├── .cargo ├── config.toml └── config.wasmer.toml ├── .github └── workflows │ └── rust.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── example ├── .gitignore ├── Cargo.toml ├── README.md ├── bootstrap.js ├── index.html ├── index.js ├── package.json ├── src │ └── lib.rs └── webpack.config.js ├── release.toml ├── rust-toolchain ├── shell.nix └── src ├── lib.rs └── single_threaded.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.wasm32-wasi] 2 | runner = "wasmtime" 3 | -------------------------------------------------------------------------------- /.cargo/config.wasmer.toml: -------------------------------------------------------------------------------- 1 | [target.wasm32-wasi] 2 | runner = "wasmer" 3 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | 13 | jobs: 14 | test: 15 | name: Test Suite 16 | runs-on: ubuntu-latest 17 | 18 | timeout-minutes: 30 19 | 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | toolchain: ['1.49.0', '1.50.0', 'stable', 'nightly'] 24 | 25 | steps: 26 | - name: Checkout sources 27 | uses: actions/checkout@v2 28 | 29 | - name: Install ${{matrix.toolchain}} toolchain 30 | uses: actions-rs/toolchain@v1 31 | with: 32 | profile: minimal 33 | toolchain: ${{matrix.toolchain}} 34 | override: true 35 | 36 | - name: Run cargo test 37 | uses: actions-rs/cargo@v1 38 | with: 39 | command: test 40 | args: --all-features 41 | 42 | wasm: 43 | name: WebAssembly 44 | runs-on: ubuntu-latest 45 | 46 | timeout-minutes: 30 47 | 48 | strategy: 49 | matrix: 50 | toolchain: ['stable'] 51 | 52 | steps: 53 | - name: Checkout sources 54 | uses: actions/checkout@v2 55 | 56 | - name: Install Node.js 57 | uses: actions/setup-node@v2 58 | with: 59 | node-version: '12' 60 | 61 | - name: Install ${{matrix.toolchain}} toolchain 62 | uses: actions-rs/toolchain@v1 63 | with: 64 | profile: minimal 65 | target: wasm32-unknown-unknown 66 | toolchain: ${{matrix.toolchain}} 67 | override: true 68 | 69 | - name: Install wasm-pack 70 | uses: jetli/wasm-pack-action@v0.3.0 71 | with: 72 | version: 'latest' 73 | 74 | - name: Use wasmtime 0.23.0 75 | uses: mwilliamson/setup-wasmtime-action@v1 76 | with: 77 | wasmtime-version: "0.23.0" 78 | 79 | - name: Install wasmer 80 | run: |- 81 | curl https://get.wasmer.io -sSfL | sh 82 | 83 | - name: Check if it tests under Node.js 84 | run: |- 85 | wasm-pack test --node -- --all-features 86 | 87 | - name: Check if it tests under wasmtime 88 | run: |- 89 | cargo test --target wasm32-wasi --all-features 90 | 91 | - name: Check if it tests under wasmer 92 | run: |- 93 | source ~/.wasmer/wasmer.sh 94 | cp .cargo/config.wasmer.toml .cargo/config.toml 95 | cargo test --target wasm32-wasi --all-features 96 | 97 | lints: 98 | name: Lints 99 | runs-on: ubuntu-latest 100 | 101 | strategy: 102 | fail-fast: false 103 | matrix: 104 | toolchain: ['stable'] 105 | 106 | steps: 107 | - name: Checkout sources 108 | uses: actions/checkout@v2 109 | 110 | - name: Install ${{matrix.toolchain}} toolchain 111 | uses: actions-rs/toolchain@v1 112 | with: 113 | profile: minimal 114 | toolchain: ${{matrix.toolchain}} 115 | override: true 116 | components: rustfmt, clippy 117 | 118 | - name: Run cargo fmt 119 | uses: actions-rs/cargo@v1 120 | with: 121 | command: fmt 122 | args: --all -- --check 123 | 124 | - name: Run cargo clippy 125 | uses: actions-rs/cargo@v1 126 | with: 127 | command: clippy 128 | args: -- -D warnings 129 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | *.swp 4 | *.bak 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## [Unreleased] - ReleaseDate 4 | 5 | ## [0.9.0] - 2021-02-21 6 | 7 | ### Changed 8 | 9 | - `single_threaded::block_on` returns `R` instead of `Option` now 10 | 11 | ## [0.8.1] - 2021-02-20 12 | 13 | ### Added 14 | 15 | - Continuous integration with `wasm32-wasi` target 16 | 17 | ## [0.8.0] - 2021-02-19 18 | 19 | ### Changed 20 | 21 | - `single_threaded::spawn` now returns `TaskHandle` that allows joining 22 | until task completion and retrieval of task's result 23 | - Tasks are no longer required to return `()` 24 | 25 | ## [0.7.0] - 2021-02-17 26 | 27 | ### Added 28 | 29 | - `TypeId` information on the task is now available through `Task.type_info().type_id()` 30 | 31 | ### Changed 32 | 33 | - `single_threaded::Token` type is no longer public 34 | - `single_threaded::tasks()` has been renamed to `tasks_count()` 35 | - `single_threaded::queued_tasks()` has been renamed to `tasks_count()` 36 | - `single_threaded::tokens()` has been replaced with `tasks()` and returns `Vec` now; 37 | it's no longer under `debug` feature gate 38 | - `single_threaded::queued_tokens()` has been replaced with `queued_tasks()` and returns `Vec` now; 39 | it's no longer under `debug` feature gate 40 | - `single_threaded::task_type()` has been replaced with `Task.type_info().type_name()` 41 | 42 | ## [0.6.1] - 2021-02-14 43 | 44 | ### Fixed 45 | 46 | - `single_threaded::yield_animation_frame` and `single_threaded::yield_until_idle` futures might 47 | panic at times 48 | 49 | ## [0.6.0] - 2021-02-13 50 | 51 | ### Added 52 | 53 | - `single_threaded::yield_timeout`, `single_threaded::yield_async` and `single_threaded::yield_animation_frame` API 54 | to orchestrate different types of yielding to the environment 55 | 56 | ### Removed 57 | 58 | - `single_threaded::run_cooperatively` is removed in favour of 59 | `single_threaded::yield_timeout` and `single_threaded::yield_animation_frame` 60 | 61 | ## [0.5.1] - 2021-02-08 62 | 63 | ### Changed 64 | 65 | - `single_threaded::run_cooperatively` is no longer marked `unsafe` 66 | (but this is not a guarantee just yet) 67 | 68 | ## [0.5.0] - 2021-02-08 69 | 70 | ### Added 71 | 72 | - A way to run the executor cooperatively with the host's JavaScript environment 73 | (`single_threaded::run_cooperatively`) 74 | 75 | ## [0.4.1] - 2021-02-06 76 | 77 | The snapshot of 0.4.0's code was published incorrectly, thus yanked. 0.4.1 replaces it. 78 | 79 | ## [0.4.0] - 2021-02-06 80 | 81 | ### Fixed 82 | 83 | - Type debugging information was removed too early 84 | - Incorrect future pinning 85 | 86 | ## [0.3.2] - 2021-02-06 87 | 88 | ### Added 89 | 90 | - Debugging capabilities in a form of `single_threaded::task_name`, `single_threaded::tokens` and 91 | `single_threaded::queued_tokens` 92 | 93 | ## [0.3.1] - 2021-02-06 94 | 95 | ### Fixed 96 | 97 | - Executor can starve if all tasks went pending 98 | 99 | ## [0.3.0] - 2021-02-06 100 | 101 | ### Added 102 | 103 | - `single_threaded::block_on` API that allows to block on non-static-lifetime futures 104 | 105 | ## [0.2.0] - 2021-02-06 106 | 107 | ### Added 108 | 109 | - `single_threaded::tasks` and `single_threaded::queued_tasks` API for executor summary 110 | - `single_threaded::evict_all` API to permanently remove all current tasks 111 | 112 | ### Fixed 113 | 114 | - single-threaded executor's token counter can panic on exhaustion 115 | 116 | ## [0.1.0] - 2021-02-05 117 | 118 | Initial release 119 | 120 | 121 | [Unreleased]: https://github.com/wasm-rs/async-executor/compare/v0.9.0...HEAD 122 | [0.9.0]: https://github.com/wasm-rs/async-executor/compare/v0.8.1...v0.9.0 123 | [0.8.1]: https://github.com/wasm-rs/async-executor/compare/v0.8.0...v0.8.1 124 | [0.8.0]: https://github.com/wasm-rs/async-executor/compare/v0.7.0...v0.8.0 125 | [0.7.0]: https://github.com/wasm-rs/async-executor/compare/v0.6.1...v0.7.0 126 | [0.6.1]: https://github.com/wasm-rs/async-executor/compare/v0.6.0...v0.6.1 127 | [0.6.0]: https://github.com/wasm-rs/async-executor/compare/v0.5.1...v0.6.0 128 | [0.5.1]: https://github.com/wasm-rs/async-executor/compare/v0.5.0...v0.5.1 129 | [0.5.0]: https://github.com/wasm-rs/async-executor/compare/v0.4.1...v0.5.0 130 | [0.4.1]: https://github.com/wasm-rs/async-executor/compare/v0.4.0...v0.4.1 131 | [0.4.0]: https://github.com/wasm-rs/async-executor/compare/v0.3.2...v0.4.0 132 | [0.3.2]: https://github.com/wasm-rs/async-executor/compare/v0.3.1...v0.3.2 133 | [0.3.1]: https://github.com/wasm-rs/async-executor/compare/v0.3.0...v0.3.1 134 | [0.3.0]: https://github.com/wasm-rs/async-executor/compare/v0.2.0...v0.3.0 135 | [0.2.0]: https://github.com/wasm-rs/async-executor/compare/v0.1.0...v0.2.0 136 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasm-rs-async-executor" 3 | version = "0.9.1-dev" 4 | authors = ["Yurii Rashkovskii "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | description = "Async executor for WebAssembly" 8 | repository = "https://github.com/wasm-rs/async-executor" 9 | documentation = "https://docs.rs/wasm-rs-async-executor" 10 | readme = "README.md" 11 | keywords = ["wasm", "async"] 12 | 13 | [lib] 14 | crate-type = ["cdylib","lib"] 15 | 16 | [dependencies] 17 | futures = { version = "0.3.12", features = ["std"] } 18 | pin-project = { version = "1.0.5", optional = true } 19 | 20 | [target.wasm32-unknown-unknown.dependencies] 21 | js-sys = { version = "0.3.47", optional = true } 22 | wasm-bindgen = { version = "0.2.70", optional = true } 23 | web-sys = { version = "0.3.47", optional = true } 24 | 25 | [target.wasm32-unknown-unknown.dev-dependencies] 26 | wasm-bindgen-test = "0.3" 27 | 28 | [dev-dependencies] 29 | tokio = { version = "1.1.1", features = ["sync", "rt"] } 30 | 31 | [features] 32 | default = [] 33 | debug = [] 34 | cooperative = ["js-sys", "wasm-bindgen", "pin-project"] 35 | cooperative-browser = ["cooperative"] 36 | # Experimental: 37 | # https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback 38 | requestIdleCallback = ["cooperative-browser", "web-sys/IdleDeadline"] 39 | 40 | [package.metadata.docs.rs] 41 | all-features = true 42 | 43 | [package.metadata.wasm.rs] 44 | targets = ["wasm32-unknown-unknown", "wasm32-wasi"] 45 | wasm-readme = "README.md" 46 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Async Executor for WebAssembly 2 | [![Crate](https://img.shields.io/crates/v/wasm-rs-async-executor.svg)](https://crates.io/crates/wasm-rs-async-executor) 3 | [![API](https://docs.rs/wasm-rs-async-executor/badge.svg)](https://docs.rs/wasm-rs-async-executor) 4 | [![Chat](https://img.shields.io/discord/807386653852565545.svg?logo=discord)](https://discord.gg/qbcbjHWjaD) 5 | 6 | There are a number of async task executors available in Rust's ecosystem. 7 | However, most (if not all?) of them rely on primitives that might not be 8 | available or optimal for WebAssembly deployment at the time. 9 | 10 | ## Usage 11 | 12 | Include this dependency in your `Cargo.toml`: 13 | 14 | ```toml 15 | [dependencies] 16 | wasm-rs-async-executor = "0.9.0" 17 | ``` 18 | 19 | `wasm-rs-async-executor` is expected to work on stable Rust, 1.49.0 and higher up. It *may* also 20 | work on earlier versions. This hasn't been tested yet. 21 | 22 | ## Supported targets 23 | 24 | Currently, it's been only tested on `wasm32-unknown-unknown` and, excluding `cooperative` functionality, 25 | it passes tests under [wasmtime](https://wasmtime.dev/) and [wasmer](https://wasmer.io/) with `wasm32-wasi` target. 26 | Further testing is to be completed. 27 | 28 | ## Notes 29 | 30 | Please note that this library hasn't received much analysis in terms of safety 31 | and soundness. Some of the caveats related to that might never be resolved 32 | completely. This is an ongoing development and the maintainer is aware of 33 | potential pitfalls. Any productive reports of unsafeties or unsoundness are 34 | welcomed (whether they can be resolved or simply walled with `unsafe` for end-user 35 | to note). 36 | 37 | ## FAQ 38 | 39 | **Q:** Why not just use [wasm-bindgen-futures](https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/)? 40 | 41 | **A:** *(short)* In many cases, `wasm-bindgen-futures` is just fine 42 | 43 | **A:** *(longer)* There are some subtle differences in the way `wasm-rs-async-executor` exposes its functionality. The 44 | core idea behind it is to expose a reasonable amount of **explicit** controls over the its operations. You need 45 | to run the executor explicitly, you can block on futures (again, explicitly -- which gives you a limited 46 | ability to do scoped futures). It does come with minor trade-offs. For example, if you want to use async APIs from 47 | your host environment, you can't simply `await` on then, as the executor won't yield to the browser until told to do 48 | so. However, this is typically solved by simply running a permanent task that loops yielding to the browser. 49 | 50 | Ultimately, if this amount of control is beneficial for your case, then perhaps 51 | this executor is waranted. It is also important to note that **currently** 52 | `wasm-rs-async-executor` **does not** support WebAssembly multi-threading in 53 | any way. `wasm-bindgen-futures` does, if the standard library is built with 54 | support for it. It is planned to support this, but hasn't been high priority 55 | so far due to [current state of 56 | things](https://github.com/rust-lang/rust/issues/77839) in Rust. 57 | 58 | 59 | ## License 60 | 61 | Licensed under either of 62 | 63 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 64 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. 65 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | pkg 3 | package-lock.json 4 | target 5 | -------------------------------------------------------------------------------- /example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async-executor-demo" 3 | version = "0.1.0" 4 | authors = ["Yurii Rashkovskii "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [dependencies] 11 | wasm-bindgen = "0.2.70" 12 | wasm-rs-async-executor = { path = "..", features = ["cooperative-browser", "debug", "requestIdleCallback"] } 13 | wasm-rs-dbg = "0.1" 14 | tokio = { version = "1.1", features = ["macros", "time", "sync"] } 15 | wasm-bindgen-futures = "0.4.20" 16 | web-sys = { version = "0.3.47", features = ["Window", "Response", "Document", "Element"] } 17 | js-sys = "0.3.47" 18 | futures = "0.3.12" 19 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Example 2 | 3 | In order to run a demo app, run: 4 | 5 | ``` 6 | wasm-pack build --release 7 | npm install 8 | npm start 9 | ``` 10 | 11 | After that, go to [https://localhost:8080](https://localhost:8080) and open Console, you will see log messages. You can 12 | try changing code in [src/lib.rs](https://github.com/wasm-rs/async-executor/blob/master/example/src/lib.rs) to see what it can do. 13 | -------------------------------------------------------------------------------- /example/bootstrap.js: -------------------------------------------------------------------------------- 1 | // A dependency graph that contains any wasm must all be imported 2 | // asynchronously. This `bootstrap.js` file does the single async import, so 3 | // that no one else needs to worry about it again. 4 | import("./index.js") 5 | .catch(e => console.error("Error importing `index.js`:", e)); 6 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | wasm-rs-async-executor 6 | 7 | 8 | 9 | 10 | Open console to see the log 11 |

task1

12 |
13 |
14 |

task1x (should stop when task1 is done)

15 |
16 |
17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import * as _ from "pkg"; 2 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wasm_rs_async_executor_demo", 3 | "version": "0.1.0", 4 | "main": "index.js", 5 | "scripts": { 6 | "build": "webpack --config webpack.config.js", 7 | "start": "webpack-dashboard -- webpack-dev-server" 8 | }, 9 | "dependencies": { 10 | "pkg": "file:pkg" 11 | }, 12 | "devDependencies": { 13 | "copy-webpack-plugin": "^5.0.0", 14 | "webpack": "^4.29.3", 15 | "webpack-cli": "^3.1.0", 16 | "webpack-dashboard": "^3.3.1", 17 | "webpack-dev-server": "^3.1.5" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /example/src/lib.rs: -------------------------------------------------------------------------------- 1 | use tokio::sync::oneshot; 2 | use wasm_bindgen::prelude::*; 3 | use wasm_bindgen_futures::JsFuture; 4 | use wasm_rs_async_executor::single_threaded as executor; 5 | use wasm_rs_dbg::dbg; 6 | 7 | #[wasm_bindgen(start)] 8 | #[allow(unused_variables)] 9 | pub fn start() { 10 | let (sender1, receiver1) = oneshot::channel(); 11 | let (sender2, receiver2) = oneshot::channel(); 12 | let task1 = executor::spawn(async move { 13 | dbg!("task 1 awaiting"); 14 | let _ = receiver1.await; 15 | dbg!("task 1 -> task 2"); 16 | let _ = sender2.send(()); 17 | let element = web_sys::window() 18 | .unwrap() 19 | .document() 20 | .unwrap() 21 | .get_element_by_id("display") 22 | .unwrap(); 23 | 24 | let mut ctr = 0u8; 25 | while ctr < 255 { 26 | element.set_inner_html(&format!("{}", ctr)); 27 | ctr = ctr.wrapping_add(1); 28 | executor::yield_animation_frame().await; 29 | } 30 | }); 31 | let task1x = executor::spawn(async move { 32 | let element = web_sys::window() 33 | .unwrap() 34 | .document() 35 | .unwrap() 36 | .get_element_by_id("display1") 37 | .unwrap(); 38 | 39 | loop { 40 | let ts = executor::yield_animation_frame().await; 41 | element.set_inner_html(&format!("{}", ts)); 42 | } 43 | }); 44 | 45 | let task2 = executor::spawn(async move { 46 | dbg!("task 2 awaiting"); 47 | let _ = receiver2.await; 48 | dbg!("task 2 fetching /"); 49 | let fut: JsFuture = web_sys::window().unwrap().fetch_with_str("/").into(); 50 | let response: web_sys::Response = executor::yield_async(fut).await.unwrap().into(); 51 | let text_fut: JsFuture = response.text().unwrap().into(); 52 | dbg!("task 2 will intentionally delay itself by 1 second"); 53 | executor::yield_timeout(std::time::Duration::from_secs(1)).await; 54 | dbg!("task 2 wait is over"); 55 | let text: String = executor::yield_async(text_fut) 56 | .await 57 | .unwrap() 58 | .as_string() 59 | .unwrap(); 60 | dbg!(text); 61 | dbg!("task 2 done"); 62 | }); 63 | 64 | let task3 = executor::spawn(async move { 65 | dbg!("task 3 awaiting idle browser"); 66 | executor::yield_until_idle(None).await; 67 | dbg!("task 3 is done"); 68 | }); 69 | dbg!("starting executor, sending to task1"); 70 | let _ = sender1.send(()); 71 | executor::run(Some(task1)); 72 | } 73 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 2 | const path = require('path'); 3 | 4 | module.exports = { 5 | entry: "./bootstrap.js", 6 | output: { 7 | path: path.resolve(__dirname, "dist"), 8 | filename: "bootstrap.js", 9 | }, 10 | mode: "development", 11 | plugins: [ 12 | new CopyWebpackPlugin(['index.html']) 13 | ], 14 | }; 15 | -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | pre-release-replacements = [ 2 | {file="README.md", search="wasm-rs-async-executor = .*", replace="{{crate_name}} = \"{{version}}\""}, 3 | {file="CHANGELOG.md", search="Unreleased", replace="{{version}}"}, 4 | {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", min=0, max=1}, 5 | {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}"}, 6 | {file="CHANGELOG.md", search="", replace="\n\n## [Unreleased] - ReleaseDate", exactly=1}, 7 | {file="CHANGELOG.md", search="", replace="\n[Unreleased]: https://github.com/wasm-rs/async-executor/compare/{{tag_name}}...HEAD", exactly=1}, 8 | ] 9 | dev-version-ext = "dev" 10 | pre-release-commit-message = "release {{crate_name}} {{version}}" 11 | post-release-commit-message="Released {{crate_name}} {{version}}, starting {{next_version}}" 12 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | targets = ["wasm32-unknown-unknown", "wasm32-wasi"] 3 | components = ["rustfmt", "clippy"] 4 | channel = "stable" 5 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | let 2 | moz_overlay = import (builtins.fetchTarball https://github.com/mozilla/nixpkgs-mozilla/archive/master.tar.gz); 3 | pkgs = import { overlays = [ moz_overlay ]; }; 4 | rustChannel = (pkgs.rustChannelOf { channel = "stable"; }); 5 | rust = (rustChannel.rust.override { 6 | targets = ["wasm32-unknown-unknown" "wasm32-wasi"]; 7 | }); 8 | in 9 | pkgs.stdenv.mkDerivation rec { 10 | name = "wasm-rs-async-channel-shell"; 11 | 12 | buildInputs = with pkgs; [ rust nodejs 13 | openssl.dev pkgconfig # for cargo-release 14 | ]; 15 | 16 | shellHook = '' 17 | # Useful for ensuring cargo tools are available (like cargo-do, for example) 18 | export PATH=$PATH:$HOME/.cargo/bin 19 | ''; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Async Executor for WebAssembly 2 | //! 3 | //! There are a number of async task executors available, however, most of them rely on primitives 4 | //! that might not be available or optimal for WebAssembly deployment at the time. 5 | //! 6 | //! This crate currently provides one [**single-threaded** async executor](`single_threaded`) 7 | pub mod single_threaded; 8 | -------------------------------------------------------------------------------- /src/single_threaded.rs: -------------------------------------------------------------------------------- 1 | //! # Single-threaded executor 2 | //! 3 | //! This executor works *strictly* in a single-threaded environment. In order to spawn a task, use 4 | //! [`spawn`]. To run the executor, use [`run`]. 5 | //! 6 | //! There is no need to create an instance of the executor, it's automatically provisioned as a 7 | //! thread-local instance. 8 | //! 9 | //! ## Example 10 | //! 11 | //! ``` 12 | //! use tokio::sync::*; 13 | //! use wasm_rs_async_executor::single_threaded::{spawn, run}; 14 | //! let (sender, receiver) = oneshot::channel::<()>(); 15 | //! let _task = spawn(async move { 16 | //! // Complete when something is received 17 | //! let _ = receiver.await; 18 | //! }); 19 | //! // Send data to be received 20 | //! let _ = sender.send(()); 21 | //! run(None); 22 | //! ``` 23 | use futures::channel::oneshot; 24 | use futures::task::{waker_ref, ArcWake}; 25 | #[cfg(feature = "debug")] 26 | use std::any::{type_name, TypeId}; 27 | use std::cell::UnsafeCell; 28 | use std::collections::BTreeMap; 29 | use std::future::Future; 30 | use std::pin::Pin; 31 | use std::sync::Arc; 32 | use std::task::{Context, Poll}; 33 | 34 | /// Task token 35 | type Token = usize; 36 | 37 | #[cfg(feature = "debug")] 38 | #[derive(Clone, Debug)] 39 | pub struct TypeInfo { 40 | type_id: Option, 41 | type_name: &'static str, 42 | } 43 | 44 | #[cfg(feature = "debug")] 45 | impl TypeInfo { 46 | fn new() -> Self 47 | where 48 | T: 'static, 49 | { 50 | Self { 51 | type_name: type_name::(), 52 | type_id: Some(TypeId::of::()), 53 | } 54 | } 55 | 56 | fn new_non_static() -> Self { 57 | Self { 58 | type_name: type_name::(), 59 | type_id: None, 60 | } 61 | } 62 | 63 | /// Returns tasks's type name 64 | pub fn type_name(&self) -> &'static str { 65 | self.type_name 66 | } 67 | 68 | /// Returns tasks's [`std::any::TypeId`] 69 | /// 70 | /// If it's `None` then the type does not have a `'static` lifetime 71 | pub fn type_id(&self) -> Option { 72 | self.type_id 73 | } 74 | } 75 | 76 | /// Task information 77 | #[derive(Clone)] 78 | pub struct Task { 79 | token: Token, 80 | #[cfg(feature = "debug")] 81 | type_info: Arc, 82 | } 83 | 84 | impl PartialEq for Task { 85 | fn eq(&self, other: &Self) -> bool { 86 | self.token == other.token 87 | } 88 | } 89 | 90 | impl Eq for Task {} 91 | 92 | impl PartialOrd for Task { 93 | fn partial_cmp(&self, other: &Self) -> Option { 94 | self.token.partial_cmp(&other.token) 95 | } 96 | } 97 | 98 | impl Ord for Task { 99 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 100 | self.token.cmp(&other.token) 101 | } 102 | } 103 | 104 | impl Task { 105 | #[cfg(feature = "debug")] 106 | pub fn type_info(&self) -> &TypeInfo { 107 | self.type_info.as_ref() 108 | } 109 | } 110 | 111 | /// Task handle 112 | /// 113 | /// Implements [`std::future::Future`] to allow for waiting for task completion 114 | pub struct TaskHandle { 115 | receiver: oneshot::Receiver, 116 | task: Task, 117 | } 118 | 119 | impl TaskHandle { 120 | /// Returns a copy of task information record 121 | pub fn task(&self) -> Task { 122 | self.task.clone() 123 | } 124 | } 125 | 126 | /// Task joining error 127 | #[derive(Debug, Clone)] 128 | pub enum JoinError { 129 | /// Task was canceled 130 | Canceled, 131 | } 132 | 133 | impl Future for TaskHandle { 134 | type Output = Result; 135 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 136 | match self.receiver.try_recv() { 137 | Err(oneshot::Canceled) => Poll::Ready(Err(JoinError::Canceled)), 138 | Ok(Some(result)) => Poll::Ready(Ok(result)), 139 | Ok(None) => { 140 | cx.waker().wake_by_ref(); 141 | Poll::Pending 142 | } 143 | } 144 | } 145 | } 146 | 147 | impl ArcWake for Task { 148 | fn wake_by_ref(arc_self: &Arc) { 149 | EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).enqueue(arc_self.clone())) 150 | } 151 | } 152 | 153 | /// Single-threaded executor 154 | struct Executor { 155 | counter: Token, 156 | futures: BTreeMap>>>, 157 | queue: Vec>, 158 | } 159 | 160 | impl Executor { 161 | fn new() -> Self { 162 | Self { 163 | counter: 0, 164 | futures: BTreeMap::new(), 165 | queue: vec![], 166 | } 167 | } 168 | 169 | fn enqueue(&mut self, task: Arc) { 170 | if self.futures.contains_key(&task) { 171 | self.queue.insert(0, task); 172 | } 173 | } 174 | 175 | fn spawn(&mut self, fut: F) -> TaskHandle 176 | where 177 | F: Future + 'static, 178 | T: 'static, 179 | { 180 | let token = self.counter; 181 | self.counter = self.counter.wrapping_add(1); 182 | let task = Task { 183 | token, 184 | #[cfg(feature = "debug")] 185 | type_info: Arc::new(TypeInfo::new::()), 186 | }; 187 | 188 | let (sender, receiver) = oneshot::channel(); 189 | 190 | self.futures.insert(task.clone(), unsafe { 191 | Pin::new_unchecked(Box::new(async move { 192 | let _ = sender.send(fut.await); 193 | }) as Box>) 194 | }); 195 | self.queue.push(Arc::new(task.clone())); 196 | TaskHandle { receiver, task } 197 | } 198 | 199 | fn spawn_non_static(&mut self, fut: F) -> TaskHandle 200 | where 201 | F: Future, 202 | { 203 | let token = self.counter; 204 | self.counter = self.counter.wrapping_add(1); 205 | let task = Task { 206 | token, 207 | #[cfg(feature = "debug")] 208 | type_info: Arc::new(TypeInfo::new_non_static::()), 209 | }; 210 | 211 | let (sender, receiver) = oneshot::channel(); 212 | 213 | self.futures.insert(task.clone(), unsafe { 214 | Pin::new_unchecked(std::mem::transmute::<_, Box>>( 215 | Box::new(async move { 216 | let _ = sender.send(fut.await); 217 | }) as Box>, 218 | )) 219 | }); 220 | self.queue.push(Arc::new(task.clone())); 221 | TaskHandle { receiver, task } 222 | } 223 | } 224 | 225 | thread_local! { 226 | static EXECUTOR: UnsafeCell = UnsafeCell::new(Executor::new()) ; 227 | } 228 | 229 | thread_local! { 230 | static UNTIL: UnsafeCell> = UnsafeCell::new(None) ; 231 | } 232 | 233 | thread_local! { 234 | static UNTIL_SATISFIED: UnsafeCell = UnsafeCell::new(false) ; 235 | } 236 | 237 | thread_local! { 238 | static YIELD: UnsafeCell = UnsafeCell::new(true) ; 239 | } 240 | 241 | thread_local! { 242 | static EXIT_LOOP: UnsafeCell = UnsafeCell::new(false) ; 243 | } 244 | 245 | /// Spawn a task 246 | pub fn spawn(fut: F) -> TaskHandle 247 | where 248 | F: Future + 'static, 249 | T: 'static, 250 | { 251 | EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).spawn(fut)) 252 | } 253 | 254 | /// Run tasks until completion of a future 255 | /// 256 | /// If `cooperative` feature is enabled, given future should have `'static` lifetime. 257 | #[cfg(not(feature = "cooperative"))] 258 | pub fn block_on(fut: F) -> R 259 | where 260 | F: Future, 261 | { 262 | // We know that this task is to complete by the end of this function, 263 | // so let's pretend it is static 264 | let mut handle = EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).spawn_non_static(fut)); 265 | run(Some(handle.task())); 266 | loop { 267 | match handle.receiver.try_recv() { 268 | Ok(None) => {} 269 | Ok(Some(v)) => return v, 270 | Err(_) => unreachable!(), // the data was sent at this point 271 | } 272 | } 273 | } 274 | 275 | /// Run tasks until completion of a future 276 | /// 277 | /// ## Important 278 | /// 279 | /// This function WILL NOT allow yielding to the environment that `cooperative` feature allows, 280 | /// and it will run the executor until the given future is ready. If yielding is expected, 281 | /// this will block forever. 282 | /// 283 | #[cfg(feature = "cooperative")] 284 | pub fn block_on(fut: F) -> R 285 | where 286 | F: Future, 287 | { 288 | let mut handle = EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).spawn_non_static(fut)); 289 | YIELD.with(|cell| unsafe { 290 | *cell.get() = false; 291 | }); 292 | run(Some(handle.task())); 293 | YIELD.with(|cell| unsafe { 294 | *cell.get() = true; 295 | }); 296 | loop { 297 | match handle.receiver.try_recv() { 298 | Ok(None) => {} 299 | Ok(Some(v)) => return v, 300 | Err(_) => unreachable!(), // the data was sent at this point 301 | } 302 | } 303 | } 304 | 305 | /// Run the executor 306 | /// 307 | /// If `until` is `None`, it will run until all tasks have been completed. Otherwise, it'll wait 308 | /// until passed task is complete, or unless a `cooperative` feature has been enabled and control 309 | /// has been yielded to the environment. In this case the function will return but the environment 310 | /// might schedule further execution of this executor in the background after termination of the 311 | /// function enclosing invocation of this [`run`] 312 | pub fn run(until: Option) { 313 | UNTIL.with(|cell| unsafe { *cell.get() = until }); 314 | UNTIL_SATISFIED.with(|cell| unsafe { *cell.get() = false }); 315 | run_internal(); 316 | } 317 | 318 | // Returns `true` if `until` task completed, or there was no `until` task and every task was 319 | // completed. 320 | // 321 | // Returns `false` if loop exit was requested 322 | fn run_internal() -> bool { 323 | let until = UNTIL.with(|cell| unsafe { &*cell.get() }); 324 | let exit_condition_met = UNTIL_SATISFIED.with(|cell| unsafe { *cell.get() }); 325 | if exit_condition_met { 326 | return true; 327 | } 328 | EXECUTOR.with(|cell| loop { 329 | let task = (unsafe { &mut *cell.get() }).queue.pop(); 330 | 331 | if let Some(task) = task { 332 | let future = (unsafe { &mut *cell.get() }).futures.get_mut(&task); 333 | let ready = if let Some(future) = future { 334 | let waker = waker_ref(&task); 335 | let context = &mut Context::from_waker(&*waker); 336 | let ready = matches!(future.as_mut().poll(context), Poll::Ready(_)); 337 | ready 338 | } else { 339 | false 340 | }; 341 | if ready { 342 | (unsafe { &mut *cell.get() }).futures.remove(&task); 343 | 344 | if let Some(Task { ref token, .. }) = until { 345 | if *token == task.token { 346 | UNTIL_SATISFIED.with(|cell| unsafe { *cell.get() = true }); 347 | return true; 348 | } 349 | } 350 | } 351 | } 352 | if until.is_none() && (unsafe { &mut *cell.get() }).futures.is_empty() { 353 | UNTIL_SATISFIED.with(|cell| unsafe { *cell.get() = true }); 354 | return true; 355 | } 356 | 357 | let exit_requested = EXIT_LOOP.with(|cell| { 358 | let v = cell.get(); 359 | let result = unsafe { *v }; 360 | // Clear the flag 361 | unsafe { 362 | *v = false; 363 | } 364 | result 365 | }) && YIELD.with(|cell| unsafe { *cell.get() }); 366 | 367 | if exit_requested { 368 | return false; 369 | } 370 | 371 | if (unsafe { &mut *cell.get() }).queue.is_empty() 372 | && !(unsafe { &mut *cell.get() }).futures.is_empty() 373 | { 374 | // the executor is starving 375 | for task in (unsafe { &mut *cell.get() }).futures.keys() { 376 | (unsafe { &mut *cell.get() }).enqueue(Arc::new(task.clone())); 377 | } 378 | } 379 | }) 380 | } 381 | 382 | #[cfg(all( 383 | feature = "cooperative", 384 | target_arch = "wasm32", 385 | not(target_os = "wasi") 386 | ))] 387 | mod cooperative { 388 | use super::{run_internal, EXIT_LOOP}; 389 | use pin_project::pin_project; 390 | use std::cell::UnsafeCell; 391 | use std::future::Future; 392 | use std::pin::Pin; 393 | use std::sync::Arc; 394 | use std::task::{Context, Poll}; 395 | use std::time::Duration; 396 | use wasm_bindgen::prelude::*; 397 | 398 | #[wasm_bindgen] 399 | extern "C" { 400 | #[wasm_bindgen(js_name = "setTimeout")] 401 | fn set_timeout(_: JsValue, delay: u32); 402 | 403 | #[cfg(feature = "requestIdleCallback")] 404 | #[wasm_bindgen(js_name = "requestIdleCallback")] 405 | fn request_idle_callback(_: JsValue, options: &JsValue); 406 | 407 | #[cfg(feature = "cooperative-browser")] 408 | #[wasm_bindgen(js_name = "requestAnimationFrame")] 409 | fn request_animation_frame(_: JsValue); 410 | 411 | } 412 | 413 | #[pin_project] 414 | struct TimeoutYield 415 | where 416 | F: Future + 'static, 417 | { 418 | yielded: bool, 419 | duration: Option, 420 | done: bool, 421 | output: Option, 422 | #[pin] 423 | future: F, 424 | ready: Arc>, 425 | } 426 | 427 | impl Future for TimeoutYield 428 | where 429 | F: Future + 'static, 430 | { 431 | type Output = O; 432 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 433 | if self.done { 434 | return Poll::Pending; 435 | } 436 | if self.yielded && !unsafe { *self.ready.get() } { 437 | cx.waker().wake_by_ref(); 438 | return Poll::Pending; 439 | } 440 | let should_yield = !self.yielded; 441 | let this = self.project(); 442 | if *this.yielded && unsafe { *this.ready.get() } && this.output.is_some() { 443 | // it's ok to unwrap here because we check `is_some` above 444 | let output = this.output.take().unwrap(); 445 | *this.done = true; 446 | return Poll::Ready(output); 447 | } 448 | match (should_yield, this.future.poll(cx)) { 449 | (_, result @ Poll::Pending) | (true, result) => { 450 | *this.yielded = true; 451 | if cfg!(target_arch = "wasm32") { 452 | // If this timeout is not immediate, 453 | // return control to the executor at the earliest opportunity 454 | if let Some(duration) = this.duration { 455 | if duration.as_millis() > 0 { 456 | set_timeout( 457 | Closure::once_into_js(move || { 458 | run_internal(); 459 | }), 460 | 0, 461 | ); 462 | } 463 | } 464 | 465 | if should_yield { 466 | let ready = this.ready.clone(); 467 | 468 | set_timeout( 469 | Closure::once_into_js(move || { 470 | unsafe { *ready.get() = true }; 471 | run_internal(); 472 | }), 473 | this.duration 474 | .unwrap_or(Duration::from_millis(0)) 475 | .as_millis() as u32, 476 | ); 477 | } 478 | EXIT_LOOP.with(|cell| unsafe { *cell.get() = true }); 479 | } 480 | if let Poll::Ready(output) = result { 481 | this.output.replace(output); 482 | } 483 | cx.waker().wake_by_ref(); 484 | Poll::Pending 485 | } 486 | (false, Poll::Ready(output)) => { 487 | *this.done = true; 488 | Poll::Ready(output) 489 | } 490 | } 491 | } 492 | } 493 | 494 | /// Yields the JavaScript environment using `setTimeout` function 495 | /// 496 | /// This future will be complete after `duration` has passed 497 | /// 498 | /// Only available under `cooperative` feature gate 499 | /// 500 | /// ## Caution 501 | /// 502 | /// Specifying a non-zero timeout duration will result in the executor not 503 | /// being called for that duration or longer. 504 | pub fn yield_timeout(duration: Duration) -> impl Future { 505 | TimeoutYield { 506 | future: futures::future::ready(()), 507 | duration: Some(duration), 508 | output: None, 509 | yielded: false, 510 | done: false, 511 | ready: Arc::new(UnsafeCell::new(false)), 512 | } 513 | } 514 | 515 | /// Yields a future to the JavaScript environment using `setTimeout` function 516 | /// 517 | /// This future will be ready after yielding and when the enclosed future is ready. 518 | /// 519 | /// Only available under `cooperative` feature gate 520 | pub fn yield_async(future: F) -> impl Future 521 | where 522 | F: Future + 'static, 523 | { 524 | TimeoutYield { 525 | future, 526 | duration: None, 527 | output: None, 528 | yielded: false, 529 | done: false, 530 | ready: Arc::new(UnsafeCell::new(false)), 531 | } 532 | } 533 | 534 | #[cfg(feature = "cooperative-browser")] 535 | #[pin_project] 536 | struct AnimationFrameYield { 537 | yielded: bool, 538 | done: bool, 539 | output: Arc>>, 540 | } 541 | 542 | #[cfg(feature = "cooperative-browser")] 543 | impl Future for AnimationFrameYield { 544 | type Output = f64; 545 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 546 | if self.done { 547 | return Poll::Pending; 548 | } 549 | let should_yield = !self.yielded; 550 | let this = self.project(); 551 | if *this.yielded && unsafe { &*this.output.get() }.is_some() { 552 | // it's ok to unwrap here because we check `is_some` above 553 | let output = unsafe { &mut *this.output.get() }.take().unwrap(); 554 | *this.done = true; 555 | return Poll::Ready(output); 556 | } 557 | 558 | if should_yield { 559 | *this.yielded = true; 560 | if cfg!(target_arch = "wasm32") { 561 | let output = this.output.clone(); 562 | request_animation_frame(Closure::once_into_js(move |timestamp| { 563 | unsafe { &mut *output.get() }.replace(timestamp); 564 | run_internal(); 565 | })); 566 | EXIT_LOOP.with(|cell| unsafe { *cell.get() = true }); 567 | } 568 | } 569 | 570 | cx.waker().wake_by_ref(); 571 | 572 | Poll::Pending 573 | } 574 | } 575 | 576 | /// Yields to the browser using `requestAnimationFrame` 577 | /// 578 | /// This allows to yield to the browser until the next animation frame is requested to be 579 | /// rendered. 580 | /// 581 | /// It will output high resolution timer as 582 | /// [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) 583 | /// 584 | /// Only available under `cooperative-browser` feature gate 585 | /// 586 | #[cfg(feature = "cooperative-browser")] 587 | pub fn yield_animation_frame() -> impl Future { 588 | AnimationFrameYield { 589 | output: Arc::new(UnsafeCell::new(None)), 590 | yielded: false, 591 | done: false, 592 | } 593 | } 594 | 595 | #[cfg(feature = "requestIdleCallback")] 596 | #[pin_project] 597 | struct UntilIdleYield { 598 | timeout: Option, 599 | yielded: bool, 600 | done: bool, 601 | output: Arc>>, 602 | } 603 | 604 | #[cfg(feature = "requestIdleCallback")] 605 | impl Future for UntilIdleYield { 606 | type Output = web_sys::IdleDeadline; 607 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 608 | if self.done { 609 | return Poll::Pending; 610 | } 611 | let should_yield = !self.yielded; 612 | let this = self.project(); 613 | if *this.yielded && unsafe { &*this.output.get() }.is_some() { 614 | // it's ok to unwrap here because we check `is_some` above 615 | let output = unsafe { &mut *this.output.get() }.take().unwrap(); 616 | *this.done = true; 617 | return Poll::Ready(output); 618 | } 619 | 620 | if should_yield { 621 | *this.yielded = true; 622 | if cfg!(target_arch = "wasm32") { 623 | let map = js_sys::Map::new(); 624 | if let Some(timeout) = this.timeout { 625 | map.set(&"timeout".into(), &(timeout.as_millis() as u32).into()); 626 | } 627 | let options = 628 | js_sys::Object::from_entries(&map).unwrap_or(js_sys::Object::new()); 629 | let output = this.output.clone(); 630 | request_idle_callback( 631 | Closure::once_into_js(move |timestamp| { 632 | unsafe { &mut *output.get() }.replace(timestamp); 633 | run_internal(); 634 | }), 635 | &options.into(), 636 | ); 637 | EXIT_LOOP.with(|cell| unsafe { *cell.get() = true }); 638 | } 639 | } 640 | 641 | cx.waker().wake_by_ref(); 642 | 643 | Poll::Pending 644 | } 645 | } 646 | 647 | /// Yields to the browser using `requestIdleCallback` 648 | /// 649 | /// This allows to yield to the browser until browser is delayed. 650 | /// 651 | /// It will output [`web_sys::IdleDeadline`] as per 652 | /// [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) 653 | /// 654 | /// Only available under `requestIdleCallback` feature gate 655 | /// 656 | #[cfg(feature = "requestIdleCallback")] 657 | pub fn yield_until_idle( 658 | timeout: Option, 659 | ) -> impl Future { 660 | UntilIdleYield { 661 | timeout, 662 | output: Arc::new(UnsafeCell::new(None)), 663 | yielded: false, 664 | done: false, 665 | } 666 | } 667 | } 668 | 669 | #[cfg(all( 670 | feature = "cooperative", 671 | target_arch = "wasm32", 672 | not(target_os = "wasi") 673 | ))] 674 | pub use cooperative::*; 675 | 676 | /// Returns the number of tasks currently registered with the executor 677 | pub fn tasks_count() -> usize { 678 | EXECUTOR.with(|cell| { 679 | let executor = unsafe { &mut *cell.get() }; 680 | executor.futures.len() 681 | }) 682 | } 683 | 684 | /// Returns the number of tasks currently in the queue to execute 685 | pub fn queued_tasks_count() -> usize { 686 | EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).queue.len()) 687 | } 688 | 689 | /// Returns all tasks that haven't completed yet 690 | pub fn tasks() -> Vec { 691 | EXECUTOR.with(|cell| { 692 | (unsafe { &*cell.get() }) 693 | .futures 694 | .keys() 695 | .map(|t| Task::clone(&t)) 696 | .collect() 697 | }) 698 | } 699 | 700 | /// Returns tokens for queued tasks 701 | pub fn queued_tasks() -> Vec { 702 | EXECUTOR.with(|cell| { 703 | (unsafe { &*cell.get() }) 704 | .queue 705 | .iter() 706 | .map(|t| Task::clone(&t)) 707 | .collect() 708 | }) 709 | } 710 | 711 | /// Removes all tasks from the executor 712 | /// 713 | /// ## Caution 714 | /// 715 | /// Evicted tasks won't be able to get re-scheduled when they will be woken up. 716 | pub fn evict_all() { 717 | EXECUTOR.with(|cell| unsafe { *cell.get() = Executor::new() }); 718 | } 719 | 720 | #[cfg(test)] 721 | fn set_counter(counter: usize) { 722 | EXECUTOR.with(|cell| (unsafe { &mut *cell.get() }).counter = counter); 723 | } 724 | 725 | #[cfg(test)] 726 | mod tests { 727 | use super::*; 728 | #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] 729 | use wasm_bindgen_test::*; 730 | 731 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 732 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 733 | fn test() { 734 | use tokio::sync::*; 735 | let (sender, receiver) = oneshot::channel::<()>(); 736 | let _handle = spawn(async move { 737 | let _ = receiver.await; 738 | }); 739 | let _ = sender.send(()); 740 | run(None); 741 | evict_all(); 742 | } 743 | 744 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 745 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 746 | fn test_until() { 747 | use tokio::sync::*; 748 | let (_sender1, receiver1) = oneshot::channel::<()>(); 749 | let _handle1 = spawn(async move { 750 | let _ = receiver1.await; 751 | }); 752 | let (sender2, receiver2) = oneshot::channel::<()>(); 753 | let handle2 = spawn(async move { 754 | let _ = receiver2.await; 755 | }); 756 | let _ = sender2.send(()); 757 | run(Some(handle2.task())); 758 | evict_all(); 759 | } 760 | 761 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 762 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 763 | fn test_counts() { 764 | use tokio::sync::*; 765 | let (sender, mut receiver) = oneshot::channel(); 766 | let (sender2, receiver2) = oneshot::channel::<()>(); 767 | let handle1 = spawn(async move { 768 | let _ = receiver2.await; 769 | let _ = sender.send((tasks_count(), queued_tasks_count())); 770 | }); 771 | let _handle2 = spawn(async move { 772 | let _ = sender2.send(()); 773 | futures::future::pending::<()>().await // this will never end 774 | }); 775 | run(Some(handle1.task())); 776 | let (tasks_, queued_tasks_) = receiver.try_recv().unwrap(); 777 | // handle1 + handle2 778 | assert_eq!(tasks_, 2); 779 | // handle1 is being executed, handle2 has nothing new 780 | assert_eq!(queued_tasks_, 0); 781 | // handle1 is gone 782 | assert_eq!(tasks_count(), 1); 783 | // handle2 still has nothing new 784 | assert_eq!(queued_tasks_count(), 0); 785 | evict_all(); 786 | } 787 | 788 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 789 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 790 | fn evicted_tasks_dont_requeue() { 791 | use tokio::sync::*; 792 | let (_sender, receiver) = oneshot::channel::<()>(); 793 | let handle = spawn(async move { 794 | let _ = receiver.await; 795 | }); 796 | assert_eq!(tasks_count(), 1); 797 | evict_all(); 798 | assert_eq!(tasks_count(), 0); 799 | ArcWake::wake_by_ref(&Arc::new(handle.task())); 800 | assert_eq!(tasks_count(), 0); 801 | assert_eq!(queued_tasks_count(), 0); 802 | evict_all(); 803 | } 804 | 805 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 806 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 807 | fn token_exhaustion() { 808 | set_counter(usize::MAX); 809 | // this should be fine anyway 810 | let handle0 = spawn(async move {}); 811 | // this should NOT crash 812 | let handle = spawn(async move {}); 813 | // new token should be different and wrap back to the beginning 814 | assert!(handle.task().token != handle0.task().token); 815 | assert_eq!(handle.task().token, 0); 816 | evict_all(); 817 | } 818 | 819 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 820 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 821 | fn blocking_on() { 822 | use tokio::sync::*; 823 | let (sender, receiver) = oneshot::channel::(); 824 | let _handle = spawn(async move { 825 | let _ = sender.send(1); 826 | }); 827 | let result = block_on(async move { receiver.await.unwrap() }); 828 | assert_eq!(result, 1); 829 | evict_all(); 830 | } 831 | 832 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 833 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 834 | fn starvation() { 835 | use tokio::sync::*; 836 | let (sender, receiver) = oneshot::channel(); 837 | let _handle = spawn(async move { 838 | tokio::task::yield_now().await; 839 | tokio::task::yield_now().await; 840 | let _ = sender.send(()); 841 | }); 842 | let result = block_on(async move { receiver.await.unwrap() }); 843 | assert_eq!(result, ()); 844 | evict_all(); 845 | } 846 | 847 | #[cfg(feature = "debug")] 848 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 849 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 850 | fn task_type_info() { 851 | spawn(futures::future::pending::<()>()); 852 | assert!(tasks()[0] 853 | .type_info() 854 | .type_name() 855 | .contains("future::pending::Pending")); 856 | assert_eq!( 857 | tasks()[0].type_info().type_id().unwrap(), 858 | TypeId::of::>() 859 | ); 860 | evict_all(); 861 | assert_eq!(tasks().len(), 0); 862 | } 863 | 864 | #[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)] 865 | #[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), wasm_bindgen_test)] 866 | fn joinining() { 867 | use tokio::sync::*; 868 | let (sender, receiver) = oneshot::channel(); 869 | let (sender1, mut receiver1) = oneshot::channel(); 870 | let _handle1 = spawn(async move { 871 | let _ = sender.send(()); 872 | }); 873 | 874 | let handle2 = spawn(async move { 875 | let _ = receiver.await; 876 | 100u8 877 | }); 878 | 879 | let handle3 = spawn(async move { 880 | let _ = sender1.send(handle2.await); 881 | }); 882 | run(Some(handle3.task())); 883 | 884 | assert_eq!(receiver1.try_recv().unwrap().unwrap(), 100); 885 | 886 | evict_all(); 887 | } 888 | } 889 | --------------------------------------------------------------------------------