request_id.go

 1package middleware
 2
 3// Ported from Goji's middleware, source:
 4// https://github.com/zenazn/goji/tree/master/web/middleware
 5
 6import (
 7	"context"
 8	"crypto/rand"
 9	"encoding/base64"
10	"fmt"
11	"net/http"
12	"os"
13	"strings"
14	"sync/atomic"
15
16	"git.kilimanjaro.io/rtw/pkg/log"
17)
18
19// Key to use when setting the request ID.
20type ctxKeyRequestID struct{}
21
22// RequestIDKey is the key that holds the unique request ID in a request context.
23var requestIDKey ctxKeyRequestID
24
25var prefix string
26var reqid uint64
27
28// A quick note on the statistics here: we're trying to calculate the chance that
29// two randomly generated base62 prefixes will collide. We use the formula from
30// http://en.wikipedia.org/wiki/Birthday_problem
31//
32// P[m, n] \approx 1 - e^{-m^2/2n}
33//
34// We ballpark an upper bound for $m$ by imagining (for whatever reason) a server
35// that restarts every second over 10 years, for $m = 86400 * 365 * 10 = 315360000$
36//
37// For a $k$ character base-62 identifier, we have $n(k) = 62^k$
38//
39// Plugging this in, we find $P[m, n(10)] \approx 5.75%$, which is good enough for
40// our purposes, and is surely more than anyone would ever need in practice -- a
41// process that is rebooted a handful of times a day for a hundred years has less
42// than a millionth of a percent chance of generating two colliding IDs.
43
44func init() {
45	hostname, err := os.Hostname()
46	if hostname == "" || err != nil {
47		hostname = "localhost"
48	}
49	var buf [12]byte
50	var b64 string
51	for len(b64) < 10 {
52		rand.Read(buf[:])
53		b64 = base64.StdEncoding.EncodeToString(buf[:])
54		b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
55	}
56
57	prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10])
58}
59
60// RequestID is a middleware that injects a request ID into the context of each
61// request. A request ID is a string of the form "host.example.com/random-0001",
62// where "random" is a base62 random string that uniquely identifies this go
63// process, and where the last number is an atomically incremented request
64// counter.
65func RequestID(next http.Handler) http.Handler {
66	fn := func(w http.ResponseWriter, r *http.Request) {
67		ctx := r.Context()
68		logger := log.FromContext(ctx)
69
70		num := atomic.AddUint64(&reqid, 1)
71		requestID := fmt.Sprintf("%s-%06d", prefix, num)
72
73		ctx = context.WithValue(ctx, requestIDKey, requestID)
74		ctx = log.ToContext(ctx, logger.With("request_id", requestID))
75		next.ServeHTTP(w, r.WithContext(ctx))
76	}
77	return http.HandlerFunc(fn)
78}
79
80// GetReqID returns a request ID from the given context if one is present.
81// Returns the empty string if a request ID cannot be found.
82func GetReqID(ctx context.Context) string {
83	if ctx == nil {
84		return ""
85	}
86	if reqID, ok := ctx.Value(requestIDKey).(string); ok {
87		return reqID
88	}
89	return ""
90}