<commit_before>/*
Copyright 2018 The Kubernetes 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 ghcache

import (
	"bufio"
	"bytes"
	"net/http"
	"net/http/httputil"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/ghproxy/ghmetrics"
)

// requestCoalescer allows concurrent requests for the same URI to share a
// single upstream request and response.
type requestCoalescer struct {
	sync.Mutex
	cache map[string]*firstRequest

	requestExecutor http.RoundTripper

	hasher ghmetrics.Hasher
}

type firstRequest struct {
	*sync.Cond

	waiting bool
	resp    []byte
	err     error
}

// RoundTrip coalesces concurrent GET requests for the same URI by blocking
// the later requests until the first request returns and then sharing the
// response between all requests.
//
// Notes: Deadlock shouldn't be possible because the map lock is always
// acquired before responseWaiter lock if both locks are to be held and we
// never hold multiple responseWaiter locks.
func (r *requestCoalescer) RoundTrip(req *http.Request) (*http.Response, error) {
	// Only coalesce GET requests
	if req.Method != http.MethodGet {
		resp, err := r.requestExecutor.RoundTrip(req)
		if strings.HasPrefix(req.URL.Path, "graphql") || strings.HasPrefix(req.URL.Path, "/graphql") {
			var tokenBudgetName string
			if val := req.Header.Get(TokenBudgetIdentifierHeader); val != "" {
				tokenBudgetName = val
			} else {
				tokenBudgetName = r.hasher.Hash(req)
			}
			collectMetrics(ModeNoStore, req, resp, tokenBudgetName)
		}
		return resp, err
	}

	var cacheMode = ModeError
	resp, err := func() (*http.Response, error) {
		key := req.URL.String()
		r.Lock()
		firstReq, ok := r.cache[key]
		if ok {
			// Earlier request in flight. Wait for it's response.
			if req.Body != nil {
				defer req.Body.Close() // Since we won't pass the request we must close it.
			}
			firstReq.L.Lock()
			r.Unlock()
			firstReq.waiting = true

			// The documentation for Wait() says:
			// "Because c.L is not locked when Wait first resumes, the caller typically
			// cannot assume that the condition is true when Wait returns. Instead, the
			// caller should Wait in a loop."
			// This does not apply to this use of Wait() because the condition we are
			// waiting for remains true once it becomes true. This lets us avoid the
			// normal check to see if the condition has switched back to false between
			// the signal being sent and this thread acquiring the lock.
			firstReq.Wait()
			firstReq.L.Unlock()

			if firstReq.err != nil {
				// Don't log the error, it will be logged by requester.
				return nil, firstReq.err
			}
			resp, err := http.ReadResponse(bufio.NewReader(bytes.NewBuffer(firstReq.resp)), nil)
			if err != nil {
				logrus.WithField("cache-key", key).WithError(err).Error("Error loading response.")
				return nil, err
			}

			cacheMode = ModeCoalesced
			return resp, nil
		}
		// No earlier request in flight (common case).
		// Register a new responseWaiter and make the request ourself.
		firstReq = &firstRequest{Cond: sync.NewCond(&sync.Mutex{})}
		r.cache[key] = firstReq
		r.Unlock()

		resp, err := r.requestExecutor.RoundTrip(req)
		// Real response received. Remove this responseWaiter from the map THEN
		// wake any requesters that were waiting on this response.
		r.Lock()
		delete(r.cache, key)
		r.Unlock()

		firstReq.L.Lock()
		if firstReq.waiting {
			if err != nil {
				firstReq.resp, firstReq.err = nil, err
			} else {
				// Copy the response before releasing to waiter(s).
				firstReq.resp, firstReq.err = httputil.DumpResponse(resp, true)
			}
			firstReq.Broadcast()
		}<commit_msg>ghproxy: rename 'waiting' field to 'subscribers'<commit_after>/*
Copyright 2018 The Kubernetes 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 ghcache

import (
	"bufio"
	"bytes"
	"net/http"
	"net/http/httputil"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/ghproxy/ghmetrics"
)

// requestCoalescer allows concurrent requests for the same URI to share a
// single upstream request and response.
type requestCoalescer struct {
	sync.Mutex
	cache map[string]*firstRequest

	requestExecutor http.RoundTripper

	hasher ghmetrics.Hasher
}

type firstRequest struct {
	*sync.Cond

	subscribers bool
	resp    []byte
	err     error
}

// RoundTrip coalesces concurrent GET requests for the same URI by blocking
// the later requests until the first request returns and then sharing the
// response between all requests.
//
// Notes: Deadlock shouldn't be possible because the map lock is always
// acquired before responseWaiter lock if both locks are to be held and we
// never hold multiple responseWaiter locks.
func (r *requestCoalescer) RoundTrip(req *http.Request) (*http.Response, error) {
	// Only coalesce GET requests
	if req.Method != http.MethodGet {
		resp, err := r.requestExecutor.RoundTrip(req)
		if strings.HasPrefix(req.URL.Path, "graphql") || strings.HasPrefix(req.URL.Path, "/graphql") {
			var tokenBudgetName string
			if val := req.Header.Get(TokenBudgetIdentifierHeader); val != "" {
				tokenBudgetName = val
			} else {
				tokenBudgetName = r.hasher.Hash(req)
			}
			collectMetrics(ModeNoStore, req, resp, tokenBudgetName)
		}
		return resp, err
	}

	var cacheMode = ModeError
	resp, err := func() (*http.Response, error) {
		key := req.URL.String()
		r.Lock()
		firstReq, ok := r.cache[key]
		if ok {
			// Earlier request in flight. Wait for it's response.
			if req.Body != nil {
				defer req.Body.Close() // Since we won't pass the request we must close it.
			}
			firstReq.L.Lock()
			r.Unlock()
			firstReq.subscribers = true

			// The documentation for Wait() says:
			// "Because c.L is not locked when Wait first resumes, the caller typically
			// cannot assume that the condition is true when Wait returns. Instead, the
			// caller should Wait in a loop."
			// This does not apply to this use of Wait() because the condition we are
			// waiting for remains true once it becomes true. This lets us avoid the
			// normal check to see if the condition has switched back to false between
			// the signal being sent and this thread acquiring the lock.
			firstReq.Wait()
			firstReq.L.Unlock()

			if firstReq.err != nil {
				// Don't log the error, it will be logged by requester.
				return nil, firstReq.err
			}
			resp, err := http.ReadResponse(bufio.NewReader(bytes.NewBuffer(firstReq.resp)), nil)
			if err != nil {
				logrus.WithField("cache-key", key).WithError(err).Error("Error loading response.")
				return nil, err
			}

			cacheMode = ModeCoalesced
			return resp, nil
		}
		// No earlier request in flight (common case).
		// Register a new responseWaiter and make the request ourself.
		firstReq = &firstRequest{Cond: sync.NewCond(&sync.Mutex{})}
		r.cache[key] = firstReq
		r.Unlock()

		resp, err := r.requestExecutor.RoundTrip(req)
		// Real response received. Remove this responseWaiter from the map THEN
		// wake any requesters that were waiting on this response.
		r.Lock()
		delete(r.cache, key)
		r.Unlock()

		firstReq.L.Lock()
		if firstReq.subscribers {
			if err != nil {
				firstReq.resp, firstReq.err = nil, err
			} else {
				// Copy the response before releasing to waiter(s).
				firstReq.resp, firstReq.err = httputil.DumpResponse(resp, true)
			}
			firstReq.Broadcast()
		}
{'fraction_non_alphanumeric': 0.0975170924793091, 'fraction_numerical': 0.0021590500179920835, 'mean_word_length': 3.4163135593220337, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '92482', 'n_tokens_mistral': 2799, 'n_tokens_neox': 2476, 'n_words': 939}