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

Namespaces storage #1383

Merged
merged 4 commits into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
30 changes: 30 additions & 0 deletions internal/server/middleware/grpc/support_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,36 @@ func (m *storeMock) String() string {
return "mock"
}

func (m *storeMock) GetNamespace(ctx context.Context, key string) (*flipt.Namespace, error) {
args := m.Called(ctx, key)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) ListNamespaces(ctx context.Context, opts ...storage.QueryOption) (storage.ResultSet[*flipt.Namespace], error) {
args := m.Called(ctx, opts)
return args.Get(0).(storage.ResultSet[*flipt.Namespace]), args.Error(1)
}

func (m *storeMock) CountNamespaces(ctx context.Context) (uint64, error) {
args := m.Called(ctx)
return args.Get(0).(uint64), args.Error(1)
}

func (m *storeMock) CreateNamespace(ctx context.Context, r *flipt.CreateNamespaceRequest) (*flipt.Namespace, error) {
args := m.Called(ctx, r)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) UpdateNamespace(ctx context.Context, r *flipt.UpdateNamespaceRequest) (*flipt.Namespace, error) {
args := m.Called(ctx, r)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) DeleteNamespace(ctx context.Context, r *flipt.DeleteNamespaceRequest) error {
args := m.Called(ctx, r)
return args.Error(0)
}

func (m *storeMock) GetFlag(ctx context.Context, namespaceKey string, key string) (*flipt.Flag, error) {
args := m.Called(ctx, namespaceKey, key)
return args.Get(0).(*flipt.Flag), args.Error(1)
Expand Down
30 changes: 30 additions & 0 deletions internal/server/support_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,36 @@ func (m *storeMock) String() string {
return "mock"
}

func (m *storeMock) GetNamespace(ctx context.Context, key string) (*flipt.Namespace, error) {
args := m.Called(ctx, key)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) ListNamespaces(ctx context.Context, opts ...storage.QueryOption) (storage.ResultSet[*flipt.Namespace], error) {
args := m.Called(ctx, opts)
return args.Get(0).(storage.ResultSet[*flipt.Namespace]), args.Error(1)
}

func (m *storeMock) CountNamespaces(ctx context.Context) (uint64, error) {
args := m.Called(ctx)
return args.Get(0).(uint64), args.Error(1)
}

func (m *storeMock) CreateNamespace(ctx context.Context, r *flipt.CreateNamespaceRequest) (*flipt.Namespace, error) {
args := m.Called(ctx, r)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) UpdateNamespace(ctx context.Context, r *flipt.UpdateNamespaceRequest) (*flipt.Namespace, error) {
args := m.Called(ctx, r)
return args.Get(0).(*flipt.Namespace), args.Error(1)
}

func (m *storeMock) DeleteNamespace(ctx context.Context, r *flipt.DeleteNamespaceRequest) error {
args := m.Called(ctx, r)
return args.Error(0)
}

func (m *storeMock) GetFlag(ctx context.Context, namespaceKey, key string) (*flipt.Flag, error) {
args := m.Called(ctx, namespaceKey, key)
return args.Get(0).(*flipt.Flag), args.Error(1)
Expand Down
225 changes: 225 additions & 0 deletions internal/storage/sql/common/namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
package common

import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"

sq "github.com/Masterminds/squirrel"
errs "go.flipt.io/flipt/errors"
"go.flipt.io/flipt/internal/storage"
fliptsql "go.flipt.io/flipt/internal/storage/sql"
flipt "go.flipt.io/flipt/rpc/flipt"
"google.golang.org/protobuf/types/known/timestamppb"
)

func (s *Store) GetNamespace(ctx context.Context, key string) (*flipt.Namespace, error) {
var (
createdAt fliptsql.Timestamp
updatedAt fliptsql.Timestamp

namespace = &flipt.Namespace{}

err = s.builder.Select("\"key\", name, description, protected, created_at, updated_at").
From("namespaces").
Where(sq.Eq{"key": key}).
QueryRowContext(ctx).
Scan(
&namespace.Key,
&namespace.Name,
&namespace.Description,
&namespace.Protected,
&createdAt,
&updatedAt)
)

if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errs.ErrNotFoundf(`namespace "%s"`, key)
}

return nil, err
}

namespace.CreatedAt = createdAt.Timestamp
namespace.UpdatedAt = updatedAt.Timestamp

return namespace, nil
}

func (s *Store) ListNamespaces(ctx context.Context, opts ...storage.QueryOption) (storage.ResultSet[*flipt.Namespace], error) {
params := &storage.QueryParams{}

for _, opt := range opts {
opt(params)
}

var (
namespaces []*flipt.Namespace
results = storage.ResultSet[*flipt.Namespace]{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Just sharing this thought out loud. Not needed for this PR.

Now that we have the generic ResultSet and we have QueryParams we could definitly create a generic paginated query function.
It would likely need to take:

  • an initial query builder (containing the select, from and so on)
  • a generic function which can scan a single row into the generic type

Then it could do the adding of order, limit (+1), page token parsing, offset, calculating of next token and returning of generic result set.

Food for thought :D

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yeah 💯 i was thinking about this as I was going through it. I'll work on another PR for creating the generic func


query = s.builder.Select("\"key\", name, description, protected, created_at, updated_at").
From("namespaces").
OrderBy(fmt.Sprintf("created_at %s", params.Order))
)

if params.Limit > 0 {
query = query.Limit(params.Limit + 1)
}

var offset uint64

if params.PageToken != "" {
var token PageToken

if err := json.Unmarshal([]byte(params.PageToken), &token); err != nil {
return results, fmt.Errorf("decoding page token %w", err)
}

offset = token.Offset
query = query.Offset(offset)
} else if params.Offset > 0 {
offset = params.Offset
query = query.Offset(offset)
}

rows, err := query.QueryContext(ctx)
if err != nil {
return results, err
}

defer func() {
if cerr := rows.Close(); cerr != nil && err == nil {
err = cerr
}
}()

for rows.Next() {
var (
namespace = &flipt.Namespace{}

createdAt fliptsql.Timestamp
updatedAt fliptsql.Timestamp
)

if err := rows.Scan(
&namespace.Key,
&namespace.Name,
&namespace.Description,
&namespace.Protected,
&createdAt,
&updatedAt,
); err != nil {
return results, err
}

namespace.CreatedAt = createdAt.Timestamp
namespace.UpdatedAt = updatedAt.Timestamp

namespaces = append(namespaces, namespace)
}

if err := rows.Err(); err != nil {
return results, err
}

if err := rows.Close(); err != nil {
return results, err
}

var next *flipt.Namespace

if len(namespaces) > int(params.Limit) && params.Limit > 0 {
next = namespaces[len(namespaces)-1]
namespaces = namespaces[:params.Limit]
}

results.Results = namespaces

if next != nil {
out, err := json.Marshal(PageToken{Key: next.Key, Offset: offset + uint64(len(namespaces))})
if err != nil {
return results, fmt.Errorf("encoding page token %w", err)
}
results.NextPageToken = string(out)
}

return results, nil
}

func (s *Store) CountNamespaces(ctx context.Context) (uint64, error) {
var count uint64

if err := s.builder.Select("COUNT(*)").
From("namespaces").
QueryRowContext(ctx).
Scan(&count); err != nil {
return 0, err
}

return count, nil
}

func (s *Store) CreateNamespace(ctx context.Context, r *flipt.CreateNamespaceRequest) (*flipt.Namespace, error) {
var (
now = timestamppb.Now()
namespace = &flipt.Namespace{
Key: r.Key,
Name: r.Name,
Description: r.Description,
Protected: r.Protected,
CreatedAt: now,
UpdatedAt: now,
}
)

if _, err := s.builder.Insert("namespaces").
Columns("\"key\"", "name", "description", "protected", "created_at", "updated_at").
Values(
namespace.Key,
namespace.Name,
namespace.Description,
namespace.Protected,
&fliptsql.Timestamp{Timestamp: namespace.CreatedAt},
&fliptsql.Timestamp{Timestamp: namespace.UpdatedAt},
).
ExecContext(ctx); err != nil {
return nil, err
}

return namespace, nil
}

func (s *Store) UpdateNamespace(ctx context.Context, r *flipt.UpdateNamespaceRequest) (*flipt.Namespace, error) {
query := s.builder.Update("namespaces").
Set("name", r.Name).
Set("description", r.Description).
Set("updated_at", &fliptsql.Timestamp{Timestamp: timestamppb.Now()}).
Where(sq.Eq{"\"key\"": r.Key})

res, err := query.ExecContext(ctx)
if err != nil {
return nil, err
}

count, err := res.RowsAffected()
if err != nil {
return nil, err
}

if count != 1 {
return nil, errs.ErrNotFoundf(`namespace "%s"`, r.Key)
}

return s.GetNamespace(ctx, r.Key)
}

func (s *Store) DeleteNamespace(ctx context.Context, r *flipt.DeleteNamespaceRequest) error {
_, err := s.builder.Delete("namespaces").
Where(sq.Eq{"\"key\"": r.Key}).
ExecContext(ctx)

return err
}
7 changes: 7 additions & 0 deletions internal/storage/sql/common/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import (
"database/sql"

sq "github.com/Masterminds/squirrel"
"go.flipt.io/flipt/internal/storage"
"go.uber.org/zap"
)

var _ storage.Store = &Store{}

type Store struct {
builder sq.StatementBuilderType
db *sql.DB
Expand All @@ -25,3 +28,7 @@ type PageToken struct {
Key string `json:"key,omitempty"`
Offset uint64 `json:"offset,omitempty"`
}

func (s *Store) String() string {
return ""
}
Loading