diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..81a3d8b --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +.PHONY: install +install: + go install ./protoc-gen-rangerrpc + +.PHONY: generate/examples +generate/examples: + go generate ./examples/pingpong + +.PHONY: run/example/server +run/example/server: install generate/examples + go run examples/pingpong/server/main.go + +.PHONY: run/example/client +run/example/client: generate/examples + go run examples/pingpong/client/main.go \ No newline at end of file diff --git a/client.go b/client.go new file mode 100644 index 0000000..fece3c1 --- /dev/null +++ b/client.go @@ -0,0 +1,92 @@ +package ranger + +import ( + "bytes" + "context" + "io/ioutil" + "net/http" + + "github.com/cockroachdb/errors" + "github.com/rs/zerolog/log" + "go.mondoo.com/ranger-rpc/status" + "google.golang.org/protobuf/proto" +) + +// Client is the client for the Ranger service. It is used as the base client for all service calls. +type Client struct{} + +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +// DoClientRequest makes a request to the Ranger service. +// It will marshal the proto.Message into the request body, do the request and then parse the response into the +// response proto.Message. +func (c *Client) DoClientRequest(ctx context.Context, client HTTPClient, url string, in, out proto.Message) (err error) { + reqBodyBytes, err := proto.Marshal(in) + if err != nil { + return errors.Wrap(err, "failed to marshal proto request") + } + + if err = ctx.Err(); err != nil { + return errors.Wrap(err, "aborted because context was done") + } + + header := make(http.Header) + header.Set("Accept", "application/protobuf") + header.Set("Content-Type", "application/protobuf") + + log.Debug().Str("url", url).Msg("call service") + reader := bytes.NewReader(reqBodyBytes) + req, err := http.NewRequest("POST", url, reader) + if err != nil { + return err + } + req = req.WithContext(ctx) + req.Header = header + + // do http call + resp, err := client.Do(req) + if err != nil { + return errors.Wrap(err, "failed to do request") + } + + defer func() { + cerr := resp.Body.Close() + if err == nil && cerr != nil { + err = errors.Wrap(cerr, "failed to close response body") + } + }() + + if err = ctx.Err(); err != nil { + return errors.Wrap(err, "aborted because context was done") + } + + if resp.StatusCode != 200 { + // TODO wrap body in error + spb, err := parseStatus(resp.Body) + if err == nil { + log.Debug().Str("body", spb.Message).Int("status", resp.StatusCode).Msg("non-ok http request") + return status.FromProto(spb).Err() + } else { + payload, err := ioutil.ReadAll(reader) + if err != nil { + log.Error().Err(err).Msg("could not parse http body") + } + return status.New(status.CodeFromHTTPStatus(resp.StatusCode), string(payload)).Err() + } + } + + if err = ctx.Err(); err != nil { + return errors.Wrap(err, "aborted because context was done") + } + + respBodyBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return errors.Wrap(err, "failed to read response body") + } + if err = proto.Unmarshal(respBodyBytes, out); err != nil { + return errors.Wrap(err, "failed to unmarshal proto response") + } + return nil +} diff --git a/codes/codes.go b/codes/codes.go new file mode 100644 index 0000000..28880aa --- /dev/null +++ b/codes/codes.go @@ -0,0 +1,244 @@ +/* + * + * Copyright 2014 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package codes defines the canonical error codes used by gRPC. It is +// consistent across various languages. +package codes + +import ( + "fmt" + "strconv" +) + +// A Code is an unsigned 32-bit error code as defined in the gRPC spec. +type Code uint32 + +const ( + // OK is returned on success. + OK Code = 0 + + // Canceled indicates the operation was canceled (typically by the caller). + // + // The gRPC framework will generate this error code when cancellation + // is requested. + Canceled Code = 1 + + // Unknown error. An example of where this error may be returned is + // if a Status value received from another address space belongs to + // an error-space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // The gRPC framework will generate this error code in the above two + // mentioned cases. + Unknown Code = 2 + + // InvalidArgument indicates client specified an invalid argument. + // Note that this differs from FailedPrecondition. It indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // This error code will not be generated by the gRPC framework. + InvalidArgument Code = 3 + + // DeadlineExceeded means operation expired before completion. + // For operations that change the state of the system, this error may be + // returned even if the operation has completed successfully. For + // example, a successful response from a server could have been delayed + // long enough for the deadline to expire. + // + // The gRPC framework will generate this error code when the deadline is + // exceeded. + DeadlineExceeded Code = 4 + + // NotFound means some requested entity (e.g., file or directory) was + // not found. + // + // This error code will not be generated by the gRPC framework. + NotFound Code = 5 + + // AlreadyExists means an attempt to create an entity failed because one + // already exists. + // + // This error code will not be generated by the gRPC framework. + AlreadyExists Code = 6 + + // PermissionDenied indicates the caller does not have permission to + // execute the specified operation. It must not be used for rejections + // caused by exhausting some resource (use ResourceExhausted + // instead for those errors). It must not be + // used if the caller cannot be identified (use Unauthenticated + // instead for those errors). + // + // This error code will not be generated by the gRPC core framework, + // but expect authentication middleware to use it. + PermissionDenied Code = 7 + + // ResourceExhausted indicates some resource has been exhausted, perhaps + // a per-user quota, or perhaps the entire file system is out of space. + // + // This error code will be generated by the gRPC framework in + // out-of-memory and server overload situations, or when a message is + // larger than the configured maximum size. + ResourceExhausted Code = 8 + + // FailedPrecondition indicates operation was rejected because the + // system is not in a state required for the operation's execution. + // For example, directory to be deleted may be non-empty, an rmdir + // operation is applied to a non-directory, etc. + // + // A litmus test that may help a service implementor in deciding + // between FailedPrecondition, Aborted, and Unavailable: + // (a) Use Unavailable if the client can retry just the failing call. + // (b) Use Aborted if the client should retry at a higher-level + // (e.g., restarting a read-modify-write sequence). + // (c) Use FailedPrecondition if the client should not retry until + // the system state has been explicitly fixed. E.g., if an "rmdir" + // fails because the directory is non-empty, FailedPrecondition + // should be returned since the client should not retry unless + // they have first fixed up the directory by deleting files from it. + // (d) Use FailedPrecondition if the client performs conditional + // REST Get/Update/Delete on a resource and the resource on the + // server does not match the condition. E.g., conflicting + // read-modify-write on the same resource. + // + // This error code will not be generated by the gRPC framework. + FailedPrecondition Code = 9 + + // Aborted indicates the operation was aborted, typically due to a + // concurrency issue like sequencer check failures, transaction aborts, + // etc. + // + // See litmus test above for deciding between FailedPrecondition, + // Aborted, and Unavailable. + // + // This error code will not be generated by the gRPC framework. + Aborted Code = 10 + + // OutOfRange means operation was attempted past the valid range. + // E.g., seeking or reading past end of file. + // + // Unlike InvalidArgument, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate InvalidArgument if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // OutOfRange if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between FailedPrecondition and + // OutOfRange. We recommend using OutOfRange (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an OutOfRange error to detect when + // they are done. + // + // This error code will not be generated by the gRPC framework. + OutOfRange Code = 11 + + // Unimplemented indicates operation is not implemented or not + // supported/enabled in this service. + // + // This error code will be generated by the gRPC framework. Most + // commonly, you will see this error code when a method implementation + // is missing on the server. It can also be generated for unknown + // compression algorithms or a disagreement as to whether an RPC should + // be streaming. + Unimplemented Code = 12 + + // Internal errors. Means some invariants expected by underlying + // system has been broken. If you see one of these errors, + // something is very broken. + // + // This error code will be generated by the gRPC framework in several + // internal error conditions. + Internal Code = 13 + + // Unavailable indicates the service is currently unavailable. + // This is a most likely a transient condition and may be corrected + // by retrying with a backoff. Note that it is not always safe to retry + // non-idempotent operations. + // + // See litmus test above for deciding between FailedPrecondition, + // Aborted, and Unavailable. + // + // This error code will be generated by the gRPC framework during + // abrupt shutdown of a server process or network connection. + Unavailable Code = 14 + + // DataLoss indicates unrecoverable data loss or corruption. + // + // This error code will not be generated by the gRPC framework. + DataLoss Code = 15 + + // Unauthenticated indicates the request does not have valid + // authentication credentials for the operation. + // + // The gRPC framework will generate this error code when the + // authentication metadata is invalid or a Credentials callback fails, + // but also expect authentication middleware to generate it. + Unauthenticated Code = 16 + + _maxCode = 17 +) + +var strToCode = map[string]Code{ + `"OK"`: OK, + `"CANCELLED"`:/* [sic] */ Canceled, + `"UNKNOWN"`: Unknown, + `"INVALID_ARGUMENT"`: InvalidArgument, + `"DEADLINE_EXCEEDED"`: DeadlineExceeded, + `"NOT_FOUND"`: NotFound, + `"ALREADY_EXISTS"`: AlreadyExists, + `"PERMISSION_DENIED"`: PermissionDenied, + `"RESOURCE_EXHAUSTED"`: ResourceExhausted, + `"FAILED_PRECONDITION"`: FailedPrecondition, + `"ABORTED"`: Aborted, + `"OUT_OF_RANGE"`: OutOfRange, + `"UNIMPLEMENTED"`: Unimplemented, + `"INTERNAL"`: Internal, + `"UNAVAILABLE"`: Unavailable, + `"DATA_LOSS"`: DataLoss, + `"UNAUTHENTICATED"`: Unauthenticated, +} + +// UnmarshalJSON unmarshals b into the Code. +func (c *Code) UnmarshalJSON(b []byte) error { + // From json.Unmarshaler: By convention, to approximate the behavior of + // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as + // a no-op. + if string(b) == "null" { + return nil + } + if c == nil { + return fmt.Errorf("nil receiver passed to UnmarshalJSON") + } + + if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { + if ci >= _maxCode { + return fmt.Errorf("invalid code: %q", ci) + } + + *c = Code(ci) + return nil + } + + if jc, ok := strToCode[string(b)]; ok { + *c = jc + return nil + } + return fmt.Errorf("invalid code: %q", string(b)) +} diff --git a/codes/codes_string.go b/codes/codes_string.go new file mode 100644 index 0000000..0b206a5 --- /dev/null +++ b/codes/codes_string.go @@ -0,0 +1,62 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package codes + +import "strconv" + +func (c Code) String() string { + switch c { + case OK: + return "OK" + case Canceled: + return "Canceled" + case Unknown: + return "Unknown" + case InvalidArgument: + return "InvalidArgument" + case DeadlineExceeded: + return "DeadlineExceeded" + case NotFound: + return "NotFound" + case AlreadyExists: + return "AlreadyExists" + case PermissionDenied: + return "PermissionDenied" + case ResourceExhausted: + return "ResourceExhausted" + case FailedPrecondition: + return "FailedPrecondition" + case Aborted: + return "Aborted" + case OutOfRange: + return "OutOfRange" + case Unimplemented: + return "Unimplemented" + case Internal: + return "Internal" + case Unavailable: + return "Unavailable" + case DataLoss: + return "DataLoss" + case Unauthenticated: + return "Unauthenticated" + default: + return "Code(" + strconv.FormatInt(int64(c), 10) + ")" + } +} diff --git a/codes/codes_test.go b/codes/codes_test.go new file mode 100644 index 0000000..d3e32d2 --- /dev/null +++ b/codes/codes_test.go @@ -0,0 +1,84 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package codes + +import ( + "encoding/json" + "reflect" + "testing" + + cpb "google.golang.org/genproto/googleapis/rpc/code" +) + +func TestUnmarshalJSON(t *testing.T) { + for s, v := range cpb.Code_value { + want := Code(v) + var got Code + if err := got.UnmarshalJSON([]byte(`"` + s + `"`)); err != nil || got != want { + t.Errorf("got.UnmarshalJSON(%q) = %v; want . got=%v; want %v", s, err, got, want) + } + } +} + +func TestJSONUnmarshal(t *testing.T) { + var got []Code + want := []Code{OK, NotFound, Internal, Canceled} + in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]` + err := json.Unmarshal([]byte(in), &got) + if err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("json.Unmarshal(%q, &got) = %v; want . got=%v; want %v", in, err, got, want) + } +} + +func TestUnmarshalJSON_NilReceiver(t *testing.T) { + var got *Code + in := OK.String() + if err := got.UnmarshalJSON([]byte(in)); err == nil { + t.Errorf("got.UnmarshalJSON(%q) = nil; want . got=%v", in, got) + } +} + +func TestUnmarshalJSON_UnknownInput(t *testing.T) { + var got Code + for _, in := range [][]byte{[]byte(""), []byte("xxx"), []byte("Code(17)"), nil} { + if err := got.UnmarshalJSON([]byte(in)); err == nil { + t.Errorf("got.UnmarshalJSON(%q) = nil; want . got=%v", in, got) + } + } +} + +func TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) { + for i := 0; i < _maxCode; i++ { + var cUnMarshaled Code + c := Code(i) + + cJSON, err := json.Marshal(c) + if err != nil { + t.Errorf("marshalling %q failed: %v", c, err) + } + + if err := json.Unmarshal(cJSON, &cUnMarshaled); err != nil { + t.Errorf("unmarshalling code failed: %s", err) + } + + if c != cUnMarshaled { + t.Errorf("code is %q after marshalling/unmarshalling, expected %q", cUnMarshaled, c) + } + } +} diff --git a/context.go b/context.go new file mode 100644 index 0000000..658b72a --- /dev/null +++ b/context.go @@ -0,0 +1,130 @@ +package ranger + +import ( + "context" + "fmt" + "net" + "net/http" + "net/textproto" + "strconv" + "strings" + "time" + + "github.com/rs/zerolog/log" + "go.mondoo.com/ranger-rpc/codes" + "go.mondoo.com/ranger-rpc/metadata" + "go.mondoo.com/ranger-rpc/status" +) + +const ( + requestTimeout = "Request-Timeout" + xForwardedFor = "X-Forwarded-For" + xForwardedHost = "X-Forwarded-Host" +) + +var ( + // DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound + // header isn't present. If the value is 0 the sent `context` will not have a timeout. + DefaultContextTimeout = 0 * time.Second +) + +/* +AnnotateContext adds context information such as metadata from the request. It is designed to work similar +to the gRPC AnnotateContext function. At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For" in +the metadata. + +The implementation is derived from GRPC-Gateway AnnotateContext (BSD3-License). See: +https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/context.go#L78 +*/ +func AnnotateContext(ctx context.Context, req *http.Request) (context.Context, context.CancelFunc, error) { + var pairs []string + + cancelFunc := func() {} + + // handle timeouts + timeout := DefaultContextTimeout + if tm := req.Header.Get(requestTimeout); tm != "" { + var err error + timeout, err = timeoutDecode(tm) + if err != nil { + return nil, nil, status.Errorf(codes.InvalidArgument, "invalid rpc-timeout: %s", tm) + } + } + + // pass all headers through + for key, vals := range req.Header { + for _, val := range vals { + key = textproto.CanonicalMIMEHeaderKey(key) + + // skip forwarded key here since it needs special handling + if key == xForwardedHost { + continue + } + pairs = append(pairs, key, val) + } + } + + // handle forward key + if host := req.Header.Get(xForwardedHost); host != "" { + pairs = append(pairs, strings.ToLower(xForwardedHost), host) + } else if req.Host != "" { + pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) + } + + // handle remotr addr key + if addr := req.RemoteAddr; addr != "" { + if remoteIP, _, err := net.SplitHostPort(addr); err == nil { + if fwd := req.Header.Get(xForwardedFor); fwd == "" { + pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP) + } else { + pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP)) + } + } else { + log.Info().Str("remote_addr", addr).Msg("invalid remote addr") + } + } + + if timeout != 0 { + ctx, cancelFunc = context.WithTimeout(ctx, timeout) + } + if len(pairs) == 0 { + return ctx, cancelFunc, nil + } + md := metadata.Pairs(pairs...) + return metadata.NewIncomingContext(ctx, md), cancelFunc, nil +} + +func timeoutDecode(s string) (time.Duration, error) { + size := len(s) + if size < 2 { + return 0, fmt.Errorf("timeout string is too short: %q", s) + } + d, ok := timeoutUnitToDuration(s[size-1]) + if !ok { + return 0, fmt.Errorf("timeout unit is not recognized: %q", s) + } + t, err := strconv.ParseInt(s[:size-1], 10, 64) + if err != nil { + return 0, err + } + return d * time.Duration(t), nil +} + +func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) { + switch u { + case 'H': + return time.Hour, true + case 'M': + return time.Minute, true + case 'S': + return time.Second, true + case 'm': + return time.Millisecond, true + case 'u': + return time.Microsecond, true + case 'n': + return time.Nanosecond, true + default: + } + return +} diff --git a/error.go b/error.go new file mode 100644 index 0000000..74206b2 --- /dev/null +++ b/error.go @@ -0,0 +1,64 @@ +package ranger + +import ( + "io" + "io/ioutil" + "net/http" + + "github.com/rs/zerolog/log" + "go.mondoo.com/ranger-rpc/codes" + "go.mondoo.com/ranger-rpc/status" + spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/protobuf/proto" +) + +// httpError writes an error to the response. +func httpError(w http.ResponseWriter, req *http.Request, err error) { + // check if the accept header is set, otherwise use the incoming content type + accept := determineResponseType(req.Header.Get("Content-Type"), req.Header.Get("Accept")) + + // check that we got a status.Error package + s, ok := status.FromError(err) + if !ok { + s = status.New(codes.Unknown, err.Error()) + } + + h := w.Header() + // write status code + status := status.HTTPStatusFromCode(s.Code()) + + if status >= 500 { + log.Error(). + Err(err). + Str("url", req.URL.Path). + Int("status", status). + Msg("returned internal error") + } else { + log.Debug(). + Err(err). + Str("url", req.URL.Path). + Int("status", status). + Msg("non 5xx error") + } + + // add body and content + // NOTE: we ignore the error here since its already an error that we return + payload, contentType, _ := convertProtoToPayload(s.Proto(), accept) + h.Set("Content-Type", contentType) + w.WriteHeader(status) + w.Write(payload) +} + +// parseStatus tries to parse the proto Status from the body of the response. +func parseStatus(reader io.Reader) (*spb.Status, error) { + payload, err := ioutil.ReadAll(reader) + if err != nil { + return nil, err + } + var status spb.Status + err = proto.Unmarshal(payload, &status) + if err != nil { + return nil, err + } + return &status, nil +} diff --git a/examples/pingpong/client/main.go b/examples/pingpong/client/main.go new file mode 100644 index 0000000..c0c7a4c --- /dev/null +++ b/examples/pingpong/client/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "context" + "fmt" + "net/http" + "time" + + "go.mondoo.com/ranger-rpc/examples/pingpong" +) + +func main() { + fmt.Println("start pingpong example client") + client, err := pingpong.NewPingPongClient("http://localhost:2155/api/", &http.Client{ + Timeout: time.Second * 10, + }) + if err != nil { + panic(err) + } + + fmt.Println("call server ping") + resp, err := client.Ping(context.Background(), &pingpong.PingRequest{Sender: "bob"}) + if err == nil { + fmt.Println("server ping response:", resp.Message) + } else { + panic(err) + } +} diff --git a/examples/pingpong/handler.go b/examples/pingpong/handler.go new file mode 100644 index 0000000..16e07a1 --- /dev/null +++ b/examples/pingpong/handler.go @@ -0,0 +1,16 @@ +package pingpong + +import ( + "context" +) + +// implement the service handler for PingPong service +type PingPongServiceImpl struct{} + +func (s *PingPongServiceImpl) Ping(ctx context.Context, in *PingRequest) (*PongReply, error) { + return &PongReply{Message: "Hello " + in.GetSender()}, nil +} + +func (s *PingPongServiceImpl) NoPing(ctx context.Context, in *Empty) (*PongReply, error) { + return &PongReply{Message: "HelloPong"}, nil +} diff --git a/examples/pingpong/pingpong.go b/examples/pingpong/pingpong.go new file mode 100644 index 0000000..dbf3196 --- /dev/null +++ b/examples/pingpong/pingpong.go @@ -0,0 +1,4 @@ +package pingpong + +// To regenerate the protocol buffer output for this package, run `go generate` +//go:generate protoc --go_out=. --go_opt=paths=source_relative --rangerrpc_out=. pingpong.proto diff --git a/examples/pingpong/pingpong.pb.go b/examples/pingpong/pingpong.pb.go new file mode 100644 index 0000000..f850801 --- /dev/null +++ b/examples/pingpong/pingpong.pb.go @@ -0,0 +1,269 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.19.1 +// source: pingpong.proto + +package pingpong + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Empty struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *Empty) Reset() { + *x = Empty{} + if protoimpl.UnsafeEnabled { + mi := &file_pingpong_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Empty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Empty) ProtoMessage() {} + +func (x *Empty) ProtoReflect() protoreflect.Message { + mi := &file_pingpong_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Empty.ProtoReflect.Descriptor instead. +func (*Empty) Descriptor() ([]byte, []int) { + return file_pingpong_proto_rawDescGZIP(), []int{0} +} + +type PingRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` +} + +func (x *PingRequest) Reset() { + *x = PingRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_pingpong_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *PingRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PingRequest) ProtoMessage() {} + +func (x *PingRequest) ProtoReflect() protoreflect.Message { + mi := &file_pingpong_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PingRequest.ProtoReflect.Descriptor instead. +func (*PingRequest) Descriptor() ([]byte, []int) { + return file_pingpong_proto_rawDescGZIP(), []int{1} +} + +func (x *PingRequest) GetSender() string { + if x != nil { + return x.Sender + } + return "" +} + +type PongReply struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *PongReply) Reset() { + *x = PongReply{} + if protoimpl.UnsafeEnabled { + mi := &file_pingpong_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *PongReply) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PongReply) ProtoMessage() {} + +func (x *PongReply) ProtoReflect() protoreflect.Message { + mi := &file_pingpong_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PongReply.ProtoReflect.Descriptor instead. +func (*PongReply) Descriptor() ([]byte, []int) { + return file_pingpong_proto_rawDescGZIP(), []int{2} +} + +func (x *PongReply) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +var File_pingpong_proto protoreflect.FileDescriptor + +var file_pingpong_proto_rawDesc = []byte{ + 0x0a, 0x0e, 0x70, 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x08, 0x70, 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x22, 0x07, 0x0a, 0x05, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x22, 0x25, 0x0a, 0x0b, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x06, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x22, 0x25, 0x0a, 0x09, 0x50, 0x6f, + 0x6e, 0x67, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x32, 0x6e, 0x0a, 0x08, 0x50, 0x69, 0x6e, 0x67, 0x50, 0x6f, 0x6e, 0x67, 0x12, 0x32, 0x0a, + 0x04, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x15, 0x2e, 0x70, 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, + 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x70, + 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x2e, 0x50, 0x6f, 0x6e, 0x67, 0x52, 0x65, 0x70, 0x6c, + 0x79, 0x12, 0x2e, 0x0a, 0x06, 0x4e, 0x6f, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x0f, 0x2e, 0x70, 0x69, + 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x13, 0x2e, 0x70, + 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x2e, 0x50, 0x6f, 0x6e, 0x67, 0x52, 0x65, 0x70, 0x6c, + 0x79, 0x42, 0x2b, 0x5a, 0x29, 0x67, 0x6f, 0x2e, 0x6d, 0x6f, 0x6e, 0x64, 0x6f, 0x6f, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x72, 0x2d, 0x72, 0x70, 0x63, 0x2f, 0x65, 0x78, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x70, 0x69, 0x6e, 0x67, 0x70, 0x6f, 0x6e, 0x67, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_pingpong_proto_rawDescOnce sync.Once + file_pingpong_proto_rawDescData = file_pingpong_proto_rawDesc +) + +func file_pingpong_proto_rawDescGZIP() []byte { + file_pingpong_proto_rawDescOnce.Do(func() { + file_pingpong_proto_rawDescData = protoimpl.X.CompressGZIP(file_pingpong_proto_rawDescData) + }) + return file_pingpong_proto_rawDescData +} + +var file_pingpong_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_pingpong_proto_goTypes = []interface{}{ + (*Empty)(nil), // 0: pingpong.Empty + (*PingRequest)(nil), // 1: pingpong.PingRequest + (*PongReply)(nil), // 2: pingpong.PongReply +} +var file_pingpong_proto_depIdxs = []int32{ + 1, // 0: pingpong.PingPong.Ping:input_type -> pingpong.PingRequest + 0, // 1: pingpong.PingPong.NoPing:input_type -> pingpong.Empty + 2, // 2: pingpong.PingPong.Ping:output_type -> pingpong.PongReply + 2, // 3: pingpong.PingPong.NoPing:output_type -> pingpong.PongReply + 2, // [2:4] is the sub-list for method output_type + 0, // [0:2] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_pingpong_proto_init() } +func file_pingpong_proto_init() { + if File_pingpong_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_pingpong_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Empty); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_pingpong_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PingRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_pingpong_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PongReply); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_pingpong_proto_rawDesc, + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_pingpong_proto_goTypes, + DependencyIndexes: file_pingpong_proto_depIdxs, + MessageInfos: file_pingpong_proto_msgTypes, + }.Build() + File_pingpong_proto = out.File + file_pingpong_proto_rawDesc = nil + file_pingpong_proto_goTypes = nil + file_pingpong_proto_depIdxs = nil +} diff --git a/examples/pingpong/pingpong.proto b/examples/pingpong/pingpong.proto new file mode 100644 index 0000000..c6b16ae --- /dev/null +++ b/examples/pingpong/pingpong.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +package pingpong; +option go_package = "go.mondoo.com/ranger-rpc/example/pingpong"; + +message Empty {} + +message PingRequest { + string sender = 1; +} + +message PongReply { + string message = 1; +} + +service PingPong { + rpc Ping (PingRequest) returns (PongReply); + rpc NoPing(Empty) returns (PongReply); +} diff --git a/examples/pingpong/pingpong.ranger.go b/examples/pingpong/pingpong.ranger.go new file mode 100644 index 0000000..cde2674 --- /dev/null +++ b/examples/pingpong/pingpong.ranger.go @@ -0,0 +1,142 @@ +// Code generated by protoc-gen-rangerrpc version DO NOT EDIT. +// source: pingpong.proto + +package pingpong + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + + ranger "go.mondoo.com/ranger-rpc" + "go.mondoo.com/ranger-rpc/metadata" + jsonpb "google.golang.org/protobuf/encoding/protojson" + pb "google.golang.org/protobuf/proto" +) + +// service interface definition + +type PingPong interface { + Ping(context.Context, *PingRequest) (*PongReply, error) + NoPing(context.Context, *Empty) (*PongReply, error) +} + +// client implementation + +type PingPongClient struct { + ranger.Client + httpclient ranger.HTTPClient + prefix string +} + +func NewPingPongClient(addr string, client ranger.HTTPClient) (*PingPongClient, error) { + base, err := url.Parse(ranger.SanitizeUrl(addr)) + if err != nil { + return nil, err + } + + u, err := url.Parse("./PingPong") + if err != nil { + return nil, err + } + + return &PingPongClient{ + httpclient: client, + prefix: base.ResolveReference(u).String(), + }, nil +} +func (c *PingPongClient) Ping(ctx context.Context, in *PingRequest) (*PongReply, error) { + out := new(PongReply) + err := c.DoClientRequest(ctx, c.httpclient, strings.Join([]string{c.prefix, "/Ping"}, ""), in, out) + return out, err +} +func (c *PingPongClient) NoPing(ctx context.Context, in *Empty) (*PongReply, error) { + out := new(PongReply) + err := c.DoClientRequest(ctx, c.httpclient, strings.Join([]string{c.prefix, "/NoPing"}, ""), in, out) + return out, err +} + +// server implementation + +type PingPongServerOption func(s *PingPongServer) + +func WithUnknownFieldsForPingPongServer() PingPongServerOption { + return func(s *PingPongServer) { + s.allowUnknownFields = true + } +} + +func NewPingPongServer(handler PingPong, opts ...PingPongServerOption) http.Handler { + srv := &PingPongServer{ + handler: handler, + } + + for i := range opts { + opts[i](srv) + } + + service := ranger.Service{ + Name: "PingPong", + Methods: map[string]ranger.Method{ + "Ping": srv.Ping, + "NoPing": srv.NoPing, + }, + } + return ranger.NewRPCServer(&service) +} + +type PingPongServer struct { + handler PingPong + allowUnknownFields bool +} + +func (p *PingPongServer) Ping(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + var req PingRequest + var err error + + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return nil, errors.New("could not access header") + } + + switch md.First("Content-Type") { + case "application/protobuf", "application/octet-stream", "application/grpc+proto": + err = pb.Unmarshal(*reqBytes, &req) + default: + // handle case of empty object + if len(*reqBytes) > 0 { + err = jsonpb.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(*reqBytes, &req) + } + } + + if err != nil { + return nil, err + } + return p.handler.Ping(ctx, &req) +} +func (p *PingPongServer) NoPing(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + var req Empty + var err error + + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return nil, errors.New("could not access header") + } + + switch md.First("Content-Type") { + case "application/protobuf", "application/octet-stream", "application/grpc+proto": + err = pb.Unmarshal(*reqBytes, &req) + default: + // handle case of empty object + if len(*reqBytes) > 0 { + err = jsonpb.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(*reqBytes, &req) + } + } + + if err != nil { + return nil, err + } + return p.handler.NoPing(ctx, &req) +} diff --git a/examples/pingpong/pingpong_test.go b/examples/pingpong/pingpong_test.go new file mode 100644 index 0000000..ba07c3e --- /dev/null +++ b/examples/pingpong/pingpong_test.go @@ -0,0 +1,35 @@ +package pingpong + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPingPong(t *testing.T) { + // create http test server and attack the pingpong service under /api/ prefix + mux := http.NewServeMux() + mux.Handle("/api/", http.StripPrefix("/api", NewPingPongServer(&PingPongServiceImpl{}))) + server := httptest.NewServer(mux) + defer server.Close() + + // create a client to call the pingpong service + client, err := NewPingPongClient(server.URL+"/api/", &http.Client{}) + assert.Nil(t, err) + + t.Run("Ping", func(t *testing.T) { + resp, err := client.Ping(context.Background(), &PingRequest{Sender: "Example"}) + require.NoError(t, err) + assert.Equal(t, "Hello Example", resp.Message) + }) + + t.Run("NoPing", func(t *testing.T) { + resp, err := client.NoPing(context.Background(), &Empty{}) + require.NoError(t, err) + assert.Equal(t, "HelloPong", resp.Message) + }) +} diff --git a/examples/pingpong/server/main.go b/examples/pingpong/server/main.go new file mode 100644 index 0000000..0ba0fa4 --- /dev/null +++ b/examples/pingpong/server/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "net/http" + + "go.mondoo.com/ranger-rpc/examples/pingpong" +) + +func main() { + fmt.Println("start pingpong example server") + + // init service implementation and attach it to the standard mux router for the /api/ prefix + mux := http.NewServeMux() + p := &pingpong.PingPongServiceImpl{} + mux.Handle("/api/", http.StripPrefix("/api", pingpong.NewPingPongServer(p))) + + // start the server on port 2155 + port := 2155 + fmt.Printf("listen on :%d\n", port) + err := http.ListenAndServe(fmt.Sprintf(":%d", port), mux) + if err != nil { + fmt.Println("was not able to start the server") + panic(err) + } +} diff --git a/go.mod b/go.mod index 0f65a26..6714599 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,33 @@ module go.mondoo.com/ranger-rpc go 1.18 + +require ( + github.com/cockroachdb/errors v1.9.0 + github.com/golang/protobuf v1.5.2 + github.com/google/go-cmp v0.5.5 + github.com/lyft/protoc-gen-star v0.6.0 + github.com/rs/zerolog v1.27.0 + github.com/stretchr/testify v1.8.0 + google.golang.org/genproto v0.0.0-20220715211116-798f69b842b9 + google.golang.org/protobuf v1.28.0 +) + +require ( + github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirect + github.com/cockroachdb/redact v1.1.3 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/getsentry/sentry-go v0.12.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/kr/pretty v0.3.0 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rogpeppe/go-internal v1.8.1 // indirect + github.com/spf13/afero v1.3.3 // indirect + golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect + golang.org/x/text v0.3.7 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..89f07ff --- /dev/null +++ b/go.sum @@ -0,0 +1,407 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/AndreasBriese/bbloom v0.0.0-20190306092124-e2d15f34fcf9/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a/go.mod h1:EFZQ978U7x8IRnstaskI3IysnWY5Ao3QgZUKOXlsAdw= +github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno= +github.com/CloudyKit/jet v2.1.3-0.20180809161101-62edd43e4f88+incompatible/go.mod h1:HPYO+50pSWkPoj9Q/eq0aRGByCL6ScRlUmiEX5Zgm+w= +github.com/CloudyKit/jet/v3 v3.0.0/go.mod h1:HKQPgSJmdK8hdoAbKUUWajkHyHo4RaU5rMdUywE7VMo= +github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= +github.com/Joker/jade v1.0.1-0.20190614124447-d475f43051e7/go.mod h1:6E6s8o2AE4KhCrqr6GRJjdC/gNfTdxkIXvuGZZda2VM= +github.com/Shopify/goreferrer v0.0.0-20181106222321-ec9c9a553398/go.mod h1:a1uqRtAwp2Xwc6WNPJEufxJ7fx3npB4UV/JOLmbu5I0= +github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cockroachdb/datadriven v1.0.1-0.20211007161720-b558070c3be0/go.mod h1:5Ib8Meh+jk1RlHIXej6Pzevx/NLlNvQB9pmSBZErGA4= +github.com/cockroachdb/datadriven v1.0.1-0.20220214170620-9913f5bc19b7/go.mod h1:hi0MtSY3AYDQNDi83kDkMH5/yqM/CsIrsOITkSoH7KI= +github.com/cockroachdb/errors v1.6.1/go.mod h1:tm6FTP5G81vwJ5lC0SizQo374JNCOPrHyXGitRJoDqM= +github.com/cockroachdb/errors v1.8.8/go.mod h1:z6VnEL3hZ/2ONZEvG7S5Ym0bU2AqPcEKnIiA1wbsSu0= +github.com/cockroachdb/errors v1.9.0 h1:B48dYem5SlAY7iU8AKsgedb4gH6mo+bDkbtLIvM/a88= +github.com/cockroachdb/errors v1.9.0/go.mod h1:vaNcEYYqbIqB5JhKBhFV9CneUqeuEbB2OYJBK4GBNYQ= +github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= +github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f h1:6jduT9Hfc0njg5jJ1DdKCFPdMBrp/mdZfCpa5h+WM74= +github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/redact v1.1.3 h1:AKZds10rFSIj7qADf0g46UixK8NNLwWTNdCIGS5wfSQ= +github.com/cockroachdb/redact v1.1.3/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/sentry-go v0.6.1-cockroachdb.2/go.mod h1:8BT+cPK6xvFOcRlk0R8eg+OTkcqI6baNH4xAkpiYVvQ= +github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0/go.mod h1:4Zcjuz89kmFXt9morQgcfYZAYZ5n8WHjt81YYWIwtTM= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= +github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= +github.com/getsentry/sentry-go v0.12.0 h1:era7g0re5iY13bHSdN/xMkyV+5zZppjRVQhZrXCaEIk= +github.com/getsentry/sentry-go v0.12.0/go.mod h1:NSap0JBYWzHND8oMbyi0+XZhUalc1TBdRL1M71JZW2c= +github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s= +github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM= +github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98= +github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-martini/martini v0.0.0-20170121215854-22fa46961aab/go.mod h1:/P9AEU963A2AYjv4d1V5eVL1CQbEJq6aCNHDDjibzu8= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/hydrogen18/memlistener v0.0.0-20141126152155-54553eb933fb/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/hydrogen18/memlistener v0.0.0-20200120041712-dcc25e7acd91/go.mod h1:qEIFzExnS6016fRpRfxrExeVn2gbClQA99gQhnIcdhE= +github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/iris-contrib/blackfriday v2.0.0+incompatible/go.mod h1:UzZ2bDEoaSGPbkg6SAB4att1aAwTmVIx/5gCVqeyUdI= +github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= +github.com/iris-contrib/i18n v0.0.0-20171121225848-987a633949d0/go.mod h1:pMCz62A0xJL6I+umB2YTlFRwWXaDFA0jy+5HzGiJjqI= +github.com/iris-contrib/jade v1.1.3/go.mod h1:H/geBymxJhShH5kecoiOCSssPX7QWYH7UaeZTSWddIk= +github.com/iris-contrib/pongo2 v0.0.1/go.mod h1:Ssh+00+3GAZqSQb30AvBRNxBx7rf0GqwkjqxNd0u65g= +github.com/iris-contrib/schema v0.0.1/go.mod h1:urYA3uvUNG1TIIjOSCzHr9/LmbQo8LrOcOqfqxa4hXw= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/loggo v0.0.0-20180524022052-584905176618/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= +github.com/juju/testing v0.0.0-20180920084828-472a3e8b2073/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= +github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= +github.com/kataras/golog v0.0.9/go.mod h1:12HJgwBIZFNGL0EJnMRhmvGA0PQGx8VFwrZtM4CqbAk= +github.com/kataras/golog v0.0.10/go.mod h1:yJ8YKCmyL+nWjERB90Qwn+bdyBZsaQwU3bTVFgkFIp8= +github.com/kataras/iris/v12 v12.0.1/go.mod h1:udK4vLQKkdDqMGJJVd/msuMtN6hpYJhg/lSzuxjhO+U= +github.com/kataras/iris/v12 v12.1.8/go.mod h1:LMYy4VlP67TQ3Zgriz8RE2h2kMZV2SgMYbq3UhfoFmE= +github.com/kataras/neffos v0.0.10/go.mod h1:ZYmJC07hQPW67eKuzlfY7SO3bC0mw83A3j6im82hfqw= +github.com/kataras/neffos v0.0.14/go.mod h1:8lqADm8PnbeFfL7CLXh1WHw53dG27MC3pgi2R1rmoTE= +github.com/kataras/pio v0.0.0-20190103105442-ea782b38602d/go.mod h1:NV88laa9UiiDuX9AhMbDPkGYSPugBOV6yTZB1l2K9Z0= +github.com/kataras/pio v0.0.2/go.mod h1:hAoW0t9UmXi4R5Oyq5Z4irTbaTsOemSrDGUtaTl7Dro= +github.com/kataras/sitemap v0.0.5/go.mod h1:KY2eugMKiPwsJgx7+U103YZehfvNGOXURubcGyk0Bz8= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.9.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/labstack/echo/v4 v4.1.11/go.mod h1:i541M3Fj6f76NZtHSj7TXnyM8n2gaodfvfxNnFqi74g= +github.com/labstack/echo/v4 v4.5.0/go.mod h1:czIriw4a0C1dFun+ObrXp7ok03xON0N1awStJ6ArI7Y= +github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= +github.com/lyft/protoc-gen-star v0.6.0 h1:xOpFu4vwmIoUeUrRuAtdCrZZymT/6AkW/bsUWA506Fo= +github.com/lyft/protoc-gen-star v0.6.0/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= +github.com/mediocregopher/mediocre-go-lib v0.0.0-20181029021733-cb65787f37ed/go.mod h1:dSsfyI2zABAdhcbvkXqgxOxrCsbYeHCPgrZkku60dSg= +github.com/mediocregopher/radix/v3 v3.3.0/go.mod h1:EmfVyvspXz1uZEyPBMyGK+kjWiKQGvsUt6O3Pj+LDCQ= +github.com/mediocregopher/radix/v3 v3.4.2/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= +github.com/microcosm-cc/bluemonday v1.0.2/go.mod h1:iVP4YcDBq+n/5fb23BhYFvIMq/leAFZyRl6bYmGDlGc= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/moul/http2curl v1.0.0/go.mod h1:8UbvGypXm98wA/IqH45anm5Y2Z6ep6O31QGOAZ3H0fQ= +github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= +github.com/nats-io/nats.go v1.8.1/go.mod h1:BrFz9vVn0fU3AcH9Vn4Kd7W0NpJ651tD5omQ3M8LwxM= +github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= +github.com/nats-io/nkeys v0.0.2/go.mod h1:dab7URMsZm6Z/jp9Z5UGa87Uutgc2mVpXLC4B7TDb/4= +github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= +github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= +github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.27.0 h1:1T7qCieN22GVc8S4Q2yuexzBb1EqjbgjSH9RohbMjKs= +github.com/rs/zerolog v1.27.0/go.mod h1:7frBqO0oezxmnO7GF86FY++uy8I0Tk/If5ni1G9Qc0U= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= +github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/afero v1.3.3 h1:p5gZEKLYoL7wh8VrJesMaYeNxdEd1v3cb4irOk9zB54= +github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.6.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w= +github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= +github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= +github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181221001348-537d06c36207/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190327201419-c70d86f8b7cf/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20220715211116-798f69b842b9 h1:1aEQRgZ4Gks2SRAkLzIPpIszRazwVfjSFe1cKc+e0Jg= +google.golang.org/genproto v0.0.0-20220715211116-798f69b842b9/go.mod h1:GkXuJDJ6aQ7lnJcRF+SJVgFdQhypqgl3LB1C9vabdRE= +google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= +gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y= +gopkg.in/ini.v1 v1.51.1/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/metadata/metadata.go b/metadata/metadata.go new file mode 100644 index 0000000..1604ad0 --- /dev/null +++ b/metadata/metadata.go @@ -0,0 +1,220 @@ +/* + * + * Copyright 2014 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package metadata define the structure of the metadata supported by gRPC library. +// Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md +// for more information about custom-metadata. +package metadata + +import ( + "context" + "fmt" + "strings" +) + +// DecodeKeyValue returns k, v, nil. +// +// Deprecated: use k and v directly instead. +func DecodeKeyValue(k, v string) (string, string, error) { + return k, v, nil +} + +// MD is a mapping from metadata keys to values. Users should use the following +// two convenience functions New and Pairs to generate MD. +type MD map[string][]string + +// New creates an MD from a given key-value map. +// +// Only the following ASCII characters are allowed in keys: +// - digits: 0-9 +// - uppercase letters: A-Z (normalized to lower) +// - lowercase letters: a-z +// - special characters: -_. +// Uppercase letters are automatically converted to lowercase. +// +// Keys beginning with "grpc-" are reserved for grpc-internal use only and may +// result in errors if set in metadata. +func New(m map[string]string) MD { + md := MD{} + for k, val := range m { + key := strings.ToLower(k) + md[key] = append(md[key], val) + } + return md +} + +// Pairs returns an MD formed by the mapping of key, value ... +// Pairs panics if len(kv) is odd. +// +// Only the following ASCII characters are allowed in keys: +// - digits: 0-9 +// - uppercase letters: A-Z (normalized to lower) +// - lowercase letters: a-z +// - special characters: -_. +// Uppercase letters are automatically converted to lowercase. +// +// Keys beginning with "grpc-" are reserved for grpc-internal use only and may +// result in errors if set in metadata. +func Pairs(kv ...string) MD { + if len(kv)%2 == 1 { + panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv))) + } + md := MD{} + var key string + for i, s := range kv { + if i%2 == 0 { + key = strings.ToLower(s) + continue + } + md[key] = append(md[key], s) + } + return md +} + +// Len returns the number of items in md. +func (md MD) Len() int { + return len(md) +} + +// Copy returns a copy of md. +func (md MD) Copy() MD { + return Join(md) +} + +// Get obtains the values for a given key. +func (md MD) Get(k string) []string { + k = strings.ToLower(k) + return md[k] +} + +// First works analogously to http.Header.Get. It returns first value if there are many set. +// If no value is set, an an empty string is returned. +func (m MD) First(k string) string { + k = strings.ToLower(k) + vv, ok := m[k] + if !ok { + return "" + } + return vv[0] +} + +// Set sets the value of a given key with a slice of values. +func (md MD) Set(k string, vals ...string) { + if len(vals) == 0 { + return + } + k = strings.ToLower(k) + md[k] = vals +} + +// Append adds the values to key k, not overwriting what was already stored at that key. +func (md MD) Append(k string, vals ...string) { + if len(vals) == 0 { + return + } + k = strings.ToLower(k) + md[k] = append(md[k], vals...) +} + +// Join joins any number of mds into a single MD. +// The order of values for each key is determined by the order in which +// the mds containing those values are presented to Join. +func Join(mds ...MD) MD { + out := MD{} + for _, md := range mds { + for k, v := range md { + out[k] = append(out[k], v...) + } + } + return out +} + +type mdIncomingKey struct{} +type mdOutgoingKey struct{} + +// NewIncomingContext creates a new context with incoming md attached. +func NewIncomingContext(ctx context.Context, md MD) context.Context { + return context.WithValue(ctx, mdIncomingKey{}, md) +} + +// NewOutgoingContext creates a new context with outgoing md attached. If used +// in conjunction with AppendToOutgoingContext, NewOutgoingContext will +// overwrite any previously-appended metadata. +func NewOutgoingContext(ctx context.Context, md MD) context.Context { + return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) +} + +// AppendToOutgoingContext returns a new context with the provided kv merged +// with any existing metadata in the context. Please refer to the +// documentation of Pairs for a description of kv. +func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context { + if len(kv)%2 == 1 { + panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv))) + } + md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) + added := make([][]string, len(md.added)+1) + copy(added, md.added) + added[len(added)-1] = make([]string, len(kv)) + copy(added[len(added)-1], kv) + return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) +} + +// FromIncomingContext returns the incoming metadata in ctx if it exists. The +// returned MD should not be modified. Writing to it may cause races. +// Modification should be made to copies of the returned MD. +func FromIncomingContext(ctx context.Context) (md MD, ok bool) { + md, ok = ctx.Value(mdIncomingKey{}).(MD) + return +} + +// FromOutgoingContextRaw returns the un-merged, intermediary contents +// of rawMD. Remember to perform strings.ToLower on the keys. The returned +// MD should not be modified. Writing to it may cause races. Modification +// should be made to copies of the returned MD. +// +// This is intended for gRPC-internal use ONLY. +func FromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) { + raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) + if !ok { + return nil, nil, false + } + + return raw.md, raw.added, true +} + +// FromOutgoingContext returns the outgoing metadata in ctx if it exists. The +// returned MD should not be modified. Writing to it may cause races. +// Modification should be made to copies of the returned MD. +func FromOutgoingContext(ctx context.Context) (MD, bool) { + raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) + if !ok { + return nil, false + } + + mds := make([]MD, 0, len(raw.added)+1) + mds = append(mds, raw.md) + for _, vv := range raw.added { + mds = append(mds, Pairs(vv...)) + } + return Join(mds...), ok +} + +type rawMD struct { + md MD + added [][]string +} diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go new file mode 100644 index 0000000..f166ffa --- /dev/null +++ b/metadata/metadata_test.go @@ -0,0 +1,250 @@ +/* + * + * Copyright 2014 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package metadata + +import ( + "context" + "reflect" + "strconv" + "testing" +) + +func TestPairsMD(t *testing.T) { + for _, test := range []struct { + // input + kv []string + // output + md MD + }{ + {[]string{}, MD{}}, + {[]string{"k1", "v1", "k1", "v2"}, MD{"k1": []string{"v1", "v2"}}}, + } { + md := Pairs(test.kv...) + if !reflect.DeepEqual(md, test.md) { + t.Fatalf("Pairs(%v) = %v, want %v", test.kv, md, test.md) + } + } +} + +func TestCopy(t *testing.T) { + const key, val = "key", "val" + orig := Pairs(key, val) + cpy := orig.Copy() + if !reflect.DeepEqual(orig, cpy) { + t.Errorf("copied value not equal to the original, got %v, want %v", cpy, orig) + } + orig[key][0] = "foo" + if v := cpy[key][0]; v != val { + t.Errorf("change in original should not affect copy, got %q, want %q", v, val) + } +} + +func TestJoin(t *testing.T) { + for _, test := range []struct { + mds []MD + want MD + }{ + {[]MD{}, MD{}}, + {[]MD{Pairs("foo", "bar")}, Pairs("foo", "bar")}, + {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz")}, Pairs("foo", "bar", "foo", "baz")}, + {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz"), Pairs("zip", "zap")}, Pairs("foo", "bar", "foo", "baz", "zip", "zap")}, + } { + md := Join(test.mds...) + if !reflect.DeepEqual(md, test.want) { + t.Errorf("context's metadata is %v, want %v", md, test.want) + } + } +} + +func TestGet(t *testing.T) { + for _, test := range []struct { + md MD + key string + wantVals []string + }{ + {md: Pairs("My-Optional-Header", "42"), key: "My-Optional-Header", wantVals: []string{"42"}}, + {md: Pairs("Header", "42", "Header", "43", "Header", "44", "other", "1"), key: "HEADER", wantVals: []string{"42", "43", "44"}}, + {md: Pairs("HEADER", "10"), key: "HEADER", wantVals: []string{"10"}}, + } { + vals := test.md.Get(test.key) + if !reflect.DeepEqual(vals, test.wantVals) { + t.Errorf("value of metadata %v is %v, want %v", test.key, vals, test.wantVals) + } + } +} + +func TestSet(t *testing.T) { + for _, test := range []struct { + md MD + setKey string + setVals []string + want MD + }{ + { + md: Pairs("My-Optional-Header", "42", "other-key", "999"), + setKey: "Other-Key", + setVals: []string{"1"}, + want: Pairs("my-optional-header", "42", "other-key", "1"), + }, + { + md: Pairs("My-Optional-Header", "42"), + setKey: "Other-Key", + setVals: []string{"1", "2", "3"}, + want: Pairs("my-optional-header", "42", "other-key", "1", "other-key", "2", "other-key", "3"), + }, + { + md: Pairs("My-Optional-Header", "42"), + setKey: "Other-Key", + setVals: []string{}, + want: Pairs("my-optional-header", "42"), + }, + } { + test.md.Set(test.setKey, test.setVals...) + if !reflect.DeepEqual(test.md, test.want) { + t.Errorf("value of metadata is %v, want %v", test.md, test.want) + } + } +} + +func TestAppend(t *testing.T) { + for _, test := range []struct { + md MD + appendKey string + appendVals []string + want MD + }{ + { + md: Pairs("My-Optional-Header", "42"), + appendKey: "Other-Key", + appendVals: []string{"1"}, + want: Pairs("my-optional-header", "42", "other-key", "1"), + }, + { + md: Pairs("My-Optional-Header", "42"), + appendKey: "my-OptIoNal-HeAder", + appendVals: []string{"1", "2", "3"}, + want: Pairs("my-optional-header", "42", "my-optional-header", "1", + "my-optional-header", "2", "my-optional-header", "3"), + }, + { + md: Pairs("My-Optional-Header", "42"), + appendKey: "my-OptIoNal-HeAder", + appendVals: []string{}, + want: Pairs("my-optional-header", "42"), + }, + } { + test.md.Append(test.appendKey, test.appendVals...) + if !reflect.DeepEqual(test.md, test.want) { + t.Errorf("value of metadata is %v, want %v", test.md, test.want) + } + } +} + +func TestAppendToOutgoingContext(t *testing.T) { + // Pre-existing metadata + ctx := NewOutgoingContext(context.Background(), Pairs("k1", "v1", "k2", "v2")) + ctx = AppendToOutgoingContext(ctx, "k1", "v3") + ctx = AppendToOutgoingContext(ctx, "k1", "v4") + md, ok := FromOutgoingContext(ctx) + if !ok { + t.Errorf("Expected MD to exist in ctx, but got none") + } + want := Pairs("k1", "v1", "k1", "v3", "k1", "v4", "k2", "v2") + if !reflect.DeepEqual(md, want) { + t.Errorf("context's metadata is %v, want %v", md, want) + } + + // No existing metadata + ctx = AppendToOutgoingContext(context.Background(), "k1", "v1") + md, ok = FromOutgoingContext(ctx) + if !ok { + t.Errorf("Expected MD to exist in ctx, but got none") + } + want = Pairs("k1", "v1") + if !reflect.DeepEqual(md, want) { + t.Errorf("context's metadata is %v, want %v", md, want) + } +} + +func TestAppendToOutgoingContext_Repeated(t *testing.T) { + ctx := context.Background() + + for i := 0; i < 100; i = i + 2 { + ctx1 := AppendToOutgoingContext(ctx, "k", strconv.Itoa(i)) + ctx2 := AppendToOutgoingContext(ctx, "k", strconv.Itoa(i+1)) + + md1, _ := FromOutgoingContext(ctx1) + md2, _ := FromOutgoingContext(ctx2) + + if reflect.DeepEqual(md1, md2) { + t.Fatalf("md1, md2 = %v, %v; should not be equal", md1, md2) + } + + ctx = ctx1 + } +} + +func TestAppendToOutgoingContext_FromKVSlice(t *testing.T) { + const k, v = "a", "b" + kv := []string{k, v} + ctx := AppendToOutgoingContext(context.Background(), kv...) + md, _ := FromOutgoingContext(ctx) + if md[k][0] != v { + t.Fatalf("md[%q] = %q; want %q", k, md[k], v) + } + kv[1] = "xxx" + md, _ = FromOutgoingContext(ctx) + if md[k][0] != v { + t.Fatalf("md[%q] = %q; want %q", k, md[k], v) + } +} + +// Old/slow approach to adding metadata to context +func Benchmark_AddingMetadata_ContextManipulationApproach(b *testing.B) { + // TODO: Add in N=1-100 tests once Go1.6 support is removed. + const num = 10 + for n := 0; n < b.N; n++ { + ctx := context.Background() + for i := 0; i < num; i++ { + md, _ := FromOutgoingContext(ctx) + NewOutgoingContext(ctx, Join(Pairs("k1", "v1", "k2", "v2"), md)) + } + } +} + +// Newer/faster approach to adding metadata to context +func BenchmarkAppendToOutgoingContext(b *testing.B) { + const num = 10 + for n := 0; n < b.N; n++ { + ctx := context.Background() + for i := 0; i < num; i++ { + ctx = AppendToOutgoingContext(ctx, "k1", "v1", "k2", "v2") + } + } +} + +func BenchmarkFromOutgoingContext(b *testing.B) { + ctx := context.Background() + ctx = NewOutgoingContext(ctx, MD{"k3": {"v3", "v4"}}) + ctx = AppendToOutgoingContext(ctx, "k1", "v1", "k2", "v2") + + for n := 0; n < b.N; n++ { + FromOutgoingContext(ctx) + } +} diff --git a/protoc-gen-rangerrpc/generator/ranger.go b/protoc-gen-rangerrpc/generator/ranger.go new file mode 100644 index 0000000..479d51d --- /dev/null +++ b/protoc-gen-rangerrpc/generator/ranger.go @@ -0,0 +1,178 @@ +package generator + +import ( + "bufio" + "bytes" + "html/template" + + _ "embed" + + pgs "github.com/lyft/protoc-gen-star" + pgsgo "github.com/lyft/protoc-gen-star/lang/go" +) + +var ( + //go:embed templates/gofile.template + embeddedTemplateGofile string + + //go:embed templates/service.template + embeddedTemplateService string + + TMP_GOFILE_FILE *template.Template + TMP_SERVICE_DEFINITION *template.Template +) + +func noescape(str string) template.HTML { + return template.HTML(str) +} + +func init() { + var fn = template.FuncMap{ + "noescape": noescape, + "gotype": goMessageType, + } + + // load file content + TMP_GOFILE_FILE = template.New("file") + TMP_GOFILE_FILE.Funcs(fn) + tmpl, err := TMP_GOFILE_FILE.Parse(embeddedTemplateGofile) + if err != nil { + panic(err) + } + TMP_GOFILE_FILE = tmpl + + // load service content + TMP_SERVICE_DEFINITION = template.New("service") + TMP_SERVICE_DEFINITION.Funcs(fn) + tmpl, err = TMP_SERVICE_DEFINITION.Parse(embeddedTemplateService) + if err != nil { + panic(err) + } + TMP_SERVICE_DEFINITION = tmpl +} + +func New() *rangerc { + return &rangerc{&pgs.ModuleBase{}} +} + +type rangerc struct { + *pgs.ModuleBase +} + +func (f *rangerc) Name() string { + return "ranger" +} + +func (fc *rangerc) Execute(targets map[string]pgs.File, pkgs map[string]pgs.Package) []pgs.Artifact { + for _, f := range targets { + ctx := fc.Push(f.Name().String()) + goctx := pgsgo.InitContext(ctx.Parameters()) + + pkgname := goctx.PackageName(f).String() + fc.Debugf("processing file %s with pkg %s", f.Name(), pkgname) + + // do not create a file if no service is part of the definition + if len(f.Services()) == 0 { + continue + } + + pkg := f.Package() + servicesRendered := "" + imports := make(map[string]bool) + + // iterate over each service + for i, service := range f.Services() { + + // collect import paths for each protobuf method + for _, m := range service.Methods() { + fc.Debugf("signature %s, %s, %s", m.Name(), m.Input().Name(), m.Output().Name()) + + if pkg != m.Input().Package() { + inputPkg := goctx.ImportPath(m.Input()).String() + fc.Debugf("found additional import in input: %s", inputPkg) + imports[inputPkg] = true + } + + if pkg != m.Output().Package() { + outputPkg := goctx.ImportPath(m.Output()).String() + fc.Debugf("found additional import in output: %s", outputPkg) + imports[outputPkg] = true + } + } + + // render service + service, err := fc.renderService(goServiceRenderOpts{ + Pkg: pkg, + Service: service, + }, i) + fc.CheckErr(err, "unable to render ", service, " to proto") + servicesRendered += service + } + + // generate complete file, services are included + fileContent, err := fc.renderFile(goFileRenderOpts{ + Version: "version", + Source: f.Name().String(), + Package: pkgname, + Service: servicesRendered, + Imports: imports, + }) + fc.CheckErr(err, "unable to convert ", f.Name().String(), " to proto") + + fp := pgs.FilePath(ctx.OutputPath()) + fc.AddGeneratorFile(fp.SetBase(f.Name().String()).SetExt(".ranger.go").String(), fileContent) + fc.Pop() + } + fc.Debugf("processing ranger generator completed") + return fc.Artifacts() +} + +// those are the input options for the gofile.templace +type goFileRenderOpts struct { + Version string + Source string + Package string + Service string + Imports map[string]bool +} + +func (fc *rangerc) renderFile(renderOpts goFileRenderOpts) (string, error) { + return fc.render(TMP_GOFILE_FILE, renderOpts) +} + +// those are the input options for the service.templace +type goServiceRenderOpts struct { + Pkg pgs.Package + Service pgs.Service +} + +func (fc *rangerc) renderService(renderOpts goServiceRenderOpts, index int) (string, error) { + return fc.render(TMP_SERVICE_DEFINITION, renderOpts) +} + +// render a given go template +func (fc *rangerc) render(tmplate *template.Template, data interface{}) (string, error) { + var buf bytes.Buffer + writer := bufio.NewWriter(&buf) + err := tmplate.Execute(writer, data) + if err != nil { + return "", err + } + writer.Flush() + return buf.String(), nil +} + +// checks if the pkg is identical of the message type pkg. if the packages +// are not identical, it adds the +func goMessageType(pkg pgs.Package, m pgs.Message) string { + goctx := pgsgo.InitContext(pgs.Parameters{}) + + typeName := pgsgo.PGGUpperCamelCase(m.Name()).String() + + // if the method + if pkg == m.Package() { + return typeName + } + + return goctx.PackageName(m.Package()).String() + "." + typeName +} diff --git a/protoc-gen-rangerrpc/generator/templates/gofile.template b/protoc-gen-rangerrpc/generator/templates/gofile.template new file mode 100644 index 0000000..d2fda8c --- /dev/null +++ b/protoc-gen-rangerrpc/generator/templates/gofile.template @@ -0,0 +1,23 @@ +// Code generated by protoc-gen-rangerrpc {{.Version}} DO NOT EDIT. +// source: {{.Source}} + +package {{.Package}} + +import ( + "context" + "net/http" + "net/url" + "strings" + "errors" + + jsonpb "google.golang.org/protobuf/encoding/protojson" + ranger "go.mondoo.com/ranger-rpc" + "go.mondoo.com/ranger-rpc/metadata" + pb "google.golang.org/protobuf/proto" + + {{- range $k, $v := .Imports }} + "{{$k}}" + {{- end }} +) + +{{ noescape .Service }} diff --git a/protoc-gen-rangerrpc/generator/templates/service.template b/protoc-gen-rangerrpc/generator/templates/service.template new file mode 100644 index 0000000..d9acba9 --- /dev/null +++ b/protoc-gen-rangerrpc/generator/templates/service.template @@ -0,0 +1,107 @@ +{{- $root := . }} +{{- $service := .Service }} +{{- $servicedesciptor := .Service.Descriptor }} +// service interface definition + +type {{$servicedesciptor.Name}} interface { + {{- range $idx, $m := $service.Methods }} + {{$m.Name.String}}(context.Context, *{{ gotype $root.Pkg .Input }}) (*{{ gotype $root.Pkg .Output }}, error) + {{- end }} +} + +// client implementation + +type {{$servicedesciptor.Name}}Client struct { + ranger.Client + httpclient ranger.HTTPClient + prefix string +} + +func New{{$servicedesciptor.Name}}Client(addr string, client ranger.HTTPClient) (*{{$service.Name}}Client, error) { + base, err := url.Parse(ranger.SanitizeUrl(addr)) + if err != nil { + return nil, err + } + + u, err := url.Parse("./{{$servicedesciptor.Name}}") + if err != nil { + return nil, err + } + + return &{{$service.Name}}Client{ + httpclient: client, + prefix: base.ResolveReference(u).String(), + }, nil +} + +{{- range $idx, $m := $service.Methods }} +func (c *{{$service.Name}}Client) {{.Name}}(ctx context.Context, in *{{ gotype $root.Pkg .Input }}) (*{{ gotype $root.Pkg .Output }}, error) { + out := new({{ gotype $root.Pkg .Output }}) + err := c.DoClientRequest(ctx, c.httpclient, strings.Join([]string{c.prefix, "/{{.Name}}"}, ""), in, out) + return out, err +} + +{{- end }} + +// server implementation + +type {{$servicedesciptor.Name}}ServerOption func(s *{{$servicedesciptor.Name}}Server) + +func WithUnknownFieldsFor{{$servicedesciptor.Name}}Server() {{$servicedesciptor.Name}}ServerOption { + return func(s *{{$servicedesciptor.Name}}Server) { + s.allowUnknownFields = true + } +} + +func New{{$servicedesciptor.Name}}Server(handler {{$servicedesciptor.Name}}, opts ...{{$servicedesciptor.Name}}ServerOption) http.Handler { + srv := &{{$servicedesciptor.Name}}Server{ + handler: handler, + } + + for i := range opts { + opts[i](srv) + } + + service := ranger.Service{ + Name: "{{$servicedesciptor.Name}}", + Methods: map[string]ranger.Method{ + {{- range $idx, $m := $service.Methods }} + "{{.Name}}": srv.{{.Name}}, + {{- end }} + }, + } + return ranger.NewRPCServer(&service) +} + +type {{$servicedesciptor.Name}}Server struct { + handler {{$servicedesciptor.Name}} + allowUnknownFields bool +} + +{{- range $idx, $m := $service.Methods }} +func (p *{{$servicedesciptor.Name}}Server) {{.Name}}(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + var req {{ gotype $root.Pkg .Input }} + var err error + + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return nil, errors.New("could not access header") + } + + switch md.First("Content-Type") { + case "application/protobuf", "application/octet-stream", "application/grpc+proto": + err = pb.Unmarshal(*reqBytes, &req) + default: + // handle case of empty object + if len(*reqBytes) > 0 { + err = jsonpb.UnmarshalOptions{DiscardUnknown: true}.Unmarshal(*reqBytes, &req) + } + } + + if err != nil { + return nil, err + } + return p.handler.{{.Name}}(ctx, &req) +} + +{{- end }} \ No newline at end of file diff --git a/protoc-gen-rangerrpc/main.go b/protoc-gen-rangerrpc/main.go new file mode 100644 index 0000000..9ee1c5d --- /dev/null +++ b/protoc-gen-rangerrpc/main.go @@ -0,0 +1,18 @@ +package main + +import ( + pgs "github.com/lyft/protoc-gen-star" + pgsgo "github.com/lyft/protoc-gen-star/lang/go" + "go.mondoo.com/ranger-rpc/protoc-gen-rangerrpc/generator" +) + +var version string + +func main() { + pgs.Init( + pgs.DebugEnv("DEBUG"), + ). + RegisterModule(generator.New()). + RegisterPostProcessor(pgsgo.GoFmt()). + Render() +} diff --git a/ranger.go b/ranger.go new file mode 100644 index 0000000..9c07bcb --- /dev/null +++ b/ranger.go @@ -0,0 +1,17 @@ +package ranger + +// Ranger RPC is a simple and fast proto-based RPC framework +// +// It is designed to stay as close as possible to GRPC without the complexity that GRPC brings. Essentially the support +// for plain json endpoints require the use of the GRPC and GRPC Gateway. +// +// To make the use of Ranger RPC as easy as possible, the following features are provided: +// +// We use the same GRPC codes +// https://github.com/grpc/grpc/blob/master/doc/statuscodes.md +// +// We use GRPC-compatible HTTP status code mapping +// https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md +// +// GRPC Status Blog +// https://jbrandhorst.com/post/grpc-errors/ diff --git a/sanitize.go b/sanitize.go new file mode 100644 index 0000000..edbc188 --- /dev/null +++ b/sanitize.go @@ -0,0 +1,19 @@ +package ranger + +import ( + "net/url" +) + +// SanitizeUrl parses the given url and returns a sanitized url. If no scheme is given, it will be set to https. +func SanitizeUrl(addr string) string { + url, err := url.Parse(addr) + if err != nil { + // url.Parse fails on it, return it unchanged. + return addr + } + + if url.Scheme == "" { + url.Scheme = "https" + } + return url.String() +} diff --git a/server.go b/server.go new file mode 100644 index 0000000..317ee2b --- /dev/null +++ b/server.go @@ -0,0 +1,194 @@ +package ranger + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "strings" + + "go.mondoo.com/ranger-rpc/codes" + "go.mondoo.com/ranger-rpc/status" + jsonpb "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +const ( + ContentTypeProtobuf = "application/protobuf" + ContentTypeOctetProtobuf = "application/octet-stream" + ContentTypeGrpcProtobuf = "application/grpc+proto" + ContentTypeJson = "application/json" +) + +var validContentTypes = []string{ + ContentTypeProtobuf, + ContentTypeOctetProtobuf, + ContentTypeGrpcProtobuf, + ContentTypeJson, +} + +// Method represents a RPC method and is used by protoc-gen-rangerrpc +type Method func(ctx context.Context, reqBytes *[]byte) (proto.Message, error) + +// Service is the struct that holds all available methods. The protoc-gen-rangerrpc will generate the +// correct client and service definition to be used. +type Service struct { + Name string + Methods map[string]Method +} + +// NewServer creates a new server. This function is used by the protoc-gen-rangerrpc generated code and +// should not be used directly. +func NewRPCServer(service *Service) *server { + var b strings.Builder + b.WriteString("/") + b.WriteString(service.Name) + b.WriteString("/") + return &server{service: service, prefix: b.String()} +} + +type server struct { + service *Service + prefix string +} + +// ServeHTTP is the main entry point for the http server. +func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + + // verify content type + err := verifyContentType(req) + if err != nil { + httpError(w, req, err) + return + } + + if !strings.HasPrefix(req.URL.Path, s.prefix) { + httpError(w, req, status.Error(codes.NotFound, req.URL.Path+" is not available")) + return + } + + // extract the rpc method name and invoke the method + name := strings.TrimPrefix(req.URL.Path, s.prefix) + + method := s.service.Methods[name] + if method == nil { + err := status.Error(codes.NotFound, "method not defined") + httpError(w, req, err) + return + } + + rctx, rcancel, body, err := PreProcessRequest(ctx, req) + if err != nil { + httpError(w, req, err) + return + } + defer rcancel() + + // invoke method and send the response + resp, err := method(rctx, &body) + s.sendResponse(w, req, resp, err) +} + +// PreProcessRequest is used to preprocess the incoming request. +// It returns the context, a cancel function and the body of the request. The cancel function can be used to cancel +// the context. It also adds the http headers to the context. +func PreProcessRequest(ctx context.Context, req *http.Request) (context.Context, context.CancelFunc, []byte, error) { + // read body content + body, err := ioutil.ReadAll(req.Body) + req.Body.Close() + if err != nil { + return nil, nil, nil, status.Error(codes.DataLoss, "unrecoverable data loss or corruption") + } + + // pass-through the http headers + rctx, rcancel, err := AnnotateContext(ctx, req) + if err != nil { + return nil, rcancel, nil, err + } + + return rctx, rcancel, body, nil +} + +func (s *server) sendResponse(w http.ResponseWriter, req *http.Request, resp proto.Message, err error) { + if err != nil { + httpError(w, req, err) + return + } + + // check if the accept header is set, otherwise use the incoming content type + accept := determineResponseType(req.Header.Get("Content-Type"), req.Header.Get("Accept")) + payload, contentType, err := convertProtoToPayload(resp, accept) + + if err != nil { + httpError(w, req, status.Error(codes.Internal, "error encoding response")) + return + } + + h := w.Header() + h.Set("Content-Type", contentType) + w.WriteHeader(http.StatusOK) + w.Write(payload) +} + +// convertProtoToPayload converts a proto message to the approaptiate formatted payload. +// Depending on the accept header it will return the payload as marshalled protobuf or json. +func convertProtoToPayload(resp proto.Message, accept string) ([]byte, string, error) { + var err error + var payload []byte + contentType := accept + switch accept { + case ContentTypeProtobuf, ContentTypeGrpcProtobuf, ContentTypeOctetProtobuf: + contentType = ContentTypeProtobuf + payload, err = proto.Marshal(resp) + // as default, we return json to be compatible with browsers, since they do not + // request as application/json as default + default: + payload, err = jsonpb.MarshalOptions{UseProtoNames: true}.Marshal(resp) + } + + return payload, contentType, err +} + +// verifyContentType validates the content type of the request is known. +func verifyContentType(req *http.Request) error { + header := req.Header.Get("Content-Type") + + // we assume "application/protobuf" if no content-type is set + if len(header) == 0 { + return nil + } + + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + + ct := strings.TrimSpace(strings.ToLower(header[:i])) + + // check that the incoming request has a valid content type + for _, a := range validContentTypes { + if a == ct { + return nil + } + } + + // if we reached here, we have to handle an unexpected incoming type + return status.Error(codes.InvalidArgument, fmt.Sprintf("unexpected content-type: %q", req.Header.Get("Content-Type"))) +} + +// determineResponseType returns the content type based on the Content-Type and Accept header. +func determineResponseType(contenttype string, accept string) string { + // use provided content type if no accept header was provided + if len(accept) == 0 { + accept = contenttype + } + + switch accept { + case ContentTypeProtobuf, ContentTypeGrpcProtobuf, ContentTypeOctetProtobuf: + return ContentTypeProtobuf + default: + return ContentTypeJson + } +} diff --git a/server_test.go b/server_test.go new file mode 100644 index 0000000..4a24e01 --- /dev/null +++ b/server_test.go @@ -0,0 +1,243 @@ +package ranger_test + +import ( + "context" + "encoding/json" + "io" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/cockroachdb/errors" + "github.com/rs/zerolog/log" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.mondoo.com/ranger-rpc" + "go.mondoo.com/ranger-rpc/codes" + "go.mondoo.com/ranger-rpc/examples/pingpong" + "go.mondoo.com/ranger-rpc/metadata" + "go.mondoo.com/ranger-rpc/status" + spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/protobuf/proto" + pb "google.golang.org/protobuf/proto" +) + +func TestRangerHttpServer(t *testing.T) { + service := ranger.Service{ + Name: "PingPong", + Methods: map[string]ranger.Method{ + "Ping": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + test := &pingpong.PongReply{} + return test, nil + }, + }, + } + + srv := ranger.NewRPCServer(&service) + + var req *http.Request + var w *httptest.ResponseRecorder + var resp *http.Response + + // get 404 since the default content-type is protobuf + req = httptest.NewRequest("POST", "http://example.com/Ping", nil) + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 404, resp.StatusCode, "correct status code") + + // get 404 since the route is not registered + req = httptest.NewRequest("POST", "http://example.com/Unknown", nil) + req.Header.Set("Content-Type", "application/protobuf") + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 404, resp.StatusCode, "correct status code") + + // get 404 since the route is not registered + req = httptest.NewRequest("POST", "http://example.com/PingPong/Ping", nil) + req.Header.Set("Content-Type", "application/protobuf") + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 200, resp.StatusCode, "correct status code") + +} + +func TestRangerHttpHeader(t *testing.T) { + service := ranger.Service{ + Name: "PingPong", + Methods: map[string]ranger.Method{ + "Ping": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + log.Debug().Msg("no header") + return nil, errors.New("could not access header") + } + + test := &pingpong.PongReply{Message: md.First("X-Custom-Header")} + return test, nil + }, + }, + } + + srv := ranger.NewRPCServer(&service) + + var req *http.Request + var w *httptest.ResponseRecorder + var resp *http.Response + + // test that the handler has access to http header + req = httptest.NewRequest("POST", "http://example.com/PingPong/Ping", nil) + req.Header.Set("Content-Type", "application/protobuf") + req.Header.Set("X-Custom-Header", "my-header") + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 200, resp.StatusCode, "correct status code") + + content, err := ioutil.ReadAll(w.Body) + assert.Nil(t, err, "should return protobuf content") + + var msg pingpong.PongReply + if err := pb.Unmarshal(content, &msg); err != nil { + t.Fatal(err) + } + + assert.Equal(t, "my-header", msg.Message, "correct header value") +} + +func runStatusCall(srv http.Handler, path string) *http.Response { + req := httptest.NewRequest("POST", path, nil) + req.Header.Set("Content-Type", "application/protobuf") + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + return w.Result() +} + +func parseStatus(reader io.Reader) (*spb.Status, error) { + payload, err := ioutil.ReadAll(reader) + if err != nil { + return nil, err + } + var status spb.Status + err = proto.Unmarshal(payload, &status) + if err != nil { + return nil, err + } + return &status, nil +} + +func TestRangerErrorHandling(t *testing.T) { + service := ranger.Service{ + Name: "Error", + Methods: map[string]ranger.Method{ + "Ping": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + test := &pingpong.PongReply{} + return test, nil + }, + "NilResponseWithStatusError": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + return nil, status.Error(codes.PermissionDenied, "you really have no permission") + }, + "NilResponseWithError": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + return nil, errors.New("my error message") + }, + "NilResponseWithoutError": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + return nil, nil + }, + }, + } + + srv := ranger.NewRPCServer(&service) + + var req *http.Request + var w *httptest.ResponseRecorder + var resp *http.Response + + // check argument error for wrong content type + req = httptest.NewRequest("POST", "http://example.com/Error/Ping", nil) + // this will result in a json error response + req.Header.Set("Content-Type", "unknown/content-type") + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 400, resp.StatusCode, "correct status code") + payload, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + + type errMsg struct { + Code int `json:"code"` + Message string `json:"message"` + } + respDecoded := errMsg{} + if err := json.Unmarshal(payload, &respDecoded); err != nil { + t.Fatal(err) + } + + assert.Equal(t, errMsg{ + Code: 3, + Message: "unexpected content-type: \"unknown/content-type\"", + }, respDecoded) + + // assume protobuf content-type if no content-type is there + req = httptest.NewRequest("POST", "http://example.com/Error/Ping", nil) + w = httptest.NewRecorder() + srv.ServeHTTP(w, req) + resp = w.Result() + assert.Equal(t, 200, resp.StatusCode, "correct status code") + + // test status codes are respected + resp = runStatusCall(srv, "http://example.com/Error/NilResponseWithStatusError") + assert.Equal(t, 403, resp.StatusCode, "correct status code") + status, err := parseStatus(resp.Body) + require.NoError(t, err) + assert.Equal(t, "you really have no permission", status.Message, "correct error message") + + resp = runStatusCall(srv, "http://example.com/Error/NilResponseWithError") + assert.Equal(t, 500, resp.StatusCode, "correct status code") + status, err = parseStatus(resp.Body) + require.NoError(t, err) + assert.Equal(t, "my error message", status.Message, "correct error message") + + resp = runStatusCall(srv, "http://example.com/Error/NilResponseWithoutError") + assert.Equal(t, 200, resp.StatusCode, "correct status code") + status, err = parseStatus(resp.Body) + require.NoError(t, err) + assert.Equal(t, "", status.Message, "correct error message") +} + +func TestRangerStatusCodes(t *testing.T) { + service := ranger.Service{ + Name: "Status", + Methods: map[string]ranger.Method{ + "NotFound": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + return nil, status.Error(codes.NotFound, "id was not found") + }, + "InvalidArgument": func(ctx context.Context, reqBytes *[]byte) (pb.Message, error) { + return nil, status.Errorf(codes.InvalidArgument, "Value of `Input` is not allowed") + }, + }, + } + + srv := ranger.NewRPCServer(&service) + var resp *http.Response + + // test 404 + resp = runStatusCall(srv, "http://example.com/Status/NotFound") + assert.Equal(t, 404, resp.StatusCode, "correct status code") + status, err := parseStatus(resp.Body) + require.NoError(t, err) + assert.Equal(t, codes.NotFound, codes.Code(status.GetCode()), "correct error message") + assert.Equal(t, "id was not found", status.GetMessage(), "correct error message") + + // test 400 + resp = runStatusCall(srv, "http://example.com/Status/InvalidArgument") + assert.Equal(t, 400, resp.StatusCode, "correct status code") + status, err = parseStatus(resp.Body) + require.NoError(t, err) + assert.Equal(t, codes.InvalidArgument, codes.Code(status.GetCode()), "correct error message") + assert.Equal(t, "Value of `Input` is not allowed", status.GetMessage(), "correct error message") +} diff --git a/status/http.go b/status/http.go new file mode 100644 index 0000000..1573c0c --- /dev/null +++ b/status/http.go @@ -0,0 +1,71 @@ +package status + +import ( + "net/http" + + "go.mondoo.com/ranger-rpc/codes" +) + +var codeMap map[codes.Code]int +var statusMap map[int]codes.Code + +func init() { + codeMap = map[codes.Code]int{ + codes.OK: http.StatusOK, + codes.Canceled: http.StatusRequestTimeout, + codes.Unknown: http.StatusInternalServerError, + codes.InvalidArgument: http.StatusBadRequest, + codes.DeadlineExceeded: http.StatusGatewayTimeout, + codes.NotFound: http.StatusNotFound, + codes.AlreadyExists: http.StatusConflict, + codes.PermissionDenied: http.StatusForbidden, + codes.Unauthenticated: http.StatusUnauthorized, + codes.ResourceExhausted: http.StatusTooManyRequests, + codes.FailedPrecondition: http.StatusPreconditionFailed, + codes.Aborted: http.StatusConflict, + codes.OutOfRange: http.StatusBadRequest, + codes.Unimplemented: http.StatusNotImplemented, + codes.Internal: http.StatusInternalServerError, + codes.Unavailable: http.StatusServiceUnavailable, + codes.DataLoss: http.StatusInternalServerError, + } + + statusMap = map[int]codes.Code{ + // 2xx + http.StatusOK: codes.OK, + http.StatusCreated: codes.OK, + http.StatusAccepted: codes.OK, + http.StatusNoContent: codes.OK, + + // 4xx + http.StatusBadRequest: codes.InvalidArgument, + http.StatusUnauthorized: codes.Unauthenticated, + http.StatusForbidden: codes.PermissionDenied, + http.StatusNotFound: codes.NotFound, + http.StatusRequestTimeout: codes.Canceled, + + // 5xx + http.StatusInternalServerError: codes.Internal, + http.StatusServiceUnavailable: codes.Unavailable, + http.StatusNotImplemented: codes.Unimplemented, + } +} + +// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. +// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +func HTTPStatusFromCode(code codes.Code) int { + status, ok := codeMap[code] + if ok { + return status + } + return http.StatusInternalServerError +} + +func CodeFromHTTPStatus(status int) codes.Code { + code, ok := statusMap[status] + if ok { + return code + } + + return codes.Unknown +} diff --git a/status/http_test.go b/status/http_test.go new file mode 100644 index 0000000..50eaed3 --- /dev/null +++ b/status/http_test.go @@ -0,0 +1,23 @@ +package status_test + +import ( + "net/http" + "testing" + + "go.mondoo.com/ranger-rpc/status" + + "github.com/stretchr/testify/assert" + "go.mondoo.com/ranger-rpc/codes" +) + +func TestHTTPStatusFromCode(t *testing.T) { + assert.Equal(t, http.StatusOK, status.HTTPStatusFromCode(codes.OK)) + assert.Equal(t, http.StatusInternalServerError, status.HTTPStatusFromCode(codes.Unknown)) + assert.Equal(t, http.StatusInternalServerError, status.HTTPStatusFromCode(codes.Code(1000))) +} + +func TestCodeFromHTTPStatus(t *testing.T) { + assert.Equal(t, codes.OK, status.CodeFromHTTPStatus(http.StatusOK)) + assert.Equal(t, codes.Internal, status.CodeFromHTTPStatus(http.StatusInternalServerError)) + assert.Equal(t, codes.Unknown, status.CodeFromHTTPStatus(1000)) +} diff --git a/status/internal/status.go b/status/internal/status.go new file mode 100644 index 0000000..ce6ee57 --- /dev/null +++ b/status/internal/status.go @@ -0,0 +1,163 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package status implements errors returned by gRPC. These errors are +// serialized and transmitted on the wire between server and client, and allow +// for additional data to be transmitted via the Details field in the status +// proto. gRPC service handlers should return an error created by this +// package, and gRPC clients should expect a corresponding error to be +// returned from the RPC call. +// +// This package upholds the invariants that a non-nil error may not +// contain an OK code, and an OK code must result in a nil error. +package status + +import ( + "errors" + "fmt" + + "github.com/golang/protobuf/ptypes" + "go.mondoo.com/ranger-rpc/codes" + spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/protobuf/proto" + anypb "google.golang.org/protobuf/types/known/anypb" +) + +// Status represents an RPC status code, message, and details. It is immutable +// and should be created with New, Newf, or FromProto. +type Status struct { + s *spb.Status +} + +// New returns a Status representing c and msg. +func New(c codes.Code, msg string) *Status { + return &Status{s: &spb.Status{Code: int32(c), Message: msg}} +} + +// Newf returns New(c, fmt.Sprintf(format, a...)). +func Newf(c codes.Code, format string, a ...interface{}) *Status { + return New(c, fmt.Sprintf(format, a...)) +} + +// FromProto returns a Status representing s. +func FromProto(s *spb.Status) *Status { + return &Status{s: proto.Clone(s).(*spb.Status)} +} + +// Err returns an error representing c and msg. If c is OK, returns nil. +func Err(c codes.Code, msg string) error { + return New(c, msg).Err() +} + +// Errorf returns Error(c, fmt.Sprintf(format, a...)). +func Errorf(c codes.Code, format string, a ...interface{}) error { + return Err(c, fmt.Sprintf(format, a...)) +} + +// Code returns the status code contained in s. +func (s *Status) Code() codes.Code { + if s == nil || s.s == nil { + return codes.OK + } + return codes.Code(s.s.Code) +} + +// Message returns the message contained in s. +func (s *Status) Message() string { + if s == nil || s.s == nil { + return "" + } + return s.s.Message +} + +// Proto returns s's status as an spb.Status proto message. +func (s *Status) Proto() *spb.Status { + if s == nil { + return nil + } + return proto.Clone(s.s).(*spb.Status) +} + +// Err returns an immutable error representing s; returns nil if s.Code() is OK. +func (s *Status) Err() error { + if s.Code() == codes.OK { + return nil + } + return &Error{e: s.Proto()} +} + +// WithDetails returns a new status with the provided details messages appended to the status. +// If any errors are encountered, it returns nil and the first error encountered. +func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { + if s.Code() == codes.OK { + return nil, errors.New("no error details for status with code OK") + } + // s.Code() != OK implies that s.Proto() != nil. + p := s.Proto() + for _, detail := range details { + any, err := anypb.New(detail) + if err != nil { + return nil, err + } + p.Details = append(p.Details, any) + } + return &Status{s: p}, nil +} + +// Details returns a slice of details messages attached to the status. +// If a detail cannot be decoded, the error is returned in place of the detail. +func (s *Status) Details() []interface{} { + if s == nil || s.s == nil { + return nil + } + details := make([]interface{}, 0, len(s.s.Details)) + for _, any := range s.s.Details { + detail := &ptypes.DynamicAny{} + if err := ptypes.UnmarshalAny(any, detail); err != nil { + details = append(details, err) + continue + } + details = append(details, detail.Message) + } + return details +} + +// Error wraps a pointer of a status proto. It implements error and Status, +// and a nil *Error should never be returned by this package. +type Error struct { + e *spb.Status +} + +func (e *Error) Error() string { + return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(e.e.GetCode()), e.e.GetMessage()) +} + +// GRPCStatus returns the Status represented by se. +func (e *Error) GRPCStatus() *Status { + return FromProto(e.e) +} + +// Is implements future error.Is functionality. +// A Error is equivalent if the code and message are identical. +func (e *Error) Is(target error) bool { + tse, ok := target.(*Error) + if !ok { + return false + } + return proto.Equal(e.e, tse.e) +} diff --git a/status/status.go b/status/status.go new file mode 100644 index 0000000..d536df9 --- /dev/null +++ b/status/status.go @@ -0,0 +1,129 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package status implements errors returned by gRPC. These errors are +// serialized and transmitted on the wire between server and client, and allow +// for additional data to be transmitted via the Details field in the status +// proto. gRPC service handlers should return an error created by this +// package, and gRPC clients should expect a corresponding error to be +// returned from the RPC call. +// +// This package upholds the invariants that a non-nil error may not +// contain an OK code, and an OK code must result in a nil error. +package status + +import ( + "context" + "fmt" + + spb "google.golang.org/genproto/googleapis/rpc/status" + + "go.mondoo.com/ranger-rpc/codes" + status "go.mondoo.com/ranger-rpc/status/internal" +) + +// Status references google.golang.org/grpc/internal/status. It represents an +// RPC status code, message, and details. It is immutable and should be +// created with New, Newf, or FromProto. +// https://godoc.org/google.golang.org/grpc/internal/status +type Status = status.Status + +// New returns a Status representing c and msg. +func New(c codes.Code, msg string) *Status { + return status.New(c, msg) +} + +// Newf returns New(c, fmt.Sprintf(format, a...)). +func Newf(c codes.Code, format string, a ...interface{}) *Status { + return New(c, fmt.Sprintf(format, a...)) +} + +// Error returns an error representing c and msg. If c is OK, returns nil. +func Error(c codes.Code, msg string) error { + return New(c, msg).Err() +} + +// Errorf returns Error(c, fmt.Sprintf(format, a...)). +func Errorf(c codes.Code, format string, a ...interface{}) error { + return Error(c, fmt.Sprintf(format, a...)) +} + +// ErrorProto returns an error representing s. If s.Code is OK, returns nil. +func ErrorProto(s *spb.Status) error { + return FromProto(s).Err() +} + +// FromProto returns a Status representing s. +func FromProto(s *spb.Status) *Status { + return status.FromProto(s) +} + +// FromError returns a Status representing err if it was produced by this +// package or has a method `GRPCStatus() *Status`. +// If err is nil, a Status is returned with codes.OK and no message. +// Otherwise, ok is false and a Status is returned with codes.Unknown and +// the original error message. +func FromError(err error) (s *Status, ok bool) { + if err == nil { + return nil, true + } + if se, ok := err.(interface { + GRPCStatus() *Status + }); ok { + return se.GRPCStatus(), true + } + return New(codes.Unknown, err.Error()), false +} + +// Convert is a convenience function which removes the need to handle the +// boolean return value from FromError. +func Convert(err error) *Status { + s, _ := FromError(err) + return s +} + +// Code returns the Code of the error if it is a Status error, codes.OK if err +// is nil, or codes.Unknown otherwise. +func Code(err error) codes.Code { + // Don't use FromError to avoid allocation of OK status. + if err == nil { + return codes.OK + } + if se, ok := err.(interface { + GRPCStatus() *Status + }); ok { + return se.GRPCStatus().Code() + } + return codes.Unknown +} + +// FromContextError converts a context error into a Status. It returns a +// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is +// non-nil and not a context error. +func FromContextError(err error) *Status { + switch err { + case nil: + return nil + case context.DeadlineExceeded: + return New(codes.DeadlineExceeded, err.Error()) + case context.Canceled: + return New(codes.Canceled, err.Error()) + default: + return New(codes.Unknown, err.Error()) + } +} diff --git a/status/status_test.go b/status/status_test.go new file mode 100644 index 0000000..24e31c9 --- /dev/null +++ b/status/status_test.go @@ -0,0 +1,366 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package status + +import ( + "context" + "errors" + "fmt" + "testing" + + "google.golang.org/protobuf/types/known/anypb" + + apb "github.com/golang/protobuf/ptypes/any" + dpb "github.com/golang/protobuf/ptypes/duration" + "github.com/google/go-cmp/cmp" + "go.mondoo.com/ranger-rpc/codes" + status "go.mondoo.com/ranger-rpc/status/internal" + cpb "google.golang.org/genproto/googleapis/rpc/code" + epb "google.golang.org/genproto/googleapis/rpc/errdetails" + spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/protobuf/proto" +) + +// errEqual is essentially a copy of testutils.StatusErrEqual(), to avoid a +// cyclic dependency. +func errEqual(err1, err2 error) bool { + status1, ok := FromError(err1) + if !ok { + return false + } + status2, ok := FromError(err2) + if !ok { + return false + } + return proto.Equal(status1.Proto(), status2.Proto()) +} + +func TestErrorsWithSameParameters(t *testing.T) { + const description = "some description" + e1 := Errorf(codes.AlreadyExists, description) + e2 := Errorf(codes.AlreadyExists, description) + if e1 == e2 || !errEqual(e1, e2) { + t.Fatalf("Errors should be equivalent but unique - e1: %v, %v e2: %p, %v", e1.(*status.Error), e1, e2.(*status.Error), e2) + } +} + +func TestFromToProto(t *testing.T) { + s := &spb.Status{ + Code: int32(codes.Internal), + Message: "test test test", + Details: []*apb.Any{{TypeUrl: "foo", Value: []byte{3, 2, 1}}}, + } + + err := FromProto(s) + if got := err.Proto(); !proto.Equal(s, got) { + t.Fatalf("Expected errors to be identical - s: %v got: %v", s, got) + } +} + +func TestFromNilProto(t *testing.T) { + tests := []*Status{nil, FromProto(nil)} + for _, s := range tests { + if c := s.Code(); c != codes.OK { + t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c) + } + if m := s.Message(); m != "" { + t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m) + } + if p := s.Proto(); p != nil { + t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p) + } + if e := s.Err(); e != nil { + t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e) + } + } +} + +func TestError(t *testing.T) { + err := Error(codes.Internal, "test description") + if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want { + t.Fatalf("err.Error() = %q; want %q", got, want) + } + s, _ := FromError(err) + if got, want := s.Code(), codes.Internal; got != want { + t.Fatalf("err.Code() = %s; want %s", got, want) + } + if got, want := s.Message(), "test description"; got != want { + t.Fatalf("err.Message() = %s; want %s", got, want) + } +} + +func TestErrorOK(t *testing.T) { + err := Error(codes.OK, "foo") + if err != nil { + t.Fatalf("Error(codes.OK, _) = %p; want nil", err.(*status.Error)) + } +} + +func TestErrorProtoOK(t *testing.T) { + s := &spb.Status{Code: int32(codes.OK)} + if got := ErrorProto(s); got != nil { + t.Fatalf("ErrorProto(%v) = %v; want nil", s, got) + } +} + +func TestFromError(t *testing.T) { + code, message := codes.Internal, "test description" + err := Error(code, message) + s, ok := FromError(err) + if !ok || s.Code() != code || s.Message() != message || s.Err() == nil { + t.Fatalf("FromError(%v) = %v, %v; want , true", err, s, ok, code, message) + } +} + +func TestFromErrorOK(t *testing.T) { + code, message := codes.OK, "" + s, ok := FromError(nil) + if !ok || s.Code() != code || s.Message() != message || s.Err() != nil { + t.Fatalf("FromError(nil) = %v, %v; want , true", s, ok, code, message) + } +} + +type customError struct { + Code codes.Code + Message string + Details []*apb.Any +} + +func (c customError) Error() string { + return fmt.Sprintf("rpc error: code = %s desc = %s", c.Code, c.Message) +} + +func (c customError) GRPCStatus() *Status { + return status.FromProto(&spb.Status{ + Code: int32(c.Code), + Message: c.Message, + Details: c.Details, + }) +} + +func TestFromErrorImplementsInterface(t *testing.T) { + code, message := codes.Internal, "test description" + details := []*apb.Any{{ + TypeUrl: "testUrl", + Value: []byte("testValue"), + }} + err := customError{ + Code: code, + Message: message, + Details: details, + } + s, ok := FromError(err) + if !ok || s.Code() != code || s.Message() != message || s.Err() == nil { + t.Fatalf("FromError(%v) = %v, %v; want , true", err, s, ok, code, message) + } + pd := s.Proto().GetDetails() + if len(pd) != 1 || !proto.Equal(pd[0], details[0]) { + t.Fatalf("s.Proto.GetDetails() = %v; want ", pd, details) + } +} + +func TestFromErrorUnknownError(t *testing.T) { + code, message := codes.Unknown, "unknown error" + err := errors.New("unknown error") + s, ok := FromError(err) + if ok || s.Code() != code || s.Message() != message { + t.Fatalf("FromError(%v) = %v, %v; want , false", err, s, ok, code, message) + } +} + +func TestConvertKnownError(t *testing.T) { + code, message := codes.Internal, "test description" + err := Error(code, message) + s := Convert(err) + if s.Code() != code || s.Message() != message { + t.Fatalf("Convert(%v) = %v; want ", err, s, code, message) + } +} + +func TestConvertUnknownError(t *testing.T) { + code, message := codes.Unknown, "unknown error" + err := errors.New("unknown error") + s := Convert(err) + if s.Code() != code || s.Message() != message { + t.Fatalf("Convert(%v) = %v; want ", err, s, code, message) + } +} + +func TestStatus_ErrorDetails(t *testing.T) { + tests := []struct { + code codes.Code + details []proto.Message + }{ + { + code: codes.NotFound, + details: nil, + }, + { + code: codes.NotFound, + details: []proto.Message{ + &epb.ResourceInfo{ + ResourceType: "book", + ResourceName: "projects/1234/books/5678", + Owner: "User", + }, + }, + }, + { + code: codes.Internal, + details: []proto.Message{ + &epb.DebugInfo{ + StackEntries: []string{ + "first stack", + "second stack", + }, + }, + }, + }, + { + code: codes.Unavailable, + details: []proto.Message{ + &epb.RetryInfo{ + RetryDelay: &dpb.Duration{Seconds: 60}, + }, + &epb.ResourceInfo{ + ResourceType: "book", + ResourceName: "projects/1234/books/5678", + Owner: "User", + }, + }, + }, + } + + for _, tc := range tests { + s, err := New(tc.code, "").WithDetails(tc.details...) + if err != nil { + t.Fatalf("(%v).WithDetails(%+v) failed: %v", str(s), tc.details, err) + } + details := s.Details() + for i := range details { + if !proto.Equal(details[i].(proto.Message), tc.details[i]) { + t.Fatalf("(%v).Details()[%d] = %+v, want %+v", str(s), i, details[i], tc.details[i]) + } + } + } +} + +func TestStatus_WithDetails_Fail(t *testing.T) { + tests := []*Status{ + nil, + FromProto(nil), + New(codes.OK, ""), + } + for _, s := range tests { + if s, err := s.WithDetails(); err == nil || s != nil { + t.Fatalf("(%v).WithDetails(%+v) = %v, %v; want nil, non-nil", str(s), []proto.Message{}, s, err) + } + } +} + +func TestStatus_ErrorDetails_Fail(t *testing.T) { + tests := []struct { + s *Status + i []interface{} + }{ + { + nil, + nil, + }, + { + FromProto(nil), + nil, + }, + { + New(codes.OK, ""), + []interface{}{}, + }, + { + FromProto(&spb.Status{ + Code: int32(cpb.Code_CANCELLED), + Details: []*apb.Any{ + { + TypeUrl: "", + Value: []byte{}, + }, + mustMarshalAny(&epb.ResourceInfo{ + ResourceType: "book", + ResourceName: "projects/1234/books/5678", + Owner: "User", + }), + }, + }), + []interface{}{ + errors.New(`message type url "" is invalid`), + &epb.ResourceInfo{ + ResourceType: "book", + ResourceName: "projects/1234/books/5678", + Owner: "User", + }, + }, + }, + } + for _, tc := range tests { + got := tc.s.Details() + if !cmp.Equal(got, tc.i, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)) { + t.Errorf("(%v).Details() = %+v, want %+v", str(tc.s), got, tc.i) + } + } +} + +func equalError(x, y error) bool { + return x == y || (x != nil && y != nil && x.Error() == y.Error()) +} + +func str(s *Status) string { + if s == nil { + return "nil" + } + if s.Proto() == nil { + return "" + } + return fmt.Sprintf("", s.Code(), s.Message(), s.Details()) +} + +// mustMarshalAny converts a protobuf message to an any. +func mustMarshalAny(msg proto.Message) *apb.Any { + any, err := anypb.New(msg) + if err != nil { + panic(fmt.Sprintf("ptypes.MarshalAny(%+v) failed: %v", msg, err)) + } + return any +} + +func TestFromContextError(t *testing.T) { + testCases := []struct { + in error + want *Status + }{ + {in: nil, want: New(codes.OK, "")}, + {in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())}, + {in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())}, + {in: errors.New("other"), want: New(codes.Unknown, "other")}, + } + for _, tc := range testCases { + got := FromContextError(tc.in) + if got.Code() != tc.want.Code() || got.Message() != tc.want.Message() { + t.Errorf("FromContextError(%v) = %v; want %v", tc.in, got, tc.want) + } + } +}