google.golang.org/grpc@v1.62.1/internal/grpcsync/callback_serializer.go (about)

     1  /*
     2   *
     3   * Copyright 2022 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  package grpcsync
    20  
    21  import (
    22  	"context"
    23  
    24  	"google.golang.org/grpc/internal/buffer"
    25  )
    26  
    27  // CallbackSerializer provides a mechanism to schedule callbacks in a
    28  // synchronized manner. It provides a FIFO guarantee on the order of execution
    29  // of scheduled callbacks. New callbacks can be scheduled by invoking the
    30  // Schedule() method.
    31  //
    32  // This type is safe for concurrent access.
    33  type CallbackSerializer struct {
    34  	// done is closed once the serializer is shut down completely, i.e all
    35  	// scheduled callbacks are executed and the serializer has deallocated all
    36  	// its resources.
    37  	done chan struct{}
    38  
    39  	callbacks *buffer.Unbounded
    40  }
    41  
    42  // NewCallbackSerializer returns a new CallbackSerializer instance. The provided
    43  // context will be passed to the scheduled callbacks. Users should cancel the
    44  // provided context to shutdown the CallbackSerializer. It is guaranteed that no
    45  // callbacks will be added once this context is canceled, and any pending un-run
    46  // callbacks will be executed before the serializer is shut down.
    47  func NewCallbackSerializer(ctx context.Context) *CallbackSerializer {
    48  	cs := &CallbackSerializer{
    49  		done:      make(chan struct{}),
    50  		callbacks: buffer.NewUnbounded(),
    51  	}
    52  	go cs.run(ctx)
    53  	return cs
    54  }
    55  
    56  // Schedule adds a callback to be scheduled after existing callbacks are run.
    57  //
    58  // Callbacks are expected to honor the context when performing any blocking
    59  // operations, and should return early when the context is canceled.
    60  //
    61  // Return value indicates if the callback was successfully added to the list of
    62  // callbacks to be executed by the serializer. It is not possible to add
    63  // callbacks once the context passed to NewCallbackSerializer is cancelled.
    64  func (cs *CallbackSerializer) Schedule(f func(ctx context.Context)) bool {
    65  	return cs.callbacks.Put(f) == nil
    66  }
    67  
    68  func (cs *CallbackSerializer) run(ctx context.Context) {
    69  	defer close(cs.done)
    70  
    71  	// TODO: when Go 1.21 is the oldest supported version, this loop and Close
    72  	// can be replaced with:
    73  	//
    74  	// context.AfterFunc(ctx, cs.callbacks.Close)
    75  	for ctx.Err() == nil {
    76  		select {
    77  		case <-ctx.Done():
    78  			// Do nothing here. Next iteration of the for loop will not happen,
    79  			// since ctx.Err() would be non-nil.
    80  		case cb := <-cs.callbacks.Get():
    81  			cs.callbacks.Load()
    82  			cb.(func(context.Context))(ctx)
    83  		}
    84  	}
    85  
    86  	// Close the buffer to prevent new callbacks from being added.
    87  	cs.callbacks.Close()
    88  
    89  	// Run all pending callbacks.
    90  	for cb := range cs.callbacks.Get() {
    91  		cs.callbacks.Load()
    92  		cb.(func(context.Context))(ctx)
    93  	}
    94  }
    95  
    96  // Done returns a channel that is closed after the context passed to
    97  // NewCallbackSerializer is canceled and all callbacks have been executed.
    98  func (cs *CallbackSerializer) Done() <-chan struct{} {
    99  	return cs.done
   100  }