Skip to content

Commit

Permalink
fix: handle non-existent keys properly in Store.SMembers (#111)
Browse files Browse the repository at this point in the history
I saw some unexpected traces when debugging some custom instrumentation
I'm adding. Basically, the service was not looking for claims in IPNI or
legacy systems even though there were no results in the cache.

Turns out that the `SMEMBERS` command doesn't return `(nil)` when the
key doesn't exist, as others commands do. Instead, it returns an empty
set (see the docs for
[SMEMBERS](https://redis.io/docs/latest/commands/smembers/#:~:text=This%20has%20the%20same%20effect%20as%20running%20SINTER%20with%20one%20argument%20key.)
and then
[SINTER](https://redis.io/docs/latest/commands/sinter/#:~:text=Keys%20that%20do%20not%20exist%20are%20considered%20to%20be%20empty%20sets.)).
Therefore, the store was returning an empty slice instead of
`ErrKeyNotFound`.

I added an explicit existence check in `SMembers` when the command
returns an empty set, assuming that it may be interesting to
differentiate between a non-existent and an empty set.
  • Loading branch information
volmedo authored Feb 6, 2025
1 parent 5c25e7e commit 4985df2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
11 changes: 8 additions & 3 deletions pkg/redis/redisstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,19 @@ func (rs *Store[Key, Value]) SetExpirable(ctx context.Context, key Key, expires
}

// Members returns all deserialized set values from redis.
// If the key does not exist, it returns ErrKeyNotFound.
func (rs *Store[Key, Value]) Members(ctx context.Context, key Key) ([]Value, error) {
data, err := rs.client.SMembers(ctx, rs.keyString(key)).Result()
if err != nil {
if err == redis.Nil {
return nil, types.ErrKeyNotFound
}
return nil, fmt.Errorf("getting set members: %w", err)
}

// as opposed to other commands, SMembers doesn't return redis.Nil when the key doesn't exist, but an empty set
// this implementation assumes there is no need to differentiate between a non-existing key and an empty set
if len(data) == 0 {
return nil, types.ErrKeyNotFound
}

var values []Value
for _, d := range data {
v, err := rs.fromRedis(d)
Expand Down
3 changes: 2 additions & 1 deletion pkg/redis/redisstore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,8 @@ func (m *MockRedis) SMembers(ctx context.Context, key string) *goredis.StringSli
}
val, ok := m.data[key]
if !ok {
cmd.SetErr(goredis.Nil)
// SMembers returns an empty set for non-existing keys
cmd.SetVal([]string{})
} else {
values := slices.Collect(maps.Keys(val.data))
cmd.SetVal(values)
Expand Down

0 comments on commit 4985df2

Please # to comment.