Skip to content
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

Add cloud region resource #535

Merged
merged 6 commits into from
Apr 15, 2024
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
44 changes: 44 additions & 0 deletions docs/resources/region.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "materialize_region Resource - terraform-provider-materialize"
subcategory: ""
description: |-
The region resource allows you to manage regions in Materialize. When a new region is created, it automatically includes an 'xsmall' quickstart cluster as part of the initialization process. Users are billed for this quickstart cluster from the moment the region is created. To avoid unnecessary charges, you can connect to the new region and drop the quickstart cluster if it is not needed. Please note that disabling a region cannot be achieved directly through this provider. If you need to disable a region, contact Materialize support for assistance. This process ensures that any necessary cleanup and billing adjustments are handled properly.
---

# materialize_region (Resource)

The region resource allows you to manage regions in Materialize. When a new region is created, it automatically includes an 'xsmall' quickstart cluster as part of the initialization process. Users are billed for this quickstart cluster from the moment the region is created. To avoid unnecessary charges, you can connect to the new region and drop the quickstart cluster if it is not needed. Please note that disabling a region cannot be achieved directly through this provider. If you need to disable a region, contact Materialize support for assistance. This process ensures that any necessary cleanup and billing adjustments are handled properly.

## Example Usage

```terraform
resource "materialize_region" "example" {
region_id = "aws/us-east-1"
}
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `region_id` (String) The ID of the region to manage. Example: aws/us-west-2

### Read-Only

- `enabled_at` (String) The timestamp when the region was enabled.
- `http_address` (String) The HTTP address of the region.
- `id` (String) The ID of this resource.
- `region_state` (Boolean) The state of the region. True if enabled, false otherwise.
- `resolvable` (Boolean) Indicates if the region is resolvable.
- `sql_address` (String) The SQL address of the region.

## Import

Import is supported using the following syntax:

```shell
# Regions can be imported using the `terraform import` command
terraform import materialize_region.example_region aws/us-east-1
```
2 changes: 2 additions & 0 deletions examples/resources/materialize_region/import.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Regions can be imported using the `terraform import` command
terraform import materialize_region.example_region aws/us-east-1
3 changes: 3 additions & 0 deletions examples/resources/materialize_region/resource.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
resource "materialize_region" "example" {
region_id = "aws/us-east-1"
}
4 changes: 4 additions & 0 deletions integration/region.tf
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ data "materialize_region" "all" {}
output "region" {
value = data.materialize_region.all
}

resource "materialize_region" "example_region" {
region_id = "aws/us-east-1"
}
4 changes: 3 additions & 1 deletion mocks/cloud/mock_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ func regionHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(mockRegion)
case http.MethodPatch:
w.WriteHeader(http.StatusOK)
enabledRegion := CloudRegion{RegionInfo: nil}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(enabledRegion)
case http.MethodDelete:
w.WriteHeader(http.StatusAccepted)
default:
Expand Down
34 changes: 34 additions & 0 deletions pkg/clients/cloud_client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package clients

import (
"bytes"
"context"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -115,6 +116,39 @@ func (c *CloudAPIClient) GetRegionDetails(ctx context.Context, provider CloudPro
return &region, nil
}

// EnableRegion sends a PATCH request to enable a cloud region
func (c *CloudAPIClient) EnableRegion(ctx context.Context, provider CloudProvider) (*CloudRegion, error) {
endpoint := fmt.Sprintf("%s/api/region", provider.Url)
emptyJSONPayload := bytes.NewBuffer([]byte("{}"))
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, endpoint, emptyJSONPayload)
if err != nil {
return nil, fmt.Errorf("error creating request to enable region: %v", err)
}

req.Header.Add("Content-Type", "application/json")

resp, err := c.FronteggClient.HTTPClient.Do(req)

Choose a reason for hiding this comment

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

Why does this use the frontegg client? This is the cloud region api, right?

Copy link
Contributor Author

@bobbyiliev bobbyiliev Apr 15, 2024

Choose a reason for hiding this comment

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

Hmm, I think that this has been flawed from the initial implementation during the large refactor a few months ago.

As far as I can tell, the main idea seems to have been to reuse the FronteggClient's HTTPClient which already includes the Authorization token.

I'll have to refactor this. I've created an issue to track this and will submit a PR tomorrow! #543

Thanks for pointing it out!

if err != nil {
return nil, fmt.Errorf("error sending request to enable region: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err)
}
return nil, fmt.Errorf("cloud API returned non-200/201 status code: %d, body: %s", resp.StatusCode, string(body))
}

var region CloudRegion
if err := json.NewDecoder(resp.Body).Decode(&region); err != nil {
return nil, err
}

return &region, nil
}

// GetHost retrieves the SQL address for a specified region
func (c *CloudAPIClient) GetHost(ctx context.Context, regionID string) (string, error) {
providers, err := c.ListCloudProviders(ctx)
Expand Down
47 changes: 47 additions & 0 deletions pkg/clients/cloud_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,50 @@ func TestNewCloudAPIClient(t *testing.T) {
require.NotNil(t, cloudAPIClient.HTTPClient)
require.Equal(t, anotherCustomEndpoint, cloudAPIClient.Endpoint)
}

func TestCloudAPIClient_EnableRegion_Success(t *testing.T) {
mockService := &MockFronteggService{
MockResponseStatus: http.StatusOK,
}
mockClient := &http.Client{Transport: mockService}
apiClient := &CloudAPIClient{
FronteggClient: &FronteggClient{HTTPClient: mockClient},
Endpoint: "http://mockendpoint.com",
}

provider := CloudProvider{
ID: "aws/us-east-1",
Name: "us-east-1",
Url: "http://mockendpoint.com/api/region",
}

region, err := apiClient.EnableRegion(context.Background(), provider)
require.NoError(t, err)
require.NotNil(t, region)
require.Equal(t, "sql.materialize.com", region.RegionInfo.SqlAddress)
require.Equal(t, "http.materialize.com", region.RegionInfo.HttpAddress)
require.True(t, region.RegionInfo.Resolvable)
require.Equal(t, "2021-01-01T00:00:00Z", region.RegionInfo.EnabledAt)
}

func TestCloudAPIClient_EnableRegion_Error(t *testing.T) {
mockService := &MockFronteggService{
MockResponseStatus: http.StatusInternalServerError,
}
mockClient := &http.Client{Transport: mockService}
apiClient := &CloudAPIClient{
FronteggClient: &FronteggClient{HTTPClient: mockClient},
Endpoint: "http://mockendpoint.com",
}

provider := CloudProvider{
ID: "aws/us-east-1",
Name: "us-east-1",
Url: "http://mockendpoint.com/api/region",
}

// Simulate an error response for EnableRegion
_, err := apiClient.EnableRegion(context.Background(), provider)
require.Error(t, err)
require.Contains(t, err.Error(), "cloud API returned non-200/201 status code:")
}
67 changes: 67 additions & 0 deletions pkg/provider/acceptance_resource_region_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package provider

import (
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
)

func TestAccResourceRegion_basic(t *testing.T) {
resourceName := "materialize_region.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccResourceRegionConfig(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "region_id", "aws/us-east-1"),
resource.TestCheckResourceAttrSet(resourceName, "sql_address"),
resource.TestCheckResourceAttr(resourceName, "sql_address", "materialized:6877"),
resource.TestCheckResourceAttrSet(resourceName, "http_address"),
resource.TestCheckResourceAttr(resourceName, "http_address", "materialized:6875"),
resource.TestCheckResourceAttr(resourceName, "resolvable", "true"),
resource.TestCheckResourceAttrSet(resourceName, "enabled_at"),
resource.TestCheckResourceAttr(resourceName, "region_state", "true"),
),
},
},
})
}

func TestAccResourceRegion_update(t *testing.T) {
resourceName := "materialize_region.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccResourceRegionConfig(),
Check: resource.TestCheckResourceAttr(resourceName, "region_id", "aws/us-east-1"),
},
{
Config: testAccResourceRegionConfig(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceName, "region_id", "aws/us-east-1"),
resource.TestCheckResourceAttrSet(resourceName, "sql_address"),
resource.TestCheckResourceAttr(resourceName, "sql_address", "materialized:6877"),
resource.TestCheckResourceAttrSet(resourceName, "http_address"),
resource.TestCheckResourceAttr(resourceName, "http_address", "materialized:6875"),
resource.TestCheckResourceAttr(resourceName, "resolvable", "true"),
resource.TestCheckResourceAttrSet(resourceName, "enabled_at"),
resource.TestCheckResourceAttr(resourceName, "region_state", "true"),
),
},
},
})
}

func testAccResourceRegionConfig() string {
return `
resource "materialize_region" "test" {
region_id = "aws/us-east-1"
}
`
}
1 change: 1 addition & 0 deletions pkg/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func Provider(version string) *schema.Provider {
"materialize_index": resources.Index(),
"materialize_materialized_view": resources.MaterializedView(),
"materialize_materialized_view_grant": resources.GrantMaterializedView(),
"materialize_region": resources.Region(),
"materialize_role": resources.Role(),
"materialize_role_grant": resources.GrantRole(),
"materialize_role_parameter": resources.RoleParameter(),
Expand Down
Loading
Loading