-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
AIP-157 Partial response implementation
This feature add capabilities to filter the response message from all the APIs. AIP detail: https://google.aip.dev/157
- Loading branch information
1 parent
21d96ba
commit 4ea8c19
Showing
21 changed files
with
6,078 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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 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 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 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 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,165 @@ | ||
package fieldmask | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"strings" | ||
|
||
jsoniter "github.com/json-iterator/go" | ||
"github.com/tidwall/gjson" | ||
"google.golang.org/grpc" | ||
"google.golang.org/grpc/metadata" | ||
"google.golang.org/protobuf/proto" | ||
"google.golang.org/protobuf/reflect/protoreflect" | ||
"google.golang.org/protobuf/types/known/fieldmaskpb" | ||
) | ||
|
||
const key = "fields" | ||
|
||
// FieldMask is recursive structure to define a path mask | ||
type FieldMask map[string]FieldMask | ||
|
||
// New create a FieldMask from the input array of paths. The array should contain JSON paths with dit "." notation. | ||
func New(paths []string) FieldMask { | ||
mask := make(FieldMask) | ||
for _, path := range paths { | ||
current := mask | ||
fields := strings.Split(path, ".") | ||
for _, field := range fields { | ||
c, ok := current[field] | ||
if !ok { | ||
c = make(FieldMask) | ||
current[field] = c | ||
} | ||
current = c | ||
} | ||
} | ||
return mask | ||
} | ||
|
||
// Filter takes a Proto message as input and updates the message according to the FieldMask. | ||
func (fm FieldMask) Filter(message proto.Message) { | ||
if len(fm) == 0 { | ||
return | ||
} | ||
|
||
reflect := message.ProtoReflect() | ||
reflect.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { | ||
mask, ok := fm[string(fd.Name())] | ||
if !ok { | ||
reflect.Clear(fd) | ||
} | ||
|
||
if len(mask) == 0 { | ||
return true | ||
} | ||
|
||
switch { | ||
case fd.IsMap(): | ||
m := reflect.Get(fd).Map() | ||
m.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { | ||
if fm, ok := mask[k.String()]; ok { | ||
if i, ok := v.Interface().(protoreflect.Message); ok && len(fm) > 0 { | ||
fm.Filter(i.Interface()) | ||
} | ||
} else { | ||
m.Clear(k) | ||
} | ||
return true | ||
}) | ||
case fd.IsList(): | ||
list := reflect.Get(fd).List() | ||
for i := 0; i < list.Len(); i++ { | ||
mask.Filter(list.Get(i).Message().Interface()) | ||
} | ||
case fd.Kind() == protoreflect.MessageKind: | ||
mask.Filter(reflect.Get(fd).Message().Interface()) | ||
case fd.Kind() == protoreflect.BytesKind: | ||
if b := v.Bytes(); gjson.ValidBytes(b) { | ||
b, err := jsoniter.Marshal(mask.FilterJSON(b, []string{})) | ||
if err == nil { | ||
reflect.Set(fd, protoreflect.ValueOfBytes(b)) | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
} | ||
|
||
// Paths return the dot "." JSON notation os all the paths in the FieldMask. | ||
// Parameter root []string is used internally for recursion, but it can also be used for setting an initial root path. | ||
func (fm FieldMask) Paths(path []string) (paths []string) { | ||
for k, v := range fm { | ||
path = append(path, k) | ||
if len(v) == 0 { | ||
paths = append(paths, strings.Join(path, ".")) | ||
} | ||
paths = append(paths, v.Paths(path)...) | ||
path = path[:len(path)-1] | ||
} | ||
return | ||
} | ||
|
||
// FilterJSON takes a JSON as input and return a map of the filtered JSON according to the FieldMask. | ||
func (fm FieldMask) FilterJSON(json []byte, path []string) (out map[string]any) { | ||
for k, v := range fm { | ||
if out == nil { | ||
out = make(map[string]interface{}) | ||
} | ||
path = append(path, k) | ||
if len(v) == 0 { | ||
out[k] = gjson.GetBytes(json, strings.Join(path, ".")).Value() | ||
} else { | ||
out[k] = v.FilterJSON(json, path) | ||
} | ||
path = path[:len(path)-1] | ||
} | ||
return | ||
} | ||
|
||
// FromMetadata gets all the filter definitions from gRPC metadata. | ||
func FromMetadata(md metadata.MD) FieldMask { | ||
fm := &fieldmaskpb.FieldMask{} | ||
masks := md.Get(key) | ||
for _, mask := range masks { | ||
paths := strings.Split(mask, ",") | ||
for _, path := range paths { | ||
fm.Paths = append(fm.Paths, strings.TrimSpace(path)) | ||
} | ||
} | ||
fm.Normalize() | ||
return New(fm.Paths) | ||
} | ||
|
||
// MetadataAnnotator injects key from query parameter to gRPC metadata (for REST client). | ||
func MetadataAnnotator(_ context.Context, req *http.Request) metadata.MD { | ||
if err := req.ParseForm(); err == nil && req.Form.Has(key) { | ||
return metadata.Pairs(key, req.Form.Get(key)) | ||
} | ||
return nil | ||
} | ||
|
||
// UnaryServerInterceptor updates the response message according to the FieldMask. | ||
func UnaryServerInterceptor() grpc.UnaryServerInterceptor { | ||
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { | ||
resp, err := handler(ctx, req) | ||
if err != nil { | ||
return resp, err | ||
} | ||
|
||
message, ok := resp.(proto.Message) | ||
if !ok { | ||
return resp, err | ||
} | ||
|
||
md, ok := metadata.FromIncomingContext(ctx) | ||
if !ok { | ||
return resp, err | ||
} | ||
|
||
fm := FromMetadata(md) | ||
fm.Filter(message) | ||
|
||
return resp, err | ||
} | ||
} |
This file contains 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,130 @@ | ||
package fieldmask | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
"net/url" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/google/go-cmp/cmp" | ||
"github.com/tektoncd/results/internal/fieldmask/test" | ||
"github.com/tidwall/gjson" | ||
"google.golang.org/grpc/metadata" | ||
"google.golang.org/protobuf/proto" | ||
"google.golang.org/protobuf/testing/protocmp" | ||
"google.golang.org/protobuf/types/known/fieldmaskpb" | ||
) | ||
|
||
var p = []string{"a.b", "a.b.c", "d.e", "f"} | ||
|
||
var m = metadata.New(map[string]string{ | ||
"fields": strings.Join(p, ","), | ||
}) | ||
|
||
var fm = FieldMask{ | ||
"a": FieldMask{ | ||
"b": {}, | ||
}, | ||
"d": FieldMask{ | ||
"e": {}, | ||
}, | ||
"f": {}, | ||
} | ||
|
||
var j = ` | ||
{ | ||
"a": { | ||
"b": { | ||
"c": "test value" | ||
} | ||
}, | ||
"d": { | ||
"e": "test value" | ||
}, | ||
"g": { | ||
"h": "test value" | ||
} | ||
}` | ||
|
||
var pm = &test.Test{ | ||
Id: "test-id", | ||
Name: "test-name", | ||
Data: []*test.Any{ | ||
{ | ||
Type: "type-1", | ||
Value: []byte(gjson.Parse(j).String()), | ||
}, | ||
{ | ||
Type: "type-2", | ||
Value: []byte(gjson.Parse(j).String()), | ||
}, | ||
}, | ||
} | ||
|
||
func TestNew(t *testing.T) { | ||
f := &fieldmaskpb.FieldMask{Paths: p} | ||
f.Normalize() | ||
want := fm | ||
got := New(f.Paths) | ||
if diff := cmp.Diff(want, got); diff != "" { | ||
t.Errorf("Fieldmask mismatch (-want +got):\n%s", diff) | ||
} | ||
} | ||
|
||
func TestFieldMask_Paths(t *testing.T) { | ||
f := &fieldmaskpb.FieldMask{Paths: p} | ||
f.Normalize() | ||
want := f.Paths | ||
got := fm.Paths(nil) | ||
if diff := cmp.Diff(want, got); diff != "" { | ||
t.Errorf("Paths mismatch (-want +got):\n%s", diff) | ||
} | ||
} | ||
|
||
func TestFieldMask_Filter(t *testing.T) { | ||
f := New([]string{"name", "data.value.d"}) | ||
got := proto.Clone(pm) | ||
f.Filter(got) | ||
d := gjson.Parse(`{"d":{"e":"test value"}}`).String() | ||
want := &test.Test{ | ||
Name: "test-name", | ||
Data: []*test.Any{ | ||
{Value: []byte(d)}, | ||
{Value: []byte(d)}, | ||
}, | ||
} | ||
if diff := cmp.Diff(want, got, protocmp.Transform()); diff != "" { | ||
t.Errorf("Proto mismatch (-want +got):\n%s", diff) | ||
} | ||
} | ||
|
||
func TestFieldMask_FilterJSON(t *testing.T) { | ||
want := gjson.Parse(`{"a":{"b":{"c":"test value"}}}`).Value() | ||
f := New([]string{"a.b"}) | ||
got := f.FilterJSON([]byte(j), []string{}) | ||
|
||
if diff := cmp.Diff(want, got); diff != "" { | ||
t.Errorf("JSON mismatch (-want +got):\n%s", diff) | ||
} | ||
} | ||
|
||
func TestFromMetadata(t *testing.T) { | ||
want := fm | ||
got := FromMetadata(m) | ||
if diff := cmp.Diff(want, got); diff != "" { | ||
t.Errorf("Fieldmask mismatch (-want +got):\n%s", diff) | ||
} | ||
} | ||
|
||
func TestMetadataAnnotator(t *testing.T) { | ||
want := m | ||
got := MetadataAnnotator(context.Background(), &http.Request{ | ||
Form: url.Values{ | ||
"fields": m.Get("fields"), | ||
}, | ||
}) | ||
if diff := cmp.Diff(want, got); diff != "" { | ||
t.Errorf("Metadata mismatch (-want +got):\n%s", diff) | ||
} | ||
} |
Oops, something went wrong.