Categorygithub.com/andrewwebber/cqrs
modulepackage
1.0.0
Repository: https://github.com/andrewwebber/cqrs.git
Documentation: pkg.go.dev

# README

CQRS framework in go

Join the chat at https://gitter.im/andrewwebber/cqrs GoDoc Build Status

Project Summary

The package provides a framework for quickly implementing a CQRS style application. The framework attempts to provides helpful functions to facilitate:

  • Event Sourcing
  • Command issuing and processing
  • Event publishing
  • Read model generation from published events

Example code

Example test scenario (inmemory)

Example test scenario (couchbase, rabbitmq)

Example CQRS scaleout/concurrent test

Test Scenario

The example test scenario is of a simple bank account that seeks to track, using event sourcing, a customers balance and login password

The are two main areas of concern at the application level, the Write model and Read model. The read model is aimed to facilitate fast reads (read model projections) The write model is where the business logic get executed and asynchronously notifies the read models

Write model - Using Event Sourcing

Account

type Account struct {
  cqrs.EventSourceBased

  FirstName    string
  LastName     string
  EmailAddress string
  PasswordHash []byte
  Balance      float64
}

To compensate for golang's lack of inheritance, a combination of type embedding and a call convention pattern are utilized.

func NewAccount(firstName string, lastName string, emailAddress string, passwordHash []byte, initialBalance float64) *Account {
  account := new(Account)
  account.EventSourceBased = cqrs.NewEventSourceBased(account)

  event := AccountCreatedEvent{firstName, lastName, emailAddress, passwordHash, initialBalance}
  account.Update(event)
  return account
}

The 'attached' Update function being called above will now provide the infrastructure for routing events to event handlers. A function prefixed with 'Handle' and named with the name of the event expected with be called by the infrastructure.

func (account *Account) HandleAccountCreatedEvent(event AccountCreatedEvent) {
  account.EmailAddress = event.EmailAddress
  account.FirstName = event.FirstName
  account.LastName = event.LastName
  account.PasswordHash = event.PasswordHash
}

The above code results in an account object being created with one single pending event namely AccountCreatedEvent. Events will then be persisted once saved to an event sourcing repository. If a repository is created with an event publisher then events saved for the purposes of event sourcing will also be published

persistance := cqrs.NewInMemoryEventStreamRepository()
bus := cqrs.NewInMemoryEventBus()
repository := cqrs.NewRepositoryWithPublisher(persistance, bus)
...
repository.Save(account)

Account Events

type AccountCreatedEvent struct {
  FirstName      string
  LastName       string
  EmailAddress   string
  PasswordHash   []byte
  InitialBalance float64
}

type EmailAddressChangedEvent struct {
  PreviousEmailAddress string
  NewEmailAddress      string
}

type PasswordChangedEvent struct {
  NewPasswordHash []byte
}

type AccountCreditedEvent struct {
  Amount float64
}

type AccountDebitedEvent struct {
  Amount float64
}

Events souring events are raised using the embedded Update function. These events will eventually be published to the read models indirectly via an event bus

func (account *Account) ChangePassword(newPassword string) error {
  if len(newPassword) < 1 {
    return errors.New("Invalid newPassword length")
  }

  hashedPassword, err := GetHashForPassword(newPassword)
  if err != nil {
    panic(err)
  }

  account.Update(PasswordChangedEvent{hashedPassword})

  return nil
}

func (account *Account) HandlePasswordChangedEvent(event PasswordChangedEvent) {
  account.PasswordHash = event.NewPasswordHash
}

Again the calling convention routes our PasswordChangedEvent to the corresponding HandlePasswordChangedEvent instance function

Read Model

Accounts projection

type ReadModelAccounts struct {
  Accounts map[string]*AccountReadModel
}

type AccountReadModel struct {
  ID           string
  FirstName    string
  LastName     string
  EmailAddress string
  Balance      float64
}

Users projection

type UsersModel struct {
  Users    map[string]*User
}

type User struct {
  ID           string
  FirstName    string
  LastName     string
  EmailAddress string
  PasswordHash []byte
}

Infrastructure

There are a number of key elements to the CQRS infrastructure.

  • Event sourcing repository (a repository for event sourcing based business objects)
  • Event publisher (publishes new events to an event bus)
  • Event handler (dispatches received events to call handlers)
  • Command publisher (publishes new commands to a command bus)
  • Command handler (dispatches received commands to call handlers)

Event sourcing and integration events

Nested packages within this repository show example implementations using Couchbase Server and RabbitMQ. The core library includes in-memory implementations for testing and quick prototyping

persistance := cqrs.NewInMemoryEventStreamRepository()
bus := cqrs.NewInMemoryEventBus()
repository := cqrs.NewRepositoryWithPublisher(persistance, bus)

With the infrastructure implementations instantiated a stock event dispatcher is provided to route received events to call handlers

readModel := NewReadModelAccounts()
usersModel := NewUsersModel()

eventDispatcher := cqrs.NewVersionedEventDispatchManager(bus)
eventDispatcher.RegisterEventHandler(AccountCreatedEvent{}, func(event cqrs.VersionedEvent) error {
  readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
  usersModel.UpdateViewModel([]cqrs.VersionedEvent{event})
  return nil
})

We can also register a global handler to be called for all events. This becomes useful when logging system wide events and when our read models are smart enough to filter out irrelevant events

integrationEventsLog := cqrs.NewInMemoryEventStreamRepository()
eventDispatcher.RegisterGlobalHandler(func(event cqrs.VersionedEvent) error {
  integrationEventsLog.SaveIntegrationEvent(event)
  readModel.UpdateViewModel([]cqrs.VersionedEvent{event})
  usersModel.UpdateViewModel([]cqrs.VersionedEvent{event})
  return nil
})

Within your read models the idea is that you implement the updating of your pre-pared read model based upon the incoming event notifications

Commands

Commands are processed by command handlers similar to event handlers. We can make direct changes to our write model and indirect changes to our read models by correctly processing commands and then raising integration events upon command completion.

commandBus := cqrs.NewInMemoryCommandBus()
commandDispatcher := cqrs.NewCommandDispatchManager(commandBus)
RegisterCommandHandlers(commandDispatcher, repository)

Commands can be issued using a command bus. Typically a command is a simple struct. The application layer command struct is then wrapped within a cqrs.Command using the cqrs.CreateCommand helper function

changePasswordCommand := cqrs.CreateCommand(
  ChangePasswordCommand{accountID, "$ThisIsANOTHERPassword"})
commandBus.PublishCommands([]cqrs.Command{changePasswordCommand})

The corresponding command handler for the ChangePassword command plays the role of a DDD aggregate root; responsible for the consistency and lifetime of aggregates and entities within the system)

commandDispatcher.RegisterCommandHandler(ChangePasswordCommand{}, func(command cqrs.Command) error {
  changePasswordCommand := command.Body.(ChangePasswordCommand)
  // Load account from storage
  account, err := NewAccountFromHistory(changePasswordCommand.AccountID, repository)
  if err != nil {
    return err
  }

  account.ChangePassword(changePasswordCommand.NewPassword)

  // Persist new events
  repository.Save(account)  
  return nil
})

As the read models become consistant, within the tests, we check at the end of the test if everything is in sync

if account.EmailAddress != lastEmailAddress {
  t.Fatal("Expected emailaddress to be ", lastEmailAddress)
}

if account.Balance != readModel.Accounts[accountID].Balance {
  t.Fatal("Expected readmodel to be synced with write model")
}

# Packages

Package couchbase provides an event sourcing implementation in couchbase for the CQRS and Event Sourcing framework Current version: experimental .
Package rabbit provides an event and command bus for the CQRS and Event Sourcing framework Current version: experimental .

# Functions

CreateCommand is a helper for creating a new command object with populated default properties.
CreateCommandWithCorrelationID is a helper for creating a new command object with populated default properties.
DeliverCQRSError will deliver a CQRS error.
NewCommandDispatchManager is a constructor for the CommandDispatchManager.
NewEventSourceBased constructor.
NewEventSourceBasedWithID constructor.
NewInMemoryCommandBus constructor.
NewInMemoryEventBus constructor.
NewInMemoryEventStreamRepository constructor.
NewMapBasedCommandDispatcher is a constructor for the MapBasedVersionedCommandDispatcher.
NewRepository constructs an EventSourcingRepository.
NewRepositoryWithPublisher constructs an EventSourcingRepository with a VersionedEventPublisher to dispatch events once persisted to the EventStreamRepository.
NewTypeRegistry constructs a new TypeRegistry.
NewUUIDString returns a new UUID.
NewVersionedEventDispatcher is a constructor for the MapBasedVersionedEventDispatcher.
NewVersionedEventDispatchManager is a constructor for the VersionedEventDispatchManager.

# Constants

CQRSErrorEventType ...

# Variables

ErrConcurrencyWhenSavingEvents is raised when a concurrency error has occured when saving events.
ErrNonePendingWhenSavingEvents is raised when a save is issued but no events are pending for the eventsourced entity.
No description provided by the author

# Structs

Command represents an actor intention to alter the state of the system.
CommandDispatchManager is responsible for coordinating receiving messages from command receivers and dispatching them to the command dispatcher.
CommandReceiverOptions is an initalization structure to communicate to and from a command receiver go routine.
CommandTransactedAccept is the message routed from a command receiver to the command manager.
ErrorEvent is a generic event raised within the CQRS framework.
EventSourceBased provider a base class for aggregate times wishing to contain basis helper functionality for event sourcing.
InMemoryCommandBus provides an inmemory implementation of the CommandPublisher CommandReceiver interfaces.
InMemoryEventBus provides an inmemory implementation of the VersionedEventPublisher VersionedEventReceiver interfaces.
InMemoryEventStreamRepository provides an inmemory event sourcing repository.
MapBasedCommandDispatcher is a simple implementation of the command dispatcher.
MapBasedVersionedEventDispatcher is a simple implementation of the versioned event dispatcher.
VersionedEvent represents an event in the past for an aggregate.
VersionedEventDispatchManager is responsible for coordinating receiving messages from event receivers and dispatching them to the event dispatcher.
VersionedEventReceiverOptions is an initalization structure to communicate to and from an event receiver go routine.
VersionedEventTransactedAccept is the message routed from an event receiver to the event manager.

# Interfaces

CommandBus ...
CommandDispatcher is responsible for routing commands from the command manager to call handlers responsible for processing received commands.
CommandPublisher is responsilbe for publishing commands.
CommandReceiver is responsible for receiving commands.
EventBus ...
EventSourced providers an interface for event sourced aggregate types.
EventSourcingRepository is a repository for event source based aggregates.
EventStreamRepository is a persistance layer for events associated with aggregates by ID.
No description provided by the author
TypeRegistry providers a helper registry for mapping event types and handlers after performance json serializaton.
VersionedEventDispatcher is responsible for routing events from the event manager to call handlers responsible for processing received events.
VersionedEventPublicationLogger is responsible to retreiving all events ever published to facilitate readmodel reconstruction.
VersionedEventPublisher is responsible for publishing events that have been saved to the event store\repository.
VersionedEventReceiver is responsible for receiving globally published events.

# Type aliases

ByCreated is an alias for sorting VersionedEvents by the create field.
CommandHandler is a function that takes a command.
HandlersCache is a map of types to functions that will be used to route event sourcing events.
TypeCache is a map of strings to reflect.Type structures.
VersionedEventHandler is a function that takes a versioned event.