github.com/kubeshop/testkube@v1.17.23/pkg/imageinspector/memorystorage.go (about)

     1  package imageinspector
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  )
     7  
     8  type memoryStorage struct {
     9  	data map[Hash]Info
    10  	mu   sync.RWMutex
    11  }
    12  
    13  func NewMemoryStorage() StorageWithTransfer {
    14  	return &memoryStorage{
    15  		data: make(map[Hash]Info),
    16  	}
    17  }
    18  
    19  func (m *memoryStorage) StoreMany(_ context.Context, data map[Hash]Info) error {
    20  	if data == nil {
    21  		return nil
    22  	}
    23  	m.mu.Lock()
    24  	defer m.mu.Unlock()
    25  	for k, v := range data {
    26  		if vv, ok := m.data[k]; !ok || v.FetchedAt.After(vv.FetchedAt) {
    27  			m.data[k] = v
    28  		}
    29  	}
    30  	return nil
    31  }
    32  
    33  func (m *memoryStorage) CopyTo(ctx context.Context, other ...StorageTransfer) (err error) {
    34  	if len(other) == 0 {
    35  		return
    36  	}
    37  	for _, v := range other {
    38  		err = v.StoreMany(ctx, m.data)
    39  		if err != nil {
    40  			return
    41  		}
    42  	}
    43  	return
    44  }
    45  
    46  func (m *memoryStorage) Store(ctx context.Context, request RequestBase, info Info) error {
    47  	return m.StoreMany(ctx, map[Hash]Info{
    48  		hash(request.Registry, request.Image): info,
    49  	})
    50  }
    51  
    52  func (m *memoryStorage) Get(_ context.Context, request RequestBase) (*Info, error) {
    53  	m.mu.RLock()
    54  	defer m.mu.RUnlock()
    55  	if v, ok := m.data[hash(request.Registry, request.Image)]; ok {
    56  		return &v, nil
    57  	}
    58  	return nil, nil
    59  }