github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/syncevent/source.go (about)

     1  // Copyright 2020 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package syncevent
    16  
    17  // Source represents an event source.
    18  type Source interface {
    19  	// SubscribeEvents causes the Source to notify the given Receiver of the
    20  	// given subset of events.
    21  	//
    22  	// Preconditions:
    23  	// * r != nil.
    24  	// * The ReceiverCallback for r must not take locks that are ordered
    25  	//   prior to the Source; for example, it cannot call any Source
    26  	//   methods.
    27  	SubscribeEvents(r *Receiver, filter Set) SubscriptionID
    28  
    29  	// UnsubscribeEvents causes the Source to stop notifying the Receiver
    30  	// subscribed by a previous call to SubscribeEvents that returned the given
    31  	// SubscriptionID.
    32  	//
    33  	// Preconditions: UnsubscribeEvents may be called at most once for any
    34  	// given SubscriptionID.
    35  	UnsubscribeEvents(id SubscriptionID)
    36  }
    37  
    38  // SubscriptionID identifies a call to Source.SubscribeEvents.
    39  type SubscriptionID uint64
    40  
    41  // UnsubscribeAndAck is a convenience function that unsubscribes r from the
    42  // given events from src and also clears them from r.
    43  func UnsubscribeAndAck(src Source, r *Receiver, filter Set, id SubscriptionID) {
    44  	src.UnsubscribeEvents(id)
    45  	r.Ack(filter)
    46  }
    47  
    48  // NoopSource implements Source by never sending events to subscribed
    49  // Receivers.
    50  type NoopSource struct{}
    51  
    52  // SubscribeEvents implements Source.SubscribeEvents.
    53  func (NoopSource) SubscribeEvents(*Receiver, Set) SubscriptionID {
    54  	return 0
    55  }
    56  
    57  // UnsubscribeEvents implements Source.UnsubscribeEvents.
    58  func (NoopSource) UnsubscribeEvents(SubscriptionID) {
    59  }
    60  
    61  // See Broadcaster for a non-noop implementations of Source.