github.com/argoproj/argo-events@v1.9.1/eventbus/kafka/base/utils.go (about)

     1  package base
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  )
     7  
     8  func EventKey(source string, subject string) string {
     9  	return fmt.Sprintf("%s.%s", source, subject)
    10  }
    11  
    12  // Batch returns a read only channel that receives values from the
    13  // input channel batched together into a slice. A value is sent to
    14  // the output channel when the slice reaches n elements, or d time
    15  // has elapsed, whichever happens first. Ordering is maintained.
    16  func Batch[T any](n int, d time.Duration, in <-chan T) <-chan []T {
    17  	out := make(chan []T, 1)
    18  
    19  	go func() {
    20  		batch := []T{}
    21  		timer := time.NewTimer(d)
    22  		timer.Stop()
    23  
    24  		defer close(out)
    25  		defer timer.Stop()
    26  
    27  		for {
    28  			select {
    29  			case item, ok := <-in:
    30  				if !ok {
    31  					return
    32  				}
    33  				if len(batch) == 0 {
    34  					timer.Reset(d)
    35  				}
    36  				if batch = append(batch, item); len(batch) == n {
    37  					timer.Stop()
    38  					out <- batch
    39  					batch = nil
    40  				}
    41  			case <-timer.C:
    42  				if len(batch) > 0 {
    43  					out <- batch
    44  					batch = nil
    45  				}
    46  			}
    47  		}
    48  	}()
    49  
    50  	return out
    51  }