File: http_client_pool.go

package info (click to toggle)
nextcloud-spreed-signaling 2.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,620 kB
  • sloc: sh: 447; makefile: 187; python: 78
file content (154 lines) | stat: -rw-r--r-- 3,673 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/**
 * Standalone signaling server for the Nextcloud Spreed app.
 * Copyright (C) 2017 struktur AG
 *
 * @author Joachim Bauch <bauch@struktur.de>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package signaling

import (
	"context"
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"sync"

	"github.com/prometheus/client_golang/prometheus"
)

func init() {
	RegisterHttpClientPoolStats()
}

type Pool struct {
	pool chan *http.Client

	currentConnections prometheus.Gauge
}

func (p *Pool) get(ctx context.Context) (client *http.Client, err error) {
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case client := <-p.pool:
		p.currentConnections.Inc()
		return client, nil
	}
}

func (p *Pool) Put(c *http.Client) {
	p.currentConnections.Dec()
	p.pool <- c
}

func newPool(host string, constructor func() *http.Client, size int) (*Pool, error) {
	if size <= 0 {
		return nil, fmt.Errorf("can't create empty pool")
	}

	p := &Pool{
		pool:               make(chan *http.Client, size),
		currentConnections: connectionsPerHostCurrent.WithLabelValues(host),
	}
	for size > 0 {
		c := constructor()
		p.pool <- c
		size--
	}
	return p, nil
}

type HttpClientPool struct {
	mu sync.Mutex

	transport *http.Transport
	clients   map[string]*Pool

	maxConcurrentRequestsPerHost int
}

func NewHttpClientPool(maxConcurrentRequestsPerHost int, skipVerify bool) (*HttpClientPool, error) {
	if maxConcurrentRequestsPerHost <= 0 {
		return nil, fmt.Errorf("can't create empty pool")
	}

	tlsconfig := &tls.Config{
		InsecureSkipVerify: skipVerify,
	}
	transport := &http.Transport{
		MaxIdleConnsPerHost: maxConcurrentRequestsPerHost,
		TLSClientConfig:     tlsconfig,
		Proxy:               http.ProxyFromEnvironment,
	}

	result := &HttpClientPool{
		transport: transport,
		clients:   make(map[string]*Pool),

		maxConcurrentRequestsPerHost: maxConcurrentRequestsPerHost,
	}
	return result, nil
}

func (p *HttpClientPool) getPool(url *url.URL) (*Pool, error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if pool, found := p.clients[url.Host]; found {
		return pool, nil
	}

	pool, err := newPool(url.Host, func() *http.Client {
		return &http.Client{
			Transport: p.transport,
			// Only send body in redirect if going to same scheme / host.
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				if len(via) >= 10 {
					return errors.New("stopped after 10 redirects")
				} else if len(via) > 0 {
					viaReq := via[len(via)-1]
					if req.URL.Scheme != viaReq.URL.Scheme || req.URL.Host != viaReq.URL.Host {
						return ErrNotRedirecting
					}
				}
				return nil
			},
		}
	}, p.maxConcurrentRequestsPerHost)
	if err != nil {
		return nil, err
	}

	p.clients[url.Host] = pool
	return pool, nil
}

func (p *HttpClientPool) Get(ctx context.Context, url *url.URL) (*http.Client, *Pool, error) {
	pool, err := p.getPool(url)
	if err != nil {
		return nil, nil, err
	}

	client, err := pool.get(ctx)
	if err != nil {
		return nil, nil, err
	}

	return client, pool, err
}