diff options
| author | Xe Iaso <me@xeiaso.net> | 2024-05-24 11:23:40 -0400 |
|---|---|---|
| committer | Xe Iaso <me@xeiaso.net> | 2024-05-24 15:36:45 -0400 |
| commit | d69787e5c65378a54de622fafbcce2a08a5c21f5 (patch) | |
| tree | 7f9faf842aa469d3d696850446927fba48c9b6ac /pb/external | |
| parent | 4fe62ffff3d1cae0b9d53f720d8fcc581fdff8db (diff) | |
| download | xesite-d69787e5c65378a54de622fafbcce2a08a5c21f5.tar.xz xesite-d69787e5c65378a54de622fafbcce2a08a5c21f5.zip | |
pb: add mi definitions
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'pb/external')
| -rw-r--r-- | pb/external/generate.go | 1 | ||||
| -rw-r--r-- | pb/external/mi.proto | 31 | ||||
| -rw-r--r-- | pb/external/mi/mi.pb.go | 290 | ||||
| -rw-r--r-- | pb/external/mi/mi.twirp.go | 1115 | ||||
| -rw-r--r-- | pb/external/mimi/announce/mimi-announce.pb.go | 2 | ||||
| -rw-r--r-- | pb/external/protofeed/protofeed.pb.go | 2 |
6 files changed, 1439 insertions, 2 deletions
diff --git a/pb/external/generate.go b/pb/external/generate.go index 5c07ba2..b580a7e 100644 --- a/pb/external/generate.go +++ b/pb/external/generate.go @@ -2,3 +2,4 @@ package protofeed //go:generate protoc --proto_path=. --proto_path=.. --go_out=./protofeed --go_opt=paths=source_relative ./protofeed.proto //go:generate protoc --proto_path=. --proto_path=.. --go_out=./mimi/announce --go_opt=paths=source_relative --twirp_out=./mimi/announce --twirp_opt=paths=source_relative ./mimi-announce.proto +//go:generate protoc --proto_path=. --proto_path=.. --go_out=./mi --go_opt=paths=source_relative --twirp_out=./mi --twirp_opt=paths=source_relative ./mi.proto diff --git a/pb/external/mi.proto b/pb/external/mi.proto new file mode 100644 index 0000000..937a15c --- /dev/null +++ b/pb/external/mi.proto @@ -0,0 +1,31 @@ +// This is a subset of github:Xe/x/proto/mi.proto + +syntax = "proto3"; +package within.website.x.mi; +option go_package = "xeiaso.net/v4/pb/external/mi"; + +import "google/protobuf/timestamp.proto"; + +// Event is a single event that Xe will be attending. +message Event { + // The name of the event + string name = 1; + // The URL for the event + string url = 2; + // The day the event starts + google.protobuf.Timestamp start_date = 3; + // The day the event ends + google.protobuf.Timestamp end_date = 4; + // The location of the event (human-readable) + string location = 5; + // The ID of the event + int32 id = 6; + // The description of the event + string description = 7; +} + +// A feed of events, result from mi query. +message EventFeed { + // The events in the feed + repeated Event events = 1; +}
\ No newline at end of file diff --git a/pb/external/mi/mi.pb.go b/pb/external/mi/mi.pb.go new file mode 100644 index 0000000..8d425d3 --- /dev/null +++ b/pb/external/mi/mi.pb.go @@ -0,0 +1,290 @@ +// This is a subset of github:Xe/x/proto/mi.proto + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.32.0 +// protoc v5.26.1 +// source: mi.proto + +package mi + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + _ "google.golang.org/protobuf/types/known/emptypb" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + 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) +) + +// Event is a single event that Xe will be attending. +type Event struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The name of the event + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // The URL for the event + Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` + // The day the event starts + StartDate *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=start_date,json=startDate,proto3" json:"start_date,omitempty"` + // The day the event ends + EndDate *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=end_date,json=endDate,proto3" json:"end_date,omitempty"` + // The location of the event (human-readable) + Location string `protobuf:"bytes,5,opt,name=location,proto3" json:"location,omitempty"` + // The ID of the event + Id int32 `protobuf:"varint,6,opt,name=id,proto3" json:"id,omitempty"` + // The description of the event + Description string `protobuf:"bytes,7,opt,name=description,proto3" json:"description,omitempty"` +} + +func (x *Event) Reset() { + *x = Event{} + if protoimpl.UnsafeEnabled { + mi := &file_mi_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Event) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Event) ProtoMessage() {} + +func (x *Event) ProtoReflect() protoreflect.Message { + mi := &file_mi_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 Event.ProtoReflect.Descriptor instead. +func (*Event) Descriptor() ([]byte, []int) { + return file_mi_proto_rawDescGZIP(), []int{0} +} + +func (x *Event) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Event) GetUrl() string { + if x != nil { + return x.Url + } + return "" +} + +func (x *Event) GetStartDate() *timestamppb.Timestamp { + if x != nil { + return x.StartDate + } + return nil +} + +func (x *Event) GetEndDate() *timestamppb.Timestamp { + if x != nil { + return x.EndDate + } + return nil +} + +func (x *Event) GetLocation() string { + if x != nil { + return x.Location + } + return "" +} + +func (x *Event) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Event) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +// A feed of events, result from mi query. +type EventFeed struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The events in the feed + Events []*Event `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` +} + +func (x *EventFeed) Reset() { + *x = EventFeed{} + if protoimpl.UnsafeEnabled { + mi := &file_mi_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EventFeed) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EventFeed) ProtoMessage() {} + +func (x *EventFeed) ProtoReflect() protoreflect.Message { + mi := &file_mi_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 EventFeed.ProtoReflect.Descriptor instead. +func (*EventFeed) Descriptor() ([]byte, []int) { + return file_mi_proto_rawDescGZIP(), []int{1} +} + +func (x *EventFeed) GetEvents() []*Event { + if x != nil { + return x.Events + } + return nil +} + +var File_mi_proto protoreflect.FileDescriptor + +var file_mi_proto_rawDesc = []byte{ + 0x0a, 0x08, 0x6d, 0x69, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x13, 0x77, 0x69, 0x74, 0x68, + 0x69, 0x6e, 0x2e, 0x77, 0x65, 0x62, 0x73, 0x69, 0x74, 0x65, 0x2e, 0x78, 0x2e, 0x6d, 0x69, 0x1a, + 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xed, 0x01, + 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x75, + 0x72, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x39, 0x0a, + 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x44, 0x61, 0x74, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, + 0x64, 0x61, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, + 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x44, 0x61, 0x74, 0x65, 0x12, + 0x1a, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x02, 0x69, + 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x64, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3f, 0x0a, + 0x09, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x46, 0x65, 0x65, 0x64, 0x12, 0x32, 0x0a, 0x06, 0x65, 0x76, + 0x65, 0x6e, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x77, 0x69, 0x74, + 0x68, 0x69, 0x6e, 0x2e, 0x77, 0x65, 0x62, 0x73, 0x69, 0x74, 0x65, 0x2e, 0x78, 0x2e, 0x6d, 0x69, + 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x42, 0x1e, + 0x5a, 0x1c, 0x78, 0x65, 0x69, 0x61, 0x73, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x2f, 0x76, 0x34, 0x2f, + 0x70, 0x62, 0x2f, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x6d, 0x69, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_mi_proto_rawDescOnce sync.Once + file_mi_proto_rawDescData = file_mi_proto_rawDesc +) + +func file_mi_proto_rawDescGZIP() []byte { + file_mi_proto_rawDescOnce.Do(func() { + file_mi_proto_rawDescData = protoimpl.X.CompressGZIP(file_mi_proto_rawDescData) + }) + return file_mi_proto_rawDescData +} + +var file_mi_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_mi_proto_goTypes = []interface{}{ + (*Event)(nil), // 0: within.website.x.mi.Event + (*EventFeed)(nil), // 1: within.website.x.mi.EventFeed + (*timestamppb.Timestamp)(nil), // 2: google.protobuf.Timestamp +} +var file_mi_proto_depIdxs = []int32{ + 2, // 0: within.website.x.mi.Event.start_date:type_name -> google.protobuf.Timestamp + 2, // 1: within.website.x.mi.Event.end_date:type_name -> google.protobuf.Timestamp + 0, // 2: within.website.x.mi.EventFeed.events:type_name -> within.website.x.mi.Event + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_mi_proto_init() } +func file_mi_proto_init() { + if File_mi_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_mi_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Event); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_mi_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EventFeed); 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_mi_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_mi_proto_goTypes, + DependencyIndexes: file_mi_proto_depIdxs, + MessageInfos: file_mi_proto_msgTypes, + }.Build() + File_mi_proto = out.File + file_mi_proto_rawDesc = nil + file_mi_proto_goTypes = nil + file_mi_proto_depIdxs = nil +} diff --git a/pb/external/mi/mi.twirp.go b/pb/external/mi/mi.twirp.go new file mode 100644 index 0000000..d650b2d --- /dev/null +++ b/pb/external/mi/mi.twirp.go @@ -0,0 +1,1115 @@ +// Code generated by protoc-gen-twirp v8.1.3, DO NOT EDIT. +// source: mi.proto + +package mi + +import context "context" +import fmt "fmt" +import http "net/http" +import io "io" +import json "encoding/json" +import strconv "strconv" +import strings "strings" + +import protojson "google.golang.org/protobuf/encoding/protojson" +import proto "google.golang.org/protobuf/proto" +import twirp "github.com/twitchtv/twirp" +import ctxsetters "github.com/twitchtv/twirp/ctxsetters" + +import google_protobuf "google.golang.org/protobuf/types/known/emptypb" + +import bytes "bytes" +import errors "errors" +import path "path" +import url "net/url" + +// Version compatibility assertion. +// If the constant is not defined in the package, that likely means +// the package needs to be updated to work with this generated code. +// See https://twitchtv.github.io/twirp/docs/version_matrix.html +const _ = twirp.TwirpPackageMinVersion_8_1_0 + +// ================ +// Events Interface +// ================ + +// Events lets users fetch the current feed of events that Xe will be attending. +type Events interface { + // Get fetches the current feed of upcoming events. + Get(context.Context, *google_protobuf.Empty) (*EventFeed, error) +} + +// ====================== +// Events Protobuf Client +// ====================== + +type eventsProtobufClient struct { + client HTTPClient + urls [1]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewEventsProtobufClient creates a Protobuf client that implements the Events interface. +// It communicates using Protobuf and can be configured with a custom HTTPClient. +func NewEventsProtobufClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) Events { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "within.website.x.mi", "Events") + urls := [1]string{ + serviceURL + "Get", + } + + return &eventsProtobufClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *eventsProtobufClient) Get(ctx context.Context, in *google_protobuf.Empty) (*EventFeed, error) { + ctx = ctxsetters.WithPackageName(ctx, "within.website.x.mi") + ctx = ctxsetters.WithServiceName(ctx, "Events") + ctx = ctxsetters.WithMethodName(ctx, "Get") + caller := c.callGet + if c.interceptor != nil { + caller = func(ctx context.Context, req *google_protobuf.Empty) (*EventFeed, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*google_protobuf.Empty) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*google_protobuf.Empty) when calling interceptor") + } + return c.callGet(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*EventFeed) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*EventFeed) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *eventsProtobufClient) callGet(ctx context.Context, in *google_protobuf.Empty) (*EventFeed, error) { + out := new(EventFeed) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// ================== +// Events JSON Client +// ================== + +type eventsJSONClient struct { + client HTTPClient + urls [1]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewEventsJSONClient creates a JSON client that implements the Events interface. +// It communicates using JSON and can be configured with a custom HTTPClient. +func NewEventsJSONClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) Events { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "within.website.x.mi", "Events") + urls := [1]string{ + serviceURL + "Get", + } + + return &eventsJSONClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *eventsJSONClient) Get(ctx context.Context, in *google_protobuf.Empty) (*EventFeed, error) { + ctx = ctxsetters.WithPackageName(ctx, "within.website.x.mi") + ctx = ctxsetters.WithServiceName(ctx, "Events") + ctx = ctxsetters.WithMethodName(ctx, "Get") + caller := c.callGet + if c.interceptor != nil { + caller = func(ctx context.Context, req *google_protobuf.Empty) (*EventFeed, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*google_protobuf.Empty) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*google_protobuf.Empty) when calling interceptor") + } + return c.callGet(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*EventFeed) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*EventFeed) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *eventsJSONClient) callGet(ctx context.Context, in *google_protobuf.Empty) (*EventFeed, error) { + out := new(EventFeed) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// ===================== +// Events Server Handler +// ===================== + +type eventsServer struct { + Events + interceptor twirp.Interceptor + hooks *twirp.ServerHooks + pathPrefix string // prefix for routing + jsonSkipDefaults bool // do not include unpopulated fields (default values) in the response + jsonCamelCase bool // JSON fields are serialized as lowerCamelCase rather than keeping the original proto names +} + +// NewEventsServer builds a TwirpServer that can be used as an http.Handler to handle +// HTTP requests that are routed to the right method in the provided svc implementation. +// The opts are twirp.ServerOption modifiers, for example twirp.WithServerHooks(hooks). +func NewEventsServer(svc Events, opts ...interface{}) TwirpServer { + serverOpts := newServerOpts(opts) + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + jsonSkipDefaults := false + _ = serverOpts.ReadOpt("jsonSkipDefaults", &jsonSkipDefaults) + jsonCamelCase := false + _ = serverOpts.ReadOpt("jsonCamelCase", &jsonCamelCase) + var pathPrefix string + if ok := serverOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + return &eventsServer{ + Events: svc, + hooks: serverOpts.Hooks, + interceptor: twirp.ChainInterceptors(serverOpts.Interceptors...), + pathPrefix: pathPrefix, + jsonSkipDefaults: jsonSkipDefaults, + jsonCamelCase: jsonCamelCase, + } +} + +// writeError writes an HTTP response with a valid Twirp error format, and triggers hooks. +// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) +func (s *eventsServer) writeError(ctx context.Context, resp http.ResponseWriter, err error) { + writeError(ctx, resp, err, s.hooks) +} + +// handleRequestBodyError is used to handle error when the twirp server cannot read request +func (s *eventsServer) handleRequestBodyError(ctx context.Context, resp http.ResponseWriter, msg string, err error) { + if context.Canceled == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.Canceled, "failed to read request: context canceled")) + return + } + if context.DeadlineExceeded == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.DeadlineExceeded, "failed to read request: deadline exceeded")) + return + } + s.writeError(ctx, resp, twirp.WrapError(malformedRequestError(msg), err)) +} + +// EventsPathPrefix is a convenience constant that may identify URL paths. +// Should be used with caution, it only matches routes generated by Twirp Go clients, +// with the default "/twirp" prefix and default CamelCase service and method names. +// More info: https://twitchtv.github.io/twirp/docs/routing.html +const EventsPathPrefix = "/twirp/within.website.x.mi.Events/" + +func (s *eventsServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + ctx := req.Context() + ctx = ctxsetters.WithPackageName(ctx, "within.website.x.mi") + ctx = ctxsetters.WithServiceName(ctx, "Events") + ctx = ctxsetters.WithResponseWriter(ctx, resp) + + var err error + ctx, err = callRequestReceived(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + if req.Method != "POST" { + msg := fmt.Sprintf("unsupported method %q (only POST is allowed)", req.Method) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + // Verify path format: [<prefix>]/<package>.<Service>/<Method> + prefix, pkgService, method := parseTwirpPath(req.URL.Path) + if pkgService != "within.website.x.mi.Events" { + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + if prefix != s.pathPrefix { + msg := fmt.Sprintf("invalid path prefix %q, expected %q, on path %q", prefix, s.pathPrefix, req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + switch method { + case "Get": + s.serveGet(ctx, resp, req) + return + default: + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } +} + +func (s *eventsServer) serveGet(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveGetJSON(ctx, resp, req) + case "application/protobuf": + s.serveGetProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *eventsServer) serveGetJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "Get") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(google_protobuf.Empty) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.Events.Get + if s.interceptor != nil { + handler = func(ctx context.Context, req *google_protobuf.Empty) (*EventFeed, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*google_protobuf.Empty) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*google_protobuf.Empty) when calling interceptor") + } + return s.Events.Get(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*EventFeed) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*EventFeed) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *EventFeed + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *EventFeed and nil error while calling Get. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *eventsServer) serveGetProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "Get") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(google_protobuf.Empty) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.Events.Get + if s.interceptor != nil { + handler = func(ctx context.Context, req *google_protobuf.Empty) (*EventFeed, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*google_protobuf.Empty) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*google_protobuf.Empty) when calling interceptor") + } + return s.Events.Get(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*EventFeed) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*EventFeed) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *EventFeed + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *EventFeed and nil error while calling Get. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *eventsServer) ServiceDescriptor() ([]byte, int) { + return twirpFileDescriptor0, 0 +} + +func (s *eventsServer) ProtocGenTwirpVersion() string { + return "v8.1.3" +} + +// PathPrefix returns the base service path, in the form: "/<prefix>/<package>.<Service>/" +// that is everything in a Twirp route except for the <Method>. This can be used for routing, +// for example to identify the requests that are targeted to this service in a mux. +func (s *eventsServer) PathPrefix() string { + return baseServicePath(s.pathPrefix, "within.website.x.mi", "Events") +} + +// ===== +// Utils +// ===== + +// HTTPClient is the interface used by generated clients to send HTTP requests. +// It is fulfilled by *(net/http).Client, which is sufficient for most users. +// Users can provide their own implementation for special retry policies. +// +// HTTPClient implementations should not follow redirects. Redirects are +// automatically disabled if *(net/http).Client is passed to client +// constructors. See the withoutRedirects function in this file for more +// details. +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +// TwirpServer is the interface generated server structs will support: they're +// HTTP handlers with additional methods for accessing metadata about the +// service. Those accessors are a low-level API for building reflection tools. +// Most people can think of TwirpServers as just http.Handlers. +type TwirpServer interface { + http.Handler + + // ServiceDescriptor returns gzipped bytes describing the .proto file that + // this service was generated from. Once unzipped, the bytes can be + // unmarshalled as a + // google.golang.org/protobuf/types/descriptorpb.FileDescriptorProto. + // + // The returned integer is the index of this particular service within that + // FileDescriptorProto's 'Service' slice of ServiceDescriptorProtos. This is a + // low-level field, expected to be used for reflection. + ServiceDescriptor() ([]byte, int) + + // ProtocGenTwirpVersion is the semantic version string of the version of + // twirp used to generate this file. + ProtocGenTwirpVersion() string + + // PathPrefix returns the HTTP URL path prefix for all methods handled by this + // service. This can be used with an HTTP mux to route Twirp requests. + // The path prefix is in the form: "/<prefix>/<package>.<Service>/" + // that is, everything in a Twirp route except for the <Method> at the end. + PathPrefix() string +} + +func newServerOpts(opts []interface{}) *twirp.ServerOptions { + serverOpts := &twirp.ServerOptions{} + for _, opt := range opts { + switch o := opt.(type) { + case twirp.ServerOption: + o(serverOpts) + case *twirp.ServerHooks: // backwards compatibility, allow to specify hooks as an argument + twirp.WithServerHooks(o)(serverOpts) + case nil: // backwards compatibility, allow nil value for the argument + continue + default: + panic(fmt.Sprintf("Invalid option type %T, please use a twirp.ServerOption", o)) + } + } + return serverOpts +} + +// WriteError writes an HTTP response with a valid Twirp error format (code, msg, meta). +// Useful outside of the Twirp server (e.g. http middleware), but does not trigger hooks. +// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) +func WriteError(resp http.ResponseWriter, err error) { + writeError(context.Background(), resp, err, nil) +} + +// writeError writes Twirp errors in the response and triggers hooks. +func writeError(ctx context.Context, resp http.ResponseWriter, err error, hooks *twirp.ServerHooks) { + // Convert to a twirp.Error. Non-twirp errors are converted to internal errors. + var twerr twirp.Error + if !errors.As(err, &twerr) { + twerr = twirp.InternalErrorWith(err) + } + + statusCode := twirp.ServerHTTPStatusFromErrorCode(twerr.Code()) + ctx = ctxsetters.WithStatusCode(ctx, statusCode) + ctx = callError(ctx, hooks, twerr) + + respBody := marshalErrorToJSON(twerr) + + resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON + resp.Header().Set("Content-Length", strconv.Itoa(len(respBody))) + resp.WriteHeader(statusCode) // set HTTP status code and send response + + _, writeErr := resp.Write(respBody) + if writeErr != nil { + // We have three options here. We could log the error, call the Error + // hook, or just silently ignore the error. + // + // Logging is unacceptable because we don't have a user-controlled + // logger; writing out to stderr without permission is too rude. + // + // Calling the Error hook would confuse users: it would mean the Error + // hook got called twice for one request, which is likely to lead to + // duplicated log messages and metrics, no matter how well we document + // the behavi |
