Skip to content

Commit

Permalink
Init for opensource
Browse files Browse the repository at this point in the history
  • Loading branch information
mustafaturan committed Apr 27, 2019
0 parents commit 3f32307
Show file tree
Hide file tree
Showing 27 changed files with 920 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
coverage.out
count.out
example
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: go

go:
- 1.12.x
- master
- tip

before_install:
- go get golang.org/x/tools/cmd/cover
- go get github.com/mattn/goveralls

script:
- go test -v -covermode=count -coverprofile=coverage.out
- $GOPATH/bin/goveralls -coverprofile=coverage.out -service=travis-ci
76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at mustafaturan.net@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
32 changes: 32 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Contributing

## Context

The bus package follows effective Go guidelines and `gofmt` tool to format
codes. It is expected from all contributors to follow the same rules in the
contributing guidelines.

### Readibility over efficiency

For the package, readibility is more important than efficiency of the software.
Ofcourse it doesn't mean that the contributors should write inefficient code.
It is usually possible to do the both at the same time. Unless it is a bug, the
maintainers should take the time to elaborate on different solutions and apply
the reasonable solution.

### Maximum chars in a line

It is intented to use at most `80 chars` in a line even if the Go programming
guidelines allows any number of character in a line. If you are planning to
contribute to the package, please be ready to accept this rule.

## Issues, Bugs, Documentation, Enhancements

Create an issue if there is a bug.

Fork the project.

Make your improvements and write your tests (make sure you covered all the
cases).

Make a pull request.
Empty file added LICENSE
Empty file.
119 changes: 119 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Bus

[![Build Status](https://travis-ci.org/mustafaturan/bus.svg?branch=master)](https://travis-ci.org/mustafaturan/bus)
[![Coverage Status](https://coveralls.io/repos/github/mustafaturan/bus/badge.svg?branch=master)](https://coveralls.io/github/mustafaturan/bus?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/mustafaturan/bus)](https://goreportcard.com/report/github.com/mustafaturan/bus)
[![GoDoc](https://godoc.org/github.com/mustafaturan/bus?status.svg)](https://godoc.org/github.com/mustafaturan/bus)

Bus is a minimalist event/message bus implementation for internal communication.
It is heavily inspired from my [event_bus](https://github.com/otobus/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:

```go
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:

```go
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.

```go
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

```go
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 with order. It
is highly recommended to process events asynchronous. Package leave the decision
to the packages/projects to use concurrency abstractions depending on use-cases.

## Contributing

All contributors should follow [Contributing Guidelines](CONTRIBUTING.md) before creating pull requests.

## Credits

[Mustafa Turan](https://github.com/mustafaturan)

## 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.
14 changes: 14 additions & 0 deletions bus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright 2019 Mustafa Turan. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.

package bus

import (
"sync"
)

type bus struct {
sync.Mutex
next func() string
}
46 changes: 46 additions & 0 deletions bus_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package bus_test

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

func setup(topicNames ...string) {
fn := func() string { return "fakeid" }
bus.Configure(bus.Config{Next: fn})
bus.RegisterTopics(topicNames...)
}

func tearDown(topicNames ...string) {
bus.DeregisterTopics(topicNames...)
}

func fakeHandler(matcher string) bus.Handler {
return bus.Handler{Handle: func(*bus.Event) {}, Matcher: matcher}
}

func fetchTopic(topicName string) *bus.Topic {
for _, t := range bus.ListTopics() {
if t.Name == topicName {
return t
}
}
return nil
}

func isTopicHandler(t *bus.Topic, h *bus.Handler) bool {
for _, th := range t.Handlers() {
if h == th {
return true
}
}
return false
}

func isHandlerKey(key string) bool {
for _, k := range bus.ListHandlerKeys() {
if k == key {
return true
}
}
return false
}
10 changes: 10 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright 2019 Mustafa Turan. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.

package bus

// Config holds configuration structure for bus library
type Config struct {
Next func() string // Unique id generator
}
21 changes: 21 additions & 0 deletions config_actions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2019 Mustafa Turan. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.

package bus

import (
"fmt"
)

var b bus

// Configure sets configuration for bus package
func Configure(c Config) error {
if c.Next == nil {
return fmt.Errorf("Next() id generator func can't be nil")
}

b = bus{next: c.Next}
return nil
}
22 changes: 22 additions & 0 deletions config_actions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package bus_test

import (
"fmt"
"github.com/mustafaturan/bus"
"github.com/stretchr/testify/assert"
"testing"
)

func TestConfigure(t *testing.T) {
fn := func() string { return "newfakeid" }

t.Run("with valid generator", func(t *testing.T) {
c := bus.Config{Next: fn}
assert.Nil(t, bus.Configure(c))
})

t.Run("with valid generator", func(t *testing.T) {
c := bus.Config{Next: nil}
assert.Error(t, fmt.Errorf("id generator func can't be nil"), bus.Configure(c))
})
}
1 change: 1 addition & 0 deletions config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package bus_test
Loading

0 comments on commit 3f32307

Please sign in to comment.