github.com/google/osv-scalibr@v0.4.1/clients/datasource/pypi_registry_cache.go (about)

     1  // Copyright 2025 Google LLC
     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  //nolint:dupl
    16  package datasource
    17  
    18  import (
    19  	"time"
    20  )
    21  
    22  type pypiRegistryCache struct {
    23  	Timestamp *time.Time
    24  	Responses map[string]response // url -> response
    25  }
    26  
    27  // GobEncode encodes cache to bytes.
    28  func (p *PyPIRegistryAPIClient) GobEncode() ([]byte, error) {
    29  	p.mu.Lock()
    30  	defer p.mu.Unlock()
    31  
    32  	if p.cacheTimestamp == nil {
    33  		now := time.Now().UTC()
    34  		p.cacheTimestamp = &now
    35  	}
    36  
    37  	cache := pypiRegistryCache{
    38  		Timestamp: p.cacheTimestamp,
    39  		Responses: p.responses.GetMap(),
    40  	}
    41  
    42  	return gobMarshal(&cache)
    43  }
    44  
    45  // GobDecode encodes bytes to cache.
    46  func (p *PyPIRegistryAPIClient) GobDecode(b []byte) error {
    47  	var cache pypiRegistryCache
    48  	if err := gobUnmarshal(b, &cache); err != nil {
    49  		return err
    50  	}
    51  
    52  	if cache.Timestamp != nil && time.Since(*cache.Timestamp) >= cacheExpiry {
    53  		// Cache expired
    54  		return nil
    55  	}
    56  
    57  	p.mu.Lock()
    58  	defer p.mu.Unlock()
    59  
    60  	p.cacheTimestamp = cache.Timestamp
    61  	p.responses.SetMap(cache.Responses)
    62  
    63  	return nil
    64  }