aboutsummaryrefslogtreecommitdiff
path: root/pb
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2024-02-12 04:32:43 -0800
committerXe Iaso <me@xeiaso.net>2024-02-12 04:32:43 -0800
commite02b9ef3ee4394db1a387b146aa5faeea95efa3a (patch)
treee5b6f2c7c21dda6a5e4ea1617e10e3437c93979c /pb
parent0eb26108f65b68aa4e99786f7f7a0b28cd356f72 (diff)
downloadxesite-e02b9ef3ee4394db1a387b146aa5faeea95efa3a.tar.xz
xesite-e02b9ef3ee4394db1a387b146aa5faeea95efa3a.zip
cmd/patreon-saasproxy: use twirp/protobuf instead of yolo json
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'pb')
-rw-r--r--pb/generate.go5
-rw-r--r--pb/xesite.pb.go189
-rw-r--r--pb/xesite.proto17
-rw-r--r--pb/xesite.twirp.go1109
4 files changed, 1320 insertions, 0 deletions
diff --git a/pb/generate.go b/pb/generate.go
new file mode 100644
index 0000000..5adfc1a
--- /dev/null
+++ b/pb/generate.go
@@ -0,0 +1,5 @@
+package pb
+
+func init() {}
+
+//go:generate protoc --proto_path=. --go_out=. --go_opt=paths=source_relative --twirp_out=. --twirp_opt=paths=source_relative xesite.proto
diff --git a/pb/xesite.pb.go b/pb/xesite.pb.go
new file mode 100644
index 0000000..1691ffd
--- /dev/null
+++ b/pb/xesite.pb.go
@@ -0,0 +1,189 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.32.0
+// protoc v4.24.4
+// source: xesite.proto
+
+package pb
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ emptypb "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)
+)
+
+type BuildInfo struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Commit string `protobuf:"bytes,1,opt,name=commit,proto3" json:"commit,omitempty"`
+ BuildTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=build_time,json=buildTime,proto3" json:"build_time,omitempty"`
+ GoVersion string `protobuf:"bytes,3,opt,name=go_version,json=goVersion,proto3" json:"go_version,omitempty"`
+ DenoVersion string `protobuf:"bytes,4,opt,name=deno_version,json=denoVersion,proto3" json:"deno_version,omitempty"`
+}
+
+func (x *BuildInfo) Reset() {
+ *x = BuildInfo{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_xesite_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *BuildInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BuildInfo) ProtoMessage() {}
+
+func (x *BuildInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_xesite_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 BuildInfo.ProtoReflect.Descriptor instead.
+func (*BuildInfo) Descriptor() ([]byte, []int) {
+ return file_xesite_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *BuildInfo) GetCommit() string {
+ if x != nil {
+ return x.Commit
+ }
+ return ""
+}
+
+func (x *BuildInfo) GetBuildTime() *timestamppb.Timestamp {
+ if x != nil {
+ return x.BuildTime
+ }
+ return nil
+}
+
+func (x *BuildInfo) GetGoVersion() string {
+ if x != nil {
+ return x.GoVersion
+ }
+ return ""
+}
+
+func (x *BuildInfo) GetDenoVersion() string {
+ if x != nil {
+ return x.DenoVersion
+ }
+ return ""
+}
+
+var File_xesite_proto protoreflect.FileDescriptor
+
+var file_xesite_proto_rawDesc = []byte{
+ 0x0a, 0x0c, 0x78, 0x65, 0x73, 0x69, 0x74, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a,
+ 0x78, 0x65, 0x69, 0x61, 0x73, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 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, 0xa0, 0x01, 0x0a, 0x09, 0x42, 0x75, 0x69,
+ 0x6c, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x16, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74,
+ 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x12, 0x39,
+ 0x0a, 0x0a, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 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,
+ 0x62, 0x75, 0x69, 0x6c, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x67, 0x6f, 0x5f,
+ 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x67,
+ 0x6f, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x65, 0x6e, 0x6f,
+ 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b,
+ 0x64, 0x65, 0x6e, 0x6f, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x32, 0x41, 0x0a, 0x04, 0x4c,
+ 0x75, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x08, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12,
+ 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
+ 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x15, 0x2e, 0x78, 0x65, 0x69, 0x61, 0x73, 0x6f,
+ 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x42, 0x12,
+ 0x5a, 0x10, 0x78, 0x65, 0x69, 0x61, 0x73, 0x6f, 0x2e, 0x6e, 0x65, 0x74, 0x2f, 0x76, 0x34, 0x2f,
+ 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+ file_xesite_proto_rawDescOnce sync.Once
+ file_xesite_proto_rawDescData = file_xesite_proto_rawDesc
+)
+
+func file_xesite_proto_rawDescGZIP() []byte {
+ file_xesite_proto_rawDescOnce.Do(func() {
+ file_xesite_proto_rawDescData = protoimpl.X.CompressGZIP(file_xesite_proto_rawDescData)
+ })
+ return file_xesite_proto_rawDescData
+}
+
+var file_xesite_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
+var file_xesite_proto_goTypes = []interface{}{
+ (*BuildInfo)(nil), // 0: xeiaso.net.BuildInfo
+ (*timestamppb.Timestamp)(nil), // 1: google.protobuf.Timestamp
+ (*emptypb.Empty)(nil), // 2: google.protobuf.Empty
+}
+var file_xesite_proto_depIdxs = []int32{
+ 1, // 0: xeiaso.net.BuildInfo.build_time:type_name -> google.protobuf.Timestamp
+ 2, // 1: xeiaso.net.Lume.Metadata:input_type -> google.protobuf.Empty
+ 0, // 2: xeiaso.net.Lume.Metadata:output_type -> xeiaso.net.BuildInfo
+ 2, // [2:3] is the sub-list for method output_type
+ 1, // [1:2] is the sub-list for method input_type
+ 1, // [1:1] is the sub-list for extension type_name
+ 1, // [1:1] is the sub-list for extension extendee
+ 0, // [0:1] is the sub-list for field type_name
+}
+
+func init() { file_xesite_proto_init() }
+func file_xesite_proto_init() {
+ if File_xesite_proto != nil {
+ return
+ }
+ if !protoimpl.UnsafeEnabled {
+ file_xesite_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*BuildInfo); 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_xesite_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 1,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_xesite_proto_goTypes,
+ DependencyIndexes: file_xesite_proto_depIdxs,
+ MessageInfos: file_xesite_proto_msgTypes,
+ }.Build()
+ File_xesite_proto = out.File
+ file_xesite_proto_rawDesc = nil
+ file_xesite_proto_goTypes = nil
+ file_xesite_proto_depIdxs = nil
+}
diff --git a/pb/xesite.proto b/pb/xesite.proto
new file mode 100644
index 0000000..a1fac69
--- /dev/null
+++ b/pb/xesite.proto
@@ -0,0 +1,17 @@
+syntax = "proto3";
+package xeiaso.net;
+option go_package = "xeiaso.net/v4/pb";
+
+import "google/protobuf/empty.proto";
+import "google/protobuf/timestamp.proto";
+
+service Lume {
+ rpc Metadata(google.protobuf.Empty) returns (BuildInfo);
+}
+
+message BuildInfo {
+ string commit = 1;
+ google.protobuf.Timestamp build_time = 2;
+ string go_version = 3;
+ string deno_version = 4;
+} \ No newline at end of file
diff --git a/pb/xesite.twirp.go b/pb/xesite.twirp.go
new file mode 100644
index 0000000..a1b59be
--- /dev/null
+++ b/pb/xesite.twirp.go
@@ -0,0 +1,1109 @@
+// Code generated by protoc-gen-twirp v8.1.3, DO NOT EDIT.
+// source: xesite.proto
+
+package pb
+
+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
+
+// ==============
+// Lume Interface
+// ==============
+
+type Lume interface {
+ Metadata(context.Context, *google_protobuf.Empty) (*BuildInfo, error)
+}
+
+// ====================
+// Lume Protobuf Client
+// ====================
+
+type lumeProtobufClient struct {
+ client HTTPClient
+ urls [1]string
+ interceptor twirp.Interceptor
+ opts twirp.ClientOptions
+}
+
+// NewLumeProtobufClient creates a Protobuf client that implements the Lume interface.
+// It communicates using Protobuf and can be configured with a custom HTTPClient.
+func NewLumeProtobufClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) Lume {
+ 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, "xeiaso.net", "Lume")
+ urls := [1]string{
+ serviceURL + "Metadata",
+ }
+
+ return &lumeProtobufClient{
+ client: client,
+ urls: urls,
+ interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...),
+ opts: clientOpts,
+ }
+}
+
+func (c *lumeProtobufClient) Metadata(ctx context.Context, in *google_protobuf.Empty) (*BuildInfo, error) {
+ ctx = ctxsetters.WithPackageName(ctx, "xeiaso.net")
+ ctx = ctxsetters.WithServiceName(ctx, "Lume")
+ ctx = ctxsetters.WithMethodName(ctx, "Metadata")
+ caller := c.callMetadata
+ if c.interceptor != nil {
+ caller = func(ctx context.Context, req *google_protobuf.Empty) (*BuildInfo, 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.callMetadata(ctx, typedReq)
+ },
+ )(ctx, req)
+ if resp != nil {
+ typedResp, ok := resp.(*BuildInfo)
+ if !ok {
+ return nil, twirp.InternalError("failed type assertion resp.(*BuildInfo) when calling interceptor")
+ }
+ return typedResp, err
+ }
+ return nil, err
+ }
+ }
+ return caller(ctx, in)
+}
+
+func (c *lumeProtobufClient) callMetadata(ctx context.Context, in *google_protobuf.Empty) (*BuildInfo, error) {
+ out := new(BuildInfo)
+ 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
+}
+
+// ================
+// Lume JSON Client
+// ================
+
+type lumeJSONClient struct {
+ client HTTPClient
+ urls [1]string
+ interceptor twirp.Interceptor
+ opts twirp.ClientOptions
+}
+
+// NewLumeJSONClient creates a JSON client that implements the Lume interface.
+// It communicates using JSON and can be configured with a custom HTTPClient.
+func NewLumeJSONClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) Lume {
+ 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, "xeiaso.net", "Lume")
+ urls := [1]string{
+ serviceURL + "Metadata",
+ }
+
+ return &lumeJSONClient{
+ client: client,
+ urls: urls,
+ interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...),
+ opts: clientOpts,
+ }
+}
+
+func (c *lumeJSONClient) Metadata(ctx context.Context, in *google_protobuf.Empty) (*BuildInfo, error) {
+ ctx = ctxsetters.WithPackageName(ctx, "xeiaso.net")
+ ctx = ctxsetters.WithServiceName(ctx, "Lume")
+ ctx = ctxsetters.WithMethodName(ctx, "Metadata")
+ caller := c.callMetadata
+ if c.interceptor != nil {
+ caller = func(ctx context.Context, req *google_protobuf.Empty) (*BuildInfo, 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.callMetadata(ctx, typedReq)
+ },
+ )(ctx, req)
+ if resp != nil {
+ typedResp, ok := resp.(*BuildInfo)
+ if !ok {
+ return nil, twirp.InternalError("failed type assertion resp.(*BuildInfo) when calling interceptor")
+ }
+ return typedResp, err
+ }
+ return nil, err
+ }
+ }
+ return caller(ctx, in)
+}
+
+func (c *lumeJSONClient) callMetadata(ctx context.Context, in *google_protobuf.Empty) (*BuildInfo, error) {
+ out := new(BuildInfo)
+ 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
+}
+
+// ===================
+// Lume Server Handler
+// ===================
+
+type lumeServer struct {
+ Lume
+ 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
+}
+
+// NewLumeServer 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 NewLumeServer(svc Lume, 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 &lumeServer{
+ Lume: 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 *lumeServer) 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 *lumeServer) 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))
+}
+
+// LumePathPrefix 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 LumePathPrefix = "/twirp/xeiaso.net.Lume/"
+
+func (s *lumeServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
+ ctx := req.Context()
+ ctx = ctxsetters.WithPackageName(ctx, "xeiaso.net")
+ ctx = ctxsetters.WithServiceName(ctx, "Lume")
+ 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 != "xeiaso.net.Lume" {
+ 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 "Metadata":
+ s.serveMetadata(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 *lumeServer) serveMetadata(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.serveMetadataJSON(ctx, resp, req)
+ case "application/protobuf":
+ s.serveMetadataProtobuf(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 *lumeServer) serveMetadataJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) {
+ var err error
+ ctx = ctxsetters.WithMethodName(ctx, "Metadata")
+ 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.Lume.Metadata
+ if s.interceptor != nil {
+ handler = func(ctx context.Context, req *google_protobuf.Empty) (*BuildInfo, 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.Lume.Metadata(ctx, typedReq)
+ },
+ )(ctx, req)
+ if resp != nil {
+ typedResp, ok := resp.(*BuildInfo)
+ if !ok {
+ return nil, twirp.InternalError("failed type assertion resp.(*BuildInfo) when calling interceptor")
+ }
+ return typedResp, err
+ }
+ return nil, err
+ }
+ }
+
+ // Call service method
+ var respContent *BuildInfo
+ 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 *BuildInfo and nil error while calling Metadata. 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 *lumeServer) serveMetadataProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) {
+ var err error
+ ctx = ctxsetters.WithMethodName(ctx, "Metadata")
+ 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.Lume.Metadata
+ if s.interceptor != nil {
+ handler = func(ctx context.Context, req *google_protobuf.Empty) (*BuildInfo, 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.Lume.Metadata(ctx, typedReq)
+ },
+ )(ctx, req)
+ if resp != nil {
+ typedResp, ok := resp.(*BuildInfo)
+ if !ok {
+ return nil, twirp.InternalError("failed type assertion resp.(*BuildInfo) when calling interceptor")
+ }
+ return typedResp, err
+ }
+ return nil, err
+ }
+ }
+
+ // Call service method
+ var respContent *BuildInfo
+ 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 *BuildInfo and nil error while calling Metadata. 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 *lumeServer) ServiceDescriptor() ([]byte, int) {
+ return twirpFileDescriptor0, 0
+}
+
+func (s *lumeServer) 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 *lumeServer) PathPrefix() string {
+ return baseServicePath(s.pathPrefix, "xeiaso.net", "Lume")
+}
+
+// =====
+// 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 behavior.
+ //
+ // Silently ignoring the error is our least-bad option. It's highly
+ // likely that the connection is broken and the original 'err' says
+ // so anyway.
+ _ = writeErr
+ }
+
+ callResponseSent(ctx, hooks)
+}
+
+// sanitizeBaseURL parses the the baseURL, and adds the "http" scheme if needed.
+// If the URL is unparsable, the baseURL is returned unchanged.
+func sanitizeBaseURL(baseURL string) string {
+ u, err := url.Parse(baseURL)
+ if err != nil {
+ return baseURL // invalid URL will fail later when making requests
+ }
+ if u.Scheme == "" {
+ u.Scheme = "http"
+ }
+ return u.String()
+}
+
+// baseServicePath composes the path prefix for the service (without <Method>).
+// e.g.: baseServicePath("/twirp", "my.pkg", "MyService")
+//
+// returns => "/twirp/my.pkg.MyService/"
+//
+// e.g.: baseServicePath("", "", "MyService")
+//
+// returns => "/MyService/"
+func baseServicePath(prefix, pkg, service string) string {
+ fullServiceName := service
+ if pkg != "" {
+ fullServiceName = pkg + "." + service
+ }
+ return path.Join("/", prefix, fullServiceName) + "/"
+}
+
+// parseTwirpPath extracts path components form a valid Twirp route.
+// Expected format: "[<prefix>]/<package>.<Service>/<Method>"
+// e.g.: prefix, pkgService, method := parseTwirpPath("/twirp/pkg.Svc/MakeHat")
+func parseTwirpPath(path string) (string, string, string) {
+ parts := strings.Split(path, "/")
+ if len(parts) < 2 {
+ return "", "", ""
+ }
+ method := parts[len(parts)-1]
+ pkgService := parts[len(parts)-2]
+ prefix := strings.Join(parts[0:len(parts)-2], "/")
+ return prefix, pkgService, method
+}
+
+// getCustomHTTPReqHeaders retrieves a copy of any headers that are set in
+// a context through the twirp.WithHTTPRequestHeaders function.
+// If there are no headers set, or if they have the wrong type, nil is returned.
+func getCustomHTTPReqHeaders(ctx context.Context) http.Header {
+ header, ok := twirp.HTTPRequestHeaders(ctx)
+ if !ok || header == nil {
+ return nil
+ }
+ copied := make(http.Header)
+ for k, vv := range header {
+ if vv == nil {
+ copied[k] = nil
+ continue
+ }
+ copied[k] = make([]string, len(vv))
+ copy(copied[k], vv)
+ }
+ return copied
+}
+
+// newRequest makes an http.Request from a client, adding common headers.
+func newRequest(ctx context.Context, url string, reqBody io.Reader, contentType string) (*http.Request, error) {
+ req, err := http.NewRequest("POST", url, reqBody)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if customHeader := getCustomHTTPReqHeaders(ctx); customHeader != nil {
+ req.Header = customHeader
+ }
+ req.Header.Set("Accept", contentType)
+ req.Header.Set("Content-Type", contentType)
+ req.Header.Set("Twirp-Version", "v8.1.3")
+ return req, nil
+}
+
+// JSON serialization for errors
+type twerrJSON struct {
+ Code string `json:"code"`
+ Msg string `json:"msg"`
+ Meta map[string]string `json:"meta,omitempty"`
+}
+
+// marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body.
+// If serialization fails, it will use a descriptive Internal error instead.
+func marshalErrorToJSON(twerr twirp.Error) []byte {
+ // make sure that msg is not too large
+ msg := twerr.Msg()
+ if len(msg) > 1e6 {
+ msg = msg[:1e6]
+ }
+
+ tj := twerrJSON{
+ Code: string(twerr.Code()),
+ Msg: msg,
+ Meta: twerr.MetaMap(),
+ }
+
+ buf, err := json.Marshal(&tj)
+ if err != nil {
+ buf = []byte("{\"type\": \"" + twirp.Internal + "\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback
+ }
+
+ return buf
+}
+
+// errorFromResponse builds a twirp.Error from a non-200 HTTP response.
+// If the response has a valid serialized Twirp error, then it's returned.
+// If not, the response status code is used to generate a similar twirp
+// error. See twirpErrorFromIntermediary for more info on intermediary errors.
+func errorFromResponse(resp *http.Response) twirp.Error {
+ statusCode := resp.StatusCode
+ statusText := http.StatusText(statusCode)
+
+ if isHTTPRedirect(statusCode) {
+ // Unexpected redirect: it must be an error from an intermediary.
+ // Twirp clients don't follow redirects automatically, Twirp only handles
+ // POST requests, redirects should only happen on GET and HEAD requests.
+ location := resp.Header.Get("Location")
+ msg := fmt.Sprintf("unexpected HTTP status code %d %q received, Location=%q", statusCode, statusText, location)
+ return twirpErrorFromIntermediary(statusCode, msg, location)