hertz

package module
v0.0.0-...-b87209e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2023 License: Apache-2.0 Imports: 26 Imported by: 4

README

hertz server for go-orb

This package contains a hertz http/h2c server for go-orb. It's a WIP and has known bugs.

Known bugs

  • Doesn't exit gracefully.
  • Slow.

Documentation

Overview

Package hertz contains a hertz server for go-orb.

Index

Constants

View Source
const (
	// DefaultAddress to use for new Hertz servers.
	// If set to "random", the default, a random address will be selected,
	// preferably on a private interface (XX subet). TODO: implement.
	// TODO(davincible): revisit default address, probably use random addr.
	DefaultAddress = "0.0.0.0:43069"

	// DefaultInsecure will create an HTTP server without TLS, for insecure connections.
	// Note: as a result you can only make insecure HTTP requests, and no HTTP2
	// unless you set WithH2C.
	//
	// WARNING: don't use this in production, unless you really know what you are
	// doing. this will result in unencrypted traffic. Really, it is even advised
	// against using this in testing environments.
	DefaultInsecure = false

	// DefaultAllowH2C allows insecure, unencrypted traffic to HTTP2 servers.
	// Don't use this, see the notes at DefaultInsecure for more details.
	DefaultAllowH2C = false

	// DefaultMaxConcurrentStreams for HTTP2.
	DefaultMaxConcurrentStreams = 512

	// DefaultHTTP2 dicates whether to also allow HTTP/2 connections.
	DefaultHTTP2 = true

	// DefaultReadTimeout see net/http pkg for more details.
	DefaultReadTimeout = 5 * time.Second

	// DefaultWriteTimeout see net/http pkg for more details.
	DefaultWriteTimeout = 5 * time.Second

	// DefaultIdleTimeout see net/http pkg for more details.
	DefaultIdleTimeout = 5 * time.Second

	// DefaultStopTimeout sets the timeout for ServerHertz.Stop().
	DefaultStopTimeout = time.Second

	// DefaultEnableGzip enables gzip response compression server wide onall responses.
	// Only use this if your messages are sufficiently large. For small messages
	// the compute overhead is not worth the reduction in transport time.
	//
	// Alternatively, you can send a gzip compressed request, and the server
	// will send back a gzip compressed respponse.
	DefaultEnableGzip = false

	// DefaultConfigSection is the section key used in config files used to
	// configure the server options.
	DefaultConfigSection = Name

	// DefaultMaxHeaderBytes is the maximum size to parse from a client's
	// HTTP request headers.
	DefaultMaxHeaderBytes = 1024 * 64
)
View Source
const Name = "hertz"

Name is the plugin name.

Variables

View Source
var (
	ErrNoRouter            = errors.New("no router plugin name set in config")
	ErrRouterNotFound      = errors.New("router plugin not found, did you register it?")
	ErrEmptyCodecWhitelist = errors.New("codec whitelist is empty")
	ErrNoMatchingCodecs    = errors.New("no matching codecs found, did you register the codec plugins?")
)

Errors.

View Source
var (
	// ErrContentTypeNotSupported is returned when there is no matching codec.
	ErrContentTypeNotSupported = errors.New("content type not supported")
	ErrInvalidConfigType       = errors.New("http server: invalid config type provided, not of type http.Config")
)

Errors.

View Source
var (
	ErrNotHTTPServer = errors.New("server provider is not of type *http.Server")
)

Errors.

Functions

func DefaultCodecWhitelist

func DefaultCodecWhitelist() []string

DefaultCodecWhitelist is the default allowed list of codecs to be used for HTTP request encoding/decoding. This means that if any of these plugins are registered, they will be included in the server's available codecs. If they are not registered, the server will not be able to handle these formats.

func GetAcceptType

func GetAcceptType(ctx codecs.Map, acceptHeader string, contentType string) string

GetAcceptType parses the Accept header and checks against the available codecs to find a matching content type.

func GetContentType

func GetContentType(header string) (string, error)

GetContentType parses the content type from the header value.

func NewGRPCHandler

func NewGRPCHandler[Tin any, Tout any](
	srv *Server,
	f func(context.Context, *Tin) (*Tout, error),
) func(c context.Context, ctx *app.RequestContext)

NewGRPCHandler wraps a gRPC function with a Hertz handler.

func WithDefaults

func WithDefaults(options ...Option) server.Option

WithDefaults sets default options to use on the creation of new HTTP entrypoints.

func WithEntrypoint

func WithEntrypoint(options ...Option) server.Option

WithEntrypoint adds an HTTP entrypoint with the provided options.

func WriteError

func WriteError(ctx *app.RequestContext, err error)

WriteError returns an error response to the HTTP request.

Types

type Config

type Config struct {
	// Name is the entrypoint name.
	//
	// The default name is 'http-<random uuid>'
	Name string `json:"name" yaml:"name"`

	// Address to listen on.
	// TODO(davincible): implement this, and the address method.
	// If no IP is provided, an interface will be selected automatically. Private
	// interfaces are preferred, if none are found a public interface will be used.
	//
	// If no port is provided, a random port will be selected. To listen on a
	// specific interface, but with a random port, you can use '<IP>:0'.
	Address string `json:"address" yaml:"address"`

	// Insecure will create an HTTP server without TLS, for insecure connections.
	// Note: as a result you can only make insecure HTTP1 requests, no HTTP2
	// unless you set WithH2C.
	//
	// WARNING: don't use this in production, unless you really know what you are
	// doing. this will result in unencrypted traffic. Really, it is even advised
	// against using this in testing environments.
	Insecure bool `json:"insecure" yaml:"insecure"`

	// TLS config, if none is provided a self-signed certificates will be generated.
	//
	// You can load a tls config from yaml/json with the following options:
	//
	// “`yaml
	// rootCAFiles:
	//    - xxx
	// clientCAFiles:
	//    - xxx
	// clientAuth: "none" | "request" | "require" |  "verify" | "require+verify"
	// certificates:
	//   - certFile: xxx
	//     keyFile: xxx
	// “`
	TLS *mtls.Config `json:"tls,omitempty" yaml:"tls,omitempty"`

	// H2C allows h2c connections; HTTP2 without TLS.
	H2C bool `json:"h2c" yaml:"h2c"`

	// HTTP2 dicates whether to also allow HTTP/2 connections. Defaults to true.
	HTTP2 bool `json:"http2" yaml:"http2"`

	// Gzip enables gzip response compression server wide onall responses.
	// Only use this if your messages are sufficiently large. For small messages
	// the compute overhead is not worth the reduction in transport time.
	//
	// Alternatively, you can send a gzip compressed request, and the server
	// will send back a gzip compressed respponse.
	Gzip bool `json:"gzip" yaml:"gzip"`

	// MaxConcurrentStreams for HTTP2.
	MaxConcurrentStreams int `json:"maxConcurrentStreams" yaml:"maxConcurrentStreams"`

	// MaxHeaderBytes is the maximum size to parse from a client's
	// HTTP request headers.
	MaxHeaderBytes int `json:"maxHeaderBytes" yaml:"maxHeaderBytes"`

	// CodecWhitelist is the list of codec names that are allowed to be used
	// with the HTTP server. This means that if registered, codecs in this list
	// will be added to the server, allowing you to make RPC requests in that format.
	// If any of the codecs in this list are not registred nothing will happen.
	//
	// We explicitly whitelist codecs, as we don't
	// want to add every codec plugin that has been registered to be automaically
	// added to the server.
	CodecWhitelist []string `json:"codecWhitelist" yaml:"codecWhitelist"`

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body. A zero or negative value means
	// there will be no timeout.
	ReadTimeout time.Duration `json:"readTimeout" yaml:"readTimeout"`

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	// A zero or negative value means there will be no timeout.
	WriteTimeout time.Duration `json:"writeTimeout" yaml:"writeTimeout"`

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration `json:"idleTimeout" yaml:"idleTimeout"`

	// StopTimeout is the timeout for ServerHertz.Stop().
	StopTimeout time.Duration `json:"stopTimeout" yaml:"stopTimeout"`

	// HandlerRegistrations are all handler registration functions that will be
	// registered to the server upon startup.
	//
	// You can statically add handlers by using the fuctional server options.
	// Optionally, you can dynamically add handlers by registering them to the
	// Handlers global, and setting them explicitly in the config.
	HandlerRegistrations server.HandlerRegistrations `json:"handlers" yaml:"handlers"`

	// Logger allows you to dynamically change the log level and plugin for a
	// specific entrypoint.
	Logger struct {
		Level  slog.Level `json:"level,omitempty" yaml:"level,omitempty"` // TODO(davincible): change with custom level
		Plugin string     `json:"plugin,omitempty" yaml:"plugin,omitempty"`
	} `json:"logger" yaml:"logger"`
}

Config provides options to the entrypoint.

func NewConfig

func NewConfig(options ...Option) *Config

NewConfig will create a new default config for the entrypoint.

func (*Config) ApplyOptions

func (c *Config) ApplyOptions(options ...Option)

ApplyOptions applies a set of options to the config.

func (Config) Copy

func (c Config) Copy() server.EntrypointConfig

Copy creates a copy of the entrypoint config.

func (Config) GetAddress

func (c Config) GetAddress() string

GetAddress returns the entrypoint address.

func (*Config) NewCodecMap

func (c *Config) NewCodecMap() (codecs.Map, error)

NewCodecMap fetches the whitelisted codec plugins from the registered codecs if present.

type Option

type Option func(*Config)

Option is a functional option to provide custom values to the config.

func WithAddress

func WithAddress(address string) Option

WithAddress specifies the address to listen on. If you want to listen on all interfaces use the format ":8080" If you want to listen on a specific interface/address use the full IP.

func WithAllowH2C

func WithAllowH2C() Option

WithAllowH2C will allow H2C connections on the entrypoint. H2C is HTTP2 without TLS. It is not recommended to turn this on.

func WithCodecWhitelist

func WithCodecWhitelist(list []string) Option

WithCodecWhitelist sets the list of codecs allowed in the HTTP entrypoint. If registered, any codecs set here will be imported into the server. You still need to register the codec plugins by importing them.

func WithConfig

func WithConfig(config Config) Option

WithConfig will set replace the server config with config provided as argument. Warning: any options applied previous to this option will be overwritten by the contents of the config provided here.

func WithDisableHTTP2

func WithDisableHTTP2() Option

WithDisableHTTP2 will prevent the creation of an HTTP2 server on the entrypoint.

func WithGzip

func WithGzip() Option

WithGzip enables gzip response compression server wide onall responses. Only use this if your messages are sufficiently large. For small messages the compute overhead is not worth the reduction in transport time.

Alternatively, you can send a gzip compressed request, and the server will send back a gzip compressed respponse.

func WithIdleTimeout

func WithIdleTimeout(timeout time.Duration) Option

WithIdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled. If IdleTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.

func WithInsecure

func WithInsecure() Option

WithInsecure will create the entrypoint without using TLS. Note: as a result you can only make insecure HTTP requests, and no HTTP2 unless you set WithH2C.

WARNING: don't use this in production, unless you really know what you are doing. this will result in unencrypted traffic. Really, it is even advised against using this in testing environments.

func WithLogLevel

func WithLogLevel(level slog.Level) Option

WithLogLevel changes the log level from the inherited logger.

func WithLogPlugin

func WithLogPlugin(plugin string) Option

WithLogPlugin changes the log level from the inherited logger.

func WithMaxConcurrentStreams

func WithMaxConcurrentStreams(value int) Option

WithMaxConcurrentStreams sets the concurrent streams limit for HTTP2.

func WithName

func WithName(name string) Option

WithName sets the entrypoint name. The default name is in the format of 'http-<uuid>'.

Setting a custom name allows you to dynamically reference the entrypoint in the file config, and makes it easier to attribute the logs.

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) Option

WithReadTimeout sets the maximum duration for reading the entire request, including the body. A zero or negative value means there will be no timeout.

func WithRegistration

func WithRegistration(name string, registration server.RegistrationFunc) Option

WithRegistration adds a named registration function to the config. The name set here allows you to dynamically add this handler to entrypoints through a config.

Registration functions are used to register handlers to a server.

func WithTLS

func WithTLS(tlsConfig *tls.Config) Option

WithTLS sets a tls config.

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

WithWriteTimeout sets the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read. Like ReadTimeout, it does not let Handlers make decisions on a per-request basis. A zero or negative value means there will be no timeout.

type Server

type Server struct {
	Config   Config
	Logger   log.Logger
	Registry registry.Type
	// contains filtered or unexported fields
}

Server is the hertz Server for go-orb.

func ProvideServer

func ProvideServer(
	_ types.ServiceName,
	logger log.Logger,
	reg registry.Type,
	cfg Config,
	options ...Option,
) (*Server, error)

ProvideServer creates a new entrypoint for a single address. You can create multiple entrypoints for multiple addresses and ports. One entrypoint can serve a HTTP1 and HTTP2/H2C server.

func (*Server) Address

func (s *Server) Address() string

Address returns the address the entrypoint is listening on.

func (*Server) EntrypointID

func (s *Server) EntrypointID() string

EntrypointID returns the id (uuid) of this entrypoint in the registry.

func (*Server) Name

func (s *Server) Name() string

Name returns the entrypoint name.

func (*Server) Register

func (s *Server) Register(register orbserver.RegistrationFunc)

Register executes a registration function on the entrypoint.

func (*Server) Router

func (s *Server) Router() *server.Hertz

Router returns the hertz server.

func (*Server) Start

func (s *Server) Start() error

Start will create the listeners and start the server on the entrypoint.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop will stop the Hertz server(s).

func (*Server) String

func (s *Server) String() string

String returns the entrypoint type; http.

func (*Server) Transport

func (s *Server) Transport() string

Transport returns the client transport to use.

func (*Server) Type

func (s *Server) Type() string

Type returns the component type.

Directories

Path Synopsis
internal
orblog
Package orblog is an internal wrapper of hertz/pkg/common/hlog for go-orb/go-orb/log.
Package orblog is an internal wrapper of hertz/pkg/common/hlog for go-orb/go-orb/log.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL