github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/common/service/message.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package service
     8  
     9  import "sync"
    10  
    11  // Message thread-safe message register structure.
    12  type Message struct {
    13  	mu     sync.RWMutex
    14  	events []chan<- StateMsg
    15  }
    16  
    17  // MsgEvents returns event message channels.
    18  func (m *Message) MsgEvents() []chan<- StateMsg {
    19  	m.mu.RLock()
    20  	events := append(m.events[:0:0], m.events...)
    21  	m.mu.RUnlock()
    22  
    23  	return events
    24  }
    25  
    26  // RegisterMsgEvent on protocol messages. The message events are triggered for incoming messages. Event
    27  // will not expect any callback on these events unlike Action events.
    28  func (m *Message) RegisterMsgEvent(ch chan<- StateMsg) error {
    29  	if ch == nil {
    30  		return ErrNilChannel
    31  	}
    32  
    33  	m.mu.Lock()
    34  	m.events = append(m.events, ch)
    35  	m.mu.Unlock()
    36  
    37  	return nil
    38  }
    39  
    40  // UnregisterMsgEvent on protocol messages. Refer RegisterMsgEvent().
    41  func (m *Message) UnregisterMsgEvent(ch chan<- StateMsg) error {
    42  	m.mu.Lock()
    43  	for i := 0; i < len(m.events); i++ {
    44  		if m.events[i] == ch {
    45  			m.events = append(m.events[:i], m.events[i+1:]...)
    46  			i--
    47  		}
    48  	}
    49  	m.mu.Unlock()
    50  
    51  	return nil
    52  }