From d33a2440d71d662c851d31ee96335e860f994a00 Mon Sep 17 00:00:00 2001 From: Wessie Date: Wed, 19 Jun 2024 23:26:35 +0100 Subject: [PATCH] rpc: make helpers handle empty-values for some types Turns out that protobuf does not send actual nils to handlers if the request is empty, but always atleast allocates the zero value of said type before the call. We check for some "required" fields now to determine if we should return nil or not from the helper --- rpc/helpers.go | 6 +++--- rpc/helpers_test.go | 8 ++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/rpc/helpers.go b/rpc/helpers.go index cf70e40..e905582 100644 --- a/rpc/helpers.go +++ b/rpc/helpers.go @@ -174,7 +174,7 @@ func toProtoSongUpdate(s *radio.SongUpdate) *SongUpdate { } func fromProtoSongUpdate(s *SongUpdate) *radio.SongUpdate { - if s == nil { + if s == nil || (s.Song == nil && s.Info == nil) { return nil } return &radio.SongUpdate{ @@ -214,7 +214,7 @@ func toProtoQueueID(rid radio.QueueID) *QueueID { } func fromProtoQueueID(id *QueueID) radio.QueueID { - if id == nil { + if id == nil || len(id.ID) == 0 { return radio.QueueID{} } @@ -276,7 +276,7 @@ func toProtoUser(u *radio.User) *User { } func fromProtoUser(u *User) *radio.User { - if u == nil { + if u == nil || (u.Id == 0 && u.Username == "") { return nil } return &radio.User{ diff --git a/rpc/helpers_test.go b/rpc/helpers_test.go index 315604f..b78930f 100644 --- a/rpc/helpers_test.go +++ b/rpc/helpers_test.go @@ -17,7 +17,7 @@ func TestRoundtrip(tt *testing.T) { // special generator for users since we don't actually pass all the fields // over the wire for reasons userGen := gen.Struct(reflect.TypeFor[radio.User](), map[string]gopter.Gen{ - "ID": a.GenForType(reflect.TypeFor[radio.UserID]()), + "ID": a.GenForType(reflect.TypeFor[radio.UserID]()).SuchThat(func(v radio.UserID) bool { return v > 0 }), "Username": gen.AnyString(), "IP": gen.AnyString(), "UpdatedAt": a.GenForType(reflect.TypeFor[*time.Time]()), @@ -95,7 +95,11 @@ func TestRoundtrip(tt *testing.T) { p.Property("user-permissions", a.ForAll(func(in radio.UserPermissions) bool { out := fromProtoUserPermissions(toProtoUserPermissions(in)) - return assert.Equal(tt, in, out) + if len(in) == 0 { + return assert.Len(tt, out, 0) + } else { + return assert.Equal(tt, in, out) + } })) p.Property("dj", a.ForAll(func(in radio.DJ) bool { out := fromProtoDJ(toProtoDJ(in))