bus

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2019 License: Apache-2.0 Imports: 4 Imported by: 44

README

🔊 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.

Installation

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

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. Here is a sample configuration using monoton id generator:

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

func init() {
    // configure id generator (it doesn't have to be monoton)
    node        := uint(1)
    initialTime := uint(0)
    monoton.Configure(sequencer.NewMillisecond(), node, initialTime)

    // configure bus
    if err := bus.Configure(bus.Config{Next: monoton.Next}); err != nil {
        panic("whoops")
    }
    // ...
}
Register Event Topics

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

func init() {
    // ...
    // register topics
    bus.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(e *Event) {
        // do something
        // NOTE: Highly recommended to process the event in an async way
    },
    Matcher: ".*", // matches all topics
}
bus.RegisterHandler("a unique key for the handler", &handler)
Emit Events
txID  := "some-transaction-id-if-exists" // if it is blank, bus will generate one
topic := "order.received" // event topic name (must be registered before)
order := make(map[string]string) // interface{} data for event
order["orderID"]     = "123456"
order["orderAmount"] = "112.20"
order["currency"]    = "USD"

bus.Emit(topic, order, txID) // emit the event for the topic
Processing Events

When an event is emitted, the topic handlers will receive events 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.

Sample Project

An example simple 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
BenchmarkEmit-8         10000000               158 ns/op              72 B/op          2 allocs/op

Contributing

All contributors should follow Contributing Guidelines before creating pull requests.

Credits

Mustafa Turan

License

Apache License 2.0

Copyright (c) 2019 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.

Documentation

Overview

Package bus is a minimalist event/message bus implementation for internal communication

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. Here is a sample configuration using `monoton` id generator:

Example code for configuration:

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

func init() {
	// configure id generator (it doesn't have to be monoton)
	node        := uint(1)
	initialTime := uint(0)
	monoton.Configure(sequencer.NewMillisecond(), node, initialTime)

	// configure bus
	if err := bus.Configure(bus.Config{Next: monoton.Next}); err != nil {
		panic("whoops")
	}
	// ...
}

Register Topics

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

Example code:

func init() {
	// ...
	// register topics
	bus.RegisterTopics("order.received", "order.fulfilled")
	// ...
}

Register 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.

Example code:

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

Emit Event

Example code:

txID  := "some-transaction-id-if-exists" // if it is blank, package will generate one
topic := "order.received" // event topic name (must be registered before)
order := make(map[string]string) // interface{} data for the event

order["orderID"]     = "123456"
order["orderAmount"] = "112.20"
order["currency"]    = "USD"

// emit the event for the topic with the transaction id
bus.Emit(topic, order, txID)

Processing Events

When an event is emitted, the topic handlers will receive events 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.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Configure

func Configure(c Config) error

Configure sets configuration for bus package

func DeregisterHandler

func DeregisterHandler(key string)

DeregisterHandler deletes handler from the registry

func DeregisterTopics

func DeregisterTopics(topicNames ...string)

DeregisterTopics deletes topic

func ListHandlerKeys

func ListHandlerKeys() []string

ListHandlerKeys returns list of registered handler keys

func RegisterHandler

func RegisterHandler(key string, h *Handler)

RegisterHandler re/register the handler to the registry

func RegisterTopics

func RegisterTopics(topicNames ...string)

RegisterTopics registers topics and fullfills handlers

Types

type Config

type Config struct {
	Next func() string // Unique id generator
}

Config holds configuration structure for bus library

type Event

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

Event is data structure for any logs

func Emit

func Emit(topicName string, data interface{}, txID string) (*Event, error)

Emit inits a new event and delivers to the interested in handlers

type Handler

type Handler struct {
	Handle  func(e *Event) // handler func to process events
	Matcher string         // topic matcher as regex pattern
}

Handler is a receiver for event reference with the given regex pattern

func (*Handler) Subscriptions

func (h *Handler) Subscriptions() []*Topic

Subscriptions returns all subscriptions of the handler

type Topic

type Topic struct {
	Name string
	// contains filtered or unexported fields
}

Topic structure

func ListTopics

func ListTopics() []*Topic

ListTopics list registered topics

func (*Topic) Handlers

func (t *Topic) Handlers() []*Handler

Handlers returns all handlers of the topic

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL