github.com/vmware/transport-go@v1.3.4/bus/message_handler.go (about) 1 // Copyright 2019-2020 VMware, Inc. 2 // SPDX-License-Identifier: BSD-2-Clause 3 4 package bus 5 6 import ( 7 "fmt" 8 "github.com/google/uuid" 9 "github.com/vmware/transport-go/model" 10 "sync" 11 ) 12 13 // Signature used for all functions used on bus stream APIs to Handle messages. 14 type MessageHandlerFunction func(*model.Message) 15 16 // Signature used for all functions used on bus stream APIs to Handle errors. 17 type MessageErrorFunction func(error) 18 19 // MessageHandler provides access to the ID the handler is listening for from all messages 20 // It also provides a Handle method that accepts a success and error function as handlers. 21 // The Fire method will fire the message queued when using RequestOnce or RequestStream 22 type MessageHandler interface { 23 GetId() *uuid.UUID 24 GetDestinationId() *uuid.UUID 25 Handle(successHandler MessageHandlerFunction, errorHandler MessageErrorFunction) 26 Fire() error 27 Close() 28 } 29 30 type messageHandler struct { 31 id *uuid.UUID 32 destination *uuid.UUID 33 eventCount int64 34 closed bool 35 channel *Channel 36 requestMessage *model.Message 37 runCount int64 38 ignoreId bool 39 wrapperFunction MessageHandlerFunction 40 successHandler MessageHandlerFunction 41 errorHandler MessageErrorFunction 42 subscriptionId *uuid.UUID 43 invokeOnce *sync.Once 44 channelManager ChannelManager 45 } 46 47 func (msgHandler *messageHandler) Handle(successHandler MessageHandlerFunction, errorHandler MessageErrorFunction) { 48 msgHandler.successHandler = successHandler 49 msgHandler.errorHandler = errorHandler 50 51 msgHandler.subscriptionId, _ = msgHandler.channelManager.SubscribeChannelHandler( 52 msgHandler.channel.Name, msgHandler.wrapperFunction, false) 53 } 54 55 func (msgHandler *messageHandler) Close() { 56 if msgHandler.subscriptionId != nil { 57 msgHandler.channelManager.UnsubscribeChannelHandler( 58 msgHandler.channel.Name, msgHandler.subscriptionId) 59 } 60 } 61 62 func (msgHandler *messageHandler) GetId() *uuid.UUID { 63 return msgHandler.id 64 } 65 66 func (msgHandler *messageHandler) GetDestinationId() *uuid.UUID { 67 return msgHandler.destination 68 } 69 70 func (msgHandler *messageHandler) Fire() error { 71 if msgHandler.requestMessage != nil { 72 sendMessageToChannel(msgHandler.channel, msgHandler.requestMessage) 73 msgHandler.channel.wg.Wait() 74 return nil 75 } else { 76 return fmt.Errorf("nothing to fire, request is empty") 77 } 78 }