-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add DynamoDB support #2090
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
Closed
aziz-shoko
wants to merge
12
commits into
gofr-dev:development
from
aziz-shoko:aziz-shoko/dynamodb-clean
Closed
Add DynamoDB support #2090
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6191171
Add aws DynamodDB feature
aziz-shoko f4d6891
update docs to the correct dynamodb name
aziz-shoko cb9e80b
change to british spelling (fix typos)
aziz-shoko f1523d5
format to gci and change to static wrapped errors
aziz-shoko 3455078
change to struct to pass tooManyResultsChecker pipeline
aziz-shoko 931b450
make lines less than 140 chars
aziz-shoko 1e2ccfe
switch to t.Context() and fix missing param in healthcheck
aziz-shoko 3c7af13
passing gofmt, gci, golangci-lint, and typos
aziz-shoko 70d2bf8
Merge branch 'development' into aziz-shoko/dynamodb-clean
Umang01-hash b83e28a
Merge branch 'development' into aziz-shoko/dynamodb-clean
aziz-shoko 0a1eaf7
Merge branch 'development' into aziz-shoko/dynamodb-clean
Umang01-hash 32408be
Merge branch 'development' into aziz-shoko/dynamodb-clean
Umang01-hash File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| # DynamoDB Client | ||
|
|
||
| This package provides a DynamoDB client for use as a key-value store in GoFr applications. | ||
| It supports basic CRUD operations (Set, Get, Delete) on items using a partition key, along with health checks. | ||
| The client integrates logging, metrics, and tracing for observability. | ||
|
|
||
| ## Quick Start | ||
| Import the package and create the client instance: | ||
| ```Go | ||
| import ( | ||
| "context" | ||
|
|
||
| "gofr.dev/pkg/gofr/datasource/kv/dynamodb" // Adjust path as needed | ||
| ) | ||
|
|
||
| func main() { | ||
| configs := dynamodb.Configs{ | ||
| Table: "your-table-name", | ||
| Region: "us-east-1", | ||
| Endpoint: "", // Leave empty for real AWS; set for local (e.g., "http://localhost:8000") | ||
| PartitionKeyName: "pk", // Default is "pk" if not specified | ||
| } | ||
|
|
||
| client := dynamodb.New(configs) | ||
| client.UseLogger(yourLogger) // Implement dynamodb.Logger interface | ||
| client.UseMetrics(yourMetrics) // Implement dynamodb.Metrics interface | ||
| // client.UseTracer(yourTracer) // Optional: trace.Tracer | ||
|
|
||
| if err := client.Connect(); err != nil { | ||
| // Handle connection error | ||
| } | ||
|
|
||
| ctx := context.Background() | ||
| key := "example-key" | ||
| attributes := map[string]any{"field": "value"} | ||
|
|
||
| // Set item | ||
| client.Set(ctx, key, attributes) | ||
|
|
||
| // Get item | ||
| result, _ := client.Get(ctx, key) | ||
|
|
||
| // Delete item | ||
| client.Delete(ctx, key) | ||
| } | ||
| ``` | ||
|
|
||
| ## Configuration | ||
| The Configs struct defines the client settings: | ||
|
|
||
| * `Table`: Required. Name of the DynamoDB table. | ||
| * `Region`: Required. AWS region (e.g., "us-east-1"). | ||
| * `Endpoint`: Optional. Custom endpoint URL (e.g., for local DynamoDB). | ||
| * `PartitionKeyName`: Optional. Partition key attribute name (defaults to "pk"). | ||
|
|
||
| The table must have a string partition key (no sort key support). | ||
|
|
||
| ## Usage | ||
|
|
||
| **Operations** | ||
| * `Set(ctx context.Context, key string, attributes map[string]any) error`: Stores attributes under the given key. Overwrites existing items. | ||
| * `Get(ctx context.Context, key string) (map[string]any, error)`: Retrieves attributes for the key. Returns error if key not found. | ||
| * `Delete(ctx context.Context, key string) error`: Deletes the item by key. | ||
| * `HealthCheck(ctx context.Context) (any, error)`: Checks table status via DescribeTable. Returns a `Health` struct with status ("UP" or "DOWN") and details. | ||
|
|
||
| All operations log details, record metrics (e.g., duration histograms), and support tracing spans. | ||
|
|
||
| ## Observability | ||
| * Logging: Use `UseLogger` to inject a logger implementing the `Logger` interface. Logs details and errors. | ||
| * Metrics: Use `UseMetrics` to inject metrics implementing the `Metrics` interface. Records histograms for query durations. | ||
| * Tracing: Use `UseTracer` to inject an OpenTelemetry tracer. Adds spans for each operation. | ||
|
|
||
| ## Notes | ||
| * This client assumes a simple key-value model; no support for sort keys, queries, or scans. | ||
| * For production, use IAM roles or credentials via AWS config. | ||
| * Ensure table exists before connecting; health check verifies accessibility. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| package dynamodb | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/aws/aws-sdk-go-v2/aws" | ||
| "github.com/aws/aws-sdk-go-v2/config" | ||
| "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" | ||
| "github.com/aws/aws-sdk-go-v2/service/dynamodb" | ||
| "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" | ||
| "go.opentelemetry.io/otel/attribute" | ||
| "go.opentelemetry.io/otel/trace" | ||
| ) | ||
|
|
||
| var errStatusDown = errors.New("status down") | ||
| var errKeyNotFound = errors.New("key not found") | ||
|
|
||
| type Configs struct { | ||
| Table string | ||
| Region string | ||
| Endpoint string | ||
| PartitionKeyName string | ||
| } | ||
| type dynamoDBInterface interface { | ||
| PutItem( | ||
| ctx context.Context, | ||
| params *dynamodb.PutItemInput, | ||
| optFns ...func(*dynamodb.Options), | ||
| ) (*dynamodb.PutItemOutput, error) | ||
| GetItem( | ||
| ctx context.Context, | ||
| params *dynamodb.GetItemInput, | ||
| optFns ...func(*dynamodb.Options), | ||
| ) (*dynamodb.GetItemOutput, error) | ||
| DeleteItem( | ||
| ctx context.Context, | ||
| params *dynamodb.DeleteItemInput, | ||
| optFns ...func(*dynamodb.Options), | ||
| ) (*dynamodb.DeleteItemOutput, error) | ||
| DescribeTable( | ||
| ctx context.Context, | ||
| params *dynamodb.DescribeTableInput, | ||
| optFns ...func(*dynamodb.Options), | ||
| ) (*dynamodb.DescribeTableOutput, error) | ||
| } | ||
|
|
||
| type Client struct { | ||
| db dynamoDBInterface | ||
| configs *Configs | ||
| logger Logger | ||
| metrics Metrics | ||
| tracer trace.Tracer | ||
| } | ||
|
|
||
| func New(configs Configs) *Client { | ||
| if configs.PartitionKeyName == "" { | ||
| configs.PartitionKeyName = "pk" | ||
| } | ||
|
|
||
| return &Client{configs: &configs} | ||
| } | ||
|
|
||
| // UseLogger sets the logger for the Dynamo client which asserts the Logger interface. | ||
| func (c *Client) UseLogger(logger any) { | ||
| if l, ok := logger.(Logger); ok { | ||
| c.logger = l | ||
| } | ||
| } | ||
|
|
||
| // UseMetrics sets the metrics for the Dynamo client which asserts the Metrics interface. | ||
| func (c *Client) UseMetrics(metrics any) { | ||
| if m, ok := metrics.(Metrics); ok { | ||
| c.metrics = m | ||
| } | ||
| } | ||
|
|
||
| // UseTracer sets the tracer for Dynamo client. | ||
| func (c *Client) UseTracer(tracer any) { | ||
| if tracer, ok := tracer.(trace.Tracer); ok { | ||
| c.tracer = tracer | ||
| } | ||
| } | ||
|
|
||
| func (c *Client) Connect() error { | ||
| c.logger.Debugf("connecting to DynamoDB table %v in region %v", c.configs.Table, c.configs.Region) | ||
|
|
||
| dynamoBuckets := []float64{1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000} | ||
| c.metrics.NewHistogram("app_dynamodb_duration_ms", "Response time of DynamoDB queries in milliseconds.", dynamoBuckets...) | ||
|
|
||
| awsCfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(c.configs.Region)) | ||
| if err != nil { | ||
| c.logger.Errorf("error loading AWS config: %v", err) | ||
| return fmt.Errorf("failed to load AWS config: %w", err) | ||
| } | ||
|
|
||
| var opts []func(*dynamodb.Options) | ||
|
|
||
| if c.configs.Endpoint != "" { | ||
| opts = append(opts, func(o *dynamodb.Options) { | ||
| o.BaseEndpoint = aws.String(c.configs.Endpoint) | ||
| }) | ||
| } | ||
|
|
||
| db := dynamodb.NewFromConfig(awsCfg, opts...) | ||
| c.db = db | ||
|
|
||
| c.logger.Infof("connected to DynamoDB table %v in region %v", c.configs.Table, c.configs.Region) | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (c *Client) Get(ctx context.Context, key string) (map[string]any, error) { | ||
| span := c.addTrace(ctx, "get", key) | ||
| defer c.sendOperationsStats(time.Now(), "GET", span, key) | ||
|
|
||
| input := &dynamodb.GetItemInput{ | ||
| TableName: aws.String(c.configs.Table), | ||
| Key: map[string]types.AttributeValue{ | ||
| c.configs.PartitionKeyName: &types.AttributeValueMemberS{Value: key}, | ||
| }, | ||
| } | ||
|
|
||
| out, err := c.db.GetItem(ctx, input) | ||
| if err != nil { | ||
| c.logger.Errorf("error while fetching data for key: %v, error: %v", key, err) | ||
| return nil, err | ||
| } | ||
|
|
||
| if out.Item == nil { | ||
| return nil, errKeyNotFound | ||
| } | ||
|
|
||
| var result map[string]any | ||
| err = attributevalue.UnmarshalMap(out.Item, &result) | ||
|
|
||
| if err != nil { | ||
| c.logger.Errorf("error unmarshalling item for key: %v, error: %v", key, err) | ||
| return nil, err | ||
| } | ||
|
|
||
| delete(result, c.configs.PartitionKeyName) | ||
|
|
||
| return result, nil | ||
| } | ||
|
|
||
| func (c *Client) Set(ctx context.Context, key string, attributes map[string]any) error { | ||
| span := c.addTrace(ctx, "set", key) | ||
| defer c.sendOperationsStats(time.Now(), "SET", span, key) | ||
|
|
||
| itemAV, err := attributevalue.MarshalMap(attributes) | ||
| if err != nil { | ||
| c.logger.Errorf("error marshaling attributes for key: %v, error: %v", key, err) | ||
| return err | ||
| } | ||
|
|
||
| itemAV[c.configs.PartitionKeyName] = &types.AttributeValueMemberS{Value: key} | ||
| input := &dynamodb.PutItemInput{ | ||
| TableName: aws.String(c.configs.Table), | ||
| Item: itemAV, | ||
| } | ||
|
|
||
| _, err = c.db.PutItem(ctx, input) | ||
| if err != nil { | ||
| c.logger.Errorf("error while setting data for key: %v, error: %v", key, err) | ||
| return err | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (c *Client) Delete(ctx context.Context, key string) error { | ||
| span := c.addTrace(ctx, "delete", key) | ||
| defer c.sendOperationsStats(time.Now(), "DELETE", span, key) | ||
|
|
||
| input := &dynamodb.DeleteItemInput{ | ||
| TableName: aws.String(c.configs.Table), | ||
| Key: map[string]types.AttributeValue{ | ||
| c.configs.PartitionKeyName: &types.AttributeValueMemberS{Value: key}, | ||
| }, | ||
| } | ||
|
|
||
| _, err := c.db.DeleteItem(ctx, input) | ||
|
|
||
| if err != nil { | ||
| c.logger.Errorf("error while deleting data for key: %v, error: %v", key, err) | ||
|
|
||
| return err | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| type Health struct { | ||
| Status string `json:"status,omitempty"` | ||
| Details map[string]any `json:"details,omitempty"` | ||
| } | ||
|
|
||
| func (c *Client) HealthCheck(ctx context.Context) (any, error) { | ||
| h := Health{ | ||
| Details: make(map[string]any), | ||
| } | ||
|
|
||
| h.Details["table"] = c.configs.Table | ||
| h.Details["region"] = c.configs.Region | ||
|
|
||
| input := &dynamodb.DescribeTableInput{TableName: aws.String(c.configs.Table)} | ||
|
|
||
| _, err := c.db.DescribeTable(ctx, input) | ||
| if err != nil { | ||
| h.Status = "DOWN" | ||
|
|
||
| return &h, errStatusDown | ||
| } | ||
|
|
||
| h.Status = "UP" | ||
|
|
||
| return &h, nil | ||
| } | ||
|
|
||
| func (c *Client) sendOperationsStats(start time.Time, methodType string, | ||
| span trace.Span, kv ...string) { | ||
| duration := time.Since(start).Microseconds() | ||
|
|
||
| c.logger.Debug(&Log{ | ||
| Type: methodType, | ||
| Duration: duration, | ||
| Key: strings.Join(kv, " "), | ||
| }) | ||
|
|
||
| if span != nil { | ||
| defer span.End() | ||
| span.SetAttributes(attribute.Int64("dynamodb.duration_us", duration)) | ||
| } | ||
|
|
||
| c.metrics.RecordHistogram(context.Background(), "app_dynamodb_duration_ms", float64(duration), "table", c.configs.Table, | ||
| "type", methodType) | ||
| } | ||
|
|
||
| func (c *Client) addTrace(ctx context.Context, method, key string) trace.Span { | ||
| if c.tracer != nil { | ||
| _, span := c.tracer.Start(ctx, fmt.Sprintf("dynamodb-%v", method)) | ||
| span.SetAttributes( | ||
| attribute.String("dynamodb.method", method), | ||
| attribute.String("dynamodb.key", key), | ||
| ) | ||
|
|
||
| return span | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this should be *gofr.Context.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are you sure? I am using the function signatures from dynamodb package, switching to gofr.Context breaks it
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey no it won't break it .... gofr's context implements the context.Context interface. You will not face any issue.