github.com/vmware/transport-go@v1.3.4/bridge/subscription.go (about)

     1  // Copyright 2019-2020 VMware, Inc.
     2  // SPDX-License-Identifier: BSD-2-Clause
     3  
     4  package bridge
     5  
     6  import (
     7  	"fmt"
     8  	"github.com/go-stomp/stomp/v3"
     9  	"github.com/google/uuid"
    10  	"github.com/vmware/transport-go/model"
    11  )
    12  
    13  type Subscription interface {
    14  	GetId() *uuid.UUID
    15  	GetMsgChannel() chan *model.Message
    16  	GetDestination() string
    17  	Unsubscribe() error
    18  }
    19  
    20  // Subscription represents a subscription to a broker destination.
    21  type subscription struct {
    22  	c           chan *model.Message // listen to this for incoming messages
    23  	id          *uuid.UUID
    24  	destination string // Destination of where this message was sent.
    25  	stompTCPSub *stomp.Subscription
    26  	wsStompSub  *BridgeClientSub
    27  }
    28  
    29  func (s *subscription) GetId() *uuid.UUID {
    30  	return s.id
    31  }
    32  
    33  func (s *subscription) GetMsgChannel() chan *model.Message {
    34  	return s.c
    35  }
    36  
    37  func (s *subscription) GetDestination() string {
    38  	return s.destination
    39  }
    40  
    41  // Unsubscribe from destination. All channels will be closed.
    42  func (s *subscription) Unsubscribe() error {
    43  
    44  	// if we're using TCP
    45  	if s.stompTCPSub != nil {
    46  		go s.stompTCPSub.Unsubscribe() // local broker hangs, so lets make sure it is non blocking.
    47  		close(s.c)
    48  		return nil
    49  	}
    50  
    51  	// if we're using Websockets.
    52  	if s.wsStompSub != nil {
    53  		s.wsStompSub.Unsubscribe()
    54  		close(s.c)
    55  		return nil
    56  	}
    57  	return fmt.Errorf("cannot unsubscribe from destination %s, no connection", s.destination)
    58  }