package v071 import ( "bytes" "encoding/json" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "testing" ) // This is only a faulting wire: every response, commit and CAS originates in // the real isolated ES. Successful bodies are recorded, then one is withheld. func formalElasticFaultProxy(t *testing.T, root, upstream, fault string) string { t.Helper() var mu sync.Mutex dropped := false events := []map[string]any{} server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, e := io.ReadAll(r.Body) if e != nil { http.Error(w, "read failed", 500) return } request, e := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw)) if e != nil { http.Error(w, "request failed", 500) return } request.Header = r.Header.Clone() response, e := http.DefaultClient.Do(request) if e != nil { http.Error(w, "upstream failed", 502) return } body, e := io.ReadAll(response.Body) response.Body.Close() if e != nil { http.Error(w, "upstream body failed", 502) return } mutating := r.Method == "PUT" || r.Method == "DELETE" || strings.Contains(r.URL.Path, "_bulk") mu.Lock() selected := fault == "apply-clean" && strings.HasSuffix(r.URL.Path, "/_doc/chunk-src") && !bytes.Contains(raw, []byte(indexClaimPrefix)) selected = selected || (fault == "restore-write" && strings.HasSuffix(r.URL.Path, "/_create/chunk-target")) selected = selected || (fault == "restore-clean" && r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/_doc/chunk-target") && !bytes.Contains(raw, []byte(indexRestoreClaimPrefix))) drop := !dropped && selected && response.StatusCode >= 200 && response.StatusCode < 300 if mutating { events = append(events, map[string]any{"method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), "response": string(body), "status": response.StatusCode, "dropped": drop}) encoded, _ := json.MarshalIndent(events, "", " ") _ = os.WriteFile(filepath.Join(root, "es-wire.json"), encoded, 0600) } if drop { dropped = true _ = os.WriteFile(filepath.Join(root, "es-response-dropped"), []byte(fault), 0600) } mu.Unlock() if drop { if hijacker, ok := w.(http.Hijacker); ok { connection, _, err := hijacker.Hijack() if err == nil { connection.Close() } } return } for k, values := range response.Header { for _, v := range values { w.Header().Add(k, v) } } w.WriteHeader(response.StatusCode) _, _ = w.Write(body) })) t.Cleanup(server.Close) return server.URL }