Skip to content
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
### Features

1. [#85](https://github.com/InfluxCommunity/influxdb3-go/pull/85): Add standard `user-agent` header to gRPC requests.
1. [#86](https://github.com/InfluxCommunity/influxdb3-go/pull/86): Add Serverless bucket creation support

## 0.7.0 [2024-04-16]

Expand Down
52 changes: 52 additions & 0 deletions influxdb3/example_management_serverless_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package influxdb3

import (
"context"
"log"
)

func ExampleServerlessClient_CreateBucket() {
client, err := NewFromEnv()
if err != nil {
log.Fatal(err)
}
defer client.Close()

serverlessClient := NewServerlessClient(client)
bucket := Bucket{
Name: "BUCKET_NAME",
OrgID: "ORG_ID",
RetentionRules: []BucketRetentionRule{
{
Type: "expire",
EverySeconds: 86400,
},
},
}
err = serverlessClient.CreateBucket(context.Background(), &bucket)
if err != nil {
log.Fatal(err)
}
}
100 changes: 100 additions & 0 deletions influxdb3/management_serverless.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package influxdb3

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)

type (
// ServerlessClient represents a client for InfluxDB Serverless administration operations.
ServerlessClient struct {
client *Client
}

Bucket struct {
Name string `json:"name"`
OrgID string `json:"orgID,omitempty"`
Description string `json:"description,omitempty"`
RetentionRules []BucketRetentionRule `json:"retentionRules"`
}

BucketRetentionRule struct {
Type string `json:"type,omitempty"`
EverySeconds int `json:"everySeconds,omitempty"`
ShardGroupDuration int `json:"shardGroupDuration,omitempty"`
}
)

// NewServerlessClient creates new ServerlessClient with given InfluxDB client.
func NewServerlessClient(client *Client) *ServerlessClient {
return &ServerlessClient{client: client}
}

// CreateBucket creates a new bucket
func (c *ServerlessClient) CreateBucket(ctx context.Context, bucket *Bucket) error {
if bucket == nil {
return fmt.Errorf("bucket must not be nil")
}

if bucket.OrgID == "" {
bucket.OrgID = c.client.config.Organization
}

if bucket.Name == "" {
bucket.Name = c.client.config.Database
}

return c.createBucket(ctx, "/api/v2/buckets", bucket)
}

// createBucket is a helper function for CreateBucket to enhance test coverage.
func (c *ServerlessClient) createBucket(ctx context.Context, path string, bucket any) error {
u, err := c.client.apiURL.Parse(path)
if err != nil {
return fmt.Errorf("failed to parth bucket creation path: %w", err)
}

body, err := json.Marshal(bucket)
if err != nil {
return fmt.Errorf("failed to marshal bucket creation request body: %w", err)
}

headers := http.Header{}
headers.Set("Content-Type", "application/json")

param := httpParams{
endpointURL: u,
queryParams: nil,
httpMethod: "POST",
headers: headers,
body: bytes.NewReader(body),
}

_, err = c.client.makeAPICall(ctx, param)
return err
}
153 changes: 153 additions & 0 deletions influxdb3/management_serverless_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package influxdb3

import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestServerlessClientCreateBucket(t *testing.T) {
correctPath := "/api/v2/buckets"

tests := []struct {
name string
bucket *Bucket
wantBody map[string]any
wantErr bool
}{
{
name: "Apply bucket orgID and name",
bucket: &Bucket{
OrgID: "my-organization",
Name: "my-bucket",
RetentionRules: []BucketRetentionRule{
{
Type: "expire",
EverySeconds: 86400,
},
},
},
wantBody: map[string]any{
"orgID": "my-organization",
"name": "my-bucket",
"retentionRules": []any{
map[string]any{
"type": "expire",
"everySeconds": float64(86400),
},
},
},
wantErr: false,
},
{
name: "fallback to client config orgID and database name",
bucket: &Bucket{
RetentionRules: []BucketRetentionRule{
{
Type: "expire",
EverySeconds: 86400,
},
},
},
wantBody: map[string]any{
"orgID": "default-organization",
"name": "default-database",
"retentionRules": []any{
map[string]any{
"type": "expire",
"everySeconds": float64(86400),
},
},
},
wantErr: false,
},
{
name: "nil bucket",
bucket: nil,
wantBody: nil,
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// initialization of query client
if r.Method == "PRI" {
return
}

assert.EqualValues(t, correctPath, r.URL.String())
bodyBytes, err := io.ReadAll(r.Body)
require.NoError(t, err)
var body map[string]any
err = json.Unmarshal(bodyBytes, &body)
require.NoError(t, err)
assert.Equal(t, tt.wantBody, body)
w.WriteHeader(201)
}))

c, err := New(ClientConfig{
Host: ts.URL,
Token: "my-token",
Organization: "default-organization",
Database: "default-database",
})
require.NoError(t, err)

sc := NewServerlessClient(c)
err = sc.CreateBucket(context.Background(), tt.bucket)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}

t.Run("Internal error cases", func(t *testing.T) {
c, err := New(ClientConfig{
Host: "dummy",
Token: "dummy",
})
require.NoError(t, err)

sc := NewServerlessClient(c)
err = sc.createBucket(context.Background(), "wrong path:", nil)
assert.Error(t, err)

wrongBody := map[string]any{
"funcField": func() {},
}
err = sc.createBucket(context.Background(), correctPath, wrongBody)
assert.Error(t, err)
})
}