github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/rpc/race.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     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 rpc
    16  
    17  import (
    18  	"context"
    19  	"sync"
    20  )
    21  
    22  type raceResult[T any] struct {
    23  	i   int
    24  	val *T
    25  	err error
    26  }
    27  
    28  type Race[T any] struct {
    29  	ctx       context.Context
    30  	cancel    context.CancelFunc
    31  	nextIndex int
    32  
    33  	resultLock sync.Mutex
    34  	result     *raceResult[T]
    35  }
    36  
    37  // NewRace creates a race to yield the result from one or more candidate
    38  // functions
    39  func NewRace[T any](ctx context.Context) *Race[T] {
    40  	ctx, cancel := context.WithCancel(ctx)
    41  	return &Race[T]{
    42  		ctx:    ctx,
    43  		cancel: cancel,
    44  	}
    45  }
    46  
    47  // Go adds a candidate function to the race by running it in a new goroutine
    48  func (r *Race[T]) Go(fn func(ctx context.Context) (*T, error)) {
    49  	i := r.nextIndex
    50  	r.nextIndex++
    51  
    52  	go func() {
    53  		val, err := fn(r.ctx)
    54  
    55  		r.resultLock.Lock()
    56  		if r.result == nil {
    57  			r.result = &raceResult[T]{i, val, err}
    58  		}
    59  		r.resultLock.Unlock()
    60  
    61  		r.cancel()
    62  	}()
    63  }
    64  
    65  // Wait awaits the first complete function and returns the index and results
    66  // or -1 if the context is cancelled before any candidate finishes.
    67  func (r *Race[T]) Wait() (int, *T, error) {
    68  	<-r.ctx.Done()
    69  
    70  	r.resultLock.Lock()
    71  	res := r.result
    72  	r.resultLock.Unlock()
    73  	if res != nil {
    74  		return res.i, res.val, res.err
    75  	}
    76  	return -1, nil, r.ctx.Err()
    77  }