|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "math/rand" |
| 5 | + "net/http" |
| 6 | + _ "net/http/pprof" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +type responseOpts struct { |
| 11 | + baseLatency time.Duration |
| 12 | + errorRatio float64 |
| 13 | + |
| 14 | + // Whenever 10*outageDuration has passed, an outage will be simulated |
| 15 | + // that lasts for outageDuration. During the outage, errorRatio is |
| 16 | + // increased by a factor of 10, and baseLatency by a factor of 3. At |
| 17 | + // start-up time, an outage is simulated, too (so that you can see the |
| 18 | + // effects right ahead and don't have to wait for 10*outageDuration). |
| 19 | + outageDuration time.Duration |
| 20 | +} |
| 21 | + |
| 22 | +var opts = map[string]map[string]responseOpts{ |
| 23 | + "/api/foo": map[string]responseOpts{ |
| 24 | + "GET": responseOpts{ |
| 25 | + baseLatency: 10 * time.Millisecond, |
| 26 | + errorRatio: 0.005, |
| 27 | + outageDuration: 23 * time.Second, |
| 28 | + }, |
| 29 | + "POST": responseOpts{ |
| 30 | + baseLatency: 20 * time.Millisecond, |
| 31 | + errorRatio: 0.02, |
| 32 | + outageDuration: time.Minute, |
| 33 | + }, |
| 34 | + }, |
| 35 | + "/api/bar": map[string]responseOpts{ |
| 36 | + "GET": responseOpts{ |
| 37 | + baseLatency: 15 * time.Millisecond, |
| 38 | + errorRatio: 0.0025, |
| 39 | + outageDuration: 13 * time.Second, |
| 40 | + }, |
| 41 | + "POST": responseOpts{ |
| 42 | + baseLatency: 50 * time.Millisecond, |
| 43 | + errorRatio: 0.01, |
| 44 | + outageDuration: 47 * time.Second, |
| 45 | + }, |
| 46 | + }, |
| 47 | +} |
| 48 | + |
| 49 | +func handleAPI(w http.ResponseWriter, r *http.Request) { |
| 50 | + pathOpts, ok := opts[r.URL.Path] |
| 51 | + if !ok { |
| 52 | + http.Error(w, "Not Found", http.StatusNotFound) |
| 53 | + return |
| 54 | + } |
| 55 | + methodOpts, ok := pathOpts[r.Method] |
| 56 | + if !ok { |
| 57 | + http.Error(w, "Method not Allowed", http.StatusMethodNotAllowed) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + latencyFactor := time.Duration(1) |
| 62 | + errorFactor := 1. |
| 63 | + if time.Since(start)%(10*methodOpts.outageDuration) < methodOpts.outageDuration { |
| 64 | + latencyFactor *= 3 |
| 65 | + errorFactor *= 10 |
| 66 | + } |
| 67 | + time.Sleep( |
| 68 | + (methodOpts.baseLatency + time.Duration(rand.NormFloat64()*float64(methodOpts.baseLatency)/10)) * latencyFactor, |
| 69 | + ) |
| 70 | + if rand.Float64() <= methodOpts.errorRatio*errorFactor { |
| 71 | + http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 72 | + } |
| 73 | +} |
0 commit comments