-
Notifications
You must be signed in to change notification settings - Fork 67
/
artifacts.go
82 lines (68 loc) · 2.41 KB
/
artifacts.go
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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"errors"
"net/http"
"time"
"github.com/Masterminds/semver/v3"
"github.com/gorilla/mux"
"go.elastic.co/apm/module/apmzap/v2"
"go.uber.org/zap"
"github.com/elastic/package-registry/packages"
"github.com/elastic/package-registry/proxymode"
)
const artifactsRouterPath = "/epr/{packageName}/{packageName:[a-z0-9_]+}-{packageVersion}.zip"
var errArtifactNotFound = errors.New("artifact not found")
func artifactsHandler(logger *zap.Logger, indexer Indexer, cacheTime time.Duration) func(w http.ResponseWriter, r *http.Request) {
return artifactsHandlerWithProxyMode(logger, indexer, proxymode.NoProxy(logger), cacheTime)
}
func artifactsHandlerWithProxyMode(logger *zap.Logger, indexer Indexer, proxyMode *proxymode.ProxyMode, cacheTime time.Duration) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
logger := logger.With(apmzap.TraceContext(r.Context())...)
vars := mux.Vars(r)
packageName, ok := vars["packageName"]
if !ok {
badRequest(w, "missing package name")
return
}
packageVersion, ok := vars["packageVersion"]
if !ok {
badRequest(w, "missing package version")
return
}
_, err := semver.StrictNewVersion(packageVersion)
if err != nil {
badRequest(w, "invalid package version")
return
}
opts := packages.NameVersionFilter(packageName, packageVersion)
pkgs, err := indexer.Get(r.Context(), &opts)
if err != nil {
logger.Error("getting package path failed",
zap.String("package.name", packageName),
zap.String("package.version", packageVersion),
zap.Error(err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if len(pkgs) == 0 && proxyMode.Enabled() {
proxiedPackage, err := proxyMode.Package(r)
if err != nil {
logger.Error("proxy mode: package failed", zap.Error(err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if proxiedPackage != nil {
pkgs = pkgs.Join(packages.Packages{proxiedPackage})
}
}
if len(pkgs) == 0 {
notFoundError(w, errArtifactNotFound)
return
}
cacheHeaders(w, cacheTime)
packages.ServePackage(logger, w, r, pkgs[0])
}
}