All Projects → mustafaturan → Bus

mustafaturan / Bus

Licence: apache-2.0
🔊Minimalist message bus implementation for internal communication

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Bus

hub
📨 A fast Message/Event Hub using publish/subscribe pattern with support for topics like* rabbitMQ exchanges for Go applications
Stars: ✭ 125 (-33.16%)
Mutual labels:  message-bus, pubsub, eventbus
pubsub-c
Pub/Sub library for C
Stars: ✭ 39 (-79.14%)
Mutual labels:  message-bus, pubsub
Message Bus
Go simple async message bus
Stars: ✭ 166 (-11.23%)
Mutual labels:  pubsub, message-bus
evon
Fast and versatile event dispatcher code generator for Golang
Stars: ✭ 15 (-91.98%)
Mutual labels:  pubsub, eventbus
pg-pubsub
Reliable PostgreSQL LISTEN/NOTIFY with inter-process lock support
Stars: ✭ 50 (-73.26%)
Mutual labels:  pubsub, eventbus
Event bus
🏄 Traceable, extendable and minimalist **event bus** implementation for Elixir with built-in **event store** and **event watcher** based on ETS.
Stars: ✭ 563 (+201.07%)
Mutual labels:  eventbus, message-bus
incubator-eventmesh
EventMesh is a dynamic event-driven application runtime used to decouple the application and backend middleware layer, which supports a wide range of use cases that encompass complex multi-cloud, widely distributed topologies using diverse technology stacks.
Stars: ✭ 939 (+402.14%)
Mutual labels:  message-bus, pubsub
Nybus
NYBus (RxBus) - A pub-sub library for Android and Java applications
Stars: ✭ 283 (+51.34%)
Mutual labels:  eventbus, pubsub
telephone-ts
Telephone-ts: The "Event Emitter-less" TypeScript Event Architecture.
Stars: ✭ 22 (-88.24%)
Mutual labels:  message-bus, eventbus
Nats.net
The official C# Client for NATS
Stars: ✭ 378 (+102.14%)
Mutual labels:  pubsub, message-bus
Messagebus
A MessageBus (CommandBus, EventBus and QueryBus) implementation in PHP7
Stars: ✭ 178 (-4.81%)
Mutual labels:  eventbus, message-bus
Dapr
Dapr is a portable, event-driven, runtime for building distributed applications across cloud and edge.
Stars: ✭ 16,274 (+8602.67%)
Mutual labels:  pubsub
Enqueue Dev
Message Queue, Job Queue, Broadcasting, WebSockets packages for PHP, Symfony, Laravel, Magento. DEVELOPMENT REPOSITORY - provided by Forma-Pro
Stars: ✭ 1,977 (+957.22%)
Mutual labels:  message-bus
Liftbridge
Lightweight, fault-tolerant message streams.
Stars: ✭ 2,175 (+1063.1%)
Mutual labels:  pubsub
Elegantbus
🔥🔥Android 平台,基于LivaData的EventBus,无侵入,更优雅,支持跨进程,跨应用粘性事件,自定义事件等功能。
Stars: ✭ 156 (-16.58%)
Mutual labels:  eventbus
Fedmsg
Federated Messaging with ZeroMQ
Stars: ✭ 165 (-11.76%)
Mutual labels:  message-bus
Garagemq
AMQP message broker implemented with golang
Stars: ✭ 153 (-18.18%)
Mutual labels:  pubsub
Eventbus
eventbus实现跨进程通讯方案
Stars: ✭ 153 (-18.18%)
Mutual labels:  eventbus
Go Sdk
Dapr SDK for go
Stars: ✭ 149 (-20.32%)
Mutual labels:  pubsub
Readhub
ReadHub Client 非官方客户端
Stars: ✭ 179 (-4.28%)
Mutual labels:  eventbus

🔊 Bus

GoDoc Build Status Coverage Status Go Report Card GitHub license

Bus is a minimalist event/message bus implementation for internal communication. It is heavily inspired from my event_bus package for Elixir language.

API

The method names and arities/args are stable now. No change should be expected on the package for the version 2.x.x except any bug fixes.

Installation

Via go packages: go get github.com/mustafaturan/bus/v2

Usage

Configure

The package requires a unique id generator to assign ids to events. You can write your own function to generate unique ids or use a package that provides unique id generation functionality.

The bus package respect to software design choice of the packages/projects. It supports both singleton and dependency injection to init a bus instance.

Hint: Check the demo project for the singleton configuration.

Here is a sample initilization using monoton id generator:

import (
    "github.com/mustafaturan/bus/v2"
    "github.com/mustafaturan/monoton"
    "github.com/mustafaturan/monoton/sequencer"
)

func NewBus() *bus.Bus {
    // configure id generator (it doesn't have to be monoton)
    node        := uint64(1)
    initialTime := uint64(1577865600000) // set 2020-01-01 PST as initial time
    m, err := monoton.New(sequencer.NewMillisecond(), node, initialTime)
    if err != nil {
        panic(err)
    }

    // init an id generator
    var idGenerator bus.Next = (*m).Next

    // create a new bus instance
    b, err := bus.NewBus(idGenerator)
    if err != nil {
        panic(err)
    }

    // maybe register topics in here
    b.RegisterTopics("order.received", "order.fulfilled")

    return b
}

Register Event Topics

To emit events to the topics, topic names need to be registered first:

// register topics
b.RegisterTopics("order.received", "order.fulfilled")

Register Event Handlers

To receive topic events you need to register handlers; A handler basically requires two vals which are a Handle function and topic Matcher regex pattern.

handler := bus.Handler{
    Handle: func(ctx context.Context, e *bus.Event) {
        // do something
        // NOTE: Highly recommended to process the event in an async way
    },
    Matcher: ".*", // matches all topics
}
b.RegisterHandler("a unique key for the handler", &handler)

Emit Events

// if txID val is blank, bus package generates one using the id generator
ctx := context.Background()
ctx = context.WithValue(ctx, bus.CtxKeyTxID, "some-transaction-id-if-exists")

// event topic name (must be registered before)
topic := "order.received"

// interface{} data for event
order := make(map[string]string)
order["orderID"]     = "123456"
order["orderAmount"] = "112.20"
order["currency"]    = "USD"

// emit the event
event, err := b.Emit(ctx, topic, order)

if err != nil {
    // report the err
    fmt.Println(err)
}

// if the caller needs the event, a ref for the event is returning as result of
// the `Emit` call.
fmt.Println(event)

Processing Events

When an event is emitted, the topic handlers receive the event synchronously. It is highly recommended to process events asynchronous. Package leave the decision to the packages/projects to use concurrency abstractions depending on use-cases. Each handlers receive the same event as ref of bus.Event struct:

// Event data structure
type Event struct {
	ID         string      // identifier
	TxID       string      // transaction identifier
	Topic      string      // topic name
	Data       interface{} // actual event data
	OccurredAt int64       // creation time in nanoseconds
}

Sample Project

A demo project with three consumers which increments a counter for each event topic, printer consumer which prints all events and lastly calculator consumer which sums amounts.

Benchmarks

When txID specified in the context:

goos: darwin
goarch: amd64
pkg: github.com/mustafaturan/bus/v2
cpu: Intel(R) Core(TM) i5-6267U CPU @ 2.90GHz
BenchmarkEmit-4   	 5315254	       205.7 ns/op	      88 B/op	       1 allocs/op

When txID is not specified in the context (the library generates and assigns txID to the context and the event):

goos: darwin
goarch: amd64
pkg: github.com/mustafaturan/bus/v2
cpu: Intel(R) Core(TM) i5-6267U CPU @ 2.90GHz
BenchmarkEmitWithoutTxID-4   	 4044715	       285.2 ns/op	     152 B/op	       3 allocs/op

Contributing

All contributors should follow Contributing Guidelines before creating pull requests.

Credits

Mustafa Turan

License

Apache License 2.0

Copyright (c) 2021 Mustafa Turan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].