<commit_before>// Copyright 2016 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package health

import (
	"sync"
	"time"
)

// HealthStatusKey is the key to the health status item in the cache.
type HealthStatusKey struct {
	ServiceID       string
	InstanceID      int
	HealthCheckName string
}

// HealthStatusItem is an item stored in the health status cache.
type HealthStatusItem struct {
	value   HealthStatus
	expires time.Time
}

// Value returns the HealthStatus data
func (item *HealthStatusItem) Value() HealthStatus {
	return item.value
}

// Expired returns true when a health status item has expired in the cache.
func (item *HealthStatusItem) Expired() bool {
	return time.Now().After(item.expires)
}

// HealthStatusCache keeps track of the health status items in memory.
type HealthStatusCache struct {
	mu   *sync.Mutex
	data map[HealthStatusKey]HealthStatusItem
	stop chan struct{}
	wg   *sync.WaitGroup
}

// New returns a new HealthStatusCache instance
func New() *HealthStatusCache {
	cache := &HealthStatusCache{
		mu:   &sync.Mutex{},
		data: make(map[HealthStatusKey]HealthStatusItem),
		wg:   &sync.WaitGroup{},
	}
	return cache
}

// SetPurgeFrequency sets the autopurge interval for cache cleanup.
// Stops autopurge if interval is <= 0.
func (cache *HealthStatusCache) SetPurgeFrequency(interval time.Duration) {
	cache.mu.Lock()
	defer cache.mu.Unlock()
	cache.setPurgeFrequency(interval)
}

func (cache *HealthStatusCache) setPurgeFrequency(interval time.Duration) {
	if cache.stop != nil {
		close(cache.stop)
		cache.wg.Wait()
	}
	if interval > 0 {
		cache.stop = make(chan struct{})
		cache.wg.Add(1)
		go func() {
			defer cache.wg.Done()
			timer := time.NewTimer(interval)
			defer timer.Stop()
			for {
				select {
				case <-timer.C:
					cache.DeleteExpired()
					timer.Reset(interval)
				case <-cache.stop:
					return
				}
			}
		}()
	} else {
		cache.stop = nil
	}
}

// Size returns the size of the cache.
func (cache *HealthStatusCache) Size() int {
	cache.mu.Lock()
	defer cache.mu.Unlock()<commit_msg>Fix deadlock btwn SetPurgeFrequency and DeleteExpired<commit_after>// Copyright 2016 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package health

import (
	"sync"
	"time"
)

// HealthStatusKey is the key to the health status item in the cache.
type HealthStatusKey struct {
	ServiceID       string
	InstanceID      int
	HealthCheckName string
}

// HealthStatusItem is an item stored in the health status cache.
type HealthStatusItem struct {
	value   HealthStatus
	expires time.Time
}

// Value returns the HealthStatus data
func (item *HealthStatusItem) Value() HealthStatus {
	return item.value
}

// Expired returns true when a health status item has expired in the cache.
func (item *HealthStatusItem) Expired() bool {
	return time.Now().After(item.expires)
}

// HealthStatusCache keeps track of the health status items in memory.
type HealthStatusCache struct {
	mu   *sync.Mutex
	data map[HealthStatusKey]HealthStatusItem
	stop chan struct{}
	wg   *sync.WaitGroup
}

// New returns a new HealthStatusCache instance
func New() *HealthStatusCache {
	cache := &HealthStatusCache{
		mu:   &sync.Mutex{},
		data: make(map[HealthStatusKey]HealthStatusItem),
		wg:   &sync.WaitGroup{},
	}
	return cache
}

// SetPurgeFrequency sets the autopurge interval for cache cleanup.
// Stops autopurge if interval is <= 0.
func (cache *HealthStatusCache) SetPurgeFrequency(interval time.Duration) {
	cache.mu.Lock()
	if cache.stop != nil {
		close(cache.stop)
		// Unlock before the Wait to avoid deadlock with DeleteExpired()
		cache.mu.Unlock()

		cache.wg.Wait()

		// Reacquire the lock because we're about to change something in cache
		cache.mu.Lock()
	}
	defer cache.mu.Unlock()

	if interval > 0 {
		cache.stop = make(chan struct{})
		cache.wg.Add(1)
		go func(stopChannel chan struct{}) {
			defer cache.wg.Done()
			timer := time.NewTimer(interval)
			defer timer.Stop()
			for {
				select {
				case <-timer.C:
					cache.DeleteExpired()
					timer.Reset(interval)
				case <-stopChannel:
					return
				}
			}
		}(cache.stop)
	} else {
		cache.stop = nil
	}
}

// Size returns the size of the cache.
func (cache *HealthStatusCache) Size() int {
	cache.mu.Lock()
	defer cache.mu.Unlock()
{'fraction_non_alphanumeric': 0.09760693423779913, 'fraction_numerical': 0.0041454682494818165, 'mean_word_length': 3.5719207579672694, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '297227', 'n_tokens_mistral': 1709, 'n_tokens_neox': 1569, 'n_words': 573}