@ -12,21 +12,51 @@ type Msg interface{}
var ErrHandlerNotFound = errors . New ( "handler not found" )
type TransactionManager interface {
Begin ( ctx context . Context ) ( context . Context , error )
End ( ctx context . Context , err error ) error
}
type Bus interface {
Dispatch ( msg Msg ) error
DispatchCtx ( ctx context . Context , msg Msg ) error
Publish ( msg Msg ) error
// InTransaction starts a transaction and store it in the context.
// The caller can then pass a function with multiple DispatchCtx calls that
// all will be executed in the same transaction. InTransaction will rollback if the
// callback returns an error.s
InTransaction ( ctx context . Context , fn func ( ctx context . Context ) error ) error
AddHandler ( handler HandlerFunc )
AddCtxHandler ( handler HandlerFunc )
AddEventListener ( handler HandlerFunc )
AddWildcardListener ( handler HandlerFunc )
// SetTransactionManager allows the user to replace the internal
// noop TransactionManager that is responsible for manageing
// transactions in `InTransaction`
SetTransactionManager ( tm TransactionManager )
}
func ( b * InProcBus ) InTransaction ( ctx context . Context , fn func ( ctx context . Context ) error ) error {
ctxWithTran , err := b . transactionManager . Begin ( ctx )
if err != nil {
return err
}
err = fn ( ctxWithTran )
b . transactionManager . End ( ctxWithTran , err )
return err
}
type InProcBus struct {
handlers map [ string ] HandlerFunc
listeners map [ string ] [ ] HandlerFunc
wildcardListeners [ ] HandlerFunc
transactionManager TransactionManager
}
// temp stuff, not sure how to handle bus instance, and init yet
@ -37,6 +67,9 @@ func New() Bus {
bus . handlers = make ( map [ string ] HandlerFunc )
bus . listeners = make ( map [ string ] [ ] HandlerFunc )
bus . wildcardListeners = make ( [ ] HandlerFunc , 0 )
bus . transactionManager = & NoopTransactionManager { }
return bus
}
@ -45,6 +78,14 @@ func GetBus() Bus {
return globalBus
}
func SetTransactionManager ( tm TransactionManager ) {
globalBus . SetTransactionManager ( tm )
}
func ( b * InProcBus ) SetTransactionManager ( tm TransactionManager ) {
b . transactionManager = tm
}
func ( b * InProcBus ) DispatchCtx ( ctx context . Context , msg Msg ) error {
var msgName = reflect . TypeOf ( msg ) . Elem ( ) . Name ( )
@ -167,6 +208,15 @@ func Publish(msg Msg) error {
return globalBus . Publish ( msg )
}
func InTransaction ( ctx context . Context , fn func ( ctx context . Context ) error ) error {
return globalBus . InTransaction ( ctx , fn )
}
func ClearBusHandlers ( ) {
globalBus = New ( )
}
type NoopTransactionManager struct { }
func ( * NoopTransactionManager ) Begin ( ctx context . Context ) ( context . Context , error ) { return ctx , nil }
func ( * NoopTransactionManager ) End ( ctx context . Context , err error ) error { return err }