Skip to content

Commit

Permalink
chore: Uses new Atlas Go SDK version (#1831)
Browse files Browse the repository at this point in the history
* apply update-atlas-sdk

* revert changes to oldAdmin

* remove atlasSDK alias

* use SlicePtrToSlice and NonEmptySliceToPtrSlice

* fix linter: fieldalignment: struct with 32 pointer bytes could be 24 (govet)

* fix project tests

* user old SDK for online archive as DataProcessRegion was removed

* update templates

* rename to NonEmptySliceToSlicePtr

* tests for slice functions

* use Run in tests

* remove SlicePtrToSlice

* extract results

* implement suggestion preallocating slice

* rename to NonEmptyToPtr as it works for arrays and slices

* add online_archive to old sdk comment

* comment NonEmptyToPtr

* use date to refer to the old sdk version
  • Loading branch information
lantoli committed Jan 15, 2024
1 parent 1e371d0 commit 02281f2
Show file tree
Hide file tree
Showing 78 changed files with 360 additions and 330 deletions.
2 changes: 1 addition & 1 deletion go.mod
Expand Up @@ -27,7 +27,7 @@ require (
github.com/zclconf/go-cty v1.14.1
go.mongodb.org/atlas v0.36.0
go.mongodb.org/atlas-sdk/v20231001002 v20231001002.0.0
go.mongodb.org/atlas-sdk/v20231115002 v20231115002.1.0
go.mongodb.org/atlas-sdk/v20231115003 v20231115003.1.0
go.mongodb.org/realm v0.1.0
golang.org/x/exp v0.0.0-20230809150735-7b3493d9a819
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Expand Up @@ -761,8 +761,8 @@ go.mongodb.org/atlas v0.36.0 h1:m05S3AO7zkl+bcG1qaNsEKBnAqnKx2FDwLooHpIG3j4=
go.mongodb.org/atlas v0.36.0/go.mod h1:nfPldE9dSama6G2IbIzmEza02Ly7yFZjMMVscaM0uEc=
go.mongodb.org/atlas-sdk/v20231001002 v20231001002.0.0 h1:h1X2CGKyN1UFvNs69vp7xpufbbreq6p7bbrg5uJ1sxw=
go.mongodb.org/atlas-sdk/v20231001002 v20231001002.0.0/go.mod h1:4TAUPaWPFNSbi8c1hbQLr1wAdkmqi48O7zvyXjBM+a8=
go.mongodb.org/atlas-sdk/v20231115002 v20231115002.1.0 h1:x6nnq2pUIP9mN4WLD4/EseBzV88OmSgexxYchPilgno=
go.mongodb.org/atlas-sdk/v20231115002 v20231115002.1.0/go.mod h1:el7cm23kEiiw72HAYimhNweKqp/ubHsNJk+Mk30yJhM=
go.mongodb.org/atlas-sdk/v20231115003 v20231115003.1.0 h1:31Li8Xb1THAzYfAVDR9hhAn4z9IhmFs/+AbGqADsyt8=
go.mongodb.org/atlas-sdk/v20231115003 v20231115003.1.0/go.mod h1:tXE5JorXFSauhnw9Xu+/tNrRh90rTX8rYs9y0i2Jy+c=
go.mongodb.org/realm v0.1.0 h1:zJiXyLaZrznQ+Pz947ziSrDKUep39DO4SfA0Fzx8M4M=
go.mongodb.org/realm v0.1.0/go.mod h1:4Vj6iy+Puo1TDERcoh4XZ+pjtwbOzPpzqy3Cwe8ZmDM=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
Expand Down
8 changes: 8 additions & 0 deletions internal/common/conversion/type_conversion.go
Expand Up @@ -56,3 +56,11 @@ func IsStringPresent(strPtr *string) bool {
func MongoDBRegionToAWSRegion(region string) string {
return strings.ReplaceAll(strings.ToLower(region), "_", "-")
}

// NonEmptyToPtr accepts an array or slice and returns a pointer to it, except if it's empty, in that case it returns nil.
func NonEmptyToPtr[T any](v []T) *[]T {
if len(v) == 0 {
return nil
}
return &v
}
23 changes: 23 additions & 0 deletions internal/common/conversion/type_conversion_test.go
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/stretchr/testify/assert"
)

func TestTimeToStringWithoutNanos(t *testing.T) {
Expand Down Expand Up @@ -67,3 +68,25 @@ func TestMongoDBRegionToAWSRegion(t *testing.T) {
}
}
}

func TestNonEmptyToPtr(t *testing.T) {
var (
nilSlice []string
emptyNonNilSlice = []string{}
)
tests := []struct {
name string
expected *[]string
given []string
}{
{"nil pointer", nil, nil},
{"nil slice", nil, nilSlice},
{"empty non-nil slice", nil, emptyNonNilSlice},
{"slice with content", &[]string{"hello", "there"}, []string{"hello", "there"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expected, conversion.NonEmptyToPtr(tc.given))
})
}
}
50 changes: 25 additions & 25 deletions internal/config/client.go
Expand Up @@ -12,8 +12,8 @@ import (
"github.com/mongodb-forks/digest"
"github.com/mongodb/terraform-provider-mongodbatlas/version"
"github.com/spf13/cast"
oldAtlasSDK "go.mongodb.org/atlas-sdk/v20231001002/admin"
atlasSDK "go.mongodb.org/atlas-sdk/v20231115002/admin"
admin20231001002 "go.mongodb.org/atlas-sdk/v20231001002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
matlasClient "go.mongodb.org/atlas/mongodbatlas"
realmAuth "go.mongodb.org/realm/auth"
"go.mongodb.org/realm/realm"
Expand All @@ -29,10 +29,10 @@ var (

// MongoDBClient contains the mongodbatlas clients and configurations
type MongoDBClient struct {
Atlas *matlasClient.Client
AtlasV2 *atlasSDK.APIClient
OldAtlasV2 *oldAtlasSDK.APIClient // Needed to avoid sudden breaking changes in federated_settings_identity_provider resource. Will be removed in terraform-provider-1.16.0
Config *Config
Atlas *matlasClient.Client
AtlasV2 *admin.APIClient
Atlas20231001002 *admin20231001002.APIClient // Needed to avoid breaking changes in federated_settings_identity_provider and online_archive resources.
Config *Config
}

// Config contains the configurations needed to use SDKs
Expand Down Expand Up @@ -89,46 +89,46 @@ func (c *Config) NewClient(ctx context.Context) (any, error) {
if err != nil {
return nil, err
}
sdkOldV2Client, err := c.newOldSDKV2Client(client)
sdk20231001002Client, err := c.newSDK20231001002Client(client)
if err != nil {
return nil, err
}

clients := &MongoDBClient{
Atlas: atlasClient,
AtlasV2: sdkV2Client,
OldAtlasV2: sdkOldV2Client,
Config: c,
Atlas: atlasClient,
AtlasV2: sdkV2Client,
Atlas20231001002: sdk20231001002Client,
Config: c,
}

return clients, nil
}

func (c *Config) newSDKV2Client(client *http.Client) (*atlasSDK.APIClient, error) {
opts := []atlasSDK.ClientModifier{
atlasSDK.UseHTTPClient(client),
atlasSDK.UseUserAgent(userAgent),
atlasSDK.UseBaseURL(c.BaseURL),
atlasSDK.UseDebug(false)}
func (c *Config) newSDKV2Client(client *http.Client) (*admin.APIClient, error) {
opts := []admin.ClientModifier{
admin.UseHTTPClient(client),
admin.UseUserAgent(userAgent),
admin.UseBaseURL(c.BaseURL),
admin.UseDebug(false)}

// Initialize the MongoDB Versioned Atlas Client.
sdkv2, err := atlasSDK.NewClient(opts...)
sdkv2, err := admin.NewClient(opts...)
if err != nil {
return nil, err
}

return sdkv2, nil
}

func (c *Config) newOldSDKV2Client(client *http.Client) (*oldAtlasSDK.APIClient, error) {
opts := []oldAtlasSDK.ClientModifier{
oldAtlasSDK.UseHTTPClient(client),
oldAtlasSDK.UseUserAgent(userAgent),
oldAtlasSDK.UseBaseURL(c.BaseURL),
oldAtlasSDK.UseDebug(false)}
func (c *Config) newSDK20231001002Client(client *http.Client) (*admin20231001002.APIClient, error) {
opts := []admin20231001002.ClientModifier{
admin20231001002.UseHTTPClient(client),
admin20231001002.UseUserAgent(userAgent),
admin20231001002.UseBaseURL(c.BaseURL),
admin20231001002.UseDebug(false)}

// Initialize the MongoDB Versioned Atlas Client.
sdkv2, err := oldAtlasSDK.NewClient(opts...)
sdkv2, err := admin20231001002.NewClient(opts...)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion internal/provider/provider_authentication_test.go
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

func TestAccSTSAssumeRole_basic(t *testing.T) {
Expand Down
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/zclconf/go-cty/cty"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

var _ datasource.DataSource = &alertConfigurationDS{}
Expand Down Expand Up @@ -319,7 +319,7 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC
resource.SetAttributeValue("enabled", cty.BoolVal(*alert.Enabled))
}

for _, matcher := range alert.Matchers {
for _, matcher := range alert.GetMatchers() {
appendBlockWithCtyValues(resource, "matcher", []string{}, convertMatcherToCtyValues(matcher))
}

Expand All @@ -331,8 +331,9 @@ func outputAlertConfigurationResourceHcl(label string, alert *admin.GroupAlertsC
appendBlockWithCtyValues(resource, "threshold_config", []string{}, convertThresholdToCtyValues(alert.Threshold))
}

for i := 0; i < len(alert.Notifications); i++ {
appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(&alert.Notifications[i]))
notifications := alert.GetNotifications()
for i := 0; i < len(notifications); i++ {
appendBlockWithCtyValues(resource, "notification", []string{}, convertNotificationToCtyValues(&notifications[i]))
}

return string(f.Bytes())
Expand Down Expand Up @@ -438,16 +439,14 @@ func convertNotificationToCtyValues(notification *admin.AlertsNotificationRootFo
values["sms_enabled"] = cty.BoolVal(*notification.SmsEnabled)
}

if len(notification.Roles) > 0 {
roles := make([]cty.Value, 0)

for _, r := range notification.Roles {
if roles := notification.GetRoles(); len(roles) > 0 {
roleList := make([]cty.Value, 0, len(roles))
for _, r := range roles {
if r != "" {
roles = append(roles, cty.StringVal(r))
roleList = append(roleList, cty.StringVal(r))
}
}

values["roles"] = cty.TupleVal(roles)
values["roles"] = cty.TupleVal(roleList)
}

return values
Expand Down
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

func TestAccConfigDSAlertConfiguration_basic(t *testing.T) {
Expand Down
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

const alertConfigurationsDataSourceName = "alert_configurations"
Expand Down Expand Up @@ -143,7 +143,7 @@ func (d *AlertConfigurationsDS) Read(ctx context.Context, req datasource.ReadReq
alertConfigurationsConfig.ID = types.StringValue(conversion.EncodeStateID(map[string]string{
"project_id": projectID,
}))
alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(alerts.Results, projectID, alertConfigurationsConfig.OutputType)
alertConfigurationsConfig.Results = NewTFAlertConfigurationDSModelList(alerts.GetResults(), projectID, alertConfigurationsConfig.OutputType)
if *params.IncludeCount {
alertConfigurationsConfig.TotalCount = types.Int64Value(int64(*alerts.TotalCount))
}
Expand Down
16 changes: 8 additions & 8 deletions internal/service/alertconfiguration/model_alert_configuration.go
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mwielbut/pointy"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

func NewNotificationList(tfNotificationSlice []TfNotificationModel) ([]admin.AlertsNotificationRootForGroup, error) {
Expand Down Expand Up @@ -43,7 +43,7 @@ func NewNotificationList(tfNotificationSlice []TfNotificationModel) ([]admin.Ale
Username: n.Username.ValueStringPointer(),
VictorOpsApiKey: n.VictorOpsAPIKey.ValueStringPointer(),
VictorOpsRoutingKey: n.VictorOpsRoutingKey.ValueStringPointer(),
Roles: n.Roles,
Roles: conversion.NonEmptyToPtr(n.Roles),
MicrosoftTeamsWebhookUrl: n.MicrosoftTeamsWebhookURL.ValueStringPointer(),
WebhookSecret: n.WebhookSecret.ValueStringPointer(),
WebhookUrl: n.WebhookURL.ValueStringPointer(),
Expand Down Expand Up @@ -108,8 +108,8 @@ func NewTFAlertConfigurationModel(apiRespConfig *admin.GroupAlertsConfig, currSt
Enabled: types.BoolPointerValue(apiRespConfig.Enabled),
MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, currState.MetricThresholdConfig),
ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, currState.ThresholdConfig),
Notification: NewTFNotificationModelList(apiRespConfig.Notifications, currState.Notification),
Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, currState.Matcher),
Notification: NewTFNotificationModelList(apiRespConfig.GetNotifications(), currState.Notification),
Matcher: NewTFMatcherModelList(apiRespConfig.GetMatchers(), currState.Matcher),
}
}

Expand All @@ -121,7 +121,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt
value := n[i]
notifications[i] = TfNotificationModel{
TeamName: conversion.StringPtrNullIfEmpty(value.TeamName),
Roles: value.Roles,
Roles: value.GetRoles(),
ChannelName: conversion.StringPtrNullIfEmpty(value.ChannelName),
DatadogRegion: conversion.StringPtrNullIfEmpty(value.DatadogRegion),
DelayMin: types.Int64PointerValue(conversion.IntPtrToInt64Ptr(value.DelayMin)),
Expand All @@ -145,7 +145,7 @@ func NewTFNotificationModelList(n []admin.AlertsNotificationRootForGroup, currSt
currState := currStateNotifications[i]
newState := TfNotificationModel{
TeamName: conversion.StringPtrNullIfEmpty(value.TeamName),
Roles: value.Roles,
Roles: value.GetRoles(),
// sentive attributes do not use value returned from API
APIToken: conversion.StringNullIfEmpty(currState.APIToken.ValueString()),
DatadogAPIKey: conversion.StringNullIfEmpty(currState.DatadogAPIKey.ValueString()),
Expand Down Expand Up @@ -303,8 +303,8 @@ func NewTfAlertConfigurationDSModel(apiRespConfig *admin.GroupAlertsConfig, proj
Enabled: types.BoolPointerValue(apiRespConfig.Enabled),
MetricThresholdConfig: NewTFMetricThresholdConfigModel(apiRespConfig.MetricThreshold, []TfMetricThresholdConfigModel{}),
ThresholdConfig: NewTFThresholdConfigModel(apiRespConfig.Threshold, []TfThresholdConfigModel{}),
Notification: NewTFNotificationModelList(apiRespConfig.Notifications, []TfNotificationModel{}),
Matcher: NewTFMatcherModelList(apiRespConfig.Matchers, []TfMatcherModel{}),
Notification: NewTFNotificationModelList(apiRespConfig.GetNotifications(), []TfNotificationModel{}),
Matcher: NewTFMatcherModelList(apiRespConfig.GetMatchers(), []TfMatcherModel{}),
}
}

Expand Down
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/service/alertconfiguration"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

const (
Expand Down Expand Up @@ -45,7 +45,7 @@ func TestNotificationSDKToTFModel(t *testing.T) {
SmsEnabled: admin.PtrBool(disabled),
EmailEnabled: admin.PtrBool(enabled),
ChannelName: admin.PtrString("#channel"),
Roles: roles,
Roles: conversion.NonEmptyToPtr(roles),
ApiToken: admin.PtrString("newApiToken"),
},
},
Expand Down Expand Up @@ -290,7 +290,7 @@ func TestNotificationTFModelToSDK(t *testing.T) {
DelayMin: admin.PtrInt(delayMin),
SmsEnabled: admin.PtrBool(disabled),
EmailEnabled: admin.PtrBool(enabled),
Roles: roles,
Roles: conversion.NonEmptyToPtr(roles),
},
},
},
Expand Down
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mwielbut/pointy"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

const (
Expand Down Expand Up @@ -380,7 +380,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe
apiReq := &admin.GroupAlertsConfig{
EventTypeName: alertConfigPlan.EventType.ValueStringPointer(),
Enabled: alertConfigPlan.Enabled.ValueBoolPointer(),
Matchers: NewMatcherList(alertConfigPlan.Matcher),
Matchers: conversion.NonEmptyToPtr(NewMatcherList(alertConfigPlan.Matcher)),
MetricThreshold: NewMetricThreshold(alertConfigPlan.MetricThresholdConfig),
Threshold: NewThreshold(alertConfigPlan.ThresholdConfig),
}
Expand All @@ -390,7 +390,7 @@ func (r *alertConfigurationRS) Create(ctx context.Context, req resource.CreateRe
resp.Diagnostics.AddError(errorCreateAlertConf, err.Error())
return
}
apiReq.Notifications = notifications
apiReq.Notifications = conversion.NonEmptyToPtr(notifications)

apiResp, _, err := connV2.AlertConfigurationsApi.CreateAlertConfiguration(ctx, projectID, apiReq).Execute()
if err != nil {
Expand Down Expand Up @@ -482,7 +482,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe
}

if !reflect.DeepEqual(alertConfigPlan.Matcher, alertConfigState.Matcher) {
apiReq.Matchers = NewMatcherList(alertConfigPlan.Matcher)
apiReq.Matchers = conversion.NonEmptyToPtr(NewMatcherList(alertConfigPlan.Matcher))
}

// Always refresh structure to handle service keys being obfuscated coming back from read API call
Expand All @@ -491,7 +491,7 @@ func (r *alertConfigurationRS) Update(ctx context.Context, req resource.UpdateRe
resp.Diagnostics.AddError(errorUpdateAlertConf, err.Error())
return
}
apiReq.Notifications = notifications
apiReq.Notifications = conversion.NonEmptyToPtr(notifications)

var updatedAlertConfigResp *admin.GroupAlertsConfig

Expand Down
Expand Up @@ -5,7 +5,7 @@ import (
"os"
"testing"

"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"

"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
Expand Down
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/mongodb/terraform-provider-mongodbatlas/internal/config"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/service/alertconfiguration"
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc"
"go.mongodb.org/atlas-sdk/v20231115002/admin"
"go.mongodb.org/atlas-sdk/v20231115003/admin"
)

func TestAccConfigRSAlertConfiguration_basic(t *testing.T) {
Expand Down

0 comments on commit 02281f2

Please sign in to comment.