package http import ( "context" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "git.zhangdeman.cn/github/ginframework/database" "git.zhangdeman.cn/github/ginframework/diagnostic" "git.zhangdeman.cn/github/ginframework/httpclient" "git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver" "git.zhangdeman.cn/github/ginframework/logger" "git.zhangdeman.cn/github/ginframework/redis/commandlog" "github.com/gin-gonic/gin" redisclient "github.com/redis/go-redis/v9" "go.uber.org/zap" "go.uber.org/zap/zaptest/observer" "gorm.io/driver/sqlite" ) type flowTransport func(*http.Request) (*http.Response, error) func (f flowTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } type flowForm struct { Meta `path:"/context-flow" method:"GET"` Bad bool `form:"bad"` } type flowController struct { database *database.Connection redis *redisclient.Client outbound *httpclient.Client } func (c *flowController) Run(ctx *gin.Context, input *flowForm) (*exampleOutput, error) { parent := ctx.Request.Context() if err := c.database.Session(parent).Exec("SELECT 1").Error; err != nil { return nil, err } if err := c.redis.Ping(parent).Err(); err != nil { return nil, err } target := "https://example.test/ok" if input.Bad { target = "https://example.test/bad" } response, err := c.outbound.Send(parent, httpclient.Request{URL: target}) if err != nil { return nil, err } var ( output exampleOutput ) if err = response.DecodeJSON(&output); err != nil { return nil, err } return &output, nil } func TestHTTPDatabaseRedisOutboundKeepOneDiagnosticSnapshot(t *testing.T) { directory := t.TempDir() if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil { t.Fatal(err) } t.Cleanup(func() { _ = logger.CloseOutputs() }) sqlCore, sqlLogs := observer.New(zap.InfoLevel) connection, err := database.Open(context.Background(), database.Config{Name: "test"}, database.Options{Dialector: sqlite.Open(":memory:"), Logger: zap.New(sqlCore)}) if err != nil { t.Fatal(err) } t.Cleanup(func() { if err := connection.Close(); err != nil { t.Error(err) } }) redis := redisserver.New(t, 3) redisCore, redisLogs := observer.New(zap.InfoLevel) redis.AddHook(commandlog.New(zap.New(redisCore), "test")) outboundCore, outboundLogs := observer.New(zap.InfoLevel) client, err := httpclient.New(httpclient.Config{}, httpclient.Options{Logger: zap.New(outboundCore), Transport: flowTransport(func(r *http.Request) (*http.Response, error) { if diagnostic.From(r.Context()).TraceID == "" { return nil, errors.New("outbound context lost") } if _, ok := r.Context().Deadline(); !ok { return nil, errors.New("outbound budget lost") } body := `{"name":"ok"}` if r.URL.Path == "/bad" { body = `{"private-token":` } return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil })}) if err != nil { t.Fatal(err) } server, err := NewServer(Config{}, Options{}) if err != nil { t.Fatal(err) } if err = server.Group("", nil, &flowController{database: connection, redis: redis, outbound: client}); err != nil { t.Fatal(err) } var ( traces []string ) for _, bad := range []bool{false, true} { path := "/context-flow" if bad { path += "?bad=true" } recorder := httptest.NewRecorder() server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil)) expected := 200 if bad { expected = 500 } if recorder.Code != expected { t.Fatalf("flow status=%d: %s", recorder.Code, recorder.Body.String()) } traces = append(traces, recorder.Header().Get("X-Request-ID")) } for _, trace := range traces { if trace == "" { t.Fatal("missing HTTP trace") } for name, logs := range map[string]*observer.ObservedLogs{"sql": sqlLogs, "redis": redisLogs, "outbound": outboundLogs} { found := false for _, entry := range logs.All() { raw, _ := json.Marshal(entry.ContextMap()) if strings.Contains(string(raw), trace) { found = true break } } if !found { t.Fatalf("%s lost HTTP diagnostic snapshot %s", name, trace) } } } if err = logger.CloseOutputs(); err != nil { t.Fatal(err) } paths, _ := filepath.Glob(filepath.Join(directory, "*")) if len(paths) != 1 { t.Fatal("source error log missing") } raw, err := os.ReadFile(paths[0]) if err != nil { t.Fatal(err) } if strings.Count(strings.TrimSpace(string(raw)), "\n") != 0 || !strings.Contains(string(raw), traces[1]) || strings.Contains(string(raw), "private-token") { t.Fatalf("outbound decode error lost context or logged twice: %s", raw) } }