├── .github └── workflows │ ├── docs.yml │ └── tests.yml ├── .gitignore ├── .rustme ├── config.ron ├── docs.md └── header.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── async.rs └── basic.rs └── src └── lib.rs /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Docs 2 | 3 | on: [push] 4 | 5 | jobs: 6 | docs: 7 | runs-on: ubuntu-latest 8 | if: github.ref == 'refs/heads/main' 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Install Rust 12 | uses: hecrj/setup-rust-action@v1 13 | - name: Generate Docs 14 | run: | 15 | cargo doc --no-deps --all-features 16 | 17 | - name: Deploy Docs 18 | uses: JamesIves/github-pages-deploy-action@releases/v4 19 | with: 20 | branch: gh-pages 21 | folder: target/doc/ 22 | git-config-name: kl-botsu 23 | git-config-email: botsu@khonsulabs.com 24 | target-folder: /main/ 25 | clean: true 26 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | timeout-minutes: 30 9 | steps: 10 | - uses: actions/checkout@v2 11 | 12 | - name: Install Rust 13 | uses: hecrj/setup-rust-action@v1 14 | 15 | - name: Run clippy 16 | run: | 17 | cargo clippy -- -D warnings 18 | 19 | - name: Run unit tests 20 | run: | 21 | cargo test -- --nocapture 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | .vscode -------------------------------------------------------------------------------- /.rustme/config.ron: -------------------------------------------------------------------------------- 1 | Configuration( 2 | files: { 3 | "../README.md": [ 4 | "header.md", 5 | "docs.md", 6 | "https://github.com/khonsulabs/.github/raw/main/snippets/readme-footer.md", 7 | ], 8 | "../CONTRIBUTING.md": [ 9 | "https://github.com/khonsulabs/.github/raw/main/docs/CONTRIBUTING.md", 10 | ], 11 | "../CODE_OF_CONDUCT.md": [ 12 | "https://github.com/khonsulabs/.github/raw/main/docs/CODE_OF_CONDUCT.md", 13 | ], 14 | "../LICENSE-APACHE": [ 15 | "https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-APACHE", 16 | ], 17 | "../LICENSE-MIT": [ 18 | "https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-MIT", 19 | ], 20 | }, 21 | glossaries: [ 22 | "https://github.com/khonsulabs/.github/raw/main/snippets/glossary.ron" 23 | ], 24 | ) -------------------------------------------------------------------------------- /.rustme/docs.md: -------------------------------------------------------------------------------- 1 | [![crate version](https://img.shields.io/crates/v/circulate.svg)](https://crates.io/crates/circulate) 2 | [![Live Build Status](https://img.shields.io/github/workflow/status/khonsulabs/circulate/Tests/main)](https://github.com/khonsulabs/circulate/actions?query=workflow:Tests) 3 | [![Documentation for `main` branch](https://img.shields.io/badge/docs-main-informational)](https://khonsulabs.github.io/circulate/main/circulate/) 4 | 5 | Circulate is a lightweight 6 | [PubSub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) 7 | framework that supports both async and non-async code. This project is written 8 | for [BonsaiDb](https://github.com/khonsulabs/bonsaidb). While BonsaiDb's async 9 | relies upon tokio, this crate is runtime agnostic thanks to the excellent crate 10 | [flume](https://github.com/zesterer/flume). 11 | 12 | ## Async Example 13 | 14 | ```rust 15 | # #[derive(serde::Serialize, serde::Deserialize, Debug)] 16 | # struct AnySerializableType; 17 | # async fn example() -> Result<(), anyhow::Error> { 18 | # use circulate::Relay; 19 | let relay = Relay::default(); 20 | let subscriber = relay.create_subscriber(); 21 | 22 | subscriber.subscribe_to(&"some topic")?; 23 | 24 | relay.publish(&"some topic", &AnySerializableType)?; 25 | 26 | let message = subscriber.receiver().recv_async().await?; 27 | println!( 28 | "Received message on topic {}: {:?}", 29 | message.topic::()?, 30 | message.payload::()? 31 | ); 32 | # Ok(()) 33 | # } 34 | ``` 35 | 36 | ## Sync Example 37 | 38 | ```rust 39 | # #[derive(serde::Serialize, serde::Deserialize, Debug)] 40 | # struct AnySerializableType; 41 | # fn example() -> Result<(), anyhow::Error> { 42 | # use circulate::Relay; 43 | let relay = Relay::default(); 44 | let subscriber = relay.create_subscriber(); 45 | 46 | subscriber.subscribe_to(&"some topic")?; 47 | 48 | relay.publish(&"some topic", &AnySerializableType)?; 49 | 50 | let message = subscriber.receiver().recv()?; 51 | println!( 52 | "Received message on topic {}: {:?}", 53 | message.topic::()?, 54 | message.payload::()? 55 | ); 56 | # Ok(()) 57 | # } 58 | ``` 59 | -------------------------------------------------------------------------------- /.rustme/header.md: -------------------------------------------------------------------------------- 1 | # Circulate 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | moderators@khonsulabs.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to our projects 2 | 3 | Thank you for your interest in contributing to one of our projects. We want 4 | everyone to have a positive experience contributing, so please carefully review 5 | our only requirements for contributing: 6 | 7 | - All contributors must agree to [our Contributor License 8 | Agreement](https://gist.github.com/ecton/b2e1e72abfa122da5e69ed30164f739e). 9 | This will be asked for during your first pull request. 10 | - All contributors must uphold the standards of our [Code of 11 | Conduct](./CODE_OF_CONDUCT.md). 12 | 13 | The rest of this document are recommendations/guidelines to help consistency and 14 | communication within our projects. 15 | 16 | ## Creating Issues 17 | 18 | ### Reporting Bugs 19 | 20 | To us, if something isn't behaving as you expect it to, that's a bug. Even if 21 | it's misbehaving due to a misunderstanding, that means there's an opportunity to 22 | improve our documentation or examples. Please don't hesitate to let us know if 23 | you run into any issues while working with one of our projects. 24 | 25 | ### Requesting New Features 26 | 27 | When requesting new features, please include details about what problem you're 28 | trying to solve, not just a solution to your problem. By helping the community 29 | understand the underlying problem, we can better evaluate what the best solution 30 | to the problem might be. 31 | 32 | ## Contributing Changes 33 | 34 | We openly welcome pull requests on our projects. We don't like bugs, and if 35 | you've found one and wish to submit a fix, we greatly appreciate it. 36 | 37 | If you find that fixing a bug requires a significant change, or you are wanting 38 | to add a somewhat large feature, please submit a proposal as an issue first. We 39 | want to make sure that your efforts have the highest chance of success, and a 40 | short discussion before starting can go a long way towards a pull request being 41 | merged with less revisions. 42 | 43 | When working on an existing issue, update the issue to reflect that you're 44 | working on it. This will help prevent duplicated efforts. 45 | 46 | If you begin working on something but need some assistance, don't hesitate to 47 | reach out inside of the issue, on [our 48 | forums](https://community.khonsulabs.com/), or [our 49 | Discord](https://discord.khonsulabs.com/). We will do our best to help you. 50 | 51 | ### Project-specific requirements 52 | 53 | Be sure to check if a project's README contains additional contributing 54 | guidelines. Each project may have different tools and commands that should be 55 | run to validate that changes pass all requirements. 56 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "circulate" 3 | version = "0.5.0" 4 | authors = ["Jonathan Johnson "] 5 | edition = "2021" 6 | description = "Lightweight PubSub framework that supports both sync and async" 7 | repository = "https://github.com/khonsulabs/circulate" 8 | license = "MIT OR Apache-2.0" 9 | keywords = ["pubsub"] 10 | categories = ["asynchronous"] 11 | readme = "./README.md" 12 | 13 | [dependencies] 14 | flume = { version = "0.11", default-features = false, features = ["async"] } 15 | serde = { version = "1.0.136", features = ["derive"] } 16 | pot = "3.0.0" 17 | futures = "0.3.21" 18 | parking_lot = "0.12.0" 19 | arc-bytes = "0.3.3" 20 | 21 | [dev-dependencies] 22 | anyhow = "1.0.55" 23 | tokio = { version = "1.16.0", features = [ 24 | "sync", 25 | "rt", 26 | "rt-multi-thread", 27 | "macros", 28 | "time", 29 | "test-util", 30 | ] } 31 | -------------------------------------------------------------------------------- /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 2021 Khonsu Labs LLC 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 2021 Khonsu Labs LLC 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Circulate 2 | 3 | [![crate version](https://img.shields.io/crates/v/circulate.svg)](https://crates.io/crates/circulate) 4 | [![Live Build Status](https://img.shields.io/github/actions/workflow/status/khonsulabs/circulate/tests.yml?branch=main)](https://github.com/khonsulabs/circulate/actions?query=workflow:Tests) 5 | [![Documentation for `main` branch](https://img.shields.io/badge/docs-main-informational)](https://khonsulabs.github.io/circulate/main/circulate/) 6 | 7 | Circulate is a lightweight 8 | [PubSub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) 9 | framework that supports both async and non-async code. This project is written 10 | for [BonsaiDb](https://github.com/khonsulabs/bonsaidb). While BonsaiDb's async 11 | relies upon tokio, this crate is runtime agnostic thanks to the excellent crate 12 | [flume](https://github.com/zesterer/flume). 13 | 14 | ## Async Example 15 | 16 | ```rust 17 | let relay = Relay::default(); 18 | let subscriber = relay.create_subscriber(); 19 | 20 | subscriber.subscribe_to(&"some topic")?; 21 | 22 | relay.publish(&"some topic", &AnySerializableType)?; 23 | 24 | let message = subscriber.receiver().recv_async().await?; 25 | println!( 26 | "Received message on topic {}: {:?}", 27 | message.topic::()?, 28 | message.payload::()? 29 | ); 30 | ``` 31 | 32 | ## Sync Example 33 | 34 | ```rust 35 | let relay = Relay::default(); 36 | let subscriber = relay.create_subscriber(); 37 | 38 | subscriber.subscribe_to(&"some topic")?; 39 | 40 | relay.publish(&"some topic", &AnySerializableType)?; 41 | 42 | let message = subscriber.receiver().recv()?; 43 | println!( 44 | "Received message on topic {}: {:?}", 45 | message.topic::()?, 46 | message.payload::()? 47 | ); 48 | ``` 49 | 50 | ## Open-source Licenses 51 | 52 | This project, like all projects from [Khonsu Labs](https://khonsulabs.com/), are 53 | open-source. This repository is available under the [MIT License](./LICENSE-MIT) 54 | or the [Apache License 2.0](./LICENSE-APACHE). 55 | 56 | To learn more about contributing, please see [CONTRIBUTING.md](./CONTRIBUTING.md). 57 | -------------------------------------------------------------------------------- /examples/async.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use circulate::Relay; 4 | use tokio::time::sleep; 5 | 6 | #[tokio::main] 7 | async fn main() -> anyhow::Result<()> { 8 | let relay = Relay::default(); 9 | 10 | let subscriber = relay.create_subscriber(); 11 | // Subscribe for messages sent to the topic "pong" 12 | subscriber.subscribe_to(&"pong")?; 13 | 14 | // Launch a task that sends out "ping" messages. 15 | tokio::spawn(pinger(relay.clone())); 16 | // Launch a task that receives "ping" messages and sends "pong" responses. 17 | tokio::spawn(ponger(relay.clone())); 18 | 19 | // Loop until a we receive a message letting us know when the ponger() has 20 | // no pings remaining. 21 | loop { 22 | let message = subscriber.receiver().recv_async().await?; 23 | let pings_remaining = message.payload::()?; 24 | println!( 25 | "<-- Received {}, pings remaining: {}", 26 | message.topic::()?, 27 | pings_remaining 28 | ); 29 | if pings_remaining == 0 { 30 | break; 31 | } 32 | } 33 | 34 | println!("Received all pongs."); 35 | 36 | Ok(()) 37 | } 38 | 39 | async fn pinger(pubsub: Relay) -> anyhow::Result<()> { 40 | let mut ping_count = 0u32; 41 | loop { 42 | ping_count += 1; 43 | println!("-> Sending ping {}", ping_count); 44 | pubsub.publish(&"ping", &ping_count)?; 45 | sleep(Duration::from_millis(250)).await; 46 | } 47 | } 48 | 49 | async fn ponger(pubsub: Relay) -> anyhow::Result<()> { 50 | const NUMBER_OF_PONGS: usize = 5; 51 | let subscriber = pubsub.create_subscriber(); 52 | subscriber.subscribe_to(&"ping")?; 53 | let mut pings_remaining = NUMBER_OF_PONGS; 54 | 55 | println!( 56 | "Ponger started, waiting to respond to {} pings", 57 | pings_remaining 58 | ); 59 | 60 | while pings_remaining > 0 { 61 | let message = subscriber.receiver().recv_async().await?; 62 | println!( 63 | "<- Received {}, id {}", 64 | message.topic::()?, 65 | message.payload::()? 66 | ); 67 | pings_remaining -= 1; 68 | pubsub.publish(&"pong", &pings_remaining)?; 69 | } 70 | 71 | println!("Ponger finished."); 72 | 73 | Ok(()) 74 | } 75 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | use std::{thread::sleep, time::Duration}; 2 | 3 | use circulate::Relay; 4 | 5 | fn main() -> anyhow::Result<()> { 6 | let relay = Relay::default(); 7 | 8 | let subscriber = relay.create_subscriber(); 9 | // Subscribe for messages sent to the topic "pong" 10 | subscriber.subscribe_to(&"pong")?; 11 | 12 | // Launch a task that sends out "ping" messages. 13 | let pinger_relay = relay.clone(); 14 | std::thread::spawn(|| pinger(pinger_relay)); 15 | // Launch a task that receives "ping" messages and sends "pong" responses. 16 | std::thread::spawn(|| ponger(relay)); 17 | 18 | // Loop until a we receive a message letting us know when the ponger() has 19 | // no pings remaining. 20 | loop { 21 | let message = subscriber.receiver().recv()?; 22 | let pings_remaining = message.payload::()?; 23 | println!( 24 | "<-- Received {}, pings remaining: {}", 25 | message.topic::()?, 26 | pings_remaining 27 | ); 28 | if pings_remaining == 0 { 29 | break; 30 | } 31 | } 32 | 33 | println!("Received all pongs."); 34 | 35 | Ok(()) 36 | } 37 | 38 | fn pinger(pubsub: Relay) -> anyhow::Result<()> { 39 | let mut ping_count = 0u32; 40 | loop { 41 | ping_count += 1; 42 | println!("-> Sending ping {}", ping_count); 43 | pubsub.publish(&"ping", &ping_count)?; 44 | sleep(Duration::from_millis(250)); 45 | } 46 | } 47 | 48 | fn ponger(pubsub: Relay) -> anyhow::Result<()> { 49 | const NUMBER_OF_PONGS: usize = 5; 50 | let subscriber = pubsub.create_subscriber(); 51 | subscriber.subscribe_to(&"ping")?; 52 | let mut pings_remaining = NUMBER_OF_PONGS; 53 | 54 | println!( 55 | "Ponger started, waiting to respond to {} pings", 56 | pings_remaining 57 | ); 58 | 59 | while pings_remaining > 0 { 60 | let message = subscriber.receiver().recv()?; 61 | println!( 62 | "<- Received {}, id {}", 63 | message.topic::()?, 64 | message.payload::()? 65 | ); 66 | pings_remaining -= 1; 67 | pubsub.publish(&"pong", &pings_remaining)?; 68 | } 69 | 70 | println!("Ponger finished."); 71 | 72 | Ok(()) 73 | } 74 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../.rustme/docs.md")] 2 | #![forbid(unsafe_code)] 3 | #![warn( 4 | clippy::cargo, 5 | missing_docs, 6 | // clippy::missing_docs_in_private_items, 7 | clippy::nursery, 8 | clippy::pedantic, 9 | future_incompatible, 10 | rust_2018_idioms, 11 | )] 12 | #![cfg_attr(doc, deny(rustdoc::all))] 13 | #![allow(clippy::option_if_let_else)] 14 | 15 | use std::{ 16 | collections::{HashMap, HashSet}, 17 | sync::{ 18 | atomic::{AtomicU64, Ordering}, 19 | Arc, 20 | }, 21 | }; 22 | 23 | use arc_bytes::OwnedBytes; 24 | pub use flume; 25 | use parking_lot::RwLock; 26 | use serde::{Deserialize, Serialize}; 27 | 28 | /// A `PubSub` message. 29 | #[derive(Clone, Debug, Serialize, Deserialize)] 30 | pub struct Message { 31 | /// The topic of the message. 32 | pub topic: OwnedBytes, 33 | /// The payload of the message. 34 | pub payload: OwnedBytes, 35 | } 36 | 37 | impl Message { 38 | /// Creates a new message. 39 | /// 40 | /// # Errors 41 | /// 42 | /// Returns an error if `payload` fails to serialize with `pot`. 43 | pub fn new( 44 | topic: &Topic, 45 | payload: &Payload, 46 | ) -> Result { 47 | Ok(Self::raw(pot::to_vec(topic)?, pot::to_vec(payload)?)) 48 | } 49 | 50 | /// Creates a new message with a raw payload. 51 | pub fn raw, B: Into>(topic: S, payload: B) -> Self { 52 | Self { 53 | topic: topic.into(), 54 | payload: payload.into(), 55 | } 56 | } 57 | 58 | /// Deserialize the topic as `Topic` using `pot`. 59 | /// 60 | /// # Errors 61 | /// 62 | /// Returns an error if `topic` fails to deserialize with `pot`. 63 | pub fn topic<'a, Topic: Deserialize<'a>>(&'a self) -> Result { 64 | pot::from_slice(&self.topic).map_err(pot::Error::from) 65 | } 66 | 67 | /// Deserialize the payload as `Payload` using `pot`. 68 | /// 69 | /// # Errors 70 | /// 71 | /// Returns an error if `payload` fails to deserialize with `pot`. 72 | pub fn payload<'a, Payload: Deserialize<'a>>(&'a self) -> Result { 73 | pot::from_slice(&self.payload).map_err(pot::Error::from) 74 | } 75 | } 76 | 77 | type TopicId = u64; 78 | type SubscriberId = u64; 79 | 80 | #[derive(Default, Debug, Clone)] 81 | /// Manages subscriptions and notifications for `PubSub`. 82 | pub struct Relay { 83 | data: Arc, 84 | } 85 | 86 | #[derive(Debug, Default)] 87 | struct Data { 88 | subscribers: RwLock>, 89 | topics: RwLock>, 90 | subscriptions: RwLock>>, 91 | last_topic_id: AtomicU64, 92 | last_subscriber_id: AtomicU64, 93 | } 94 | 95 | impl Relay { 96 | /// Create a new [`Subscriber`] for this relay. 97 | pub fn create_subscriber(&self) -> Subscriber { 98 | let mut subscribers = self.data.subscribers.write(); 99 | let id = self.data.last_subscriber_id.fetch_add(1, Ordering::SeqCst); 100 | let (sender, receiver) = flume::unbounded(); 101 | subscribers.insert( 102 | id, 103 | SubscriberInfo { 104 | sender, 105 | topics: HashSet::default(), 106 | }, 107 | ); 108 | Subscriber { 109 | data: Arc::new(SubscriberData { 110 | id, 111 | receiver, 112 | relay: self.clone(), 113 | }), 114 | } 115 | } 116 | 117 | /// Publishes a `payload` to all subscribers of `topic`. 118 | /// 119 | /// # Errors 120 | /// 121 | /// Returns an error if `topic` or `payload` fails to serialize with `pot`. 122 | pub fn publish( 123 | &self, 124 | topic: &Topic, 125 | payload: &P, 126 | ) -> Result<(), pot::Error> { 127 | let message = Message::new(topic, payload)?; 128 | self.publish_message(&message); 129 | Ok(()) 130 | } 131 | 132 | /// Publishes a `payload` to all subscribers of `topic`. 133 | pub fn publish_raw, Payload: Into>( 134 | &self, 135 | topic: Topic, 136 | payload: Payload, 137 | ) { 138 | let message = Message::raw(topic, payload); 139 | self.publish_message(&message); 140 | } 141 | 142 | /// Publishes a `payload` to all subscribers of `topic`. 143 | /// 144 | /// # Errors 145 | /// 146 | /// Returns an error if `topics` or `payload` fail to serialize with `pot`. 147 | pub fn publish_to_all< 148 | 'topics, 149 | Topics: IntoIterator + 'topics, 150 | Topic: Serialize + 'topics, 151 | Payload: Serialize, 152 | >( 153 | &self, 154 | topics: Topics, 155 | payload: &Payload, 156 | ) -> Result<(), pot::Error> { 157 | for topic in topics { 158 | let message = Message::new(topic, payload)?; 159 | self.publish_message(&message); 160 | } 161 | 162 | Ok(()) 163 | } 164 | 165 | /// Publishes a `payload` to all subscribers of `topic`. 166 | pub fn publish_raw_to_all( 167 | &self, 168 | topics: impl IntoIterator, 169 | payload: impl Into, 170 | ) { 171 | let payload = payload.into(); 172 | for topic in topics { 173 | self.publish_message(&Message { 174 | topic, 175 | payload: payload.clone(), 176 | }); 177 | } 178 | } 179 | 180 | /// Publishes a message to all subscribers of its topic. 181 | pub fn publish_message(&self, message: &Message) { 182 | if let Some(topic_id) = self.topic_id(&message.topic) { 183 | self.post_message_to_topic(message, topic_id); 184 | } 185 | } 186 | 187 | fn add_subscriber_to_topic(&self, subscriber_id: u64, topic: OwnedBytes) { 188 | let mut subscribers = self.data.subscribers.write(); 189 | let mut topics = self.data.topics.write(); 190 | let mut subscriptions = self.data.subscriptions.write(); 191 | 192 | // Lookup or create a topic id 193 | let topic_id = *topics 194 | .entry(topic) 195 | .or_insert_with(|| self.data.last_topic_id.fetch_add(1, Ordering::SeqCst)); 196 | if let Some(subscriber) = subscribers.get_mut(&subscriber_id) { 197 | subscriber.topics.insert(topic_id); 198 | } 199 | let subscribers = subscriptions 200 | .entry(topic_id) 201 | .or_insert_with(HashSet::default); 202 | subscribers.insert(subscriber_id); 203 | } 204 | 205 | fn remove_subscriber_from_topic(&self, subscriber_id: u64, topic: &[u8]) { 206 | let mut subscribers = self.data.subscribers.write(); 207 | let mut topics = self.data.topics.write(); 208 | 209 | let remove_topic = if let Some(topic_id) = topics.get(topic) { 210 | if let Some(subscriber) = subscribers.get_mut(&subscriber_id) { 211 | if !subscriber.topics.remove(topic_id) { 212 | // subscriber isn't subscribed to this topic 213 | return; 214 | } 215 | } else { 216 | // subscriber_id is not subscribed anymore 217 | return; 218 | } 219 | 220 | let mut subscriptions = self.data.subscriptions.write(); 221 | let remove_topic = if let Some(subscriptions) = subscriptions.get_mut(topic_id) { 222 | subscriptions.remove(&subscriber_id); 223 | subscriptions.is_empty() 224 | } else { 225 | // Shouldn't be reachable, but this allows cleanup to proceed if it does. 226 | true 227 | }; 228 | 229 | if remove_topic { 230 | subscriptions.remove(topic_id); 231 | true 232 | } else { 233 | false 234 | } 235 | } else { 236 | false 237 | }; 238 | if remove_topic { 239 | topics.remove(topic); 240 | } 241 | } 242 | 243 | fn topic_id(&self, topic: &[u8]) -> Option { 244 | let topics = self.data.topics.read(); 245 | topics.get(topic).copied() 246 | } 247 | 248 | fn post_message_to_topic(&self, message: &Message, topic: TopicId) { 249 | let failures = { 250 | // For an optimal-flow case, we're going to acquire read permissions 251 | // only, allowing messages to be posted in parallel. This block is 252 | // responsible for returning `SubscriberId`s that failed to send. 253 | let subscribers = self.data.subscribers.read(); 254 | let subscriptions = self.data.subscriptions.read(); 255 | if let Some(registered) = subscriptions.get(&topic) { 256 | let failures = registered 257 | .iter() 258 | .filter_map(|id| { 259 | subscribers.get(id).and_then(|subscriber| { 260 | let message = message.clone(); 261 | if subscriber.sender.send(message).is_ok() { 262 | None 263 | } else { 264 | Some(*id) 265 | } 266 | }) 267 | }) 268 | .collect::>(); 269 | 270 | failures 271 | } else { 272 | return; 273 | } 274 | }; 275 | 276 | if !failures.is_empty() { 277 | for failed in failures { 278 | self.unsubscribe_all(failed); 279 | } 280 | } 281 | } 282 | 283 | fn unsubscribe_all(&self, subscriber_id: SubscriberId) { 284 | let mut subscribers = self.data.subscribers.write(); 285 | let mut topics = self.data.topics.write(); 286 | let mut subscriptions = self.data.subscriptions.write(); 287 | if let Some(subscriber) = subscribers.remove(&subscriber_id) { 288 | for topic in &subscriber.topics { 289 | let remove = if let Some(subscriptions) = subscriptions.get_mut(topic) { 290 | subscriptions.remove(&subscriber_id); 291 | subscriptions.is_empty() 292 | } else { 293 | false 294 | }; 295 | 296 | if remove { 297 | subscriptions.remove(topic); 298 | topics.retain(|_name, id| id != topic); 299 | } 300 | } 301 | } 302 | } 303 | } 304 | 305 | #[derive(Debug)] 306 | struct SubscriberInfo { 307 | sender: flume::Sender, 308 | topics: HashSet, 309 | } 310 | 311 | /// A subscriber for [`Message`]s published to subscribed topics. 312 | #[derive(Debug, Clone)] 313 | #[must_use] 314 | pub struct Subscriber { 315 | data: Arc, 316 | } 317 | 318 | impl Subscriber { 319 | /// Subscribe to [`Message`]s published to `topic`. 320 | /// 321 | /// # Errors 322 | /// 323 | /// Returns an error if `topic` fails to serialize with `pot`. 324 | pub fn subscribe_to(&self, topic: &Topic) -> Result<(), pot::Error> { 325 | let topic = pot::to_vec(topic)?; 326 | self.subscribe_to_raw(topic); 327 | Ok(()) 328 | } 329 | 330 | /// Subscribe to [`Message`]s published to `topic`. 331 | pub fn subscribe_to_raw(&self, topic: impl Into) { 332 | self.data 333 | .relay 334 | .add_subscriber_to_topic(self.data.id, topic.into()); 335 | } 336 | 337 | /// Unsubscribe from [`Message`]s published to `topic`. 338 | /// 339 | /// # Errors 340 | /// 341 | /// Returns an error if `topic` fails to serialize with `pot`. 342 | pub fn unsubscribe_from(&self, topic: &Topic) -> Result<(), pot::Error> { 343 | let topic = pot::to_vec(topic)?; 344 | self.unsubscribe_from_raw(&topic); 345 | Ok(()) 346 | } 347 | 348 | /// Unsubscribe from [`Message`]s published to `topic`. 349 | pub fn unsubscribe_from_raw(&self, topic: &[u8]) { 350 | self.data 351 | .relay 352 | .remove_subscriber_from_topic(self.data.id, topic); 353 | } 354 | 355 | /// Returns the receiver to receive [`Message`]s. 356 | #[must_use] 357 | pub fn receiver(&self) -> &'_ flume::Receiver { 358 | &self.data.receiver 359 | } 360 | 361 | #[must_use] 362 | /// Returns the unique ID of the subscriber. 363 | pub fn id(&self) -> u64 { 364 | self.data.id 365 | } 366 | } 367 | 368 | #[derive(Debug)] 369 | struct SubscriberData { 370 | id: SubscriberId, 371 | relay: Relay, 372 | receiver: flume::Receiver, 373 | } 374 | 375 | impl Drop for SubscriberData { 376 | fn drop(&mut self) { 377 | self.relay.unsubscribe_all(self.id); 378 | } 379 | } 380 | 381 | #[cfg(test)] 382 | mod tests { 383 | use super::*; 384 | 385 | #[tokio::test] 386 | async fn simple_pubsub_test() -> anyhow::Result<()> { 387 | let pubsub = Relay::default(); 388 | let subscriber = pubsub.create_subscriber(); 389 | subscriber.subscribe_to(&"mytopic")?; 390 | pubsub.publish(&"mytopic", &String::from("test"))?; 391 | let receiver = subscriber.receiver().clone(); 392 | let message = receiver.recv_async().await.expect("No message received"); 393 | assert_eq!(message.topic::()?, "mytopic"); 394 | assert_eq!(message.payload::()?, "test"); 395 | // The message should only be received once. 396 | assert!(matches!( 397 | tokio::task::spawn_blocking( 398 | move || receiver.recv_timeout(std::time::Duration::from_millis(100)) 399 | ) 400 | .await, 401 | Ok(Err(_)) 402 | )); 403 | Ok(()) 404 | } 405 | 406 | #[tokio::test] 407 | async fn multiple_subscribers_test() -> anyhow::Result<()> { 408 | let pubsub = Relay::default(); 409 | let subscriber_a = pubsub.create_subscriber(); 410 | let subscriber_ab = pubsub.create_subscriber(); 411 | subscriber_a.subscribe_to(&"a")?; 412 | subscriber_ab.subscribe_to(&"a")?; 413 | subscriber_ab.subscribe_to(&"b")?; 414 | 415 | pubsub.publish(&"a", &String::from("a1"))?; 416 | pubsub.publish(&"b", &String::from("b1"))?; 417 | pubsub.publish(&"a", &String::from("a2"))?; 418 | 419 | // Check subscriber_a for a1 and a2. 420 | let message = subscriber_a.receiver().recv()?; 421 | assert_eq!(message.payload::()?, "a1"); 422 | let message = subscriber_a.receiver().recv()?; 423 | assert_eq!(message.payload::()?, "a2"); 424 | 425 | let message = subscriber_ab.receiver().recv()?; 426 | assert_eq!(message.payload::()?, "a1"); 427 | let message = subscriber_ab.receiver().recv()?; 428 | assert_eq!(message.payload::()?, "b1"); 429 | let message = subscriber_ab.receiver().recv()?; 430 | assert_eq!(message.payload::()?, "a2"); 431 | 432 | Ok(()) 433 | } 434 | 435 | #[tokio::test] 436 | async fn unsubscribe_test() -> anyhow::Result<()> { 437 | let pubsub = Relay::default(); 438 | let subscriber = pubsub.create_subscriber(); 439 | subscriber.subscribe_to(&"a")?; 440 | 441 | pubsub.publish(&"a", &String::from("a1"))?; 442 | subscriber.unsubscribe_from(&"a")?; 443 | pubsub.publish(&"a", &String::from("a2"))?; 444 | subscriber.subscribe_to(&"a")?; 445 | pubsub.publish(&"a", &String::from("a3"))?; 446 | 447 | // Check subscriber_a for a1 and a2. 448 | let message = subscriber.receiver().recv()?; 449 | assert_eq!(message.payload::()?, "a1"); 450 | let message = subscriber.receiver().recv()?; 451 | assert_eq!(message.payload::()?, "a3"); 452 | 453 | Ok(()) 454 | } 455 | 456 | #[tokio::test] 457 | async fn drop_and_send_test() -> anyhow::Result<()> { 458 | let pubsub = Relay::default(); 459 | let subscriber_a = pubsub.create_subscriber(); 460 | let subscriber_to_drop = pubsub.create_subscriber(); 461 | subscriber_a.subscribe_to(&"a")?; 462 | subscriber_to_drop.subscribe_to(&"a")?; 463 | 464 | pubsub.publish(&"a", &String::from("a1"))?; 465 | drop(subscriber_to_drop); 466 | pubsub.publish(&"a", &String::from("a2"))?; 467 | 468 | // Check subscriber_a for a1 and a2. 469 | let message = subscriber_a.receiver().recv()?; 470 | assert_eq!(message.payload::()?, "a1"); 471 | let message = subscriber_a.receiver().recv()?; 472 | assert_eq!(message.payload::()?, "a2"); 473 | 474 | let subscribers = pubsub.data.subscribers.read(); 475 | assert_eq!(subscribers.len(), 1); 476 | let topics = pubsub.data.topics.read(); 477 | let topic_id = topics.values().next().expect("topic not found"); 478 | let subscriptions = pubsub.data.subscriptions.read(); 479 | assert_eq!( 480 | subscriptions 481 | .get(topic_id) 482 | .expect("subscriptions not found") 483 | .len(), 484 | 1 485 | ); 486 | 487 | Ok(()) 488 | } 489 | 490 | #[tokio::test] 491 | async fn drop_cleanup_test() -> anyhow::Result<()> { 492 | let pubsub = Relay::default(); 493 | let subscriber = pubsub.create_subscriber(); 494 | subscriber.subscribe_to(&"a")?; 495 | drop(subscriber); 496 | 497 | let subscribers = pubsub.data.subscribers.read(); 498 | assert_eq!(subscribers.len(), 0); 499 | let subscriptions = pubsub.data.subscriptions.read(); 500 | assert_eq!(subscriptions.len(), 0); 501 | let topics = pubsub.data.topics.read(); 502 | assert_eq!(topics.len(), 0); 503 | 504 | Ok(()) 505 | } 506 | } 507 | --------------------------------------------------------------------------------