Skip to content

Commit 04f0644

Browse files
committed
Fix linter findings for: funlen, nestif, gocognit, revive, cyclop
1 parent 635ac45 commit 04f0644

File tree

4 files changed

+125
-104
lines changed

4 files changed

+125
-104
lines changed

.golangci.yaml

-5
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,7 @@ linters:
1717
- ireturn
1818
- gosec
1919
- noctx
20-
- funlen
21-
- nestif
22-
- gocognit
2320
- interfacer
24-
- revive
25-
- cyclop
2621

2722
# deprecated:
2823
- scopelint

internal/processor/peak.go

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ func (rp *RequestProcessor) startPeakHandling() error {
3535
return nil
3636
}
3737

38+
// registerPeakRequest registers requests coming in the peak time.
39+
// Such requests can be prefetched afterwards just before the peak time comes.
3840
func (rp *RequestProcessor) savePeakRequest(cacheDigest string, r *http.Request) {
3941
if _, min, _ := time.Now().Clock(); min == 30 {
4042
rp.peakRequest30.Store(cacheDigest, *r)

internal/processor/processor.go

+63-42
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func plainTextAgents() []string {
3939
}
4040
}
4141

42-
type responseWithHeader struct {
42+
type ResponseWithHeader struct {
4343
InProgress bool // true if the request is being processed
4444
Expires time.Time // expiration time of the cache entry
4545

@@ -105,14 +105,12 @@ func (rp *RequestProcessor) Start() error {
105105
return rp.startPeakHandling()
106106
}
107107

108-
func (rp *RequestProcessor) ProcessRequest(r *http.Request) (*responseWithHeader, error) {
108+
func (rp *RequestProcessor) ProcessRequest(r *http.Request) (*ResponseWithHeader, error) {
109109
var (
110-
response *responseWithHeader
111-
cacheEntry responseWithHeader
112-
err error
110+
response *ResponseWithHeader
111+
ip = util.ReadUserIP(r)
113112
)
114113

115-
ip := util.ReadUserIP(r)
116114
if ip != "127.0.0.1" {
117115
rp.stats.Inc("total")
118116
}
@@ -137,46 +135,68 @@ func (rp *RequestProcessor) ProcessRequest(r *http.Request) (*responseWithHeader
137135
return get(r, rp.upstreamTransport)
138136
}
139137

138+
// processing cached request
140139
cacheDigest := getCacheDigest(r)
141140

142-
foundInCache := false
143-
144141
rp.savePeakRequest(cacheDigest, r)
145142

146-
cacheBody, ok := rp.lruCache.Get(cacheDigest)
147-
if ok {
148-
cacheEntry, ok = cacheBody.(responseWithHeader)
143+
response = rp.processRequestFromCache(r)
144+
if response != nil {
145+
return response, nil
149146
}
150-
if ok {
151-
rp.stats.Inc("cache1")
152147

153-
// if after all attempts we still have no answer,
154-
// we try to make the query on our own
155-
for attempts := 0; attempts < 300; attempts++ {
156-
if !ok || !cacheEntry.InProgress {
157-
break
158-
}
159-
time.Sleep(30 * time.Millisecond)
160-
cacheBody, ok = rp.lruCache.Get(cacheDigest)
161-
if ok && cacheBody != nil {
162-
if v, ok := cacheBody.(responseWithHeader); ok {
163-
cacheEntry = v
164-
}
165-
}
166-
}
167-
if cacheEntry.InProgress {
168-
log.Printf("TIMEOUT: %s\n", cacheDigest)
148+
return rp.processUncachedRequest(r)
149+
}
150+
151+
// processRequestFromCache processes requests using the cache.
152+
// If no entry in cache found, nil is returned.
153+
func (rp *RequestProcessor) processRequestFromCache(r *http.Request) *ResponseWithHeader {
154+
var (
155+
cacheEntry ResponseWithHeader
156+
cacheDigest = getCacheDigest(r)
157+
ok bool
158+
)
159+
160+
cacheBody, _ := rp.lruCache.Get(cacheDigest)
161+
cacheEntry, ok = cacheBody.(ResponseWithHeader)
162+
if !ok {
163+
return nil
164+
}
165+
166+
// if after all attempts we still have no answer,
167+
// we try to make the query on our own
168+
for attempts := 0; attempts < 300; attempts++ {
169+
if !ok || !cacheEntry.InProgress {
170+
break
169171
}
170-
if ok && !cacheEntry.InProgress && cacheEntry.Expires.After(time.Now()) {
171-
response = &cacheEntry
172-
foundInCache = true
172+
time.Sleep(30 * time.Millisecond)
173+
cacheBody, _ = rp.lruCache.Get(cacheDigest)
174+
v, ok := cacheBody.(ResponseWithHeader)
175+
if ok {
176+
cacheEntry = v
173177
}
174178
}
179+
if cacheEntry.InProgress {
180+
log.Printf("TIMEOUT: %s\n", cacheDigest)
181+
}
182+
if ok && !cacheEntry.InProgress && cacheEntry.Expires.After(time.Now()) {
183+
rp.stats.Inc("cache1")
175184

176-
if foundInCache {
177-
return response, nil
185+
return &cacheEntry
178186
}
179187

188+
return nil
189+
}
190+
191+
// processUncachedRequest processes requests that were not found in the cache.
192+
func (rp *RequestProcessor) processUncachedRequest(r *http.Request) (*ResponseWithHeader, error) {
193+
var (
194+
cacheDigest = getCacheDigest(r)
195+
ip = util.ReadUserIP(r)
196+
response *ResponseWithHeader
197+
err error
198+
)
199+
180200
// Response was not found in cache.
181201
// Starting real handling.
182202
format := r.URL.Query().Get("format")
@@ -187,13 +207,14 @@ func (rp *RequestProcessor) ProcessRequest(r *http.Request) (*responseWithHeader
187207
}
188208
}
189209

190-
// How many IP addresses are known.
210+
// Count, how many IP addresses are known.
191211
_, err = rp.geoIPCache.Read(ip)
192212
if err == nil {
193213
rp.stats.Inc("geoip")
194214
}
195215

196-
rp.lruCache.Add(cacheDigest, responseWithHeader{InProgress: true})
216+
// Indicate, that the request is being handled.
217+
rp.lruCache.Add(cacheDigest, ResponseWithHeader{InProgress: true})
197218

198219
response, err = get(r, rp.upstreamTransport)
199220
if err != nil {
@@ -209,7 +230,7 @@ func (rp *RequestProcessor) ProcessRequest(r *http.Request) (*responseWithHeader
209230
return response, nil
210231
}
211232

212-
func get(req *http.Request, transport *http.Transport) (*responseWithHeader, error) {
233+
func get(req *http.Request, transport *http.Transport) (*ResponseWithHeader, error) {
213234
client := &http.Client{
214235
Transport: transport,
215236
}
@@ -245,7 +266,7 @@ func get(req *http.Request, transport *http.Transport) (*responseWithHeader, err
245266
return nil, err
246267
}
247268

248-
return &responseWithHeader{
269+
return &ResponseWithHeader{
249270
InProgress: false,
250271
Expires: time.Now().Add(time.Duration(randInt(1000, 1500)) * time.Second),
251272
Body: body,
@@ -282,7 +303,7 @@ func dontCache(req *http.Request) bool {
282303
// Insecure queries are marked by the frontend web server
283304
// with X-Forwarded-Proto header:
284305
// `proxy_set_header X-Forwarded-Proto $scheme;`.
285-
func redirectInsecure(req *http.Request) (*responseWithHeader, bool) {
306+
func redirectInsecure(req *http.Request) (*ResponseWithHeader, bool) {
286307
if isPlainTextAgent(req.Header.Get("User-Agent")) {
287308
return nil, false
288309
}
@@ -304,7 +325,7 @@ The document has moved
304325
</BODY></HTML>
305326
`, target))
306327

307-
return &responseWithHeader{
328+
return &ResponseWithHeader{
308329
InProgress: false,
309330
Expires: time.Now().Add(time.Duration(randInt(1000, 1500)) * time.Second),
310331
Body: body,
@@ -340,8 +361,8 @@ func ipFromAddr(s string) string {
340361
}
341362

342363
// fromCadre converts Cadre into a responseWithHeader.
343-
func fromCadre(cadre *routing.Cadre) *responseWithHeader {
344-
return &responseWithHeader{
364+
func fromCadre(cadre *routing.Cadre) *ResponseWithHeader {
365+
return &ResponseWithHeader{
345366
Body: cadre.Body,
346367
Expires: cadre.Expires,
347368
StatusCode: 200,

srv.go

+60-57
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ func serve(conf *config.Config) error {
7979
mux = http.NewServeMux()
8080

8181
// logger is optimized requests logger.
82-
logger *logging.RequestLogger
82+
logger = logging.NewRequestLogger(
83+
conf.Logging.AccessLog,
84+
time.Duration(conf.Logging.Interval)*time.Second)
8385

8486
rp *processor.RequestProcessor
8587

@@ -89,25 +91,18 @@ func serve(conf *config.Config) error {
8991
// numberOfServers started. If 0, exit.
9092
numberOfServers int
9193

92-
errorsLog *logging.LogSuppressor
94+
errorsLog = logging.NewLogSuppressor(
95+
conf.Logging.ErrorsLog,
96+
[]string{
97+
"error reading preface from client",
98+
"TLS handshake error from",
99+
},
100+
logLineStart,
101+
)
93102

94103
err error
95104
)
96105

97-
// logger is optimized requests logger.
98-
logger = logging.NewRequestLogger(
99-
conf.Logging.AccessLog,
100-
time.Duration(conf.Logging.Interval)*time.Second)
101-
102-
errorsLog = logging.NewLogSuppressor(
103-
conf.Logging.ErrorsLog,
104-
[]string{
105-
"error reading preface from client",
106-
"TLS handshake error from",
107-
},
108-
logLineStart,
109-
)
110-
111106
rp, err = processor.NewRequestProcessor(conf)
112107
if err != nil {
113108
return fmt.Errorf("log processor initialization: %w", err)
@@ -123,11 +118,32 @@ func serve(conf *config.Config) error {
123118
return err
124119
}
125120

126-
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
121+
mux.HandleFunc("/", mainHandler(rp, logger))
122+
123+
if conf.Server.PortHTTP != 0 {
124+
go serveHTTP(mux, conf.Server.PortHTTP, errorsLog, errs)
125+
numberOfServers++
126+
}
127+
if conf.Server.PortHTTPS != 0 {
128+
go serveHTTPS(mux, conf.Server.PortHTTPS, conf.Server.TLSCertFile, conf.Server.TLSKeyFile, errorsLog, errs)
129+
numberOfServers++
130+
}
131+
if numberOfServers == 0 {
132+
return types.ErrNoServersConfigured
133+
}
134+
135+
return <-errs // block until one of the servers writes an error
136+
}
137+
138+
func mainHandler(
139+
rp *processor.RequestProcessor,
140+
logger *logging.RequestLogger,
141+
) func(http.ResponseWriter, *http.Request) {
142+
return func(w http.ResponseWriter, r *http.Request) {
127143
if err := logger.Log(r); err != nil {
128144
log.Println(err)
129145
}
130-
// printStat()
146+
131147
response, err := rp.ProcessRequest(r)
132148
if err != nil {
133149
log.Println(err)
@@ -147,21 +163,7 @@ func serve(conf *config.Config) error {
147163
if err != nil {
148164
log.Println(err)
149165
}
150-
})
151-
152-
if conf.Server.PortHTTP != 0 {
153-
go serveHTTP(mux, conf.Server.PortHTTP, errorsLog, errs)
154-
numberOfServers++
155-
}
156-
if conf.Server.PortHTTPS != 0 {
157-
go serveHTTPS(mux, conf.Server.PortHTTPS, conf.Server.TLSCertFile, conf.Server.TLSKeyFile, errorsLog, errs)
158-
numberOfServers++
159-
}
160-
if numberOfServers == 0 {
161-
return types.ErrNoServersConfigured
162166
}
163-
164-
return <-errs // block until one of the servers writes an error
165167
}
166168

167169
func main() {
@@ -192,38 +194,39 @@ func main() {
192194
return
193195
}
194196

195-
if cli.ConvertGeoIPCache {
196-
geoIPCache, err := geoip.NewCache(conf)
197-
if err != nil {
198-
ctx.FatalIfErrorf(err)
199-
}
200-
201-
ctx.FatalIfErrorf(geoIPCache.ConvertCache())
202-
203-
return
204-
}
205-
206-
if cli.ConvertGeoLocationCache {
207-
geoLocCache, err := geoloc.NewCache(conf)
208-
if err != nil {
209-
ctx.FatalIfErrorf(err)
210-
}
211-
212-
ctx.FatalIfErrorf(geoLocCache.ConvertCache())
213-
214-
return
215-
}
216-
217-
if cli.GeoResolve != "" {
197+
switch {
198+
case cli.ConvertGeoIPCache:
199+
ctx.FatalIfErrorf(convertGeoIPCache(conf))
200+
case cli.ConvertGeoLocationCache:
201+
ctx.FatalIfErrorf(convertGeoLocationCache(conf))
202+
case cli.GeoResolve != "":
218203
sr := geoloc.NewSearcher(conf)
219204
loc, err := sr.Search(cli.GeoResolve)
220205
ctx.FatalIfErrorf(err)
221206
if loc != nil {
222207
//nolint:forbidigo
223208
fmt.Println(*loc)
224209
}
210+
default:
211+
err = serve(conf)
212+
ctx.FatalIfErrorf(err)
213+
}
214+
}
215+
216+
func convertGeoIPCache(conf *config.Config) error {
217+
geoIPCache, err := geoip.NewCache(conf)
218+
if err != nil {
219+
return err
220+
}
221+
222+
return geoIPCache.ConvertCache()
223+
}
224+
225+
func convertGeoLocationCache(conf *config.Config) error {
226+
geoLocCache, err := geoloc.NewCache(conf)
227+
if err != nil {
228+
return err
225229
}
226230

227-
err = serve(conf)
228-
ctx.FatalIfErrorf(err)
231+
return geoLocCache.ConvertCache()
229232
}

0 commit comments

Comments
 (0)