github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/multitonservice.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 utils
    16  
    17  import (
    18  	"sync"
    19  )
    20  
    21  type KillableService interface {
    22  	Kill()
    23  }
    24  
    25  type MultitonService[K comparable] struct {
    26  	mu sync.Mutex
    27  	m  map[K]KillableService
    28  }
    29  
    30  func (s *MultitonService[K]) Replace(k K, v KillableService) func() {
    31  	s.mu.Lock()
    32  	defer s.mu.Unlock()
    33  
    34  	if s.m == nil {
    35  		s.m = map[K]KillableService{}
    36  	}
    37  
    38  	if prev, ok := s.m[k]; ok {
    39  		prev.Kill()
    40  	}
    41  
    42  	s.m[k] = v
    43  
    44  	return func() {
    45  		s.mu.Lock()
    46  		defer s.mu.Unlock()
    47  		if s.m[k] == v {
    48  			v.Kill()
    49  			delete(s.m, k)
    50  		}
    51  	}
    52  }
    53  
    54  func (s *MultitonService[K]) Kill() {
    55  	s.mu.Lock()
    56  	defer s.mu.Unlock()
    57  	for _, v := range s.m {
    58  		v.Kill()
    59  	}
    60  	s.m = nil
    61  }