Performance improvements to Replacer implementation (placeholders) (#2674)

Closes #2673
This commit is contained in:
Matt Holt 2019-07-16 12:27:11 -06:00 committed by GitHub
parent bdf92ee84e
commit b44a22a9d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 204 additions and 99 deletions

View File

@ -15,86 +15,143 @@
package caddyhttp package caddyhttp
import ( import (
"fmt"
"net" "net"
"net/http" "net/http"
"net/textproto"
"path" "path"
"strconv"
"strings" "strings"
"github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2"
) )
// TODO: A simple way to format or escape or encode each value would be nice
// ... TODO: Should we just use templates? :-/ yeesh...
func addHTTPVarsToReplacer(repl caddy.Replacer, req *http.Request, w http.ResponseWriter) { func addHTTPVarsToReplacer(repl caddy.Replacer, req *http.Request, w http.ResponseWriter) {
httpVars := func() map[string]string { httpVars := func(key string) (string, bool) {
m := make(map[string]string)
if req != nil { if req != nil {
m["http.request.host"] = func() string { if strings.HasPrefix(key, queryReplPrefix) {
vals := req.URL.Query()[key[len(queryReplPrefix):]]
// always return true, since the query param might
// be present only in some requests
return strings.Join(vals, ","), true
}
if strings.HasPrefix(key, reqHeaderReplPrefix) {
field := key[len(reqHeaderReplPrefix):]
vals := req.Header[textproto.CanonicalMIMEHeaderKey(field)]
// always return true, since the header field might
// be present only in some requests
return strings.Join(vals, ","), true
}
if strings.HasPrefix(key, cookieReplPrefix) {
name := key[len(cookieReplPrefix):]
for _, cookie := range req.Cookies() {
if strings.EqualFold(name, cookie.Name) {
// always return true, since the cookie might
// be present only in some requests
return cookie.Value, true
}
}
}
switch key {
case "http.request.host":
host, _, err := net.SplitHostPort(req.Host) host, _, err := net.SplitHostPort(req.Host)
if err != nil { if err != nil {
return req.Host // OK; there probably was no port return req.Host, true // OK; there probably was no port
} }
return host return host, true
}() case "http.request.hostport":
m["http.request.hostport"] = req.Host // may include both host and port return req.Host, true
m["http.request.method"] = req.Method case "http.request.method":
m["http.request.port"] = func() string { return req.Method, true
// if there is no port, there will be an error; in case "http.request.port":
// that case, port is the empty string anyway
_, port, _ := net.SplitHostPort(req.Host) _, port, _ := net.SplitHostPort(req.Host)
return port return port, true
}() case "http.request.scheme":
m["http.request.scheme"] = func() string {
if req.TLS != nil { if req.TLS != nil {
return "https" return "https", true
} }
return "http" return "http", true
}() case "http.request.uri":
m["http.request.uri"] = req.URL.RequestURI() return req.URL.RequestURI(), true
m["http.request.uri.path"] = req.URL.Path case "http.request.uri.path":
m["http.request.uri.path.file"] = func() string { return req.URL.Path, true
case "http.request.uri.path.file":
_, file := path.Split(req.URL.Path) _, file := path.Split(req.URL.Path)
return file return file, true
}() case "http.request.uri.path.dir":
m["http.request.uri.path.dir"] = func() string {
dir, _ := path.Split(req.URL.Path) dir, _ := path.Split(req.URL.Path)
return dir return dir, true
}() case "http.request.uri.query":
m["http.request.uri.query"] = req.URL.RawQuery return req.URL.RawQuery, true
for param, vals := range req.URL.Query() {
m["http.request.uri.query."+param] = strings.Join(vals, ",")
}
for field, vals := range req.Header {
m["http.request.header."+strings.ToLower(field)] = strings.Join(vals, ",")
}
for _, cookie := range req.Cookies() {
m["http.request.cookie."+cookie.Name] = cookie.Value
} }
hostLabels := strings.Split(req.Host, ".") if strings.HasPrefix(key, respHeaderReplPrefix) {
for i, label := range hostLabels { field := key[len(respHeaderReplPrefix):]
key := fmt.Sprintf("http.request.host.labels.%d", len(hostLabels)-i-1) vals := w.Header()[textproto.CanonicalMIMEHeaderKey(field)]
m[key] = label // always return true, since the header field might
// be present only in some requests
return strings.Join(vals, ","), true
} }
pathParts := strings.Split(req.URL.Path, "/") if strings.HasPrefix(key, hostLabelReplPrefix) {
for i, label := range pathParts { idxStr := key[len(hostLabelReplPrefix):]
key := fmt.Sprintf("http.request.uri.path.%d", i) idx, err := strconv.Atoi(idxStr)
m[key] = label if err != nil {
return "", false
}
hostLabels := strings.Split(req.Host, ".")
if idx < 0 {
return "", false
}
if idx >= len(hostLabels) {
return "", true
}
return hostLabels[idx], true
}
if strings.HasPrefix(key, pathPartsReplPrefix) {
idxStr := key[len(pathPartsReplPrefix):]
idx, err := strconv.Atoi(idxStr)
if err != nil {
return "", false
}
pathParts := strings.Split(req.URL.Path, "/")
if len(pathParts) > 0 && pathParts[0] == "" {
pathParts = pathParts[1:]
}
if idx < 0 {
return "", false
}
if idx >= len(pathParts) {
return "", true
}
return pathParts[idx], true
} }
} }
if w != nil { if w != nil {
for field, vals := range w.Header() { if strings.HasPrefix(key, respHeaderReplPrefix) {
m["http.response.header."+strings.ToLower(field)] = strings.Join(vals, ",") field := key[len(respHeaderReplPrefix):]
vals := w.Header()[textproto.CanonicalMIMEHeaderKey(field)]
// always return true, since the header field might
// be present only in some responses
return strings.Join(vals, ","), true
} }
} }
return m return "", false
} }
repl.Map(httpVars) repl.Map(httpVars)
} }
const (
queryReplPrefix = "http.request.uri.query."
reqHeaderReplPrefix = "http.request.header."
cookieReplPrefix = "http.request.cookie."
hostLabelReplPrefix = "http.request.host.labels."
pathPartsReplPrefix = "http.request.uri.path."
respHeaderReplPrefix = "http.response.header."
)

View File

@ -25,7 +25,7 @@ import (
type Replacer interface { type Replacer interface {
Set(variable, value string) Set(variable, value string)
Delete(variable string) Delete(variable string)
Map(func() map[string]string) Map(ReplacementFunc)
ReplaceAll(input, empty string) string ReplaceAll(input, empty string) string
} }
@ -34,23 +34,22 @@ func NewReplacer() Replacer {
rep := &replacer{ rep := &replacer{
static: make(map[string]string), static: make(map[string]string),
} }
rep.providers = []ReplacementsFunc{ rep.providers = []ReplacementFunc{
defaultReplacements, globalDefaultReplacements,
func() map[string]string { return rep.static }, rep.fromStatic,
} }
return rep return rep
} }
type replacer struct { type replacer struct {
providers []ReplacementsFunc providers []ReplacementFunc
static map[string]string static map[string]string
} }
// Map augments the map of replacements with those returned // Map adds mapFunc to the list of value providers.
// by the given replacements function. The function is only // mapFunc will be executed only at replace-time.
// executed at replace-time. func (r *replacer) Map(mapFunc ReplacementFunc) {
func (r *replacer) Map(replacements func() map[string]string) { r.providers = append(r.providers, mapFunc)
r.providers = append(r.providers, replacements)
} }
// Set sets a custom variable to a static value. // Set sets a custom variable to a static value.
@ -64,55 +63,104 @@ func (r *replacer) Delete(variable string) {
delete(r.static, variable) delete(r.static, variable)
} }
// ReplaceAll replaces placeholders in input with their values. // fromStatic provides values from r.static.
// Values that are empty string will be substituted with the func (r *replacer) fromStatic(key string) (val string, ok bool) {
// empty parameter. val, ok = r.static[key]
func (r *replacer) ReplaceAll(input, empty string) string { return
if !strings.Contains(input, phOpen) {
return input
}
for _, replacements := range r.providers {
for key, val := range replacements() {
if val == "" {
val = empty
}
input = strings.ReplaceAll(input, phOpen+key+phClose, val)
}
}
return input
} }
// ReplacementsFunc is a function that returns replacements, // ReplaceAll efficiently replaces placeholders in input with
// which is variable names mapped to their values. The // their values. Unrecognized placeholders will not be replaced.
// function will be evaluated only at replace-time to ensure // Values that are empty string will be substituted with empty.
// the most current values are mapped. func (r *replacer) ReplaceAll(input, empty string) string {
type ReplacementsFunc func() map[string]string if !strings.Contains(input, string(phOpen)) {
return input
var defaultReplacements = func() map[string]string {
m := map[string]string{
"system.hostname": func() string {
// OK if there is an error; just return empty string
name, _ := os.Hostname()
return name
}(),
"system.slash": string(filepath.Separator),
"system.os": runtime.GOOS,
"system.arch": runtime.GOARCH,
} }
// add environment variables var sb strings.Builder
for _, keyval := range os.Environ() {
parts := strings.SplitN(keyval, "=", 2) // it is reasonable to assume that the output
if len(parts) != 2 { // will be approximately as long as the input
sb.Grow(len(input))
// iterate the input to find each placeholder
var lastWriteCursor int
for i := 0; i < len(input); i++ {
if input[i] != phOpen {
continue continue
} }
m["env."+strings.ToLower(parts[0])] = parts[1]
// write the substring from the last cursor to this point
sb.WriteString(input[lastWriteCursor:i])
// find the end of the placeholder
end := strings.Index(input[i:], string(phClose)) + i
// trim opening bracket
key := input[i+1 : end]
// try to get a value for this key; if
// the key is not recognized, do not
// perform any replacement
var found bool
for _, mapFunc := range r.providers {
if val, ok := mapFunc(key); ok {
found = true
if val != "" {
sb.WriteString(val)
} else if empty != "" {
sb.WriteString(empty)
}
break
}
}
if !found {
continue
}
// advance cursor to end of placeholder
i = end + 1
lastWriteCursor = i
} }
return m // flush any unwritten remainder
sb.WriteString(input[lastWriteCursor:])
return sb.String()
}
// ReplacementFunc is a function that returns a replacement
// for the given key along with true if the function is able
// to service that key (even if the value is blank). If the
// function does not recognize the key, false should be
// returned.
type ReplacementFunc func(key string) (val string, ok bool)
func globalDefaultReplacements(key string) (string, bool) {
// check environment variable
const envPrefix = "env."
if strings.HasPrefix(key, envPrefix) {
val := os.Getenv(key[len(envPrefix):])
return val, val != ""
}
switch key {
case "system.hostname":
// OK if there is an error; just return empty string
name, _ := os.Hostname()
return name, true
case "system.slash":
return string(filepath.Separator), true
case "system.os":
return runtime.GOOS, true
case "system.arch":
return runtime.GOARCH, true
}
return "", false
} }
// ReplacerCtxKey is the context key for a replacer. // ReplacerCtxKey is the context key for a replacer.
const ReplacerCtxKey CtxKey = "replacer" const ReplacerCtxKey CtxKey = "replacer"
const phOpen, phClose = "{", "}" const phOpen, phClose = '{', '}'