-
Notifications
You must be signed in to change notification settings - Fork 30
Added hash and json support for Redis. #206
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
Open
foogaro
wants to merge
3
commits into
jrnd-io:main
Choose a base branch
from
foogaro:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
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
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,63 @@ | ||
package redis | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"os" | ||
"time" | ||
|
||
"github.com/redis/go-redis/v9" | ||
"github.com/rs/zerolog/log" | ||
) | ||
|
||
type HashProducer struct { | ||
client redis.Client | ||
Ttl time.Duration | ||
} | ||
|
||
func (p *HashProducer) Initialize(configFile string) { | ||
var options redis.Options | ||
|
||
data, err := os.ReadFile(configFile) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to load Redis configFile") | ||
} | ||
|
||
err = json.Unmarshal(data, &options) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to parse configuration parameters") | ||
} | ||
|
||
p.client = *redis.NewClient(&options) | ||
} | ||
|
||
func (p *HashProducer) Close(_ context.Context) error { | ||
err := p.client.Close() | ||
if err != nil { | ||
log.Warn().Err(err).Msg("Failed to close Redis connection") | ||
} | ||
return err | ||
} | ||
|
||
func (p *HashProducer) Produce(ctx context.Context, k []byte, v []byte, _ any) { | ||
// Parse the JSON value into a map | ||
var fields map[string]interface{} | ||
err := json.Unmarshal(v, &fields) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to unmarshal JSON into hash fields") | ||
} | ||
|
||
// Use HSet to set multiple hash fields at once | ||
err = p.client.HSet(ctx, string(k), fields).Err() | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to write hash data to Redis") | ||
} | ||
|
||
// Set TTL if specified | ||
if p.Ttl > 0 { | ||
err = p.client.Expire(ctx, string(k), p.Ttl).Err() | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to set TTL on Redis hash") | ||
} | ||
} | ||
} |
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,82 @@ | ||
//go:build exclude | ||
|
||
// Copyright © 2024 JR team | ||
// | ||
// 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 redis | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"testing" | ||
"time" | ||
|
||
"github.com/redis/go-redis/v9" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestHashProducer_Initialize(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &HashProducer{} | ||
producer.Initialize(configFile) | ||
|
||
assert.NotNil(t, producer.client, "Redis client should be initialized") | ||
} | ||
|
||
func TestHashProducer_Produce(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &HashProducer{ | ||
Ttl: time.Minute, | ||
} | ||
producer.Initialize(configFile) | ||
|
||
ctx := context.Background() | ||
key := "test_hash_key" | ||
value := map[string]interface{}{ | ||
"field1": "value1", | ||
"field2": "value2", | ||
} | ||
valueBytes, _ := json.Marshal(value) | ||
|
||
producer.Produce(ctx, []byte(key), valueBytes, nil) | ||
|
||
// Verify the data in Redis | ||
client := redis.NewClient(&redis.Options{ | ||
Addr: "localhost:6379", // Adjust as necessary | ||
}) | ||
defer client.Close() | ||
|
||
result, err := client.HGetAll(ctx, key).Result() | ||
assert.NoError(t, err, "Should not error when getting hash from Redis") | ||
assert.Equal(t, "value1", result["field1"], "Field1 should match") | ||
assert.Equal(t, "value2", result["field2"], "Field2 should match") | ||
} | ||
|
||
func TestHashProducer_Close(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &HashProducer{} | ||
producer.Initialize(configFile) | ||
|
||
err := producer.Close(context.Background()) | ||
assert.NoError(t, err, "Should not error when closing Redis connection") | ||
} |
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,63 @@ | ||
package redis | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"os" | ||
"time" | ||
|
||
"github.com/redis/go-redis/v9" | ||
"github.com/rs/zerolog/log" | ||
) | ||
|
||
type JSONProducer struct { | ||
client redis.Client | ||
Ttl time.Duration | ||
} | ||
|
||
func (p *JSONProducer) Initialize(configFile string) { | ||
var options redis.Options | ||
|
||
data, err := os.ReadFile(configFile) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to load Redis configFile") | ||
} | ||
|
||
err = json.Unmarshal(data, &options) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to parse configuration parameters") | ||
} | ||
|
||
p.client = *redis.NewClient(&options) | ||
} | ||
|
||
func (p *JSONProducer) Close(_ context.Context) error { | ||
err := p.client.Close() | ||
if err != nil { | ||
log.Warn().Err(err).Msg("Failed to close Redis connection") | ||
} | ||
return err | ||
} | ||
|
||
func (p *JSONProducer) Produce(ctx context.Context, k []byte, v []byte, _ any) { | ||
// Verify the input is valid JSON | ||
var jsonData interface{} | ||
err := json.Unmarshal(v, &jsonData) | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to validate JSON data") | ||
} | ||
|
||
// Use JSON.SET to store the JSON document | ||
err = p.client.Do(ctx, "JSON.SET", string(k), "$", string(v)).Err() | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to write JSON data to Redis") | ||
} | ||
|
||
// Set TTL if specified | ||
if p.Ttl > 0 { | ||
err = p.client.Expire(ctx, string(k), p.Ttl).Err() | ||
if err != nil { | ||
log.Fatal().Err(err).Msg("Failed to set TTL on Redis key") | ||
} | ||
} | ||
} |
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,94 @@ | ||
//go:build exclude | ||
|
||
// Copyright © 2024 JR team | ||
// | ||
// 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 redis | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"testing" | ||
"time" | ||
|
||
"github.com/redis/go-redis/v9" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestJSONProducer_Initialize(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &JSONProducer{} | ||
producer.Initialize(configFile) | ||
|
||
assert.NotNil(t, producer.client, "Redis client should be initialized") | ||
} | ||
|
||
func TestJSONProducer_Produce(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &JSONProducer{ | ||
Ttl: time.Minute, | ||
} | ||
producer.Initialize(configFile) | ||
|
||
ctx := context.Background() | ||
key := "test_json_key" | ||
// Create a test JSON object with nested structures | ||
testJSON := `{ | ||
"id": "2210", | ||
"user": { | ||
"name": "Foogaro", | ||
"year": 1978, | ||
"email": "luigi@foogaro.com" | ||
} | ||
}` | ||
producer.Produce(ctx, []byte(key), []byte(testJSON), nil) | ||
|
||
// Verify the data in Redis | ||
client := redis.NewClient(&redis.Options{ | ||
Addr: "localhost:6379", // Adjust as necessary | ||
}) | ||
defer client.Close() | ||
|
||
// Use JSON.GET to retrieve the stored JSON | ||
result, err := client.Do(ctx, "JSON.GET", key, "$").Text() | ||
assert.NoError(t, err, "Should not error when getting JSON from Redis") | ||
|
||
// Compare the JSON strings (after normalizing them) | ||
var expected, actual interface{} | ||
err = json.Unmarshal([]byte(testJSON), &expected) | ||
assert.NoError(t, err, "Should parse expected JSON") | ||
|
||
err = json.Unmarshal([]byte(result), &actual) | ||
assert.NoError(t, err, "Should parse actual JSON") | ||
|
||
assert.Equal(t, expected, actual, "Stored JSON should match original") | ||
} | ||
|
||
func TestJSONProducer_Close(t *testing.T) { | ||
configFile := "config.json.example" | ||
|
||
producer := &JSONProducer{} | ||
producer.Initialize(configFile) | ||
|
||
err := producer.Close(context.Background()) | ||
assert.NoError(t, err, "Should not error when closing Redis connection") | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.