github.com/cloudwego/kitex@v0.9.0/pkg/streaming/util.go (about)

     1  /*
     2   * Copyright 2023 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package streaming
    18  
    19  import (
    20  	"sync"
    21  
    22  	"github.com/cloudwego/kitex/pkg/klog"
    23  	"github.com/cloudwego/kitex/pkg/serviceinfo"
    24  )
    25  
    26  // KitexUnusedProtection may be anonymously referenced in another package to avoid build error
    27  const KitexUnusedProtection = 0
    28  
    29  var userStreamNotImplementingWithDoFinish sync.Once
    30  
    31  // UnaryCompatibleMiddleware returns whether to use compatible middleware for unary.
    32  func UnaryCompatibleMiddleware(mode serviceinfo.StreamingMode, allow bool) bool {
    33  	return allow && mode == serviceinfo.StreamingUnary
    34  }
    35  
    36  // FinishStream records the end of stream
    37  // you can call it manually when all business logic is done, and you don't want to call Recv/Send
    38  // for the io.EOF (which triggers the DoFinish automatically).
    39  // Note: if you're to wrap the original stream in a Client middleware, you should also implement
    40  // WithDoFinish in your Stream implementation.
    41  func FinishStream(s Stream, err error) {
    42  	if st, ok := s.(WithDoFinish); ok {
    43  		st.DoFinish(err)
    44  		return
    45  	}
    46  	// A gentle (only once) warning for existing implementation of streaming.Stream(s)
    47  	userStreamNotImplementingWithDoFinish.Do(func() {
    48  		klog.Warnf("Failed to record the RPCFinish event, due to"+
    49  			" the stream type [%T] does not implement streaming.WithDoFinish", s)
    50  	})
    51  }