github.com/blend/go-sdk@v1.20220411.3/grpcutil/stream_server_chain.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package grpcutil
     9  
    10  import (
    11  	"google.golang.org/grpc"
    12  )
    13  
    14  // StreamServerChain reads the middleware variadic args and organizes the calls recursively in the order they appear.
    15  func StreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor {
    16  	// if we don't have interceptors, return a no-op.
    17  	if len(interceptors) == 0 {
    18  		return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
    19  			return handler(srv, ss)
    20  		}
    21  	}
    22  
    23  	// if we only have one interceptor, return it
    24  	if len(interceptors) == 1 {
    25  		return interceptors[0]
    26  	}
    27  
    28  	// nest the interceptors
    29  	var nest = func(a, b grpc.StreamServerInterceptor) grpc.StreamServerInterceptor {
    30  		if b == nil {
    31  			return a
    32  		}
    33  		return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
    34  			curried := func(isrv interface{}, istream grpc.ServerStream) error {
    35  				return b(isrv, istream, info, handler)
    36  			}
    37  			return a(srv, ss, info, curried)
    38  		}
    39  	}
    40  
    41  	var outer grpc.StreamServerInterceptor
    42  	for _, step := range interceptors {
    43  		outer = nest(step, outer)
    44  	}
    45  	return outer
    46  }