github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/ghcache/partitioner.go (about) 1 /* 2 Copyright 2020 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package ghcache 18 19 import ( 20 "crypto/sha256" 21 "fmt" 22 "net/http" 23 "sync" 24 "time" 25 26 "github.com/sirupsen/logrus" 27 ) 28 29 type roundTripperCreator func(partitionKey string, expiresAt *time.Time) http.RoundTripper 30 31 // partitioningRoundTripper is a http.RoundTripper 32 var _ http.RoundTripper = &partitioningRoundTripper{} 33 34 func newPartitioningRoundTripper(rtc roundTripperCreator) *partitioningRoundTripper { 35 return &partitioningRoundTripper{ 36 roundTripperCreator: rtc, 37 lock: &sync.Mutex{}, 38 roundTrippers: map[string]http.RoundTripper{}, 39 } 40 } 41 42 type partitioningRoundTripper struct { 43 roundTripperCreator roundTripperCreator 44 lock *sync.Mutex 45 roundTrippers map[string]http.RoundTripper 46 } 47 48 func getCachePartition(r *http.Request) string { 49 // Hash the key to make sure we dont leak it into the directory layout 50 return fmt.Sprintf("%x", sha256.Sum256([]byte(r.Header.Get("Authorization")))) 51 } 52 53 func getExpiry(r *http.Request) *time.Time { 54 raw := r.Header.Get(TokenExpiryAtHeader) 55 if raw == "" { 56 return nil 57 } 58 parsed, err := time.Parse(time.RFC3339, raw) 59 if err != nil { 60 logrus.WithError(err).WithFields(logrus.Fields{ 61 "path": r.URL.Path, 62 "raw_value": raw, 63 "user-agent": r.Header.Get("User-Agent"), 64 }).Errorf("failed to parse value of %s header as RFC3339 time", TokenExpiryAtHeader) 65 return nil 66 } 67 return &parsed 68 } 69 70 func (prt *partitioningRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { 71 cachePartition := getCachePartition(r) 72 expiresAt := getExpiry(r) 73 74 prt.lock.Lock() 75 roundTripper, found := prt.roundTrippers[cachePartition] 76 if !found { 77 logrus.WithField("cache-parition-key", cachePartition).Info("Creating a new cache for partition") 78 cachePartitionsCounter.WithLabelValues(cachePartition).Add(1) 79 prt.roundTrippers[cachePartition] = prt.roundTripperCreator(cachePartition, expiresAt) 80 roundTripper = prt.roundTrippers[cachePartition] 81 } 82 prt.lock.Unlock() 83 84 return roundTripper.RoundTrip(r) 85 }