Skip to content

CLOUDP-319781: Added http RoundTripper that logs payload diffs for Atlas API endpoints #2525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .licenses-gomod.sha256
Original file line number Diff line number Diff line change
@@ -1 +1 @@
100644 b70bbe378c03133042f1234347ba66493c607947 go.mod
100644 2eb735b209d48bcf2f3009003bafe7735bab42dd go.mod
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ require (
github.com/onsi/gomega v1.37.0
github.com/sethvargo/go-password v0.3.1
github.com/stretchr/testify v1.10.0
github.com/yudai/gojsondiff v1.0.0
go.mongodb.org/atlas v0.38.0
go.mongodb.org/atlas-sdk/v20250312002 v20250312002.0.0
go.mongodb.org/mongo-driver v1.17.4
Expand Down Expand Up @@ -66,11 +67,16 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/spf13/cobra v1.8.1 // indirect
github.com/stoewer/go-strcase v1.3.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
Expand Down
61 changes: 61 additions & 0 deletions go.sum

Large diffs are not rendered by default.

16 changes: 11 additions & 5 deletions internal/controller/atlas/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ type ClientSet struct {
}

type ProductionProvider struct {
domain string
dryRun bool
domain string
dryRun bool
isLogInDebug bool
}

// ConnectionConfig is the type that contains connection configuration to Atlas, including credentials.
Expand All @@ -73,10 +74,11 @@ type APIKeys struct {
PrivateKey string
}

func NewProductionProvider(atlasDomain string, dryRun bool) *ProductionProvider {
func NewProductionProvider(atlasDomain string, dryRun, isLogInDebug bool) *ProductionProvider {
return &ProductionProvider{
domain: atlasDomain,
dryRun: dryRun,
domain: atlasDomain,
dryRun: dryRun,
isLogInDebug: isLogInDebug,
}
}

Expand Down Expand Up @@ -141,6 +143,10 @@ func (p *ProductionProvider) SdkClientSet(ctx context.Context, creds *Credential
var transport http.RoundTripper = digest.NewTransport(creds.APIKeys.PublicKey, creds.APIKeys.PrivateKey)
transport = p.newDryRunTransport(transport)
transport = httputil.NewLoggingTransport(log, false, transport)
if p.isLogInDebug {
log.Debug("JSON payload diff is enabled for Atlas API requests (PATCH & PUT)")
transport = httputil.NewTransportWithDiff(transport, log.Named("payload_diff"))
}

httpClient := &http.Client{Transport: transport}

Expand Down
8 changes: 4 additions & 4 deletions internal/controller/atlas/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ import (

func TestProvider_IsCloudGov(t *testing.T) {
t.Run("should return false for invalid domain", func(t *testing.T) {
p := NewProductionProvider("http://x:namedport", false)
p := NewProductionProvider("http://x:namedport", false, false)
assert.False(t, p.IsCloudGov())
})

t.Run("should return false for commercial Atlas domain", func(t *testing.T) {
p := NewProductionProvider("https://cloud.mongodb.com/", false)
p := NewProductionProvider("https://cloud.mongodb.com/", false, false)
assert.False(t, p.IsCloudGov())
})

t.Run("should return true for Atlas for government domain", func(t *testing.T) {
p := NewProductionProvider("https://cloud.mongodbgov.com/", false)
p := NewProductionProvider("https://cloud.mongodbgov.com/", false, false)
assert.True(t, p.IsCloudGov())
})
}
Expand Down Expand Up @@ -137,7 +137,7 @@ func TestProvider_IsResourceSupported(t *testing.T) {

for desc, data := range dataProvider {
t.Run(desc, func(t *testing.T) {
p := NewProductionProvider(data.domain, false)
p := NewProductionProvider(data.domain, false, false)
assert.Equal(t, data.expectation, p.IsResourceSupported(data.resource))
})
}
Expand Down
127 changes: 127 additions & 0 deletions internal/httputil/diff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright 2025 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package httputil

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/yudai/gojsondiff"
"github.com/yudai/gojsondiff/formatter"
"go.uber.org/zap"
)

type TransportWithDiff struct {
transport http.RoundTripper
log *zap.SugaredLogger
}

func NewTransportWithDiff(transport http.RoundTripper, log *zap.SugaredLogger) *TransportWithDiff {
return &TransportWithDiff{
transport: transport,
log: log,
}
}

func (t *TransportWithDiff) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Method == http.MethodPut || req.Method == http.MethodPatch {
diffString, err := t.tryCalculateDiff(req,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:nit: why try...?

Suggested change
diffString, err := t.tryCalculateDiff(req,
diffString, err := t.calculateDiff(req,

"Do or do not, there is no try"

cleanLinksField,
cleanCreatedField,
)
if err != nil {
t.log.Debug("failed to calculate diff", zap.Error(err))
} else {
t.log.Debug("JSON diff text",
zap.String("url", req.URL.String()),
zap.Any("diff", diffString),
)
}
}
return t.transport.RoundTrip(req)
}

type cleanupFunc func(map[string]interface{})

func cleanLinksField(data map[string]interface{}) {
if _, ok := data["links"]; ok {
delete(data, "links")
}
}

func cleanCreatedField(data map[string]interface{}) {
if _, ok := data["created"]; ok {
delete(data, "created")
}
}

func (t *TransportWithDiff) tryCalculateDiff(req *http.Request, cleanupFuncs ...cleanupFunc) (string, error) {
var bodyCopy []byte
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: would have split this into further functions, but ok.

if req.Body != nil {
bodyCopy, _ = io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(bodyCopy))
}

defer func() {
req.Body = io.NopCloser(bytes.NewBuffer(bodyCopy))
}()

getReq, _ := http.NewRequestWithContext(req.Context(), http.MethodGet, req.URL.String(), nil)
getReq.Header = req.Header

getResp, err := t.transport.RoundTrip(getReq)
if err != nil {
return "", fmt.Errorf("failed to GET original resource: %w", err)
}
defer getResp.Body.Close()

payloadFromGet, _ := io.ReadAll(getResp.Body)

var payloadFromGetParsed map[string]interface{}
err = json.Unmarshal(payloadFromGet, &payloadFromGetParsed)
if err != nil {
return "", fmt.Errorf("failed to unmarshal payloadFromGetParsed JSON: %w", err)
}

for _, cFn := range cleanupFuncs {
cFn(payloadFromGetParsed)
}

payloadBytes, err := json.Marshal(payloadFromGetParsed)
if err != nil {
return "", fmt.Errorf("failed to marshal payloadFromGetParsed JSON: %w", err)
}

differ := gojsondiff.New()
diff, err := differ.Compare(payloadBytes, bodyCopy)
if err != nil {
return "", fmt.Errorf("failed to compare JSON payloads: %w", err)
}

fmtr := formatter.NewAsciiFormatter(payloadFromGetParsed, formatter.AsciiFormatterConfig{
ShowArrayIndex: true,
Coloring: false,
})

diffString, err := fmtr.Format(diff)
if err != nil {
return "", fmt.Errorf("failed to format diff: %w", err)
}

return diffString, nil
}
Loading
Loading