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

GO-5175 Fix nil interface issue #397

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion app/ocache/ocache.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"github.com/anyproto/any-sync/util/reflection"
"sync"
"time"

Expand Down Expand Up @@ -168,7 +169,7 @@ func (c *oCache) load(ctx context.Context, id string, e *entry) {

c.mu.Lock()
defer c.mu.Unlock()
if value == nil && err == nil {
if reflection.IsNilish(value) && err == nil {
err = fmt.Errorf("loaded value is nil, id: %s", id)
}
if err != nil {
Expand Down
12 changes: 12 additions & 0 deletions app/ocache/ocache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func TestOCache_Get(t *testing.T) {
assert.Equal(t, 1, c.Len())
assert.NoError(t, c.Close())
})

t.Run("error", func(t *testing.T) {
tErr := errors.New("err")
c := New(func(ctx context.Context, id string) (value Object, err error) {
Expand Down Expand Up @@ -283,6 +284,17 @@ func TestOCache_GC(t *testing.T) {
}

func Test_OCache_Remove(t *testing.T) {
t.Run("remove puzzler", func(t *testing.T) {
c := New(func(ctx context.Context, id string) (value Object, err error) {
var p *testObject
return p, err
})
val, err := c.Get(context.TODO(), "test")
require.Error(t, err, "loaded value is nil, id: test")
require.Nil(t, val)
require.Equal(t, 0, c.Len())
require.NoError(t, c.Close())
})
t.Run("remove simple", func(t *testing.T) {
closeCh := make(chan struct{})
getCh := make(chan struct{})
Expand Down
19 changes: 19 additions & 0 deletions util/reflection/reflect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package reflection

import "reflect"

func IsNilish(val any) bool {
if val == nil {
return true
}

v := reflect.ValueOf(val)
k := v.Kind()
switch k {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer,
reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return v.IsNil()
}

return false
}