├── .github └── workflows │ └── go.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.MD ├── eventstore.go ├── eventstore_test.go ├── examples ├── drop_oldest │ └── main.go ├── fasthttp │ └── main.go ├── goroutines-subscribe-publisher │ ├── go.mod │ ├── go.sum │ └── main.go ├── handler_timeout │ └── main.go ├── hello_world │ ├── go.mod │ ├── go.sum │ └── main.go ├── middleware │ └── main.go ├── publisher │ ├── go.mod │ ├── go.sum │ └── main.go ├── publisher_timeout │ └── main.go └── return_error │ └── main.go ├── go.mod ├── go.sum ├── go.work ├── logoGoEventBus.png ├── transaction.go └── transaction_test.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v4 18 | with: 19 | go-version: '1.22.2' 20 | 21 | - name: Clear Go Module Cache 22 | run: go clean -modcache 23 | 24 | - name: Install dependencies 25 | run: | 26 | go get github.com/lib/pq 27 | go get github.com/gorilla/mux 28 | 29 | - name: Tidy and install modules 30 | run: go mod tidy 31 | 32 | - name: Build 33 | run: go build -v ./... 34 | 35 | - name: Run Tests with Coverage 36 | run: | 37 | go test -v -coverprofile=coverage.out ./... 38 | go tool cover -func=coverage.out -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *go.work 2 | *go.work.sum 3 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Citizen Code of Conduct 2 | 3 | ## 1. Purpose 4 | 5 | A primary goal of GoEventBus is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). 6 | 7 | This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. 8 | 9 | We invite all those who participate in GoEventBus to help us create safe and positive experiences for everyone. 10 | 11 | ## 2. Open [Source/Culture/Tech] Citizenship 12 | 13 | A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. 14 | 15 | Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. 16 | 17 | If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. 18 | 19 | ## 3. Expected Behavior 20 | 21 | The following behaviors are expected and requested of all community members: 22 | 23 | * Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. 24 | * Exercise consideration and respect in your speech and actions. 25 | * Attempt collaboration before conflict. 26 | * Refrain from demeaning, discriminatory, or harassing behavior and speech. 27 | * Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. 28 | * Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. 29 | 30 | ## 4. Unacceptable Behavior 31 | 32 | The following behaviors are considered harassment and are unacceptable within our community: 33 | 34 | * Violence, threats of violence or violent language directed against another person. 35 | * Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. 36 | * Posting or displaying sexually explicit or violent material. 37 | * Posting or threatening to post other people's personally identifying information ("doxing"). 38 | * Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. 39 | * Inappropriate photography or recording. 40 | * Inappropriate physical contact. You should have someone's consent before touching them. 41 | * Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. 42 | * Deliberate intimidation, stalking or following (online or in person). 43 | * Advocating for, or encouraging, any of the above behavior. 44 | * Sustained disruption of community events, including talks and presentations. 45 | 46 | ## 5. Weapons Policy 47 | 48 | No weapons will be allowed at GoEventBus events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter. 49 | 50 | ## 6. Consequences of Unacceptable Behavior 51 | 52 | Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. 53 | 54 | Anyone asked to stop unacceptable behavior is expected to comply immediately. 55 | 56 | If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). 57 | 58 | ## 7. Reporting Guidelines 59 | 60 | If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. kmosc@protonmail.com. 61 | 62 | 63 | 64 | Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. 65 | 66 | ## 8. Addressing Grievances 67 | 68 | If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies. 69 | 70 | 71 | 72 | ## 9. Scope 73 | 74 | We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business. 75 | 76 | This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. 77 | 78 | ## 10. Contact info 79 | 80 | kmosc@protonmail.com 81 | 82 | ## 11. License and attribution 83 | 84 | The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). 85 | 86 | Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). 87 | 88 | _Revision 2.3. Posted 6 March 2017._ 89 | 90 | _Revision 2.2. Posted 4 February 2016._ 91 | 92 | _Revision 2.1. Posted 23 June 2014._ 93 | 94 | _Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._ 95 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributing to GoEventBus 3 | 4 | First off, thanks for taking the time to contribute! ❤️ 5 | 6 | All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 7 | 8 | > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: 9 | > - Star the project 10 | > - Tweet about it 11 | > - Refer this project in your project's readme 12 | > - Mention the project at local meetups and tell your friends/colleagues 13 | 14 | 15 | ## Table of Contents 16 | 17 | - [Code of Conduct](#code-of-conduct) 18 | - [I Have a Question](#i-have-a-question) 19 | - [I Want To Contribute](#i-want-to-contribute) 20 | - [Reporting Bugs](#reporting-bugs) 21 | - [Suggesting Enhancements](#suggesting-enhancements) 22 | - [Your First Code Contribution](#your-first-code-contribution) 23 | - [Improving The Documentation](#improving-the-documentation) 24 | - [Styleguides](#styleguides) 25 | - [Commit Messages](#commit-messages) 26 | - [Join The Project Team](#join-the-project-team) 27 | 28 | 29 | ## Code of Conduct 30 | 31 | This project and everyone participating in it is governed by the 32 | [GoEventBus Code of Conduct](https://github.com/Raezil/GoEventBus/blob//CODE_OF_CONDUCT.md). 33 | By participating, you are expected to uphold this code. Please report unacceptable behavior 34 | to <>. 35 | 36 | 37 | ## I Have a Question 38 | 39 | > If you want to ask a question, we assume that you have read the available [Documentation](). 40 | 41 | Before you ask a question, it is best to search for existing [Issues](https://github.com/Raezil/GoEventBus/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. 42 | 43 | If you then still feel the need to ask a question and need clarification, we recommend the following: 44 | 45 | - Open an [Issue](https://github.com/Raezil/GoEventBus/issues/new). 46 | - Provide as much context as you can about what you're running into. 47 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 48 | 49 | We will then take care of the issue as soon as possible. 50 | 51 | 65 | 66 | ## I Want To Contribute 67 | 68 | > ### Legal Notice 69 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project licence. 70 | 71 | ### Reporting Bugs 72 | 73 | 74 | #### Before Submitting a Bug Report 75 | 76 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. 77 | 78 | - Make sure that you are using the latest version. 79 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). 80 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/Raezil/GoEventBus/issues?q=label%3Abug). 81 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. 82 | - Collect information about the bug: 83 | - Stack trace (Traceback) 84 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) 85 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. 86 | - Possibly your input and the output 87 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions? 88 | 89 | 90 | #### How Do I Submit a Good Bug Report? 91 | 92 | > You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . 93 | 94 | 95 | We use GitHub issues to track bugs and errors. If you run into an issue with the project: 96 | 97 | - Open an [Issue](https://github.com/Raezil/GoEventBus/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) 98 | - Explain the behavior you would expect and the actual behavior. 99 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. 100 | - Provide the information you collected in the previous section. 101 | 102 | Once it's filed: 103 | 104 | - The project team will label the issue accordingly. 105 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. 106 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution). 107 | 108 | 109 | 110 | 111 | ### Suggesting Enhancements 112 | 113 | This section guides you through submitting an enhancement suggestion for GoEventBus, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. 114 | 115 | 116 | #### Before Submitting an Enhancement 117 | 118 | - Make sure that you are using the latest version. 119 | - Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. 120 | - Perform a [search](https://github.com/Raezil/GoEventBus/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 121 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. 122 | 123 | 124 | #### How Do I Submit a Good Enhancement Suggestion? 125 | 126 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/Raezil/GoEventBus/issues). 127 | 128 | - Use a **clear and descriptive title** for the issue to identify the suggestion. 129 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible. 130 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. 131 | - You may want to **include screenshots or screen recordings** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [LICEcap](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and the built-in [screen recorder in GNOME](https://help.gnome.org/users/gnome-help/stable/screen-shot-record.html.en) or [SimpleScreenRecorder](https://github.com/MaartenBaert/ssr) on Linux. 132 | - **Explain why this enhancement would be useful** to most GoEventBus users. You may also want to point out the other projects that solved it better and which could serve as inspiration. 133 | 134 | 135 | 136 | ### Your First Code Contribution 137 | 141 | 142 | ### Improving The Documentation 143 | 147 | 148 | ## Styleguides 149 | ### Commit Messages 150 | 153 | 154 | ## Join The Project Team 155 | 156 | 157 | 158 | ## Attribution 159 | This guide is based on the [contributing.md](https://contributing.md/generator)! 160 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Kamil Mościszko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | # GoEventBus 6 | 7 | A blazing‑fast, in‑memory, lock‑free event bus for Go—ideal for low‑latency pipelines, microservices, and game loops. 8 | 9 | [![Go Report Card](https://goreportcard.com/badge/github.com/Raezil/GoEventBus)](...) 10 | 11 | ## 📚 Table of Contents 12 | - [Features](#features) 13 | - [Why GoEventBus?](#why-goeventbus) 14 | - [Installation](#installation) 15 | - [Quick Start](#quick-start) 16 | - [Transactions](#transactions) 17 | - [API Reference](#api-reference) 18 | - [Back-pressure and Overrun Policies](#back-pressure-and-overrun-policies) 19 | - [Use Cases](#-use-cases) 20 | - [Benchmarks](#benchmarks) 21 | - [Contributing](#contributing) 22 | - [License](#license) 23 | 24 | ## Features 25 | 26 | - **Lock‑free ring buffer**: Efficient event dispatching using atomic operations and cache‑line padding. 27 | - **Context‑aware handlers**: Every handler now receives a `context.Context`, enabling deadlines, cancellation and tracing. 28 | - **Back‑pressure policies**: Choose whether to drop, block, or error when the buffer is full. 29 | - **Configurable buffer size**: Specify the ring buffer size (must be a power of two) when creating the store. 30 | - **Async or Sync processing**: Toggle between synchronous handling or async goroutine‑based processing via the `Async` flag. 31 | - **Metrics**: Track published, processed, and errored event counts with a simple API. 32 | - **Simple API**: Easy to subscribe, publish, and retrieve metrics. 33 | 34 | ## Why GoEventBus? 35 | 36 | Modern Go apps demand lightning‑fast, non‑blocking communication—but channels can bottleneck and external brokers add latency, complexity and ops overhead. GoEventBus is your in‑process, lock‑free solution: 37 | 38 | - **Micro‑latency dispatch** 39 | Atomic, cache‑aligned ring buffers deliver sub‑microsecond hand‑offs—no locks, no syscalls, zero garbage. 40 | - **Sync or Async at will** 41 | Flip a switch to run handlers inline for predictability or in goroutines for massive parallelism. 42 | - **Back‑pressure your way** 43 | Choose from _DropOldest_, _Block_ or _ReturnError_ to match your system’s tolerance for loss or latency. 44 | - **Built‑in observability** 45 | Expose counters for published, processed and errored events out of the box—no extra instrumentation. 46 | - **Drop‑in, zero deps** 47 | One import, no external services, no workers to manage—just Go 1.21+ and you’re off. 48 | 49 | Whether you’re building real‑time analytics, high‑throughput microservices, or game engines, GoEventBus keeps your events moving at Go‑speed. 50 | 51 | ## Installation 52 | 53 | ```bash 54 | go get github.com/Raezil/GoEventBus 55 | ``` 56 | 57 | ## Quick Start 58 | 59 | ```go 60 | package main 61 | 62 | import ( 63 | "context" 64 | "fmt" 65 | "log" 66 | 67 | "github.com/Raezil/GoEventBus" 68 | ) 69 | 70 | // Define a typed projection as a struct 71 | type HouseWasSold struct{} 72 | 73 | func main() { 74 | // Create a dispatcher mapping projections (string or struct) to handlers 75 | dispatcher := GoEventBus.Dispatcher{ 76 | "user_created": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 77 | userID := args["id"].(string) 78 | fmt.Println("User created with ID:", userID) 79 | return GoEventBus.Result{Message: "handled user_created"}, nil 80 | }, 81 | HouseWasSold{}: func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 82 | address := args["address"].(string) 83 | price := args["price"].(int) 84 | fmt.Printf("House sold at %s for $%d\n", address, price) 85 | return GoEventBus.Result{Message: "handled HouseWasSold"}, nil 86 | }, 87 | } 88 | 89 | // Initialise an EventStore with a 64K ring buffer and DropOldest overrun policy 90 | store := GoEventBus.NewEventStore(&dispatcher, 1<<16, GoEventBus.DropOldest) 91 | 92 | // Enable asynchronous processing 93 | store.Async = true 94 | 95 | // Enqueue a string-based event 96 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ 97 | ID: "evt1", 98 | Projection: "user_created", 99 | Args: map[string]any{"id": "12345"}, 100 | }) 101 | 102 | // Enqueue a struct-based event 103 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ 104 | ID: "evt2", 105 | Projection: HouseWasSold{}, 106 | Args: map[string]any{"address": "123 Main St", "price": 500000}, 107 | }) 108 | 109 | // Process pending events 110 | store.Publish() 111 | 112 | // Wait for all async handlers to finish 113 | if err := store.Drain(context.Background()); err != nil { 114 | log.Fatalf("Failed to drain EventStore: %v", err) 115 | } 116 | 117 | // Retrieve metrics 118 | published, processed, errors := store.Metrics() 119 | fmt.Printf("published=%d processed=%d errors=%d\n", published, processed, errors) 120 | } 121 | ``` 122 | 123 | ## Transactions 124 | 125 | GoEventBus now supports atomic transactions, allowing you to group multiple events and commit them together. This ensures that either all events are successfully published and handled, or none are. 126 | 127 | ```go 128 | package main 129 | 130 | import ( 131 | "context" 132 | "log" 133 | 134 | "github.com/Raezil/GoEventBus" 135 | ) 136 | 137 | func main() { 138 | // Begin a new transaction on the existing EventStore 139 | 140 | // Create a dispatcher mapping projections to handlers 141 | dispatcher := GoEventBus.Dispatcher{ 142 | "user_created": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 143 | return GoEventBus.Result{Message: "handled user_created"}, nil 144 | }, 145 | "send_email": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 146 | log.Println("Hello") 147 | return GoEventBus.Result{Message: "handled send_email"}, nil 148 | }, 149 | } 150 | 151 | // Initialise an EventStore with a 64K ring buffer and DropOldest policy 152 | store := GoEventBus.NewEventStore(&dispatcher, 1<<16, GoEventBus.DropOldest) 153 | tx := store.BeginTransaction() 154 | 155 | // Buffer multiple events 156 | tx.Publish(GoEventBus.Event{ 157 | ID: "evtA", 158 | Projection: "user_created", 159 | Args: map[string]any{"id": "12345"}, 160 | }) 161 | tx.Publish(GoEventBus.Event{ 162 | ID: "evtB", 163 | Projection: "send_email", 164 | Args: map[string]any{"template": "welcome", "userID": "12345"}, 165 | }) 166 | tx.Rollback() 167 | 168 | // Commit the transaction atomically 169 | if err := tx.Commit(context.Background()); err != nil { 170 | log.Fatalf("transaction failed: %v", err) 171 | } 172 | } 173 | ``` 174 | 175 | ## API Reference 176 | 177 | ### `type Result` 178 | 179 | ```go 180 | type Result struct { 181 | Message string // Outcome message from handler 182 | } 183 | ``` 184 | 185 | ### `type Dispatcher` 186 | 187 | ```go 188 | type Dispatcher map[interface{}]func(context.Context, map[string]any) (Result, error) 189 | ``` 190 | A map from projection keys to handler functions. Handlers receive a `context.Context` and an argument map, and return a `Result` and an error. 191 | 192 | ### `type Event` 193 | 194 | ```go 195 | type Event struct { 196 | ID string // Unique identifier for the event 197 | Projection interface{} // Key to look up the handler in the dispatcher 198 | Args map[string]any // Payload data for the event 199 | } 200 | ``` 201 | 202 | ### `type Transaction` 203 | 204 | ```go 205 | type Transaction struct { 206 | store *EventStore 207 | events []Event 208 | startHead uint64 // head position when transaction began 209 | 210 | } 211 | ``` 212 | 213 | - `BeginTransaction() *Transaction`: Start a new transaction. 214 | - `Publish(e Event)`: Buffer an event within the transaction. 215 | - `Commit(ctx context.Context) error`: Atomically enqueue and process all buffered events, returning on the first error. 216 | - `Rollback()`: Discard buffered events without publishing. 217 | 218 | ### `type OverrunPolicy` 219 | 220 | ```go 221 | type OverrunPolicy int 222 | 223 | const ( 224 | DropOldest OverrunPolicy = iota // Default: discard oldest events 225 | Block // Block until space is available 226 | ReturnError // Fail fast with ErrBufferFull 227 | ) 228 | ``` 229 | 230 | ### `type EventStore` 231 | 232 | ```go 233 | type EventStore struct { 234 | dispatcher *Dispatcher // Pointer to the dispatcher map 235 | size uint64 // Buffer size (power of two) 236 | buf []unsafe.Pointer // Ring buffer of event pointers 237 | events []Event // Backing slice for Event data 238 | head uint64 // Atomic write index 239 | tail uint64 // Atomic read index 240 | 241 | // Config flags 242 | Async bool 243 | OverrunPolicy OverrunPolicy 244 | 245 | // Counters 246 | publishedCount uint64 247 | processedCount uint64 248 | errorCount uint64 249 | } 250 | ``` 251 | 252 | #### `NewEventStore` 253 | 254 | ```go 255 | func NewEventStore(dispatcher *Dispatcher, bufferSize uint64, policy OverrunPolicy) *EventStore 256 | ``` 257 | Creates a new `EventStore` with the provided dispatcher, ring buffer size, and overrun policy. 258 | 259 | #### `Subscribe` 260 | 261 | ```go 262 | func (es *EventStore) Subscribe(ctx context.Context, e Event) error 263 | ``` 264 | Atomically enqueues an `Event` for later publication, applying back‑pressure according to `OverrunPolicy`. If `OverrunPolicy` is `ReturnError` and the buffer is full, the function returns `ErrBufferFull`. 265 | 266 | #### `Publish` 267 | 268 | ```go 269 | func (es *EventStore) Publish() 270 | ``` 271 | Dispatches all events from the last published position to the current head. If `Async` is true, handlers run in separate goroutines; otherwise they run in the caller's goroutine. 272 | 273 | #### `Drain` 274 | 275 | ```go 276 | func (es *EventStore) Drain(ctx context.Context) error 277 | ``` 278 | Blocks until all in-flight asynchronous handlers complete, then stops the worker pool. Returns an error if the provided context.Context is canceled or its deadline is exceeded. 279 | 280 | #### `Close` 281 | 282 | ```go 283 | func (es *EventStore) Close(ctx context.Context) error 284 | ``` 285 | Drains all pending asynchronous handlers and shuts down the EventStore. Blocks until all in-flight handlers complete or the provided context.Context is canceled. Returns an error if the context’s deadline is exceeded or it is otherwise canceled. 286 | 287 | #### `Metrics` 288 | 289 | ```go 290 | func (es *EventStore) Metrics() (published, processed, errors uint64) 291 | ``` 292 | Returns the total count of published, processed, and errored events. 293 | 294 | ## Back-pressure and Overrun Policies 295 | 296 | GoEventBus provides three strategies for handling a saturated ring buffer: 297 | 298 | | Policy | Behaviour | When to use | 299 | |--------------|------------------------------------------------------------------------------------------------|----------------------------------------------| 300 | | `DropOldest` | Atomically advances the read index, discarding the oldest event to make room for the new one. | Low‑latency scenarios where the newest data is most valuable and occasional loss is acceptable. | 301 | | `Block` | Causes `Subscribe` to block (respecting its context) until space becomes available. | Workloads that must not lose events but can tolerate the latency of back‑pressure. | 302 | | `ReturnError`| `Subscribe` returns `ErrBufferFull` immediately, allowing the caller to decide what to do. | Pipelines where upstream logic controls retries and failures explicitly. | 303 | 304 | `DropOldest` is the default behaviour and matches releases prior to April 2025. 305 | 306 | ## 💡 Use Cases 307 | 308 | GoEventBus is ideal for scenarios where low‑latency, high‑throughput, and non‑blocking event dispatching is needed: 309 | 310 | - 🔄 Real‑time event pipelines (e.g. analytics, telemetry) 311 | - 📥 Background task execution or job queues 312 | - 🧩 Microservice communication using in‑process events 313 | - ⚙️ Observability/event sourcing in domain‑driven designs 314 | - 🔁 In‑memory pub/sub for small‑scale distributed systems 315 | - 🎮 Game loops or simulations requiring lock‑free dispatching 316 | 317 | ## Benchmarks 318 | 319 | All benchmarks were run with Go’s testing harness (`go test -bench .`) on an `-8` procs configuration. Numbers below are from the April 2025 release. 320 | 321 | | Benchmark | Iterations | ns/op | 322 | |-----------------------------------|-------------:|-------:| 323 | | `BenchmarkSubscribe-8` | 27,080,376 | 40.37 | 324 | | `BenchmarkSubscribeParallel-8` | 26,418,999 | 38.42 | 325 | | `BenchmarkPublish-8` | 295,661,464 | 3.910 | 326 | | `BenchmarkPublishAfterPrefill-8` | 252,943,526 | 4.585 | 327 | | `BenchmarkSubscribeLargePayload-8`| 1,613,017 | 771.5 | 328 | | `BenchmarkPublishLargePayload-8` | 296,434,225 | 3.910 | 329 | | `BenchmarkEventStore_Async-8` | 2,816,988 | 436.5 | 330 | | `BenchmarkEventStore_Sync-8` | 2,638,519 | 428.5 | 331 | | `BenchmarkFastHTTPSync-8` | 6,275,112 | 163.8 | 332 | | `BenchmarkFastHTTPAsync-8` | 1,954,884 | 662.0 | 333 | | `BenchmarkFastHTTPParallel-8` | 4,489,274 | 262.3 | 334 | 335 | ## Contributing 336 | 337 | Contributions, issues, and feature requests are welcome! Feel free to check the [issues page](https://github.com/Raezil/GoEventBus/issues). 338 | 339 | ## License 340 | 341 | Distributed under the MIT License. See `LICENSE` for more information. 342 | 343 | -------------------------------------------------------------------------------- /eventstore.go: -------------------------------------------------------------------------------- 1 | package GoEventBus 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "runtime" 7 | "sync" 8 | "sync/atomic" 9 | "time" 10 | "unsafe" 11 | ) 12 | 13 | // Result represents the outcome of an event handler. 14 | type Result struct { 15 | Message string 16 | } 17 | 18 | // OverrunPolicy defines what happens when the ring buffer is full. 19 | type OverrunPolicy int 20 | 21 | const ( 22 | // DropOldest discards the oldest events when the buffer is full. 23 | DropOldest OverrunPolicy = iota 24 | // Block causes Subscribe to block (respecting ctx) until space is available. 25 | Block 26 | // ReturnError makes Subscribe fail fast with ErrBufferFull. 27 | ReturnError 28 | ) 29 | 30 | // ErrBufferFull is returned by Subscribe when OverrunPolicy==ReturnError and the ring buffer is saturated. 31 | var ErrBufferFull = errors.New("goeventbus: buffer is full") 32 | 33 | const cacheLine = 64 34 | 35 | type pad [cacheLine - unsafe.Sizeof(uint64(0))]byte 36 | 37 | // HandlerFunc is the signature for event handlers and middleware. 38 | type HandlerFunc func(context.Context, map[string]any) (Result, error) 39 | 40 | // Middleware wraps a HandlerFunc, returning a new HandlerFunc. 41 | type Middleware func(HandlerFunc) HandlerFunc 42 | 43 | // Hook types for before, after, and error events. 44 | type BeforeHook func(context.Context, Event) 45 | type AfterHook func(context.Context, Event, Result, error) 46 | type ErrorHook func(context.Context, Event, error) 47 | 48 | // Dispatcher maps event projections to handler functions. 49 | type Dispatcher map[interface{}]HandlerFunc 50 | 51 | // Event is a unit of work to be dispatched. 52 | type Event struct { 53 | ID string 54 | Projection interface{} 55 | Args map[string]any 56 | Ctx context.Context // carried context from Subscribe 57 | } 58 | 59 | // internal work unit for async dispatch 60 | type eventWork struct { 61 | handler HandlerFunc 62 | ev Event 63 | } 64 | 65 | // EventStore is a high-performance, lock-free ring buffer with middleware and hooks support. 66 | type EventStore struct { 67 | dispatcher *Dispatcher 68 | size uint64 69 | buf []atomic.Pointer[Event] // holds *Event pointers safely 70 | events []Event 71 | _ pad 72 | head uint64 // write index 73 | _ pad 74 | tail uint64 // read index 75 | 76 | // Config flags 77 | Async bool 78 | OverrunPolicy OverrunPolicy 79 | 80 | // Middleware chain and hooks 81 | middlewares []Middleware 82 | beforeHooks []BeforeHook 83 | afterHooks []AfterHook 84 | errorHooks []ErrorHook 85 | 86 | // Async worker pool 87 | asyncWorkers int 88 | workCh chan eventWork 89 | wg sync.WaitGroup 90 | shutdownOnce sync.Once 91 | shutdownSignal chan struct{} 92 | 93 | // Counters 94 | publishedCount uint64 95 | processedCount uint64 96 | errorCount uint64 97 | } 98 | 99 | // NewEventStore initializes a new EventStore. It spins up a default worker pool. 100 | func NewEventStore(dispatcher *Dispatcher, bufferSize uint64, policy OverrunPolicy) *EventStore { 101 | if bufferSize&(bufferSize-1) != 0 { 102 | panic("bufferSize must be a power of two") 103 | } 104 | es := &EventStore{ 105 | dispatcher: dispatcher, 106 | size: bufferSize, 107 | buf: make([]atomic.Pointer[Event], bufferSize), 108 | events: make([]Event, bufferSize), 109 | OverrunPolicy: policy, 110 | asyncWorkers: runtime.NumCPU(), 111 | workCh: make(chan eventWork, bufferSize), 112 | shutdownSignal: make(chan struct{}), 113 | } 114 | // start worker pool 115 | for i := 0; i < es.asyncWorkers; i++ { 116 | go es.worker() 117 | } 118 | return es 119 | } 120 | 121 | // worker processes eventWork from the channel until shutdown. 122 | func (es *EventStore) worker() { 123 | for w := range es.workCh { 124 | es.execute(w.handler, w.ev) 125 | es.wg.Done() 126 | } 127 | } 128 | 129 | // Use adds middleware to the EventStore. It will be applied in the order added. 130 | func (es *EventStore) Use(mw Middleware) { 131 | es.middlewares = append(es.middlewares, mw) 132 | } 133 | 134 | // OnBefore registers a hook that runs before each handler invocation. 135 | func (es *EventStore) OnBefore(hook BeforeHook) { 136 | es.beforeHooks = append(es.beforeHooks, hook) 137 | } 138 | 139 | // OnAfter registers a hook that runs after each handler invocation (even on error). 140 | func (es *EventStore) OnAfter(hook AfterHook) { 141 | es.afterHooks = append(es.afterHooks, hook) 142 | } 143 | 144 | // OnError registers a hook that runs only when a handler returns an error. 145 | func (es *EventStore) OnError(hook ErrorHook) { 146 | es.errorHooks = append(es.errorHooks, hook) 147 | } 148 | 149 | // Subscribe enqueues an Event, applying back-pressure according to OverrunPolicy. 150 | func (es *EventStore) Subscribe(ctx context.Context, e Event) error { 151 | // record caller context 152 | e.Ctx = ctx 153 | for { 154 | head := atomic.LoadUint64(&es.head) 155 | tail := atomic.LoadUint64(&es.tail) 156 | if head-tail < es.size { 157 | idx := atomic.AddUint64(&es.head, 1) - 1 158 | slot := idx & (es.size - 1) 159 | evPtr := &es.events[slot] 160 | *evPtr = e 161 | es.buf[slot].Store(evPtr) 162 | atomic.AddUint64(&es.publishedCount, 1) 163 | return nil 164 | } 165 | // buffer full – resolve based on policy 166 | switch es.OverrunPolicy { 167 | case DropOldest: 168 | atomic.AddUint64(&es.tail, 1) 169 | continue 170 | case ReturnError: 171 | return ErrBufferFull 172 | case Block: 173 | runtime.Gosched() 174 | select { 175 | case <-ctx.Done(): 176 | return ctx.Err() 177 | case <-time.After(10 * time.Microsecond): 178 | } 179 | } 180 | } 181 | } 182 | 183 | // Publish processes all pending events, applying middleware and hooks. 184 | func (es *EventStore) Publish() { 185 | head := atomic.LoadUint64(&es.head) 186 | tail := atomic.LoadUint64(&es.tail) 187 | if tail == head { 188 | return 189 | } 190 | 191 | disp := *es.dispatcher 192 | mask := es.size - 1 193 | 194 | for i := tail; i < head; i++ { 195 | p := es.buf[i&mask].Load() 196 | if p == nil { 197 | continue 198 | } 199 | ev := *p 200 | if handler, ok := disp[ev.Projection]; ok { 201 | if es.Async { 202 | es.wg.Add(1) 203 | select { 204 | case es.workCh <- eventWork{handler, ev}: 205 | case <-es.shutdownSignal: 206 | es.wg.Done() 207 | } 208 | } else { 209 | es.execute(handler, ev) 210 | } 211 | } 212 | } 213 | atomic.StoreUint64(&es.tail, head) 214 | } 215 | 216 | // execute runs the handler with middleware and hooks. 217 | func (es *EventStore) execute(h HandlerFunc, ev Event) { 218 | // pick up recorded context 219 | ctx := ev.Ctx 220 | if ctx == nil { 221 | ctx = context.Background() 222 | } 223 | // override with explicit __ctx if set 224 | if c, ok := ev.Args["__ctx"].(context.Context); ok && c != nil { 225 | ctx = c 226 | } 227 | 228 | for _, hook := range es.beforeHooks { 229 | hook(ctx, ev) 230 | } 231 | wrapped := h 232 | for i := len(es.middlewares) - 1; i >= 0; i-- { 233 | wrapped = es.middlewares[i](wrapped) 234 | } 235 | res, err := wrapped(ctx, ev.Args) 236 | atomic.AddUint64(&es.processedCount, 1) 237 | 238 | for _, hook := range es.afterHooks { 239 | hook(ctx, ev, res, err) 240 | } 241 | if err != nil { 242 | atomic.AddUint64(&es.errorCount, 1) 243 | for _, hook := range es.errorHooks { 244 | hook(ctx, ev, err) 245 | } 246 | } 247 | } 248 | 249 | // Drain waits for all in-flight async handlers to complete, stopping new dispatch. 250 | func (es *EventStore) Drain(ctx context.Context) error { 251 | es.shutdownOnce.Do(func() { 252 | close(es.shutdownSignal) 253 | close(es.workCh) 254 | }) 255 | done := make(chan struct{}) 256 | go func() { 257 | es.wg.Wait() 258 | close(done) 259 | }() 260 | select { 261 | case <-done: 262 | return nil 263 | case <-ctx.Done(): 264 | return ctx.Err() 265 | } 266 | } 267 | 268 | // Close drains all pending async events and shuts down the EventStore. 269 | func (es *EventStore) Close(ctx context.Context) error { 270 | return es.Drain(ctx) 271 | } 272 | 273 | // Metrics returns snapshot counters. 274 | func (es *EventStore) Metrics() (published, processed, errors uint64) { 275 | return atomic.LoadUint64(&es.publishedCount), 276 | atomic.LoadUint64(&es.processedCount), 277 | atomic.LoadUint64(&es.errorCount) 278 | } 279 | -------------------------------------------------------------------------------- /eventstore_test.go: -------------------------------------------------------------------------------- 1 | package GoEventBus 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "strconv" 7 | "sync" 8 | "sync/atomic" 9 | "testing" 10 | "time" 11 | 12 | "github.com/valyala/fasthttp" 13 | ) 14 | 15 | const size = 1 << 16 16 | 17 | // helper context value 18 | var bg = context.Background() 19 | 20 | // TestSubscribeAndPublish verifies that events are stored and published correctly. 21 | func TestSubscribeAndPublish(t *testing.T) { 22 | dispatcher := Dispatcher{} 23 | var called1, called2 int32 24 | dispatcher["evt1"] = func(_ context.Context, args map[string]any) (Result, error) { 25 | atomic.AddInt32(&called1, 1) 26 | return Result{Message: "ok1"}, nil 27 | } 28 | dispatcher["evt2"] = func(_ context.Context, args map[string]any) (Result, error) { 29 | atomic.AddInt32(&called2, 1) 30 | return Result{Message: "ok2"}, nil 31 | } 32 | 33 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 34 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "evt1", Args: nil}) 35 | _ = es.Subscribe(bg, Event{ID: "2", Projection: "evt2", Args: nil}) 36 | 37 | es.Publish() 38 | 39 | if called1 != 1 { 40 | t.Errorf("handler evt1 called %d times; want 1", called1) 41 | } 42 | if called2 != 1 { 43 | t.Errorf("handler evt2 called %d times; want 1", called2) 44 | } 45 | } 46 | 47 | // TestPublishWithMissingHandler ensures no panic when a handler is missing. 48 | func TestPublishWithMissingHandler(t *testing.T) { 49 | dispatcher := Dispatcher{} 50 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 51 | _ = es.Subscribe(bg, Event{ID: "3", Projection: "unknown", Args: nil}) 52 | es.Publish() // should not panic 53 | } 54 | 55 | // TestPublishMixedExistingAndNonExisting ensures missing projections don't affect existing handlers. 56 | func TestPublishMixedExistingAndNonExisting(t *testing.T) { 57 | dispatcher := Dispatcher{} 58 | var called int32 59 | dispatcher["evt"] = func(_ context.Context, args map[string]any) (Result, error) { 60 | atomic.AddInt32(&called, 1) 61 | return Result{}, nil 62 | } 63 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 64 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "evt", Args: nil}) 65 | _ = es.Subscribe(bg, Event{ID: "2", Projection: "noexist", Args: nil}) 66 | es.Publish() 67 | 68 | if called != 1 { 69 | t.Errorf("handler called %d times; want 1", called) 70 | } 71 | } 72 | 73 | // TestOverflowBehavior ensures that when more events than buffer size are enqueued, the oldest events are dropped. 74 | func TestOverflowBehavior(t *testing.T) { 75 | dispatcher := Dispatcher{} 76 | var count uint64 77 | dispatcher["evtOverflow"] = func(_ context.Context, args map[string]any) (Result, error) { 78 | atomic.AddUint64(&count, 1) 79 | return Result{}, nil 80 | } 81 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 82 | for i := 0; i < size+100; i++ { 83 | _ = es.Subscribe(bg, Event{ID: "o", Projection: "evtOverflow", Args: nil}) 84 | } 85 | es.Publish() 86 | if count != size { 87 | t.Errorf("overflow: got %d events; want %d", count, size) 88 | } 89 | } 90 | 91 | // TestOverflowReturnError ensures ReturnError policy fails fast. 92 | func TestOverflowReturnError(t *testing.T) { 93 | dispatcher := Dispatcher{} 94 | es := NewEventStore(&dispatcher, 8, ReturnError) // small buffer 95 | for i := 0; i < 8; i++ { 96 | if err := es.Subscribe(bg, Event{ID: strconv.Itoa(i), Projection: "x", Args: nil}); err != nil { 97 | t.Fatalf("unexpected error pre-fill: %v", err) 98 | } 99 | } 100 | if err := es.Subscribe(bg, Event{ID: "9", Projection: "x", Args: nil}); err != ErrBufferFull { 101 | t.Errorf("expected ErrBufferFull; got %v", err) 102 | } 103 | } 104 | 105 | // TestConcurrentSubscribe ensures safety of concurrent subscriptions. 106 | func TestConcurrentSubscribe(t *testing.T) { 107 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 108 | var count uint64 109 | dispatcher["evt"] = func(_ context.Context, args map[string]any) (Result, error) { 110 | atomic.AddUint64(&count, 1) 111 | return Result{}, nil 112 | } 113 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 114 | var wg sync.WaitGroup 115 | const n = 1000 116 | wg.Add(n) 117 | for i := 0; i < n; i++ { 118 | go func() { 119 | _ = es.Subscribe(bg, Event{ID: "c", Projection: "evt", Args: nil}) 120 | wg.Done() 121 | }() 122 | } 123 | wg.Wait() 124 | es.Publish() 125 | 126 | if count != n { 127 | t.Errorf("concurrent subscribe: got %d events; want %d", count, n) 128 | } 129 | } 130 | 131 | // Benchmarks -------------------------------------------------------------- 132 | 133 | func BenchmarkSubscribe(b *testing.B) { 134 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 135 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 136 | b.ResetTimer() 137 | for i := 0; i < b.N; i++ { 138 | _ = es.Subscribe(bg, Event{ID: "bench", Projection: "evt", Args: nil}) 139 | } 140 | } 141 | 142 | func BenchmarkSubscribeParallel(b *testing.B) { 143 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 144 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 145 | b.RunParallel(func(pb *testing.PB) { 146 | for pb.Next() { 147 | _ = es.Subscribe(bg, Event{ID: "pp", Projection: "evt", Args: nil}) 148 | } 149 | }) 150 | } 151 | 152 | func BenchmarkPublish(b *testing.B) { 153 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 154 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 155 | for i := 0; i < size; i++ { 156 | _ = es.Subscribe(bg, Event{ID: "p", Projection: "evt", Args: nil}) 157 | } 158 | b.ResetTimer() 159 | for i := 0; i < b.N; i++ { 160 | es.Publish() 161 | } 162 | } 163 | 164 | func BenchmarkPublishAfterPrefill(b *testing.B) { 165 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 166 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 167 | for i := 0; i < size; i++ { 168 | _ = es.Subscribe(bg, Event{ID: "pp", Projection: "evt", Args: nil}) 169 | } 170 | b.ResetTimer() 171 | for i := 0; i < b.N; i++ { 172 | es.Publish() 173 | } 174 | } 175 | 176 | // Large payload benchmarks remain mostly unchanged but updated API 177 | 178 | // LargeStruct is a sample struct for payload-heavy benchmarks. 179 | type LargeStruct struct { 180 | Data [1024]byte 181 | } 182 | 183 | func BenchmarkSubscribeLargePayload(b *testing.B) { 184 | dispatcher := Dispatcher{"evtLarge": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 185 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 186 | var payload LargeStruct 187 | 188 | b.ResetTimer() 189 | for i := 0; i < b.N; i++ { 190 | _ = es.Subscribe(bg, Event{ID: "bench", Projection: "evtLarge", Args: map[string]any{"payload": payload}}) 191 | } 192 | } 193 | 194 | func BenchmarkPublishLargePayload(b *testing.B) { 195 | dispatcher := Dispatcher{"evtLarge": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 196 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 197 | var payload LargeStruct 198 | const largeSize = 100 199 | for i := 0; i < largeSize; i++ { 200 | _ = es.Subscribe(bg, Event{ID: "bench", Projection: "evtLarge", Args: map[string]any{"payload": payload}}) 201 | } 202 | b.ResetTimer() 203 | for i := 0; i < b.N; i++ { 204 | es.Publish() 205 | } 206 | } 207 | 208 | // Additional tests for exact buffer behaviour 209 | func TestExactBufferSizeNoOverflow(t *testing.T) { 210 | dispatcher := Dispatcher{} 211 | var count uint64 212 | dispatcher["evtExact"] = func(_ context.Context, args map[string]any) (Result, error) { 213 | atomic.AddUint64(&count, 1) 214 | return Result{}, nil 215 | } 216 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 217 | for i := 0; i < size; i++ { 218 | _ = es.Subscribe(bg, Event{ID: strconv.Itoa(i), Projection: "evtExact", Args: nil}) 219 | } 220 | es.Publish() 221 | if count != size { 222 | t.Errorf("no-overflow: got %d calls; want %d", count, size) 223 | } 224 | } 225 | 226 | func TestOverflowThreshold(t *testing.T) { 227 | dispatcher := Dispatcher{} 228 | var count uint64 229 | dispatcher["evtThresh"] = func(_ context.Context, args map[string]any) (Result, error) { 230 | atomic.AddUint64(&count, 1) 231 | return Result{}, nil 232 | } 233 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 234 | for i := 0; i < size+1; i++ { 235 | _ = es.Subscribe(bg, Event{ID: strconv.Itoa(i), Projection: "evtThresh", Args: nil}) 236 | } 237 | es.Publish() 238 | if count != size { 239 | t.Errorf("threshold-overflow: got %d calls; want %d", count, size) 240 | } 241 | } 242 | 243 | func TestPublishIdempotent(t *testing.T) { 244 | dispatcher := Dispatcher{} 245 | var called int32 246 | dispatcher["evtOnce"] = func(_ context.Context, args map[string]any) (Result, error) { 247 | atomic.AddInt32(&called, 1) 248 | return Result{}, nil 249 | } 250 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 251 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "evtOnce", Args: nil}) 252 | es.Publish() 253 | es.Publish() 254 | if called != 1 { 255 | t.Errorf("idempotent publish: got %d calls; want 1", called) 256 | } 257 | } 258 | 259 | func TestEventStore_AsyncDispatch(t *testing.T) { 260 | var mu sync.Mutex 261 | called := 0 262 | 263 | dispatcher := Dispatcher{ 264 | "print": func(_ context.Context, args map[string]any) (Result, error) { 265 | mu.Lock() 266 | defer mu.Unlock() 267 | called++ 268 | return Result{Message: "ok"}, nil 269 | }, 270 | } 271 | 272 | store := NewEventStore(&dispatcher, 1<<16, DropOldest) 273 | store.Async = true 274 | 275 | for i := 0; i < 10; i++ { 276 | _ = store.Subscribe(bg, Event{ID: "e1", Projection: "print", Args: map[string]any{"data": i}}) 277 | } 278 | 279 | store.Publish() 280 | time.Sleep(100 * time.Millisecond) 281 | 282 | mu.Lock() 283 | defer mu.Unlock() 284 | if called != 10 { 285 | t.Errorf("Expected 10 calls, got %d", called) 286 | } 287 | } 288 | 289 | func BenchmarkEventStore_Async(b *testing.B) { 290 | dispatcher := Dispatcher{"async": func(_ context.Context, args map[string]any) (Result, error) { return Result{Message: "done"}, nil }} 291 | store := NewEventStore(&dispatcher, 1<<16, DropOldest) 292 | store.Async = true 293 | for i := 0; i < b.N; i++ { 294 | _ = store.Subscribe(bg, Event{ID: "event", Projection: "async", Args: map[string]any{"n": i}}) 295 | } 296 | store.Publish() 297 | } 298 | 299 | func BenchmarkEventStore_Sync(b *testing.B) { 300 | dispatcher := Dispatcher{"sync": func(_ context.Context, args map[string]any) (Result, error) { return Result{Message: "done"}, nil }} 301 | store := NewEventStore(&dispatcher, 1<<16, DropOldest) 302 | store.Async = false 303 | for i := 0; i < b.N; i++ { 304 | _ = store.Subscribe(bg, Event{ID: "event", Projection: "sync", Args: map[string]any{"n": i}}) 305 | } 306 | store.Publish() 307 | } 308 | 309 | // FastHTTP benchmarks updated for new API 310 | func benchmarkFastHTTP(b *testing.B, async bool) { 311 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 312 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 313 | es.Async = async 314 | 315 | handler := func(ctx *fasthttp.RequestCtx) { 316 | _ = es.Subscribe(bg, Event{ID: "bench", Projection: "evt", Args: nil}) 317 | es.Publish() 318 | } 319 | 320 | b.ResetTimer() 321 | for i := 0; i < b.N; i++ { 322 | var ctx fasthttp.RequestCtx 323 | handler(&ctx) 324 | } 325 | } 326 | 327 | func BenchmarkFastHTTPSync(b *testing.B) { benchmarkFastHTTP(b, false) } 328 | func BenchmarkFastHTTPAsync(b *testing.B) { benchmarkFastHTTP(b, true) } 329 | 330 | func BenchmarkFastHTTPParallel(b *testing.B) { 331 | dispatcher := Dispatcher{"evt": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 332 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 333 | es.Async = true 334 | 335 | handler := func(ctx *fasthttp.RequestCtx) { 336 | _ = es.Subscribe(bg, Event{ID: "bench", Projection: "evt", Args: nil}) 337 | es.Publish() 338 | } 339 | 340 | b.RunParallel(func(pb *testing.PB) { 341 | for pb.Next() { 342 | var ctx fasthttp.RequestCtx 343 | handler(&ctx) 344 | } 345 | }) 346 | } 347 | 348 | // TestPublishEmpty ensures Publish on empty store does nothing 349 | func TestPublishEmpty(t *testing.T) { 350 | dispatcher := Dispatcher{} 351 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 352 | initialHead, initialTail := es.head, es.tail 353 | es.Publish() 354 | if es.head != initialHead || es.tail != initialTail { 355 | t.Errorf("counters changed: head %d->%d tail %d->%d", initialHead, es.head, initialTail, es.tail) 356 | } 357 | } 358 | 359 | // TestArgsPassing ensures arguments are passed through 360 | func TestArgsPassing(t *testing.T) { 361 | dispatcher := Dispatcher{} 362 | var received string 363 | dispatcher["echo"] = func(_ context.Context, args map[string]any) (Result, error) { 364 | received = args["foo"].(string) 365 | return Result{}, nil 366 | } 367 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 368 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "echo", Args: map[string]any{"foo": "bar"}}) 369 | es.Publish() 370 | if received != "bar" { 371 | t.Errorf("expected 'bar'; got '%s'", received) 372 | } 373 | } 374 | 375 | func TestDispatcherSnapshot(t *testing.T) { 376 | dispatcher := Dispatcher{} 377 | var calledOriginal, calledModified int32 378 | dispatcher["snap"] = func(_ context.Context, args map[string]any) (Result, error) { 379 | atomic.AddInt32(&calledOriginal, 1) 380 | return Result{}, nil 381 | } 382 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 383 | // swap handler 384 | dispatcher["snap"] = func(_ context.Context, args map[string]any) (Result, error) { 385 | atomic.AddInt32(&calledModified, 1) 386 | return Result{}, nil 387 | } 388 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "snap", Args: nil}) 389 | es.Publish() 390 | if calledOriginal != 0 { 391 | t.Errorf("original handler called %d", calledOriginal) 392 | } 393 | if calledModified != 1 { 394 | t.Errorf("modified handler should be called once; got %d", calledModified) 395 | } 396 | } 397 | 398 | func TestEventStore_Metrics(t *testing.T) { 399 | dispatcher := Dispatcher{"metric": func(_ context.Context, args map[string]any) (Result, error) { return Result{}, nil }} 400 | es := NewEventStore(&dispatcher, 1<<16, DropOldest) 401 | _ = es.Subscribe(bg, Event{ID: "1", Projection: "metric", Args: nil}) 402 | _ = es.Subscribe(bg, Event{ID: "2", Projection: "metric", Args: nil}) 403 | 404 | published, processed, errors := es.Metrics() 405 | if published != 2 || processed != 0 || errors != 0 { 406 | t.Fatalf("before publish: got %d %d %d", published, processed, errors) 407 | } 408 | es.Publish() 409 | published, processed, errors = es.Metrics() 410 | if published != 2 || processed != 2 || errors != 0 { 411 | t.Fatalf("after publish: got %d %d %d", published, processed, errors) 412 | } 413 | } 414 | 415 | // helper no‑op handler that increments a counter so we know it was invoked. 416 | func noopHandler(counter *uint64) func(context.Context, map[string]any) (Result, error) { 417 | return func(ctx context.Context, args map[string]any) (Result, error) { 418 | atomic.AddUint64(counter, 1) 419 | return Result{Message: "ok"}, nil 420 | } 421 | } 422 | 423 | // TestMetricsCounts ensures that the published/processed/error counters are accurate. 424 | func TestMetricsCounts(t *testing.T) { 425 | var invoked uint64 426 | disp := Dispatcher{"test": noopHandler(&invoked)} 427 | es := NewEventStore(&disp, 8, DropOldest) 428 | 429 | // publish 5 successful events 430 | for i := 0; i < 5; i++ { 431 | if err := es.Subscribe(context.Background(), Event{ID: "e", Projection: "test", Args: map[string]any{}}); err != nil { 432 | t.Fatalf("unexpected Subscribe error: %v", err) 433 | } 434 | } 435 | 436 | es.Publish() 437 | 438 | pub, proc, errCnt := es.Metrics() 439 | if pub != 5 || proc != 5 || errCnt != 0 { 440 | t.Fatalf("unexpected metrics: published=%d processed=%d errors=%d", pub, proc, errCnt) 441 | } 442 | if atomic.LoadUint64(&invoked) != 5 { 443 | t.Fatalf("handler invoked %d times, want 5", invoked) 444 | } 445 | } 446 | 447 | // TestOverrunPolicyReturnError verifies that Subscribe returns ErrBufferFull 448 | // when the buffer is full and policy is ReturnError. 449 | func TestOverrunPolicyReturnError(t *testing.T) { 450 | disp := Dispatcher{} 451 | es := NewEventStore(&disp, 2, ReturnError) 452 | 453 | // fill buffer 454 | _ = es.Subscribe(context.Background(), Event{}) 455 | _ = es.Subscribe(context.Background(), Event{}) 456 | 457 | if err := es.Subscribe(context.Background(), Event{}); err != ErrBufferFull { 458 | t.Fatalf("expected ErrBufferFull, got %v", err) 459 | } 460 | } 461 | 462 | // BenchmarkPublish measures throughput of synchronous vs asynchronous Publish. 463 | func BenchmarkSubscribePublish(b *testing.B) { 464 | bench := func(async bool) { 465 | var invoked uint64 466 | disp := Dispatcher{"bench": noopHandler(&invoked)} 467 | es := NewEventStore(&disp, 1024, DropOldest) 468 | es.Async = async 469 | ctx := context.Background() 470 | 471 | b.ResetTimer() 472 | for i := 0; i < b.N; i++ { 473 | _ = es.Subscribe(ctx, Event{Projection: "bench"}) 474 | es.Publish() 475 | } 476 | b.StopTimer() 477 | 478 | // wait for async goroutines to finish to avoid leaking 479 | if async { 480 | time.Sleep(10 * time.Millisecond) 481 | } 482 | } 483 | 484 | b.Run("Sync", func(b *testing.B) { bench(false) }) 485 | b.Run("Async", func(b *testing.B) { bench(true) }) 486 | } 487 | 488 | // TestContextPropagation verifies that a context injected through Args["__ctx"] 489 | // is forwarded to the handler. 490 | func TestContextPropagation(t *testing.T) { 491 | const key, val = "myKey", "myVal" 492 | 493 | // prepare a context with a distinctive value 494 | ctx := context.WithValue(context.Background(), key, val) 495 | 496 | var received string 497 | disp := Dispatcher{ 498 | "ctx": func(c context.Context, _ map[string]any) (Result, error) { 499 | if v, ok := c.Value(key).(string); ok { 500 | received = v 501 | } 502 | return Result{}, nil 503 | }, 504 | } 505 | 506 | es := NewEventStore(&disp, 8, DropOldest) 507 | // inject ctx via the reserved "__ctx" argument key 508 | _ = es.Subscribe(context.Background(), Event{ID: "1", Projection: "ctx", Args: map[string]any{"__ctx": ctx}}) 509 | es.Publish() 510 | 511 | if received != val { 512 | t.Fatalf("context value mismatch: want %q got %q", val, received) 513 | } 514 | } 515 | 516 | // TestOverrunPolicyBlockRespectsContext ensures that Subscribe returns the 517 | // caller's context error when the buffer remains full beyond the deadline. 518 | func TestOverrunPolicyBlockRespectsContext(t *testing.T) { 519 | disp := Dispatcher{} 520 | es := NewEventStore(&disp, 2, Block) // intentionally small buffer 521 | 522 | // pre‑fill to capacity so subsequent Subscribe must block 523 | _ = es.Subscribe(context.Background(), Event{}) 524 | _ = es.Subscribe(context.Background(), Event{}) 525 | 526 | ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) 527 | defer cancel() 528 | 529 | start := time.Now() 530 | err := es.Subscribe(ctx, Event{}) 531 | elapsed := time.Since(start) 532 | 533 | if err == nil { 534 | t.Fatalf("expected error, got nil") 535 | } 536 | if !errors.Is(err, context.DeadlineExceeded) { 537 | t.Fatalf("expected context deadline exceeded, got %v", err) 538 | } 539 | if elapsed < 40*time.Millisecond { 540 | t.Fatalf("Subscribe returned too early: elapsed %v < ctx timeout", elapsed) 541 | } 542 | } 543 | 544 | // TestErrorMetrics verifies that handler failures are reflected in Metrics(). 545 | func TestErrorMetrics(t *testing.T) { 546 | disp := Dispatcher{"boom": func(_ context.Context, _ map[string]any) (Result, error) { 547 | return Result{}, errors.New("boom") 548 | }} 549 | es := NewEventStore(&disp, 4, DropOldest) 550 | 551 | _ = es.Subscribe(context.Background(), Event{ID: "e", Projection: "boom"}) 552 | es.Publish() 553 | 554 | pub, proc, errs := es.Metrics() 555 | if pub != 1 || proc != 1 || errs != 1 { 556 | t.Fatalf("unexpected metrics – published=%d processed=%d errors=%d", pub, proc, errs) 557 | } 558 | } 559 | 560 | // ----------------------------------------------------------------------------- 561 | // Micro‑benchmarks for Block policy and error‑heavy workloads. 562 | // ----------------------------------------------------------------------------- 563 | 564 | func BenchmarkSubscribeBlockPolicy(b *testing.B) { 565 | disp := Dispatcher{} 566 | es := NewEventStore(&disp, 1024, Block) 567 | 568 | // Fill the buffer to force Subscribe to exercise the Block path. 569 | for i := 0; i < 1024; i++ { 570 | _ = es.Subscribe(context.Background(), Event{}) 571 | } 572 | 573 | b.ResetTimer() 574 | for i := 0; i < b.N; i++ { 575 | // use an already‑expired context so the call returns immediately via the Block path 576 | ctx, cancel := context.WithCancel(context.Background()) 577 | cancel() 578 | _ = es.Subscribe(ctx, Event{}) 579 | } 580 | } 581 | 582 | func BenchmarkPublishWithErrors(b *testing.B) { 583 | disp := Dispatcher{"err": func(_ context.Context, _ map[string]any) (Result, error) { return Result{}, errors.New("fail") }} 584 | es := NewEventStore(&disp, 1<<16, DropOldest) 585 | 586 | // pre‑populate with events that will all fail 587 | for i := 0; i < 1<<16; i++ { 588 | _ = es.Subscribe(context.Background(), Event{ID: "e", Projection: "err"}) 589 | } 590 | 591 | b.ResetTimer() 592 | for i := 0; i < b.N; i++ { 593 | es.Publish() 594 | } 595 | } 596 | 597 | // Test basic Subscribe and Publish functionality in synchronous mode. 598 | func TestEventStore_SubscribePublish_Sync(t *testing.T) { 599 | disp := Dispatcher{} 600 | // simple echo handler 601 | disp["echo"] = func(ctx context.Context, args map[string]any) (Result, error) { 602 | return Result{Message: args["msg"].(string)}, nil 603 | } 604 | store := NewEventStore(&disp, 8, DropOldest) 605 | e := Event{ID: "1", Projection: "echo", Args: map[string]any{"msg": "hello"}} 606 | if err := store.Subscribe(context.Background(), e); err != nil { 607 | t.Fatalf("Subscribe failed: %v", err) 608 | } 609 | store.Publish() 610 | pub, proc, errs := store.Metrics() 611 | if pub != 1 || proc != 1 || errs != 0 { 612 | t.Errorf("Metrics mismatch: published=%d, processed=%d, errors=%d", pub, proc, errs) 613 | } 614 | } 615 | 616 | // Test middleware chaining. 617 | func TestEventStore_Middleware(t *testing.T) { 618 | disp := Dispatcher{} 619 | disp["inc"] = func(ctx context.Context, args map[string]any) (Result, error) { 620 | // return current value 621 | return Result{Message: ""}, nil 622 | } 623 | store := NewEventStore(&disp, 8, DropOldest) 624 | // middleware increments counter before handler 625 | store.Use(func(next HandlerFunc) HandlerFunc { 626 | return func(ctx context.Context, args map[string]any) (Result, error) { 627 | args["cnt"] = args["cnt"].(int) + 1 628 | return next(ctx, args) 629 | } 630 | }) 631 | e := Event{ID: "1", Projection: "inc", Args: map[string]any{"cnt": 0}} 632 | if err := store.Subscribe(context.Background(), e); err != nil { 633 | t.Fatalf("Subscribe failed: %v", err) 634 | } 635 | store.Publish() 636 | // after middleware, cnt should be 1 637 | if e.Args["cnt"].(int) != 1 { 638 | t.Errorf("Middleware did not run, cnt=%v", e.Args["cnt"]) 639 | } 640 | } 641 | 642 | // Test hooks invocation order and error hooks. 643 | func TestEventStore_Hooks(t *testing.T) { 644 | disp := Dispatcher{} 645 | errorMsg := "handler error" 646 | disp["fail"] = func(ctx context.Context, args map[string]any) (Result, error) { 647 | return Result{}, errors.New(errorMsg) 648 | } 649 | store := NewEventStore(&disp, 8, DropOldest) 650 | 651 | var beforeCalled, afterCalled, errorCalled atomic.Bool 652 | 653 | store.OnBefore(func(ctx context.Context, ev Event) { 654 | beforeCalled.Store(true) 655 | }) 656 | store.OnAfter(func(ctx context.Context, ev Event, res Result, err error) { 657 | afterCalled.Store(true) 658 | }) 659 | store.OnError(func(ctx context.Context, ev Event, err error) { 660 | errorCalled.Store(true) 661 | }) 662 | 663 | e := Event{ID: "1", Projection: "fail", Args: map[string]any{}} 664 | _ = store.Subscribe(context.Background(), e) 665 | store.Publish() 666 | 667 | if !beforeCalled.Load() { 668 | t.Error("Before hook not called") 669 | } 670 | if !afterCalled.Load() { 671 | t.Error("After hook not called") 672 | } 673 | if !errorCalled.Load() { 674 | t.Error("Error hook not called") 675 | } 676 | } 677 | 678 | func TestEventStore_SubscribePublishDrainMetrics(t *testing.T) { 679 | var processed atomic.Uint64 680 | dispatcher := Dispatcher{ 681 | "testEvent": func(ctx context.Context, args map[string]any) (Result, error) { 682 | processed.Add(1) 683 | return Result{Message: "ok"}, nil 684 | }, 685 | } 686 | store := NewEventStore(&dispatcher, 16, DropOldest) 687 | store.Async = true 688 | 689 | // Subscribe multiple events 690 | for i := 0; i < 5; i++ { 691 | err := store.Subscribe(context.Background(), Event{ 692 | ID: "evt" + strconv.Itoa(i), 693 | Projection: "testEvent", 694 | Args: nil, 695 | }) 696 | if err != nil { 697 | t.Fatalf("Subscribe failed: %v", err) 698 | } 699 | } 700 | 701 | // Check metrics after Subscribe 702 | published, processedCount, errorCount := store.Metrics() 703 | if published != 5 || processedCount != 0 || errorCount != 0 { 704 | t.Errorf("after subscribe: published=%d processed=%d errors=%d", published, processedCount, errorCount) 705 | } 706 | 707 | // Publish events 708 | store.Publish() 709 | 710 | // Drain to wait for async handlers to finish 711 | if err := store.Drain(context.Background()); err != nil { 712 | t.Fatalf("Drain failed: %v", err) 713 | } 714 | 715 | // Check final metrics 716 | published, processedCount, errorCount = store.Metrics() 717 | if published != 5 || processedCount != 5 || errorCount != 0 { 718 | t.Errorf("after drain: published=%d processed=%d errors=%d", published, processedCount, errorCount) 719 | } 720 | 721 | // Check processed counter 722 | if processed.Load() != 5 { 723 | t.Errorf("expected 5 events processed, got %d", processed.Load()) 724 | } 725 | } 726 | 727 | // noOpHandler is a dummy handler for benchmarks. 728 | func noOpHandler(ctx context.Context, args map[string]any) (Result, error) { 729 | return Result{}, nil 730 | } 731 | 732 | // setupEventStore initializes an EventStore with the given async flag and buffer size. 733 | func setupEventStore(async bool, bufferSize uint64) *EventStore { 734 | disp := Dispatcher{"test": noOpHandler} 735 | es := NewEventStore(&disp, bufferSize, DropOldest) 736 | es.Async = async 737 | return es 738 | } 739 | 740 | // BenchmarkDrainSync measures the performance of Drain on a synchronous EventStore. 741 | func BenchmarkDrainSync(b *testing.B) { 742 | // Prepare a store with a batch of events 743 | es := setupEventStore(false, 1024) 744 | for i := 0; i < 1000; i++ { 745 | es.Subscribe(context.Background(), Event{Projection: "test", Args: map[string]any{}}) 746 | } 747 | es.Publish() 748 | 749 | b.ResetTimer() 750 | for i := 0; i < b.N; i++ { 751 | // In sync mode, Drain should return immediately (no-op) 752 | es.Drain(context.Background()) 753 | } 754 | } 755 | 756 | // BenchmarkDrainAsync measures the performance of Drain on an asynchronous EventStore. 757 | // It uses StopTimer/StartTimer to exclude setup work (subscribe and publish) from timing. 758 | func BenchmarkDrainAsync(b *testing.B) { 759 | for i := 0; i < b.N; i++ { 760 | // Setup a fresh async store 761 | es := setupEventStore(true, 1024) 762 | 763 | // Enqueue events and publish outside timed section 764 | b.StopTimer() 765 | for j := 0; j < 1000; j++ { 766 | es.Subscribe(context.Background(), Event{Projection: "test", Args: map[string]any{}}) 767 | } 768 | es.Publish() 769 | 770 | // Time only the Drain call 771 | b.StartTimer() 772 | es.Drain(context.Background()) 773 | } 774 | } 775 | -------------------------------------------------------------------------------- /examples/drop_oldest/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/Raezil/GoEventBus" 9 | ) 10 | 11 | // OverrunPolicy=DropOldest silently discards events. 12 | func main() { 13 | dispatcher := GoEventBus.Dispatcher{ 14 | "noop": func(ctx context.Context, _ map[string]any) (GoEventBus.Result, error) { 15 | time.Sleep(80 * time.Millisecond) 16 | return GoEventBus.Result{}, nil 17 | }, 18 | } 19 | store := GoEventBus.NewEventStore(&dispatcher, 2, GoEventBus.DropOldest) 20 | 21 | for i := 0; i < 5; i++ { 22 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ 23 | ID: fmt.Sprintf("D-%d", i), 24 | Projection: "noop", 25 | }) 26 | } 27 | 28 | store.Publish() 29 | time.Sleep(200 * time.Millisecond) 30 | 31 | pub, proc, errs := store.Metrics() 32 | fmt.Printf("published=%d processed=%d errors=%d\n", pub, proc, errs) 33 | } 34 | -------------------------------------------------------------------------------- /examples/fasthttp/main.go: -------------------------------------------------------------------------------- 1 | // main.go 2 | package main 3 | 4 | import ( 5 | "context" 6 | "fmt" 7 | "log" 8 | "strconv" 9 | "time" 10 | 11 | "github.com/Raezil/GoEventBus" 12 | "github.com/fasthttp/router" 13 | "github.com/valyala/fasthttp" 14 | ) 15 | 16 | func main() { 17 | // 1) Setup your dispatcher 18 | dispatcher := GoEventBus.Dispatcher{ 19 | "sayHello": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 20 | fmt.Printf("[%s] Hello, %s!\n", 21 | time.Now().Format(time.StampMilli), 22 | args["name"], 23 | ) 24 | return GoEventBus.Result{}, nil 25 | }, 26 | "computeSum": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 27 | a := args["a"].(int) 28 | b := args["b"].(int) 29 | sum := a + b 30 | fmt.Printf("[%s] %d + %d = %d\n", 31 | time.Now().Format(time.StampMilli), 32 | a, b, sum, 33 | ) 34 | return GoEventBus.Result{Message: strconv.Itoa(sum)}, nil 35 | }, 36 | } 37 | 38 | // 2) Create the EventStore 39 | store := GoEventBus.NewEventStore(&dispatcher, 1<<16, GoEventBus.DropOldest) 40 | store.Async = false // synchronous dispatch on Publish() 41 | 42 | // 3) HTTP router only enqueues 43 | r := router.New() 44 | r.GET("/enqueue", func(ctx *fasthttp.RequestCtx) { 45 | name := string(ctx.QueryArgs().Peek("name")) 46 | a, _ := ctx.QueryArgs().GetUint("a") 47 | b, _ := ctx.QueryArgs().GetUint("b") 48 | 49 | // enqueue two events 50 | store.Subscribe(context.Background(), GoEventBus.Event{ 51 | ID: fmt.Sprintf("hello-%d", time.Now().UnixNano()), 52 | Projection: "sayHello", 53 | Args: map[string]any{"name": name}, 54 | }) 55 | store.Subscribe(context.Background(), GoEventBus.Event{ 56 | ID: fmt.Sprintf("sum-%d", time.Now().UnixNano()), 57 | Projection: "computeSum", 58 | Args: map[string]any{"a": int(a), "b": int(b)}, 59 | }) 60 | 61 | ctx.SetStatusCode(fasthttp.StatusAccepted) 62 | ctx.WriteString("✅ Events enqueued\n") 63 | }) 64 | 65 | // 4) Start HTTP server 66 | go func() { 67 | log.Println("▶️ Listening on :8080") 68 | if err := fasthttp.ListenAndServe(":8080", r.Handler); err != nil { 69 | log.Fatalf("HTTP error: %v", err) 70 | } 71 | }() 72 | 73 | // 5) Background for‐loop: publish every 5 seconds 74 | go func() { 75 | for { 76 | time.Sleep(5 * time.Second) 77 | store.Publish() 78 | } 79 | }() 80 | 81 | // 6) Block forever (or replace with signal handling if you like) 82 | select {} 83 | } 84 | -------------------------------------------------------------------------------- /examples/goroutines-subscribe-publisher/go.mod: -------------------------------------------------------------------------------- 1 | module main 2 | 3 | go 1.23.7 4 | 5 | require github.com/Raezil/GoEventBus v0.1.45 6 | -------------------------------------------------------------------------------- /examples/goroutines-subscribe-publisher/go.sum: -------------------------------------------------------------------------------- 1 | github.com/Raezil/GoEventBus v0.1.45 h1:Pohc7qlHBCnve+ZbuMrhiY02hFzUAGE0bBK/2xi6fh4= 2 | github.com/Raezil/GoEventBus v0.1.45/go.mod h1:gGI/WnqrWjPuTCqhxUbaWxaLX+KIp5R50euawvgmqjg= 3 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= 4 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= 5 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= 6 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= 7 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 8 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 9 | github.com/valyala/fasthttp v1.61.0 h1:VV08V0AfoRaFurP1EWKvQQdPTZHiUzaVoulX1aBDgzU= 10 | github.com/valyala/fasthttp v1.61.0/go.mod h1:wRIV/4cMwUPWnRcDno9hGnYZGh78QzODFfo1LTUhBog= 11 | -------------------------------------------------------------------------------- /examples/goroutines-subscribe-publisher/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | "time" 11 | 12 | "github.com/Raezil/GoEventBus" 13 | ) 14 | 15 | func main() { 16 | // 1) Build your dispatcher 17 | dispatcher := GoEventBus.Dispatcher{ 18 | "user_created": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 19 | select { 20 | case <-time.After(500 * time.Millisecond): 21 | fmt.Println("Processed user_created:", args["id"]) 22 | case <-ctx.Done(): 23 | return GoEventBus.Result{}, ctx.Err() 24 | } 25 | return GoEventBus.Result{Message: "done"}, nil 26 | }, 27 | } 28 | 29 | // 2) Create your store (async handlers) 30 | store := GoEventBus.NewEventStore(&dispatcher, 1<<10, GoEventBus.Block) 31 | store.Async = true 32 | 33 | // 3) Prepare a root context that we can cancel on shutdown 34 | rootCtx, cancel := context.WithCancel(context.Background()) 35 | defer cancel() 36 | 37 | // ---- 38 | // 4a) Enqueue loop: ticks every 200ms, pushes new events 39 | go func() { 40 | ticker := time.NewTicker(200 * time.Millisecond) 41 | defer ticker.Stop() 42 | count := 0 43 | for { 44 | select { 45 | case <-ticker.C: 46 | count++ 47 | evt := GoEventBus.Event{ 48 | ID: fmt.Sprintf("u-%d", count), 49 | Projection: "user_created", 50 | Args: map[string]any{"id": count}, 51 | } 52 | store.Subscribe(rootCtx, evt) 53 | case <-rootCtx.Done(): 54 | return 55 | } 56 | } 57 | }() 58 | 59 | // 4b) Dispatch loop: ticks every 100ms, calls Publish() 60 | go func() { 61 | ticker := time.NewTicker(1000 * time.Millisecond) 62 | defer ticker.Stop() 63 | for { 64 | select { 65 | case <-ticker.C: 66 | // fire off whatever's in the ring buffer 67 | store.Publish() 68 | case <-rootCtx.Done(): 69 | return 70 | } 71 | } 72 | }() 73 | 74 | // ---- 75 | // 5) Listen for SIGINT/SIGTERM 76 | sigs := make(chan os.Signal, 1) 77 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 78 | <-sigs 79 | log.Println("🔔 Shutdown signal received, stopping new work…") 80 | cancel() // stop both loops 81 | 82 | // 6) Final publish to catch any last enqueued events 83 | store.Publish() 84 | 85 | // 7) Drain with timeout so we finish in-flight handlers 86 | drainCtx, cancelDrain := context.WithTimeout(context.Background(), 5*time.Second) 87 | defer cancelDrain() 88 | 89 | if err := store.Drain(drainCtx); err != nil { 90 | log.Printf("⚠️ Drain error: %v\n", err) 91 | } else { 92 | log.Println("✅ All events processed, exiting.") 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /examples/handler_timeout/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/Raezil/GoEventBus" 9 | ) 10 | 11 | // Handler runs for 150 ms unless its context is cancelled. 12 | func main() { 13 | dispatcher := GoEventBus.Dispatcher{ 14 | "demo": func(ctx context.Context, _ map[string]any) (GoEventBus.Result, error) { 15 | select { 16 | case <-time.After(150 * time.Millisecond): 17 | fmt.Println("handler OK") 18 | return GoEventBus.Result{Message: "ok"}, nil 19 | case <-ctx.Done(): 20 | fmt.Println("handler cancelled:", ctx.Err()) 21 | return GoEventBus.Result{}, ctx.Err() 22 | } 23 | }, 24 | } 25 | 26 | store := GoEventBus.NewEventStore(&dispatcher, 4, GoEventBus.Block) 27 | 28 | // Handler‑only 40 ms timeout → will cancel. 29 | hctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) 30 | defer cancel() 31 | 32 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ 33 | ID: "H-1", Projection: "demo", Args: map[string]any{"__ctx": hctx}, 34 | }) 35 | 36 | store.Publish() 37 | time.Sleep(60 * time.Millisecond) 38 | 39 | pub, proc, errs := store.Metrics() 40 | fmt.Printf("published=%d processed=%d errors=%d\n", pub, proc, errs) 41 | } 42 | -------------------------------------------------------------------------------- /examples/hello_world/go.mod: -------------------------------------------------------------------------------- 1 | module main 2 | 3 | go 1.23.7 4 | 5 | require github.com/Raezil/GoEventBus v0.1.44 6 | -------------------------------------------------------------------------------- /examples/hello_world/go.sum: -------------------------------------------------------------------------------- 1 | github.com/Raezil/GoEventBus v0.1.44 h1:taY+Pu6SRqORPlXGHID+ICsQwDNtH27FA3nAqLp/A7k= 2 | github.com/Raezil/GoEventBus v0.1.44/go.mod h1:gGI/WnqrWjPuTCqhxUbaWxaLX+KIp5R50euawvgmqjg= 3 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= 4 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= 5 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= 6 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= 7 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 8 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 9 | github.com/valyala/fasthttp v1.61.0 h1:VV08V0AfoRaFurP1EWKvQQdPTZHiUzaVoulX1aBDgzU= 10 | github.com/valyala/fasthttp v1.61.0/go.mod h1:wRIV/4cMwUPWnRcDno9hGnYZGh78QzODFfo1LTUhBog= 11 | -------------------------------------------------------------------------------- /examples/hello_world/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/Raezil/GoEventBus" 8 | ) 9 | 10 | func main() { 11 | // 1) Create a dispatcher mapping projections to handlers 12 | dispatcher := GoEventBus.Dispatcher{ 13 | "say_hello": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 14 | name := args["name"].(string) 15 | fmt.Printf("Hello, %s!\n", name) 16 | return GoEventBus.Result{Message: "greeted"}, nil 17 | }, 18 | } 19 | 20 | // 2) Initialize the EventStore with 8K buffer, DropOldest policy 21 | store := GoEventBus.NewEventStore(&dispatcher, 1<<13, GoEventBus.DropOldest) 22 | 23 | // 3) Enqueue an event 24 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ 25 | ID: "evt1", 26 | Projection: "say_hello", 27 | Args: map[string]any{"name": "World"}, 28 | }) 29 | 30 | // 4) Dispatch and wait 31 | store.Publish() 32 | } 33 | -------------------------------------------------------------------------------- /examples/middleware/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/Raezil/GoEventBus" 9 | ) 10 | 11 | // Example of a logging middleware that logs before and after handler execution. 12 | func loggingMiddleware(next GoEventBus.HandlerFunc) GoEventBus.HandlerFunc { 13 | return func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 14 | start := time.Now() 15 | fmt.Printf("[Middleware] Starting handler, args=%v\n", args) 16 | res, err := next(ctx, args) 17 | fmt.Printf("[Middleware] Finished handler in %s, result=%+v, err=%v\n", time.Since(start), res, err) 18 | return res, err 19 | } 20 | } 21 | 22 | // beforeHook prints a message before the handler runs. 23 | func beforeHook(ctx context.Context, ev GoEventBus.Event) { 24 | fmt.Printf("[Hook Before] Event ID=%s, Projection=%v, Args=%v\n", ev.ID, ev.Projection, ev.Args) 25 | } 26 | 27 | // afterHook prints a message after the handler completes (regardless of error). 28 | func afterHook(ctx context.Context, ev GoEventBus.Event, res GoEventBus.Result, err error) { 29 | fmt.Printf("[Hook After] Event ID=%s done: result=%+v, err=%v\n", ev.ID, res, err) 30 | } 31 | 32 | // errorHook handles errors from the handler. 33 | func errorHook(ctx context.Context, ev GoEventBus.Event, err error) { 34 | fmt.Printf("[Hook Error] Event ID=%s, error=%v\n", ev.ID, err) 35 | } 36 | 37 | func main() { 38 | // 1. Create dispatcher and register handlers 39 | disp := GoEventBus.Dispatcher{} 40 | disp["greet"] = func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 41 | name := args["name"].(string) 42 | msg := fmt.Sprintf("Hello, %s!", name) 43 | return GoEventBus.Result{Message: msg}, nil 44 | } 45 | // A handler that sometimes errors 46 | disp["fail"] = func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 47 | return GoEventBus.Result{}, fmt.Errorf("intentional error") 48 | } 49 | 50 | // 2. Initialize EventStore 51 | store := GoEventBus.NewEventStore(&disp, 16, GoEventBus.DropOldest) 52 | 53 | // 3. Register middleware and hooks 54 | store.Use(loggingMiddleware) 55 | store.OnBefore(beforeHook) 56 | store.OnAfter(afterHook) 57 | store.OnError(errorHook) 58 | 59 | // 4. Publish a successful event 60 | e1 := GoEventBus.Event{ 61 | ID: "evt-1", 62 | Projection: "greet", 63 | Args: map[string]any{"name": "Alice"}, 64 | } 65 | store.Subscribe(context.Background(), e1) 66 | // 5. Publish a failing event 67 | e2 := GoEventBus.Event{ 68 | ID: "evt-2", 69 | Projection: "fail", 70 | Args: map[string]any{}, 71 | } 72 | store.Subscribe(context.Background(), e2) 73 | 74 | // 6. Process all queued events 75 | store.Publish() 76 | 77 | // 7. Retrieve and display metrics 78 | pub, proc, errs := store.Metrics() 79 | fmt.Printf("Metrics: published=%d, processed=%d, errors=%d\n", pub, proc, errs) 80 | } 81 | -------------------------------------------------------------------------------- /examples/publisher/go.mod: -------------------------------------------------------------------------------- 1 | module main 2 | 3 | go 1.23.7 4 | 5 | require github.com/Raezil/GoEventBus v0.1.44 6 | -------------------------------------------------------------------------------- /examples/publisher/go.sum: -------------------------------------------------------------------------------- 1 | github.com/Raezil/GoEventBus v0.1.44 h1:taY+Pu6SRqORPlXGHID+ICsQwDNtH27FA3nAqLp/A7k= 2 | github.com/Raezil/GoEventBus v0.1.44/go.mod h1:gGI/WnqrWjPuTCqhxUbaWxaLX+KIp5R50euawvgmqjg= 3 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= 4 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= 5 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= 6 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= 7 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 8 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 9 | github.com/valyala/fasthttp v1.61.0 h1:VV08V0AfoRaFurP1EWKvQQdPTZHiUzaVoulX1aBDgzU= 10 | github.com/valyala/fasthttp v1.61.0/go.mod h1:wRIV/4cMwUPWnRcDno9hGnYZGh78QzODFfo1LTUhBog= 11 | -------------------------------------------------------------------------------- /examples/publisher/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | "time" 11 | 12 | "github.com/Raezil/GoEventBus" 13 | ) 14 | 15 | // Define a typed projection as a struct 16 | type HouseWasSold struct{} 17 | 18 | func main() { 19 | dispatcher := GoEventBus.Dispatcher{ 20 | "user_created": func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 21 | userID := args["id"].(string) 22 | fmt.Println("User created with ID:", userID) 23 | return GoEventBus.Result{Message: "handled user_created"}, nil 24 | }, 25 | HouseWasSold{}: func(ctx context.Context, args map[string]any) (GoEventBus.Result, error) { 26 | address := args["address"].(string) 27 | price := args["price"].(int) 28 | fmt.Printf("House sold at %s for $%d\n", address, price) 29 | return GoEventBus.Result{Message: "handled HouseWasSold"}, nil 30 | }, 31 | } 32 | 33 | store := GoEventBus.NewEventStore(&dispatcher, 1<<16, GoEventBus.DropOldest) 34 | store.Async = true 35 | 36 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) 37 | defer stop() 38 | 39 | // Goroutine: Publish every 5 seconds 40 | go func() { 41 | for { 42 | select { 43 | case <-ctx.Done(): 44 | return 45 | default: 46 | store.Publish() 47 | time.Sleep(5 * time.Second) 48 | } 49 | } 50 | }() 51 | 52 | // Goroutine: Subscribe every 6 seconds 53 | go func() { 54 | i := 0 55 | for { 56 | select { 57 | case <-ctx.Done(): 58 | return 59 | default: 60 | eventType := "" 61 | var projection any 62 | var args map[string]any 63 | 64 | if i%2 == 0 { 65 | eventType = "user_created" 66 | projection = "user_created" 67 | args = map[string]any{"id": fmt.Sprintf("%d", i)} 68 | } else { 69 | eventType = "HouseWasSold" 70 | projection = HouseWasSold{} 71 | args = map[string]any{ 72 | "address": fmt.Sprintf("%d Main St", 100+i), 73 | "price": 400000 + (i * 1000), 74 | } 75 | } 76 | 77 | err := store.Subscribe(context.Background(), GoEventBus.Event{ 78 | ID: fmt.Sprintf("evt%d", i), 79 | Projection: projection, 80 | Args: args, 81 | }) 82 | if err != nil { 83 | log.Printf("Failed to subscribe event (%s): %v", eventType, err) 84 | } else { 85 | log.Printf("Subscribed event: %s", eventType) 86 | } 87 | 88 | i++ 89 | time.Sleep(6 * time.Second) 90 | } 91 | } 92 | }() 93 | 94 | // Wait for Ctrl+C 95 | <-ctx.Done() 96 | fmt.Println("Shutting down...") 97 | 98 | // After stop signal: Drain and report metrics 99 | store.Publish() 100 | if err := store.Drain(context.Background()); err != nil { 101 | log.Fatalf("Failed to drain EventStore: %v", err) 102 | } 103 | 104 | published, processed, errors := store.Metrics() 105 | fmt.Printf("published=%d processed=%d errors=%d\n", published, processed, errors) 106 | } 107 | -------------------------------------------------------------------------------- /examples/publisher_timeout/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/Raezil/GoEventBus" 9 | ) 10 | 11 | // Shows back‑pressure timeout when the buffer is full. 12 | func main() { 13 | dispatcher := GoEventBus.Dispatcher{} 14 | store := GoEventBus.NewEventStore(&dispatcher, 1, GoEventBus.Block) 15 | 16 | // Fill the single slot. 17 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ID: "P-0"}) 18 | 19 | // Next publish must wait; we give it only 30 ms. 20 | pubCtx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) 21 | defer cancel() 22 | 23 | err := store.Subscribe(pubCtx, GoEventBus.Event{ID: "P-1"}) 24 | fmt.Println("Subscribe error:", err) 25 | 26 | pub, proc, errs := store.Metrics() 27 | fmt.Printf("published=%d processed=%d errors=%d\n", pub, proc, errs) 28 | } 29 | -------------------------------------------------------------------------------- /examples/return_error/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/Raezil/GoEventBus" 8 | ) 9 | 10 | // Demonstrates OverrunPolicy=ReturnError (fail fast). 11 | func main() { 12 | dispatcher := GoEventBus.Dispatcher{} 13 | store := GoEventBus.NewEventStore(&dispatcher, 2, GoEventBus.ReturnError) 14 | 15 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ID: "R-0"}) 16 | _ = store.Subscribe(context.Background(), GoEventBus.Event{ID: "R-1"}) // buffer full 17 | 18 | err := store.Subscribe(context.Background(), GoEventBus.Event{ID: "R-2"}) 19 | fmt.Println("Subscribe error:", err) 20 | } 21 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Raezil/GoEventBus 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.23.7 6 | 7 | require ( 8 | github.com/fasthttp/router v1.5.4 9 | github.com/valyala/fasthttp v1.61.0 10 | ) 11 | 12 | require ( 13 | github.com/andybalholm/brotli v1.1.1 // indirect 14 | github.com/klauspost/compress v1.18.0 // indirect 15 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 // indirect 16 | github.com/valyala/bytebufferpool v1.0.0 // indirect 17 | ) 18 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= 2 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= 3 | github.com/fasthttp/router v1.5.4 h1:oxdThbBwQgsDIYZ3wR1IavsNl6ZS9WdjKukeMikOnC8= 4 | github.com/fasthttp/router v1.5.4/go.mod h1:3/hysWq6cky7dTfzaaEPZGdptwjwx0qzTgFCKEWRjgc= 5 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= 6 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= 7 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 h1:D0vL7YNisV2yqE55+q0lFuGse6U8lxlg7fYTctlT5Gc= 8 | github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg= 9 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 10 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 11 | github.com/valyala/fasthttp v1.61.0 h1:VV08V0AfoRaFurP1EWKvQQdPTZHiUzaVoulX1aBDgzU= 12 | github.com/valyala/fasthttp v1.61.0/go.mod h1:wRIV/4cMwUPWnRcDno9hGnYZGh78QzODFfo1LTUhBog= 13 | github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= 14 | github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= 15 | -------------------------------------------------------------------------------- /go.work: -------------------------------------------------------------------------------- 1 | go 1.23.0 2 | 3 | toolchain go1.23.7 4 | 5 | use . 6 | -------------------------------------------------------------------------------- /logoGoEventBus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Raezil/GoEventBus/b1f32df3d67d105fffc8275bdf2583cb65d210ec/logoGoEventBus.png -------------------------------------------------------------------------------- /transaction.go: -------------------------------------------------------------------------------- 1 | package GoEventBus 2 | 3 | import ( 4 | "context" 5 | "sync/atomic" 6 | ) 7 | 8 | // Transaction encapsulates a set of events to be committed atomically. 9 | type Transaction struct { 10 | store *EventStore 11 | events []Event 12 | startHead uint64 // head position when transaction began 13 | } 14 | 15 | // BeginTransaction starts a new transaction on the EventStore. 16 | func (es *EventStore) BeginTransaction() *Transaction { 17 | // snapshot the head so we can restore it on rollback 18 | h := atomic.LoadUint64(&es.head) 19 | return &Transaction{store: es, startHead: h} 20 | } 21 | 22 | // Publish adds an event to the transaction buffer. 23 | func (tx *Transaction) Publish(e Event) { 24 | tx.events = append(tx.events, e) 25 | } 26 | 27 | // Commit enqueues all buffered events and processes them immediately. 28 | // It returns the first error encountered from Subscribe or handler execution. 29 | func (tx *Transaction) Commit(ctx context.Context) error { 30 | // 1) Enqueue 31 | for _, e := range tx.events { 32 | e.Ctx = ctx 33 | if err := tx.store.Subscribe(ctx, e); err != nil { 34 | return err 35 | } 36 | } 37 | 38 | // 2) Process synchronously 39 | head := atomic.LoadUint64(&tx.store.head) 40 | tail := atomic.LoadUint64(&tx.store.tail) 41 | disp := *tx.store.dispatcher 42 | mask := tx.store.size - 1 43 | 44 | for i := tail; i < head; i++ { 45 | // load event pointer atomically 46 | evPtr := tx.store.buf[i&mask].Load() 47 | if evPtr == nil { 48 | continue 49 | } 50 | ev := *evPtr 51 | if handler, ok := disp[ev.Projection]; ok { 52 | // pick up recorded context 53 | cctx := ev.Ctx 54 | if c2, ok2 := ev.Args["__ctx"].(context.Context); ok2 && c2 != nil { 55 | cctx = c2 56 | } 57 | 58 | // before hooks 59 | for _, hook := range tx.store.beforeHooks { 60 | hook(cctx, ev) 61 | } 62 | 63 | // wrap middlewares 64 | wrapped := handler 65 | for j := len(tx.store.middlewares) - 1; j >= 0; j-- { 66 | wrapped = tx.store.middlewares[j](wrapped) 67 | } 68 | 69 | // invoke handler 70 | res, err := wrapped(cctx, ev.Args) 71 | atomic.AddUint64(&tx.store.processedCount, 1) 72 | 73 | // after hooks 74 | for _, hook := range tx.store.afterHooks { 75 | hook(cctx, ev, res, err) 76 | } 77 | 78 | if err != nil { 79 | atomic.AddUint64(&tx.store.errorCount, 1) 80 | for _, hook := range tx.store.errorHooks { 81 | hook(cctx, ev, err) 82 | } 83 | // advance tail and exit on first handler error 84 | atomic.StoreUint64(&tx.store.tail, head) 85 | return err 86 | } 87 | } 88 | } 89 | 90 | // 3) Advance tail past processed events 91 | atomic.StoreUint64(&tx.store.tail, head) 92 | 93 | // 4) Clear transaction buffer 94 | tx.events = tx.events[:0] 95 | return nil 96 | } 97 | 98 | // Rollback clears the local buffer *and* any events that have already 99 | // been pushed into the store’s ring-buffer since the transaction began. 100 | func (tx *Transaction) Rollback() { 101 | // clear our local buffer 102 | tx.events = tx.events[:0] 103 | 104 | // remove any partial enqueues from the store 105 | currHead := atomic.LoadUint64(&tx.store.head) 106 | mask := tx.store.size - 1 107 | for i := tx.startHead; i < currHead; i++ { 108 | // clear slot atomically 109 | tx.store.buf[i&mask].Store(nil) 110 | } 111 | 112 | // restore the head pointer 113 | atomic.StoreUint64(&tx.store.head, tx.startHead) 114 | } 115 | -------------------------------------------------------------------------------- /transaction_test.go: -------------------------------------------------------------------------------- 1 | package GoEventBus 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "sync/atomic" 7 | "testing" 8 | ) 9 | 10 | // dummy handler just increments a counter 11 | func makeCounterHandler(counter *uint64) HandlerFunc { 12 | return func(ctx context.Context, args map[string]any) (Result, error) { 13 | atomic.AddUint64(counter, 1) 14 | return Result{Message: "ok"}, nil 15 | } 16 | } 17 | 18 | func TestTransaction_CommitAndRollback(t *testing.T) { 19 | // set up dispatcher with a no-op projection 20 | var processed uint64 21 | dispatcher := Dispatcher{ 22 | "p": makeCounterHandler(&processed), 23 | } 24 | 25 | es := NewEventStore(&dispatcher, 8, DropOldest) 26 | ctx := context.Background() 27 | 28 | // Test Commit 29 | tx := es.BeginTransaction() 30 | tx.Publish(Event{ID: "1", Projection: "p", Args: map[string]any{}}) 31 | tx.Publish(Event{ID: "2", Projection: "p", Args: map[string]any{}}) 32 | if err := tx.Commit(ctx); err != nil { 33 | t.Fatalf("Commit failed: %v", err) 34 | } 35 | // actually publish into store 36 | es.Publish() 37 | if got := atomic.LoadUint64(&processed); got != 2 { 38 | t.Errorf("expected 2 events processed, got %d", got) 39 | } 40 | 41 | // Test Rollback 42 | processed = 0 43 | tx2 := es.BeginTransaction() 44 | tx2.Publish(Event{ID: "3", Projection: "p", Args: map[string]any{}}) 45 | tx2.Rollback() 46 | if err := tx2.Commit(ctx); err != nil { 47 | t.Fatalf("Commit after rollback should not error, got %v", err) 48 | } 49 | es.Publish() 50 | if got := atomic.LoadUint64(&processed); got != 0 { 51 | t.Errorf("expected 0 events after rollback, got %d", got) 52 | } 53 | } 54 | 55 | func TestTransaction_PartialFailure(t *testing.T) { 56 | // handler that errors on the second event 57 | cnt := uint64(0) 58 | dispatcher := Dispatcher{ 59 | "x": func(ctx context.Context, args map[string]any) (Result, error) { 60 | i := atomic.AddUint64(&cnt, 1) 61 | if i == 2 { 62 | return Result{}, errors.New("boom") 63 | } 64 | return Result{Message: "ok"}, nil 65 | }, 66 | } 67 | 68 | es := NewEventStore(&dispatcher, 4, ReturnError) 69 | ctx := context.Background() 70 | 71 | tx := es.BeginTransaction() 72 | tx.Publish(Event{ID: "a", Projection: "x", Args: map[string]any{}}) 73 | tx.Publish(Event{ID: "b", Projection: "x", Args: map[string]any{}}) 74 | err := tx.Commit(ctx) 75 | if err == nil { 76 | t.Fatal("expected Commit to return error on second event, got nil") 77 | } 78 | if err.Error() != "goeventbus: buffer is full" && err.Error() != "boom" { 79 | // Depending on overrun policy, could bubble Subscribe error or handler error 80 | t.Fatalf("unexpected error: %v", err) 81 | } 82 | } 83 | 84 | func BenchmarkTransaction_SyncCommit(b *testing.B) { 85 | dispatcher := Dispatcher{ 86 | "p": func(ctx context.Context, args map[string]any) (Result, error) { 87 | return Result{Message: "ok"}, nil 88 | }, 89 | } 90 | es := NewEventStore(&dispatcher, 256, DropOldest) 91 | es.Async = false 92 | 93 | b.ResetTimer() 94 | for i := 0; i < b.N; i++ { 95 | tx := es.BeginTransaction() 96 | // buffer N events per transaction 97 | for j := 0; j < 16; j++ { 98 | tx.Publish(Event{ID: "t", Projection: "p", Args: map[string]any{}}) 99 | } 100 | if err := tx.Commit(context.Background()); err != nil { 101 | b.Fatalf("Commit error: %v", err) 102 | } 103 | es.Publish() 104 | } 105 | } 106 | 107 | func BenchmarkTransaction_AsyncCommit(b *testing.B) { 108 | dispatcher := Dispatcher{ 109 | "p": func(ctx context.Context, args map[string]any) (Result, error) { 110 | return Result{Message: "ok"}, nil 111 | }, 112 | } 113 | es := NewEventStore(&dispatcher, 256, DropOldest) 114 | es.Async = true 115 | 116 | b.ResetTimer() 117 | for i := 0; i < b.N; i++ { 118 | tx := es.BeginTransaction() 119 | for j := 0; j < 16; j++ { 120 | tx.Publish(Event{ID: "t", Projection: "p", Args: map[string]any{}}) 121 | } 122 | if err := tx.Commit(context.Background()); err != nil { 123 | b.Fatalf("Commit error: %v", err) 124 | } 125 | es.Publish() 126 | es.Drain(context.Background()) 127 | } 128 | } 129 | --------------------------------------------------------------------------------