panurge

package module
v1.14.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2023 License: MIT Imports: 22 Imported by: 0

README

Panurge

[...] Panurge, without another word, threw his sheep, crying and bleating, into the sea. All the other sheep, crying and bleating in the same intonation, started to throw themselves in the sea after it, all in a line. The herd was such that once one jumped, so jumped its companions. It was not possible to stop them, as you know, with sheep, it's natural to always follow the first one, wherever it may go. — Francois Rabelais, Quart Livre, chapter VIII

Common libraries and utility functions for our Go applications.

Example usage of StandardApp

	opts := options{
		Port:         8081,
		InternalPort: 8090,
	}

	err := copperhead.Configure(&opts,
		copperhead.WithEnvironment(map[string]string{
			"Port":                   "PORT",
			"InternalPort":           "INTERNAL_PORT",
			"ImasURL":                "IMAS_URL",
		}),
		copperhead.Require(
			"ImasURL",
		),
	)
	if err != nil {
		return fmt.Errorf("failed to read configuration: %v", err)
	}

	sess, err := session.NewSession()
	if err != nil {
		return errors.Errorf(
			"failed to create AWS SDK session: %w", err)
	}

	service, err := sendmail.NewEmailService(sendmail.EmailServiceOptions{
		Sender: sesv2.New(sess),
	})

	app, err := panurge.NewStandardApp(logger,
		panurge.WithAppPorts(
			opts.Port, opts.InternalPort),
	    panurge.WithImasURL(opts.ImasURL),
		panurge.WithAppService(
			rpc.EmailPathPrefix,
			func(hooks *twirp.ServerHooks) http.Handler {
				return rpc.NewEmailServer(service, hooks)
			},
		),
	)
	if err != nil {
		return err
	}

	return app.ListenAndServe()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAnnotation

func AddAnnotation[T AllowedAnnotationTypes](ctx context.Context, key string, value T)

func AddMetadata

func AddMetadata(ctx context.Context, key string, value interface{})

func AddTwirpRequestHeaders

func AddTwirpRequestHeaders(next http.Handler, names ...string) http.Handler

AddTwirpRequestHeaders is a middleware that adds HTTP request headers to the context for twirp to consume.

func AddUserAnnotation

func AddUserAnnotation(ctx context.Context, user string)

func AnnotationMiddleware

func AnnotationMiddleware(handler http.Handler) http.Handler

AnnotationMiddleware adds annotation support to the request context.

func CombineMetricsAndAuthHooks

func CombineMetricsAndAuthHooks(metrics, auth *twirp.ServerHooks) *twirp.ServerHooks

CombineMetricsAndAuthHooks tweaks how the hooks are chained so that the metrics.RequestRouted always is called regardless of auth errors. An auth error will still fail the request, but any errors returned by the metrics hook will be ignored.

func ConfigureXRay

func ConfigureXRay(logger *logrus.Logger, version string)

ConfigureXRay sets up XRay with a logrus logger and makes sure that XRay doesn't panic when a context is missing.

func ContextWithAnnotations

func ContextWithAnnotations(ctx context.Context) context.Context

ContextWithAnnotations allows us to annotate the request context independently of the XRay instrumentation.

func DefaultCORSDomains

func DefaultCORSDomains() []string

DefaultCORSDomains returns the default allowed domain suffixes.

func DefaultCORSMiddleware

func DefaultCORSMiddleware() *cors.Cors

DefaultCorsMiddleware creates a middleware with the default settings.

func HealthcheckHandler

func HealthcheckHandler(
	logger *logrus.Logger, test HealthcheckFunc,
) http.Handler

func Logger

func Logger(rawLogLevel string) *logrus.Logger

Logger creates a new logger for structured logging.

func NewCORSMiddleware

func NewCORSMiddleware(opts CORSOptions) *cors.Cors

NewCORSMiddleware creates a CORS middleware suitable for our editorial application APIs.

func NewErrorLoggingHooks

func NewErrorLoggingHooks(logger *logrus.Logger) *twirp.ServerHooks

NewErrorLoggingHooks will log outgoing error responses. XRay annotations should be logged together with the error, so we do not add information about the method and service here.

func NewTwirpMetricsHooks

func NewTwirpMetricsHooks(opts ...TwirpMetricOptionFunc) (*twirp.ServerHooks, error)

NewTwirpMetricsHooks creates new twirp hooks enabling prometheus metrics

func NoopHealthcheck

func NoopHealthcheck(ctx context.Context) error

func SafeClose

func SafeClose(logger ErrorLogger, name string, c io.Closer)

SafeClose closes an io.Closer (f.ex. an io.ReadCloser) and logs an error if the Close() fails. This is meant to be used to capture close errors together with defer.

func SafeFailingClose

func SafeFailingClose(logger ErrorLogger, outErr *error, name string, c io.Closer)

SafeClose closes an io.Closer (f.ex. an io.ReadCloser) and either sets outErr (if it's nil) or logs an error if the Close() fails. This is meant to be used to capture close errors together with defer.

func StandardInternalMux

func StandardInternalMux(
	logger *logrus.Logger, test HealthcheckFunc,
) *http.ServeMux

func StandardServer

func StandardServer(port int, handler http.Handler) *http.Server

func StandardTwirpHooks

func StandardTwirpHooks(
	logger *logrus.Logger, opts TwirpHookOptions,
) (*twirp.ServerHooks, error)

StandardTwirpHooks sets up the standard twirp server hooks for metrics, authentication, and error logging.

Types

type AllowedAnnotationTypes added in v1.13.5

type AllowedAnnotationTypes interface {
	bool | int | uint | float32 | float64 | string
}

type AnnotationHook

type AnnotationHook struct{}

func (*AnnotationHook) Fire

func (h *AnnotationHook) Fire(e *logrus.Entry) error

func (*AnnotationHook) Levels

func (h *AnnotationHook) Levels() []logrus.Level

type CORSOptions

type CORSOptions struct {
	AllowHTTP      bool
	AllowedDomains []string
	Custom         cors.Options
}

CORSOptions controls the behaviour of the CORS middleware.

type ContextAnnotations

type ContextAnnotations struct {
	// contains filtered or unexported fields
}

func GetContextAnnotations

func GetContextAnnotations(ctx context.Context) *ContextAnnotations

func (*ContextAnnotations) AddAnnotation

func (a *ContextAnnotations) AddAnnotation(key string, value interface{})

func (*ContextAnnotations) AddMetadata

func (a *ContextAnnotations) AddMetadata(key string, value interface{})

func (*ContextAnnotations) GetAnnotations

func (a *ContextAnnotations) GetAnnotations() map[string]interface{}

func (*ContextAnnotations) GetID

func (a *ContextAnnotations) GetID() string

func (*ContextAnnotations) GetMetadata

func (a *ContextAnnotations) GetMetadata() map[string]interface{}

func (*ContextAnnotations) GetUser

func (a *ContextAnnotations) GetUser() string

func (*ContextAnnotations) SetUser

func (a *ContextAnnotations) SetUser(user string)

type ErrorLogger

type ErrorLogger interface {
	Errorf(format string, args ...interface{})
}

type HealthcheckFunc

type HealthcheckFunc func(ctx context.Context) error

type NewServiceFunc

type NewServiceFunc func(hooks *twirp.ServerHooks) http.Handler

type StandardApp

type StandardApp struct {
	Server *http.Server
	Mux    *http.ServeMux
	// contains filtered or unexported fields
}

StandardApp provides a framework for setting up our applications in a consistent way.

func NewStandardApp

func NewStandardApp(
	logger *logrus.Logger, name string, opts ...StandardAppOption,
) (*StandardApp, error)

NewStandardApp creates a standard panurge Twirp application.

func (*StandardApp) LambdaHandler

func (app *StandardApp) LambdaHandler() lambda.LambdaHandlerFunc

LambdaHandler creates an HTTP event handler (Loadbalancer/APIGateway) that proxies requests to the application ServeMux.

func (*StandardApp) ListenAndServe

func (app *StandardApp) ListenAndServe() error

ListenAndServe starts both the internal and external servers. If the application was configured with test servers this function will return once they have been set up, otherwise it will block as long as the servers are listening.

type StandardAppOption

type StandardAppOption func(app *StandardApp)

func WithAppAuthHook

func WithAppAuthHook(
	authHook *twirp.ServerHooks,
	authOrg func(ctx context.Context) string,
) StandardAppOption

WithAppAuth hook is used to add "legacy" authentication methods.

func WithAppHealthCheck

func WithAppHealthCheck(check HealthcheckFunc) StandardAppOption

WithAppHealthCheck provides a custom function that evaluates the health of the application.

func WithAppPorts

func WithAppPorts(public, internal int) StandardAppOption

WithAppPorts sets the public and internal listener ports

func WithAppService

func WithAppService(pathPrefix string, fn NewServiceFunc) StandardAppOption

WithAppService exposes a Twirp service.

func WithAppTestServers

func WithAppTestServers(ts *TestServers) StandardAppOption

func WithAppVersion

func WithAppVersion(version string) StandardAppOption

WithAppVersion sets the application version for reporting purposes.

func WithImasURL

func WithImasURL(imasURL string) StandardAppOption

WithImasURL configures the application to fetch JWKs from IMAS and verify incoming bearer access tokens for twirp APIs.

func WithTwirpCORSOptions

func WithTwirpCORSOptions(opts CORSOptions) StandardAppOption

WithTwirpCORSOptions customise the cors options for the Twirp services.

func WithTwirpMetricsOptions

func WithTwirpMetricsOptions(opts ...TwirpMetricOptionFunc) StandardAppOption

WithTwirpMetricsOptions changes the metric collection behaviours.

type TestServers

type TestServers struct {
	// contains filtered or unexported fields
}

func (*TestServers) Close

func (ts *TestServers) Close()

func (*TestServers) GetInternal

func (ts *TestServers) GetInternal() *httptest.Server

func (*TestServers) GetPublic

func (ts *TestServers) GetPublic() *httptest.Server

type TwirpHookOptions

type TwirpHookOptions struct {
	AuthHook       *twirp.ServerHooks
	ImasURL        string
	MetricsOptions []TwirpMetricOptionFunc
}

TwirpHookOptions controls the configuration of the standard twirp hooks.

type TwirpMetricOptionFunc

type TwirpMetricOptionFunc func(opts *TwirpMetricsOptions)

func WithTwirpMetricsOrgFunction

func WithTwirpMetricsOrgFunction(fn func(ctx context.Context) string) TwirpMetricOptionFunc

WithTwirpMetricsOrgFunction uses a custom function for resolving the current organisation from the context.

func WithTwirpMetricsRegisterer

func WithTwirpMetricsRegisterer(reg prometheus.Registerer) TwirpMetricOptionFunc

WithTwirpMetricsRegisterer uses a custom registerer for Twirp metrics.

func WithTwirpMetricsStaticTestLatency

func WithTwirpMetricsStaticTestLatency(latency time.Duration) TwirpMetricOptionFunc

WithTwirpMetricsStaticTestLatency configures the RPC metrics to report a static duration.

type TwirpMetricsOptions

type TwirpMetricsOptions struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
cmd
internal

Jump to

Keyboard shortcuts

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