Skip to main content

Tool to simplify the communication of event based services.

Project description

EventPeople

CircleCI

EventPeople is a tool to simplify the communication of event based services. It is an based on the EventBus gem.

The main idea is to provide a tool that can emit or consume events based on its names, the event name has 4 words (resource.origin.action.destination) which defines some important info about what kind of event it is, where it comes from and who is eligible to consume it:

  • resource: Defines which resource this event is related like a user, a product, company or anything that you want;
  • origin: Defines the name of the system which emitted the event;
  • action: What action is made on the resource like create, delete, update, etc. PS: It is recommended to use the Simple Present tense for actions;
  • destination (Optional): This word is optional and if not provided EventPeople will add a .all to the end of the event name. It defines which service should consume the event being emitted, so if it is defined and there is a service whith the given name only this service will receive it. It is very helpful when you need to re-emit some events. Also if it is .all all services will receive it.

As of today EventPeople uses RabbitMQ as its datasource, but there are plans to add support for other Brokers in the future.

Installation

Add this line to your project's requirements.txt file:

event_people>=0.0.3

And then execute

python -m pip install -r requirements.txt

Or install it with:

python -m pip install event_people

And set env vars:

export RABBIT_URL='amqp://guest:guest@localhost:5672'
export RABBIT_EVENT_PEOPLE_APP_NAME='service_name'
export RABBIT_EVENT_PEOPLE_VHOST='event_people'
export RABBIT_EVENT_PEOPLE_TOPIC_NAME='event_people'

Usage

Events

The main component of EventPeople is the Event class which wraps all the logic of an event and whenever you receive or want to send an event you will use it.

It has 2 attributes name and payload:

  • name: The name must follow our conventions, being it 3 (resource.origin.action) or 4 words (resource.origin.action.destination);
  • payload: It is the body of the massage, it should be a Hash object for simplicity and flexibility.
from event_people import Event
from event_people import Emitter

name = 'user.users.create'
body = { id: 42, name: 'John Doe', age: 35 }

event = Event(name, body)

There are 3 main interfaces to use EventPeople on your project:

  • Calling event_people.Emitter.trigger(event) inside your project;
  • Calling event_people.Listener.on(event_name) inside your project;
  • Or extending event_people.ListenersBase and use it as a daemon.

Using the Emitter

You can emit events on your project passing an event_people.event.Event instance to the event_people.emitter.trigger method. Doing this other services that are subscribed to these events will receive it.

from event_people import Event
from event_people import Emitter

event_name = 'receipt.payments.pay.users'
body = { amount: 350.76 }
event = Event(event_name, body)

Emitter.trigger(event)

See more details

Listeners

You can subscribe to events based on patterns for the event names you want to consume or you can use the full name of the event to consume single events.

We follow the RabbitMQ pattern matching model, so given each word of the event name is separated by a dot (.), you can use the following symbols:

  • * (star): to match exactly one word. Example resource.*.*.all;
  • # (hash): to match zero or more words. Example resource.#.all.

Other important aspect of event consumming is the result of the processing we provide 3 methods so you can inform the Broker what to do with the event next:

  • success!: should be called when the event was processed successfuly and the can be discarded;
  • fail!: should be called when an error ocurred processing the event and the message should be requeued;
  • reject!: should be called whenever a message should be discarded without being processed.

Given you want to consume a single event inside your project you can use the event_people.Listener.on method. It consumes a single event, given there are events available to be consumed with the given name pattern.

from event_people import Listener
from event_people import Event


def callback_method(event, context):
    print("")
    print("  - Received the %r message from %r:", event.name, event.origin)
    print("     Message: %r", event.body)
    print("")

    context.success()


event_name = 'resource.origin.action.all'

Listener.on(event_name, callback_method)

See more details

You can also receive all available messages using a loop:

from event_people import Listener
from event_people import Event

has_events = true

def callback_method(event, context):
    has_events = true
    print("")
    print("  - Received the %r message from %r:", event.name, event.origin)
    print("     Message: %r", event.body)
    print("")

    context.success()


event_name = 'resource.origin.action.all'


while(has_events):
    has_events = false
    Listener.on(event_name, callback_method)

Multiple events routing

If your project needs to handle lots of events you can extend eventPeople.ListenersBase class to bind how many events you need to instance methods, so whenever an event is received the method will be called automatically.

from event_people import ListenersBase
from event_people import Event

class CustomEventListener(Base):
    self.bind('resource.custom.pay', self.pay)
    self.bind('resource.custom.receive', self.receive)
    self.bind('resource.custom.private.service', self.private_channel)

    def pay(event):
        print("Paid %r for %r ~> %r", event.body['amount'], event.body['name'], event.name)

        self.success()

    def receive(event):
        if (event.body.amount > 500):
          print("Received %r from %r ~> %r", event.body['amount'], event.body['name'], event.name)
      else:
          print("[consumer] Got SKIPPED message")
          return self.reject()

          self.success();

  def private_channel(event):
    print("[consumer] Got a private message: \"%r\" ~> %r", event.body['message'], event.name)

    self.success();

See more details

Creating a Daemon

If you have the need to create a deamon to consume messages on background you can use the eventPeople.Daemon.start method to do so with ease. Just remember to define or import all the event bindings before starting the daemon.

from event_people import Daemon
from event_people import BaseListener

class CustomEventListener(BaseListener):
    def pay(self, event):
        print(f"Paid {event.body['amount']} for {event.body['name']} ~> {event.name}")

        self.success()

    def receive(self, event):
        if event.body['amount'] > 500:
            print(f"Received {event.body['amount']} from {event.body['name']} ~> {event.name}")
        else:
            print('[consumer] Got SKIPPED message')

            return self.reject()

        self.success()

    def private_channel(self, event):
        print(f"[consumer] Got a private message: \"{event.body['message']}\" ~> {event.name}")

        self.success()

    def ignore_me(self, event):
        print(f"This should never be called...")
        print(f"Spying on other systems: \"{event.body['message']}\" ~> {event.name}")

        self.success()

CustomEventListener.bind_event('resource.*.pay', 'pay')
CustomEventListener.bind_event('resource.custom.receive', 'receive')
CustomEventListener.bind_event('resource.custom.private.service_name', 'private_channel')
CustomEventListener.bind_event('resource.custom.ignored.other_service', 'ignore_me')
CustomEventListener.bind_event('resource.custom.pay.all', 'receive')

print('****************** Daemon Ready ******************');

Daemon.start()

See more details

Development

After checking out the repo, run bin/setup to install dependencies. Then, run bin/test to run the tests.

To install this package onto your local machine, run python -m pip install -e ..

Contributing

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request

License

The package is available as open source under the terms of the LGPL 3.0 License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

event_people-0.1.1.tar.gz (14.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

event_people-0.1.1-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file event_people-0.1.1.tar.gz.

File metadata

  • Download URL: event_people-0.1.1.tar.gz
  • Upload date:
  • Size: 14.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.2

File hashes

Hashes for event_people-0.1.1.tar.gz
Algorithm Hash digest
SHA256 fed35bd6163917e9fe97261ca6b018c4aa708f71051e7de80b3b14629d1a26be
MD5 1124d5cbc6f85f2014f8c0abaa1c1096
BLAKE2b-256 194ed3763acc219e4a0d92bb9014810d9470f867c9824dff7b9d4f88d2e51b2b

See more details on using hashes here.

File details

Details for the file event_people-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: event_people-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 14.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.2

File hashes

Hashes for event_people-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1ecd4842e8544c3f88e622071b650bf32e587380eb868ab09fc9b50f62334e6c
MD5 1210e8a0056514ae534146cf1f6b3936
BLAKE2b-256 2459924bd65779418976fcc0bf9baf9e25e126732194e9da50712fa7cd406c01

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page