trpc.group/trpc-go/trpc-go@v1.0.3/server/options.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package server
    15  
    16  import (
    17  	"context"
    18  	"net"
    19  	"time"
    20  
    21  	"trpc.group/trpc-go/trpc-go/codec"
    22  	"trpc.group/trpc-go/trpc-go/filter"
    23  	"trpc.group/trpc-go/trpc-go/naming/registry"
    24  	"trpc.group/trpc-go/trpc-go/restful"
    25  	"trpc.group/trpc-go/trpc-go/transport"
    26  )
    27  
    28  // Options are server side options.
    29  type Options struct {
    30  	container string // container name
    31  
    32  	Namespace   string // namespace like "Production", "Development" etc.
    33  	EnvName     string // environment name
    34  	SetName     string // "Set" name
    35  	ServiceName string // service name
    36  
    37  	Address                  string        // listen address, ip:port
    38  	Timeout                  time.Duration // timeout for handling a request
    39  	DisableRequestTimeout    bool          // whether to disable request timeout that inherits from upstream
    40  	DisableKeepAlives        bool          // disables keep-alives
    41  	CurrentSerializationType int
    42  	CurrentCompressType      int
    43  
    44  	protocol   string // protocol like "trpc", "http" etc.
    45  	network    string // network like "tcp", "udp" etc.
    46  	handlerSet bool   // whether that custom handler is set
    47  
    48  	ServeOptions []transport.ListenServeOption
    49  	Transport    transport.ServerTransport
    50  
    51  	Registry registry.Registry
    52  	Codec    codec.Codec
    53  
    54  	Filters          filter.ServerChain              // filter chain
    55  	FilterNames      []string                        // the name of filters
    56  	StreamHandle     StreamHandle                    // server stream processing
    57  	StreamTransport  transport.ServerStreamTransport // server stream transport plugin
    58  	MaxWindowSize    uint32                          // max window size for server stream
    59  	CloseWaitTime    time.Duration                   // min waiting time when closing server for wait deregister finish
    60  	MaxCloseWaitTime time.Duration                   // max waiting time when closing server for wait requests finish
    61  
    62  	RESTOptions   []restful.Option // RESTful router options
    63  	StreamFilters StreamFilterChain
    64  }
    65  
    66  // StreamHandle is the interface that defines server stream processing.
    67  type StreamHandle interface {
    68  	// StreamHandleFunc does server stream processing.
    69  	StreamHandleFunc(ctx context.Context, sh StreamHandler, si *StreamServerInfo, req []byte) ([]byte, error)
    70  	// Init does the initialization, mainly passing and saving Options.
    71  	Init(opts *Options) error
    72  }
    73  
    74  // Option sets server options.
    75  type Option func(*Options)
    76  
    77  // WithNamespace returns an Option that sets namespace for server.
    78  func WithNamespace(namespace string) Option {
    79  	return func(o *Options) {
    80  		o.Namespace = namespace
    81  	}
    82  }
    83  
    84  // WithStreamTransport returns an Option that sets transport.ServerStreamTransport for server.
    85  func WithStreamTransport(st transport.ServerStreamTransport) Option {
    86  	return func(o *Options) {
    87  		o.StreamTransport = st
    88  	}
    89  }
    90  
    91  // WithEnvName returns an Option that sets environment name.
    92  func WithEnvName(envName string) Option {
    93  	return func(o *Options) {
    94  		o.EnvName = envName
    95  	}
    96  }
    97  
    98  // WithContainer returns an Option that sets container name.
    99  func WithContainer(container string) Option {
   100  	return func(o *Options) {
   101  		o.container = container
   102  	}
   103  }
   104  
   105  // WithSetName returns an Option that sets "Set" name.
   106  func WithSetName(setName string) Option {
   107  	return func(o *Options) {
   108  		o.SetName = setName
   109  	}
   110  }
   111  
   112  // WithServiceName returns an Option that sets service name.
   113  func WithServiceName(s string) Option {
   114  	return func(o *Options) {
   115  		o.ServiceName = s
   116  		o.ServeOptions = append(o.ServeOptions, transport.WithServiceName(s))
   117  	}
   118  }
   119  
   120  // WithFilter returns an Option that adds a filter.Filter (pre or post).
   121  func WithFilter(f filter.ServerFilter) Option {
   122  	return func(o *Options) {
   123  		const filterName = "server.WithFilter"
   124  		o.Filters = append(o.Filters, f)
   125  		o.FilterNames = append(o.FilterNames, filterName)
   126  	}
   127  }
   128  
   129  // WithNamedFilter returns an Option that adds named filter
   130  func WithNamedFilter(name string, f filter.ServerFilter) Option {
   131  	return func(o *Options) {
   132  		o.Filters = append(o.Filters, f)
   133  		o.FilterNames = append(o.FilterNames, name)
   134  	}
   135  }
   136  
   137  // WithFilters returns an Option that adds a filter chain.
   138  func WithFilters(fs []filter.ServerFilter) Option {
   139  	return func(o *Options) {
   140  		for _, f := range fs {
   141  			o.Filters = append(o.Filters, f)
   142  			o.FilterNames = append(o.FilterNames, "server.WithFilters")
   143  		}
   144  	}
   145  }
   146  
   147  // WithStreamFilter returns an Option that adds a stream filter (pre or post).
   148  func WithStreamFilter(sf StreamFilter) Option {
   149  	return func(o *Options) {
   150  		o.StreamFilters = append(o.StreamFilters, sf)
   151  	}
   152  }
   153  
   154  // WithStreamFilters returns an Option that adds a stream filter chain.
   155  func WithStreamFilters(sfs ...StreamFilter) Option {
   156  	return func(o *Options) {
   157  		o.StreamFilters = append(o.StreamFilters, sfs...)
   158  	}
   159  }
   160  
   161  // WithAddress returns an Option that sets address (ip:port or :port).
   162  func WithAddress(s string) Option {
   163  	return func(o *Options) {
   164  		o.ServeOptions = append(o.ServeOptions, transport.WithListenAddress(s))
   165  		o.Address = s
   166  	}
   167  }
   168  
   169  // WithTLS returns an Option that sets TLS certificate files' path.
   170  // The input param certFile represents server certificate.
   171  // The input param keyFile represents server private key.
   172  // The input param caFile represents CA certificate, which is used for client-to-server authentication(mTLS).
   173  // If cafile is empty, no client validation.
   174  // Also, caFile="root" means local ca file would be used to validate client.
   175  // All certificates must be X.509 certificates.
   176  func WithTLS(certFile, keyFile, caFile string) Option {
   177  	return func(o *Options) {
   178  		o.ServeOptions = append(o.ServeOptions, transport.WithServeTLS(certFile, keyFile, caFile))
   179  	}
   180  }
   181  
   182  // WithNetwork returns an Option that sets network, tcp by default.
   183  func WithNetwork(s string) Option {
   184  	return func(o *Options) {
   185  		o.network = s
   186  		o.ServeOptions = append(o.ServeOptions, transport.WithListenNetwork(s))
   187  	}
   188  }
   189  
   190  // WithListener returns an Option that sets net.Listener for accept, read/write op customization.
   191  func WithListener(lis net.Listener) Option {
   192  	return func(o *Options) {
   193  		o.ServeOptions = append(o.ServeOptions, transport.WithListener(lis))
   194  	}
   195  }
   196  
   197  // WithServerAsync returns an Option that sets whether to enable server asynchronous or not.
   198  // When enable it, the server can cyclically receive packets and process request and response
   199  // packets concurrently for the same connection.
   200  func WithServerAsync(serverAsync bool) Option {
   201  	return func(o *Options) {
   202  		o.ServeOptions = append(o.ServeOptions, transport.WithServerAsync(serverAsync))
   203  	}
   204  }
   205  
   206  // WithWritev returns an Option that sets whether to enable writev or not.
   207  func WithWritev(writev bool) Option {
   208  	return func(o *Options) {
   209  		o.ServeOptions = append(o.ServeOptions, transport.WithWritev(writev))
   210  	}
   211  }
   212  
   213  // WithMaxRoutines returns an Option that sets max number of goroutines.
   214  // It only works for server async mode.
   215  // MaxRoutines should be set to twice as expected number of routines (can be calculated by expected QPS),
   216  // and larger than MAXPROCS.
   217  // If MaxRoutines is not set or set to 0, it will be set to (1<<31 - 1).
   218  // Requests exceeding MaxRoutines will be queued. Prolonged overages may lead to OOM!
   219  // MaxRoutines is not the solution to alleviate server overloading.
   220  func WithMaxRoutines(routines int) Option {
   221  	return func(o *Options) {
   222  		o.ServeOptions = append(o.ServeOptions, transport.WithMaxRoutines(routines))
   223  	}
   224  }
   225  
   226  // WithTimeout returns an Option that sets timeout for handling a request.
   227  func WithTimeout(t time.Duration) Option {
   228  	return func(o *Options) {
   229  		o.Timeout = t
   230  	}
   231  }
   232  
   233  // WithDisableRequestTimeout returns an Option that disables timeout for handling requests.
   234  func WithDisableRequestTimeout(disable bool) Option {
   235  	return func(o *Options) {
   236  		o.DisableRequestTimeout = disable
   237  	}
   238  }
   239  
   240  // WithRegistry returns an Option that sets registry.Registry.
   241  // One service, one registry.Registry.
   242  func WithRegistry(r registry.Registry) Option {
   243  	return func(o *Options) {
   244  		o.Registry = r
   245  	}
   246  }
   247  
   248  // WithTransport returns an Option that sets transport.ServerTransport.
   249  func WithTransport(t transport.ServerTransport) Option {
   250  	return func(o *Options) {
   251  		if t != nil {
   252  			o.Transport = t
   253  		}
   254  	}
   255  }
   256  
   257  // WithProtocol returns an Option that sets protocol of service.
   258  // This Option also sets framerbuilder and codec plugin.
   259  func WithProtocol(s string) Option {
   260  	return func(o *Options) {
   261  		o.protocol = s
   262  		o.Codec = codec.GetServer(s)
   263  		fb := transport.GetFramerBuilder(s)
   264  		if fb != nil {
   265  			o.ServeOptions = append(o.ServeOptions, transport.WithServerFramerBuilder(fb))
   266  		}
   267  		trans := transport.GetServerTransport(s)
   268  		if trans != nil {
   269  			o.Transport = trans
   270  		}
   271  	}
   272  }
   273  
   274  // WithHandler returns an Option that sets transport.Handler (service itself by default).
   275  func WithHandler(h transport.Handler) Option {
   276  	return func(o *Options) {
   277  		o.ServeOptions = append(o.ServeOptions, transport.WithHandler(h))
   278  		o.handlerSet = true
   279  	}
   280  }
   281  
   282  // WithCurrentSerializationType returns an Option that sets current serialization type.
   283  // It's often used for transparent proxy without serialization.
   284  // If current serialization type is not set, serialization type will be determined by
   285  // serialization field of request protocol.
   286  func WithCurrentSerializationType(t int) Option {
   287  	return func(o *Options) {
   288  		o.CurrentSerializationType = t
   289  	}
   290  }
   291  
   292  // WithCurrentCompressType returns an Option that sets current compress type.
   293  func WithCurrentCompressType(t int) Option {
   294  	return func(o *Options) {
   295  		o.CurrentCompressType = t
   296  	}
   297  }
   298  
   299  // WithMaxWindowSize returns an Option that sets max window size for server stream.
   300  func WithMaxWindowSize(w uint32) Option {
   301  	return func(o *Options) {
   302  		o.MaxWindowSize = w
   303  	}
   304  }
   305  
   306  // WithCloseWaitTime returns an Option that sets min waiting time when close service.
   307  // It's used for service's graceful restart.
   308  // Default: 0ms, max: 10s.
   309  func WithCloseWaitTime(t time.Duration) Option {
   310  	return func(o *Options) {
   311  		o.CloseWaitTime = t
   312  	}
   313  }
   314  
   315  // WithMaxCloseWaitTime returns an Option that sets max waiting time when close service.
   316  // It's used for wait requests finish.
   317  // Default: 0ms.
   318  func WithMaxCloseWaitTime(t time.Duration) Option {
   319  	return func(o *Options) {
   320  		o.MaxCloseWaitTime = t
   321  	}
   322  }
   323  
   324  // WithRESTOptions returns an Option that sets RESTful router options.
   325  func WithRESTOptions(opts ...restful.Option) Option {
   326  	return func(o *Options) {
   327  		o.RESTOptions = append(o.RESTOptions, opts...)
   328  	}
   329  }
   330  
   331  // WithIdleTimeout returns an Option that sets idle connection timeout.
   332  // Notice: it doesn't work for server streaming.
   333  func WithIdleTimeout(t time.Duration) Option {
   334  	return func(o *Options) {
   335  		o.ServeOptions = append(o.ServeOptions, transport.WithServerIdleTimeout(t))
   336  	}
   337  }
   338  
   339  // WithDisableKeepAlives returns an Option that disables keep-alives.
   340  func WithDisableKeepAlives(disable bool) Option {
   341  	return func(o *Options) {
   342  		o.ServeOptions = append(o.ServeOptions, transport.WithDisableKeepAlives(disable))
   343  	}
   344  }