github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/rpc/subscription.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"sync"
    23  )
    24  
    25  var (
    26  	// ErrNotificationsUnsupported is returned when the connection doesn't support notifications
    27  	ErrNotificationsUnsupported = errors.New("notifications not supported")
    28  	// ErrNotificationNotFound is returned when the notification for the given id is not found
    29  	ErrSubscriptionNotFound = errors.New("subscription not found")
    30  )
    31  
    32  // ID defines a pseudo random number that is used to identify RPC subscriptions.
    33  type ID string
    34  
    35  // a Subscription is created by a notifier and tight to that notifier. The client can use
    36  // this subscription to wait for an unsubscribe request for the client, see Err().
    37  type Subscription struct {
    38  	ID        ID
    39  	namespace string
    40  	err       chan error // closed on unsubscribe
    41  }
    42  
    43  // Err returns a channel that is closed when the client send an unsubscribe request.
    44  func (s *Subscription) Err() <-chan error {
    45  	return s.err
    46  }
    47  
    48  // notifierKey is used to store a notifier within the connection context.
    49  type notifierKey struct{}
    50  
    51  // Notifier is tight to a RPC connection that supports subscriptions.
    52  // Server callbacks use the notifier to send notifications.
    53  type Notifier struct {
    54  	codec    ServerCodec
    55  	subMu    sync.Mutex
    56  	active   map[ID]*Subscription
    57  	inactive map[ID]*Subscription
    58  	buffer   map[ID][]interface{} // unsent notifications of inactive subscriptions
    59  }
    60  
    61  // newNotifier creates a new notifier that can be used to send subscription
    62  // notifications to the client.
    63  func newNotifier(codec ServerCodec) *Notifier {
    64  	return &Notifier{
    65  		codec:    codec,
    66  		active:   make(map[ID]*Subscription),
    67  		inactive: make(map[ID]*Subscription),
    68  		buffer:   make(map[ID][]interface{}),
    69  	}
    70  }
    71  
    72  // NotifierFromContext returns the Notifier value stored in ctx, if any.
    73  func NotifierFromContext(ctx context.Context) (*Notifier, bool) {
    74  	n, ok := ctx.Value(notifierKey{}).(*Notifier)
    75  	return n, ok
    76  }
    77  
    78  // CreateSubscription returns a new subscription that is coupled to the
    79  // RPC connection. By default subscriptions are inactive and notifications
    80  // are dropped until the subscription is marked as active. This is done
    81  // by the RPC server after the subscription ID is send to the client.
    82  func (n *Notifier) CreateSubscription() *Subscription {
    83  	s := &Subscription{ID: NewID(), err: make(chan error)}
    84  	n.subMu.Lock()
    85  	n.inactive[s.ID] = s
    86  	n.subMu.Unlock()
    87  	return s
    88  }
    89  
    90  // Notify sends a notification to the client with the given data as payload.
    91  // If an error occurs the RPC connection is closed and the error is returned.
    92  func (n *Notifier) Notify(id ID, data interface{}) error {
    93  	n.subMu.Lock()
    94  	defer n.subMu.Unlock()
    95  
    96  	if sub, active := n.active[id]; active {
    97  		n.send(sub, data)
    98  	} else {
    99  		n.buffer[id] = append(n.buffer[id], data)
   100  	}
   101  	return nil
   102  }
   103  
   104  func (n *Notifier) send(sub *Subscription, data interface{}) error {
   105  	notification := n.codec.CreateNotification(string(sub.ID), sub.namespace, data)
   106  	err := n.codec.Write(notification)
   107  	if err != nil {
   108  		n.codec.Close()
   109  	}
   110  	return err
   111  }
   112  
   113  // Closed returns a channel that is closed when the RPC connection is closed.
   114  func (n *Notifier) Closed() <-chan interface{} {
   115  	return n.codec.Closed()
   116  }
   117  
   118  // unsubscribe a subscription.
   119  // If the subscription could not be found ErrSubscriptionNotFound is returned.
   120  func (n *Notifier) unsubscribe(id ID) error {
   121  	n.subMu.Lock()
   122  	defer n.subMu.Unlock()
   123  	if s, found := n.active[id]; found {
   124  		close(s.err)
   125  		delete(n.active, id)
   126  		return nil
   127  	}
   128  	return ErrSubscriptionNotFound
   129  }
   130  
   131  // activate enables a subscription. Until a subscription is enabled all
   132  // notifications are dropped. This method is called by the RPC server after
   133  // the subscription ID was sent to client. This prevents notifications being
   134  // send to the client before the subscription ID is send to the client.
   135  func (n *Notifier) activate(id ID, namespace string) {
   136  	n.subMu.Lock()
   137  	defer n.subMu.Unlock()
   138  
   139  	if sub, found := n.inactive[id]; found {
   140  		sub.namespace = namespace
   141  		n.active[id] = sub
   142  		delete(n.inactive, id)
   143  		// Send buffered notifications.
   144  		for _, data := range n.buffer[id] {
   145  			n.send(sub, data)
   146  		}
   147  		delete(n.buffer, id)
   148  	}
   149  }