frame

package module
v1.25.21 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2024 License: Apache-2.0 Imports: 66 Imported by: 1

README

frame Build Status

A simple frame for quickly setting up api servers based on gocloud framework.

Features include:

  • An http server
  • A grpc server
  • Database setup using Gorm with migrations and multitenancy support
  • Easy queue publish and subscription support
  • Localization
  • Authentication adaptor for oauth2 and jwt access
  • Authorization adaptor

The goal of this project is to simplify starting up servers with minimal boiler plate code. All components are very pluggable with only the necessary configured items loading at runtime thanks to the power of go-cloud under the hood.

Getting started:

    go get -u github.com/pitabwire/frame

Example

import (
	"context"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/pitabwire/frame"
	"log"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Frame says yelloo!")
}


func main() {

	serviceName := "service_authentication"
	ctx := context.Background()

	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", handler)

	server := frame.HttpHandler(router)
	service := frame.NewService(serviceName,server)
	err := service.Run(ctx, ":7654")
	if err != nil {
		log.Fatal("main -- Could not run Server : %v", err)
	}

}

Detailed guides can be found here

development

To run tests start the docker compose file in ./tests then run :

    go test -json -cover ./...

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthHasAccess added in v1.4.0

func AuthHasAccess(ctx context.Context, action string, subject string) (bool, error)

AuthHasAccess binary check to confirm if subject can perform action specified

func ConfigFromContext added in v1.25.4

func ConfigFromContext(ctx context.Context) any

ConfigFromContext extracts service configuration from the supplied context if any exist

func ConfigProcess added in v1.7.15

func ConfigProcess(prefix string, config any) error

ConfigProcess convenience method to processFunc configs

func ConfigToContext added in v1.25.4

func ConfigToContext(ctx context.Context, config any) context.Context

ConfigToContext adds service configuration to the current supplied context

func DBErrorIsRecordNotFound added in v1.2.6

func DBErrorIsRecordNotFound(err error) bool

DBErrorIsRecordNotFound validate if supplied error is because of record missing in DB

func DBPropertiesFromMap added in v1.2.6

func DBPropertiesFromMap(propsMap map[string]string) datatypes.JSONMap

DBPropertiesFromMap converts a map into a JSONMap object

func DBPropertiesToMap added in v1.2.6

func DBPropertiesToMap(props datatypes.JSONMap) map[string]string

DBPropertiesToMap converts the supplied db json content into a golang map

func GetEnv

func GetEnv(key, fallback string) string

GetEnv Obtains the environment key or returns the default value

func GetIp

func GetIp(r *http.Request) string

GetIp convenience method to extract the remote ip address from our inbound request

func GetLocalIP

func GetLocalIP() string

GetLocalIP convenince method that obtains the non localhost ip address for machine running app

func GetLoggingOptions added in v1.17.6

func GetLoggingOptions() []logging.Option

func GetMacAddress

func GetMacAddress() string

GetMacAddress convenience method to get some unique address based on the network interfaces the application is running on.

func JwtFromContext added in v1.17.3

func JwtFromContext(ctx context.Context) string

JwtFromContext extracts authentication jwt from the supplied context if any exist

func LoggingInterceptor added in v1.17.6

func LoggingInterceptor(l logrus.FieldLogger) logging.Logger

LoggingInterceptor adapts logrus logger to interceptor logger.

func NewGrpcHealthServer added in v1.13.3

func NewGrpcHealthServer(service *Service) grpc_health_v1.HealthServer

func RecoveryHandlerFun added in v1.21.5

func RecoveryHandlerFun(ctx context.Context, p interface{}) error

func RemoveClaimsFromContext added in v1.25.8

func RemoveClaimsFromContext(ctx context.Context) context.Context

RemoveClaimsFromContext removes authentication claims from the current supplied context

func SafeChannelRead added in v1.23.0

func SafeChannelRead(ctx context.Context, ch <-chan any) (any, bool, error)

func SafeChannelWrite added in v1.21.6

func SafeChannelWrite(ctx context.Context, ch chan<- any, value any) error

SafeChannelWrite writes a value to a channel, returning an error if the context is canceled.

func ToContext

func ToContext(ctx context.Context, service *Service) context.Context

ToContext pushes a service instance into the supplied context for easier propagation.

Types

type AuthenticationClaims added in v1.0.7

type AuthenticationClaims struct {
	Ext         map[string]any `json:"ext,omitempty"`
	TenantID    string         `json:"tenant_id,omitempty"`
	PartitionID string         `json:"partition_id,omitempty"`
	AccessID    string         `json:"access_id,omitempty"`
	ContactID   string         `json:"contact_id,omitempty"`
	Roles       []string       `json:"roles,omitempty"`
	jwt.RegisteredClaims
}

AuthenticationClaims Create a struct that will be encoded to a JWT. We add jwt.StandardClaims as an embedded type, to provide fields like expiry time

func ClaimsFromContext added in v1.0.7

func ClaimsFromContext(ctx context.Context) *AuthenticationClaims

ClaimsFromContext extracts authentication claims from the supplied context if any exist

func ClaimsFromMap added in v1.1.0

func ClaimsFromMap(m map[string]string) *AuthenticationClaims

ClaimsFromMap extracts authentication claims from the supplied map if they exist

func (*AuthenticationClaims) AsMetadata added in v1.0.7

func (a *AuthenticationClaims) AsMetadata() map[string]string

AsMetadata Creates a string map to be used as metadata in queue data

func (*AuthenticationClaims) ClaimsToContext added in v1.0.7

func (a *AuthenticationClaims) ClaimsToContext(ctx context.Context) context.Context

ClaimsToContext adds authentication claims to the current supplied context

func (*AuthenticationClaims) GetAccessId added in v1.20.3

func (a *AuthenticationClaims) GetAccessId() string

func (*AuthenticationClaims) GetContactId added in v1.20.3

func (a *AuthenticationClaims) GetContactId() string

func (*AuthenticationClaims) GetPartitionId added in v1.20.3

func (a *AuthenticationClaims) GetPartitionId() string

func (*AuthenticationClaims) GetRoles added in v1.20.3

func (a *AuthenticationClaims) GetRoles() []string

func (*AuthenticationClaims) GetTenantId added in v1.20.3

func (a *AuthenticationClaims) GetTenantId() string

func (*AuthenticationClaims) ServiceName added in v1.17.4

func (a *AuthenticationClaims) ServiceName() string

type BaseModel

type BaseModel struct {
	ID          string `gorm:"type:varchar(50);primary_key"`
	CreatedAt   time.Time
	ModifiedAt  time.Time
	Version     uint           `gorm:"DEFAULT 0"`
	TenantID    string         `gorm:"type:varchar(50);"`
	PartitionID string         `gorm:"type:varchar(50);"`
	AccessID    string         `gorm:"type:varchar(50);"`
	DeletedAt   gorm.DeletedAt `sql:"index"`
}

BaseModel base table struct to be extended by other models

func (*BaseModel) BeforeCreate

func (model *BaseModel) BeforeCreate(db *gorm.DB) error

func (*BaseModel) BeforeSave added in v1.2.9

func (model *BaseModel) BeforeSave(db *gorm.DB) error

BeforeSave Ensures we update a migrations time stamps

func (*BaseModel) BeforeUpdate

func (model *BaseModel) BeforeUpdate(db *gorm.DB) error

BeforeUpdate Updates time stamp every time we update status of a migration

func (*BaseModel) CopyPartitionInfo added in v1.18.3

func (model *BaseModel) CopyPartitionInfo(parent *BaseModel)

func (*BaseModel) GenID added in v1.2.5

func (model *BaseModel) GenID(ctx context.Context)

GenID creates a new id for model if its not existent

func (*BaseModel) GetID

func (model *BaseModel) GetID() string

func (*BaseModel) GetVersion added in v1.7.3

func (model *BaseModel) GetVersion() uint

func (*BaseModel) ValidXID added in v1.7.0

func (model *BaseModel) ValidXID(id string) bool

ValidXID Validates that the supplied string is an xid

type BaseModelI

type BaseModelI interface {
	GetID() string
	GetVersion() uint
}

type BaseRepository added in v1.7.4

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

func NewBaseRepository added in v1.7.5

func NewBaseRepository(readDb *gorm.DB, writeDB *gorm.DB, instanceCreator func() BaseModelI) *BaseRepository

func (*BaseRepository) Delete added in v1.7.4

func (repo *BaseRepository) Delete(id string) error

func (*BaseRepository) GetAllBy added in v1.7.4

func (repo *BaseRepository) GetAllBy(properties map[string]any, result []BaseModelI) error

func (*BaseRepository) GetByID added in v1.7.4

func (repo *BaseRepository) GetByID(id string, result BaseModelI) error

func (*BaseRepository) GetLastestBy added in v1.7.4

func (repo *BaseRepository) GetLastestBy(properties map[string]any, result BaseModelI) error

func (*BaseRepository) Save added in v1.7.4

func (repo *BaseRepository) Save(instance BaseModelI) error

func (*BaseRepository) Search added in v1.7.4

func (repo *BaseRepository) Search(query string, searchFields []string, result []BaseModelI) error

type BaseRepositoryI added in v1.7.6

type BaseRepositoryI interface {
	GetByID(id string, result BaseModelI) error
	Delete(id string) error
	Save(instance BaseModelI) error
}

type Checker added in v1.7.13

type Checker interface {
	CheckHealth() error
}

Checker wraps the CheckHealth method.

CheckHealth returns nil if the resource is healthy, or a non-nil error if the resource is not healthy. CheckHealth must be safe to call from multiple goroutines.

type CheckerFunc added in v1.7.13

type CheckerFunc func() error

CheckerFunc is an adapter type to allow the use of ordinary functions as health checks. If f is a function with the appropriate signature, CheckerFunc(f) is a Checker that calls f.

func (CheckerFunc) CheckHealth added in v1.7.13

func (f CheckerFunc) CheckHealth() error

CheckHealth calls f().

type ConfigurationAuthorization added in v1.7.21

type ConfigurationAuthorization interface {
	GetAuthorizationServiceReadURI() string
	GetAuthorizationServiceWriteURI() string
}

type ConfigurationCORS added in v1.16.0

type ConfigurationCORS interface {
	IsCORSEnabled() bool
	IsCORSAllowCredentials() bool
	GetCORSAllowedHeaders() []string
	GetCORSExposedHeaders() []string
	GetCORSAllowedOrigins() []string
	GetCORSAllowedMethods() []string
	GetCORSMaxAge() int
}

type ConfigurationDatabase added in v1.8.0

type ConfigurationDatabase interface {
	GetDatabasePrimaryHostURL() []string
	GetDatabaseReplicaHostURL() []string
	DoDatabaseMigrate() bool
	SkipDefaultTransaction() bool
	GetMaxIdleConnections() int
	GetMaxOpenConnections() int
	GetMaxConnectionLifeTimeInSeconds() time.Duration

	GetDatabaseMigrationPath() string
}

type ConfigurationDefault added in v1.7.21

type ConfigurationDefault struct {
	LogLevel           string `default:"info" envconfig:"LOG_LEVEL"`
	RunServiceSecurely bool   `default:"true" envconfig:"RUN_SERVICE_SECURELY"`

	ServerPort     string `default:":7000" envconfig:"PORT"`
	HttpServerPort string `default:":8080" envconfig:"HTTP_PORT"`
	GrpcServerPort string `default:":50051" envconfig:"GRPC_PORT"`

	CORSEnabled          bool     `default:"false" envconfig:"CORS_ENABLED"`
	CORSAllowCredentials bool     `default:"false" envconfig:"CORS_ALLOW_CREDENTIALS"`
	CORSAllowedHeaders   []string `default:"Authorization" envconfig:"CORS_ALLOWED_HEADERS"`
	CORSExposedHeaders   []string `default:"*" envconfig:"CORS_EXPOSED_HEADERS"`
	CORSAllowedOrigins   []string `default:"*" envconfig:"CORS_ALLOWED_ORIGINS"`
	CORSAllowedMethods   []string `default:"GET,HEAD,POST,PUT,OPTIONS" envconfig:"CORS_ALLOWED_METHODS"`
	CORSMaxAge           int      `default:"3600" envconfig:"CORS_MAX_AGE"`

	TLSCertificatePath    string `envconfig:"TLS_CERTIFICATE_PATH"`
	TLSCertificateKeyPath string `envconfig:"TLS_CERTIFICATE_KEY_PATH"`

	Oauth2WellKnownJwk        string `envconfig:"OAUTH2_WELL_KNOWN_JWK"`
	Oauth2JwtVerifyAudience   string `envconfig:"OAUTH2_JWT_VERIFY_AUDIENCE"`
	Oauth2JwtVerifyIssuer     string `envconfig:"OAUTH2_JWT_VERIFY_ISSUER"`
	Oauth2ServiceURI          string `envconfig:"OAUTH2_SERVICE_URI"`
	Oauth2ServiceClientSecret string `envconfig:"OAUTH2_SERVICE_CLIENT_SECRET"`
	Oauth2ServiceAudience     string `envconfig:"OAUTH2_SERVICE_AUDIENCE"`
	Oauth2ServiceAdminURI     string `envconfig:"OAUTH2_SERVICE_ADMIN_URI"`

	AuthorizationServiceReadURI  string `envconfig:"AUTHORIZATION_SERVICE_READ_URI"`
	AuthorizationServiceWriteURI string `envconfig:"AUTHORIZATION_SERVICE_WRITE_URI"`

	DatabasePrimaryURL             []string `envconfig:"DATABASE_URL"`
	DatabaseReplicaURL             []string `envconfig:"REPLICA_DATABASE_URL"`
	DatabaseMigrate                string   `default:"false" envconfig:"DO_MIGRATION"`
	DatabaseMigrationPath          string   `default:"./migrations/0001" envconfig:"MIGRATION_PATH"`
	DatabaseSkipDefaultTransaction bool     `default:"true" envconfig:"SKIP_DEFAULT_TRANSACTION"`

	DatabaseMaxIdleConnections           int `default:"2" envconfig:"DATABASE_MAX_IDLE_CONNECTIONS"`
	DatabaseMaxOpenConnections           int `default:"5" envconfig:"DATABASE_MAX_OPEN_CONNECTIONS"`
	DatabaseMaxConnectionLifeTimeSeconds int `default:"300" envconfig:"DATABASE_MAX_CONNECTION_LIFE_TIME_IN_SECONDS"`

	EventsQueueName string `default:"frame.events.internal_._queue" envconfig:"EVENTS_QUEUE_NAME"`
	EventsQueueUrl  string `default:"mem://frame.events.internal_._queue" envconfig:"EVENTS_QUEUE_URL"`
}

func (*ConfigurationDefault) DoDatabaseMigrate added in v1.8.0

func (c *ConfigurationDefault) DoDatabaseMigrate() bool

func (*ConfigurationDefault) GetAuthorizationServiceReadURI added in v1.7.21

func (c *ConfigurationDefault) GetAuthorizationServiceReadURI() string

func (*ConfigurationDefault) GetAuthorizationServiceWriteURI added in v1.7.21

func (c *ConfigurationDefault) GetAuthorizationServiceWriteURI() string

func (*ConfigurationDefault) GetCORSAllowedHeaders added in v1.16.0

func (c *ConfigurationDefault) GetCORSAllowedHeaders() []string

func (*ConfigurationDefault) GetCORSAllowedMethods added in v1.16.0

func (c *ConfigurationDefault) GetCORSAllowedMethods() []string

func (*ConfigurationDefault) GetCORSAllowedOrigins added in v1.16.0

func (c *ConfigurationDefault) GetCORSAllowedOrigins() []string

func (*ConfigurationDefault) GetCORSExposedHeaders added in v1.20.2

func (c *ConfigurationDefault) GetCORSExposedHeaders() []string

func (*ConfigurationDefault) GetCORSMaxAge added in v1.20.2

func (c *ConfigurationDefault) GetCORSMaxAge() int

func (*ConfigurationDefault) GetDatabaseMigrationPath added in v1.8.0

func (c *ConfigurationDefault) GetDatabaseMigrationPath() string

func (*ConfigurationDefault) GetDatabasePrimaryHostURL added in v1.8.5

func (c *ConfigurationDefault) GetDatabasePrimaryHostURL() []string

func (*ConfigurationDefault) GetDatabaseReplicaHostURL added in v1.8.5

func (c *ConfigurationDefault) GetDatabaseReplicaHostURL() []string

func (*ConfigurationDefault) GetEventsQueueName added in v1.8.18

func (c *ConfigurationDefault) GetEventsQueueName() string

func (*ConfigurationDefault) GetEventsQueueUrl added in v1.8.18

func (c *ConfigurationDefault) GetEventsQueueUrl() string

func (*ConfigurationDefault) GetMaxConnectionLifeTimeInSeconds added in v1.24.0

func (c *ConfigurationDefault) GetMaxConnectionLifeTimeInSeconds() time.Duration

func (*ConfigurationDefault) GetMaxIdleConnections added in v1.24.0

func (c *ConfigurationDefault) GetMaxIdleConnections() int

func (*ConfigurationDefault) GetMaxOpenConnections added in v1.24.0

func (c *ConfigurationDefault) GetMaxOpenConnections() int

func (*ConfigurationDefault) GetOauth2ServiceAdminURI added in v1.8.5

func (c *ConfigurationDefault) GetOauth2ServiceAdminURI() string

func (*ConfigurationDefault) GetOauth2ServiceAudience added in v1.8.5

func (c *ConfigurationDefault) GetOauth2ServiceAudience() string

func (*ConfigurationDefault) GetOauth2ServiceClientSecret added in v1.8.5

func (c *ConfigurationDefault) GetOauth2ServiceClientSecret() string

func (*ConfigurationDefault) GetOauth2ServiceURI added in v1.7.21

func (c *ConfigurationDefault) GetOauth2ServiceURI() string

func (*ConfigurationDefault) GetOauthWellKnownJwk added in v1.7.21

func (c *ConfigurationDefault) GetOauthWellKnownJwk() string

func (*ConfigurationDefault) GrpcPort added in v1.13.0

func (c *ConfigurationDefault) GrpcPort() string

func (*ConfigurationDefault) HttpPort added in v1.14.0

func (c *ConfigurationDefault) HttpPort() string

func (*ConfigurationDefault) IsCORSAllowCredentials added in v1.19.8

func (c *ConfigurationDefault) IsCORSAllowCredentials() bool

func (*ConfigurationDefault) IsCORSEnabled added in v1.16.0

func (c *ConfigurationDefault) IsCORSEnabled() bool

func (*ConfigurationDefault) IsRunSecurely added in v1.25.4

func (c *ConfigurationDefault) IsRunSecurely() bool

func (*ConfigurationDefault) LoggingLevel added in v1.19.1

func (c *ConfigurationDefault) LoggingLevel() string

func (*ConfigurationDefault) LoggingLevelIsDebug added in v1.19.1

func (c *ConfigurationDefault) LoggingLevelIsDebug() bool

func (*ConfigurationDefault) Port added in v1.13.0

func (c *ConfigurationDefault) Port() string

func (*ConfigurationDefault) SetTLSCertAndKeyPath added in v1.13.0

func (c *ConfigurationDefault) SetTLSCertAndKeyPath(certificatePath, certificateKeyPath string)

func (*ConfigurationDefault) SkipDefaultTransaction added in v1.23.3

func (c *ConfigurationDefault) SkipDefaultTransaction() bool

func (*ConfigurationDefault) TLSCertKeyPath added in v1.13.0

func (c *ConfigurationDefault) TLSCertKeyPath() string

func (*ConfigurationDefault) TLSCertPath added in v1.13.0

func (c *ConfigurationDefault) TLSCertPath() string

type ConfigurationEvents added in v1.8.18

type ConfigurationEvents interface {
	GetEventsQueueName() string
	GetEventsQueueUrl() string
}

type ConfigurationLogLevel added in v1.19.1

type ConfigurationLogLevel interface {
	LoggingLevel() string
	LoggingLevelIsDebug() bool
}

type ConfigurationOAUTH2 added in v1.7.21

type ConfigurationOAUTH2 interface {
	GetOauthWellKnownJwk() string
	GetOauth2ServiceURI() string
	GetOauth2ServiceClientSecret() string
	GetOauth2ServiceAudience() string
	GetOauth2ServiceAdminURI() string
}

type ConfigurationPorts added in v1.14.0

type ConfigurationPorts interface {
	Port() string
	HttpPort() string
	GrpcPort() string
}

type ConfigurationSecurity added in v1.25.4

type ConfigurationSecurity interface {
	IsRunSecurely() bool
}

type ConfigurationTLS added in v1.13.0

type ConfigurationTLS interface {
	TLSCertPath() string
	TLSCertKeyPath() string
	SetTLSCertAndKeyPath(certificatePath, certificateKeyPath string)
}

type EventI added in v1.6.1

type EventI interface {
	// Name represents the unique human readable id of the event that is used to pick it from the registry
	//or route follow up processing for system to processFunc using this particular event
	Name() string

	// PayloadType determines the type of payload the event uses. This is useful for decoding queue data.
	PayloadType() any

	// Validate enables automatic validation of payload supplied to the event without handling it in the execute block
	Validate(ctx context.Context, payload any) error

	// Execute performs all the logic required to action a step in the sequence of events required to achieve the end goal.
	Execute(ctx context.Context, payload any) error
}

EventI an interface to represent a system event. All logic of an event is handled in the execute task and can also emit other events into the system or if they don't emit an event the processFunc is deemed complete.

type JSONWebKeys added in v1.1.7

type JSONWebKeys struct {
	Kty string   `json:"kty"`
	Kid string   `json:"kid"`
	Use string   `json:"use"`
	N   string   `json:"n"`
	E   string   `json:"e"`
	X5c []string `json:"x5c"`
}

type Job added in v1.9.1

type Job interface {
	JobResultPipe
	F() func(ctx context.Context, result JobResultPipe) error
	ID() string
	CanRun() bool
	Retries() int
	Runs() int
	IncreaseRuns()
}

type JobImpl added in v1.9.1

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

func (*JobImpl) CanRun added in v1.22.0

func (ji *JobImpl) CanRun() bool

func (*JobImpl) Close added in v1.22.0

func (ji *JobImpl) Close()

func (*JobImpl) F added in v1.15.2

func (ji *JobImpl) F() func(ctx context.Context, result JobResultPipe) error

func (*JobImpl) ID added in v1.9.1

func (ji *JobImpl) ID() string

func (*JobImpl) IncreaseRuns added in v1.23.0

func (ji *JobImpl) IncreaseRuns()

func (*JobImpl) IsClosed added in v1.22.0

func (ji *JobImpl) IsClosed() bool

func (*JobImpl) ReadResult added in v1.23.0

func (ji *JobImpl) ReadResult(ctx context.Context) (any, bool, error)

func (*JobImpl) ResultBufferSize added in v1.22.0

func (ji *JobImpl) ResultBufferSize() int

func (*JobImpl) ResultChan added in v1.22.0

func (ji *JobImpl) ResultChan() <-chan any

func (*JobImpl) Retries added in v1.9.1

func (ji *JobImpl) Retries() int

func (*JobImpl) Runs added in v1.22.0

func (ji *JobImpl) Runs() int

func (*JobImpl) WriteResult added in v1.22.0

func (ji *JobImpl) WriteResult(ctx context.Context, val any) error

type JobResultPipe added in v1.23.0

type JobResultPipe interface {
	ResultBufferSize() int
	ResultChan() <-chan any
	WriteResult(ctx context.Context, val any) error
	ReadResult(ctx context.Context) (any, bool, error)
	IsClosed() bool
	Close()
}

type Jwks added in v1.1.7

type Jwks struct {
	Keys []JSONWebKeys `json:"keys"`
}

type Migration

type Migration struct {
	BaseModel

	Name      string `gorm:"type:varchar(50);uniqueIndex:idx_migrations_name"`
	Patch     string `gorm:"type:text"`
	AppliedAt sql.NullTime
}

Migration Our simple table holding all the migration data

type Option

type Option func(service *Service)

func BackGroundConsumer added in v1.8.15

func BackGroundConsumer(deque func(ctx context.Context) error) Option

BackGroundConsumer Option to register a background processing function that is initialized before running servers this function is maintained alive using the same error group as the servers so that if any exit earlier due to error all stop functioning

func Config added in v1.7.13

func Config(config any) Option

Config Option that helps to specify or override the configuration object of our service.

func Datastore

func Datastore(ctx context.Context) Option

func DatastoreConnection added in v1.24.0

func DatastoreConnection(ctx context.Context, postgresqlConnection string, readOnly bool) Option

DatastoreConnection Option method to store a connection that will be utilized when connecting to the database

func EnableGrpcServerReflection added in v1.13.6

func EnableGrpcServerReflection() Option

func GrpcPort added in v1.13.0

func GrpcPort(port string) Option

GrpcPort Option to specify the grpc port for server to bind to

func GrpcServer

func GrpcServer(grpcServer *grpc.Server) Option

GrpcServer Option to specify an instantiated grpc server with an implementation that can be utilized to handle incoming requests.

func GrpcServerListener added in v1.13.0

func GrpcServerListener(listener net.Listener) Option

GrpcServerListener Option to specify user preferred grpcListener instead of the default provided one. This one is mostly useful when grpc is being utilised

func HealthCheckPath added in v1.12.6

func HealthCheckPath(path string) Option

HealthCheckPath Option checks that the system is up and running

func HttpHandler

func HttpHandler(h http.Handler) Option

HttpHandler Option to specify an http handler that can be used to handle inbound http requests

func Logger added in v1.6.1

func Logger() Option

Logger Option that helps with initialization of our internal logger

func NoopDriver added in v1.7.13

func NoopDriver() Option

NoopDriver Option to force the underlying http driver to not listen on a port. This is mostly useful when writing tests especially against the frame service

func RegisterEvents added in v1.6.3

func RegisterEvents(events ...EventI) Option

RegisterEvents Option to write an event or list of events into the service registry for future use. All events are unique and shouldn't share a name otherwise the last one registered will take presedence

func RegisterPublisher

func RegisterPublisher(reference string, queueURL string) Option

RegisterPublisher Option to register publishing path referenced within the system

func RegisterSubscriber

func RegisterSubscriber(reference string, queueURL string, concurrency int,
	handler SubscribeWorker) Option

RegisterSubscriber Option to register a new subscription handler

func ServerListener

func ServerListener(listener net.Listener) Option

ServerListener Option to specify user preferred priListener instead of the default provided one.

func TraceExporter added in v1.7.13

func TraceExporter(exporter sdktrace.SpanExporter) Option

TraceExporter Option that specify the trace exporter to use

func TraceSampler added in v1.7.13

func TraceSampler(sampler sdktrace.Sampler) Option

TraceSampler Option that specify the trace sampler to use

func Translations added in v1.0.5

func Translations(translationsFolder string, languages ...string) Option

Translations Option to initialize/load different language packs

func WithPoolCapacity added in v1.11.2

func WithPoolCapacity(capacity int) Option

WithPoolCapacity Option sets the capacity of pool workers to handle server load. By default this is 100

func WithPoolConcurrency added in v1.11.2

func WithPoolConcurrency(workers int) Option

WithPoolConcurrency Option sets the count of pool workers to handle server load. By default this is count of CPU + 1

type Service

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

Service framework struct to hold together all application components An instance of this type scoped to stay for the lifetime of the application. It is pushed and pulled from contexts to make it easy to pass around.

func FromContext

func FromContext(ctx context.Context) *Service

FromContext obtains a service instance being propagated through the context.

func NewService

func NewService(name string, opts ...Option) (context.Context, *Service)

NewService creates a new instance of Service with the name and supplied options. Internally it calls NewServiceWithContext and creates a background context for use.

func NewServiceWithContext added in v1.25.3

func NewServiceWithContext(ctx context.Context, name string, opts ...Option) (context.Context, *Service)

NewServiceWithContext creates a new instance of Service with context, name and supplied options It is used together with the Init option to setup components of a service that is not yet running.

func (*Service) AddCleanupMethod

func (s *Service) AddCleanupMethod(f func(ctx context.Context))

AddCleanupMethod Adds user defined functions to be run just before completely stopping the service. These are responsible for properly and gracefully stopping active components.

func (*Service) AddHealthCheck

func (s *Service) AddHealthCheck(checker Checker)

AddHealthCheck Adds health checks that are run periodically to ascertain the system is ok The arguments are implementations of the checker interface and should work with just about any system that is given to them.

func (*Service) AddPreStartMethod added in v1.1.3

func (s *Service) AddPreStartMethod(f func(s *Service))

AddPreStartMethod Adds user defined functions that can be run just before the service starts receiving requests but is fully initialized.

func (*Service) AddPublisher added in v1.16.2

func (s *Service) AddPublisher(ctx context.Context, reference string, queueURL string) error

func (*Service) Authenticate added in v1.8.14

func (s *Service) Authenticate(ctx context.Context,
	jwtToken string, audience string, issuer string) (context.Context, error)

func (*Service) AuthenticationMiddleware added in v1.7.17

func (s *Service) AuthenticationMiddleware(next http.Handler, audience string, issuer string) http.Handler

AuthenticationMiddleware Simple http middleware function to verify and extract authentication data supplied in a jwt as authorization bearer token

func (*Service) Bundle added in v1.0.6

func (s *Service) Bundle() *i18n.Bundle

Bundle Access the translation bundle instatiated in the system

func (*Service) Config added in v1.7.13

func (s *Service) Config() any

func (*Service) DB

func (s *Service) DB(ctx context.Context, readOnly bool) *gorm.DB

DB obtains an already instantiated db connection with the option to specify if you want write or read only db connection

func (*Service) Emit added in v1.6.1

func (s *Service) Emit(ctx context.Context, name string, payload any) error

Emit a simple method used to deploy

func (*Service) Environment added in v1.7.13

func (s *Service) Environment() string

Environment gets the runtime environment of the service.

func (*Service) H added in v1.12.5

func (s *Service) H() http.Handler

func (*Service) HandleHealth added in v1.12.5

func (s *Service) HandleHealth(w http.ResponseWriter, _ *http.Request)

HandleHealth returns 200 if it is healthy, 500 otherwise.

func (*Service) HandleHealthByDefault added in v1.12.6

func (s *Service) HandleHealthByDefault(w http.ResponseWriter, r *http.Request)

HandleHealthByDefault returns 200 if it is healthy, 500 when there is an err or 404 otherwise.

func (*Service) HealthCheckers added in v1.7.13

func (s *Service) HealthCheckers() []Checker

func (*Service) Init added in v1.0.4

func (s *Service) Init(opts ...Option)

Init evaluates the options provided as arguments and supplies them to the service object

func (*Service) InvokeRestService added in v1.0.15

func (s *Service) InvokeRestService(ctx context.Context,
	method string, endpointURL string, payload map[string]any,
	headers map[string][]string) (int, []byte, error)

InvokeRestService convenience method to call a http endpoint and utilize the raw results

func (*Service) InvokeRestServiceUrlEncoded added in v1.9.1

func (s *Service) InvokeRestServiceUrlEncoded(ctx context.Context,
	method string, endpointURL string, payload url.Values,
	headers map[string]string) (int, []byte, error)

InvokeRestServiceUrlEncoded convenience method to call a http endpoint and utilize the raw results

func (*Service) IsPublisherRegistered added in v1.16.2

func (s *Service) IsPublisherRegistered(_ context.Context, reference string) bool

func (*Service) JwtClient added in v1.10.0

func (s *Service) JwtClient() map[string]any

JwtClient gets the authenticated jwt client if configured at startup

func (*Service) JwtClientID added in v1.10.0

func (s *Service) JwtClientID() string

JwtClientID gets the authenticated jwt client if configured at startup

func (*Service) JwtClientSecret added in v1.10.1

func (s *Service) JwtClientSecret() string

JwtClientSecret gets the authenticated jwt client if configured at startup

func (*Service) L added in v1.6.1

func (s *Service) L(ctx context.Context) *logrus.Entry

func (*Service) MigrateDatastore

func (s *Service) MigrateDatastore(ctx context.Context, migrationsDirPath string, migrations ...any) error

MigrateDatastore finds missing migrations and records them in the database

func (*Service) Name added in v1.4.0

func (s *Service) Name() string

Name gets the name of the service. Its the first argument used when NewService is called.

func (*Service) NewJob added in v1.9.1

func (s *Service) NewJob(process func(ctx context.Context, result JobResultPipe) error) Job

func (*Service) NewJobWithBuffer added in v1.22.0

func (s *Service) NewJobWithBuffer(process func(ctx context.Context, result JobResultPipe) error, buffer int) Job

func (*Service) NewJobWithBufferAndRetry added in v1.22.0

func (s *Service) NewJobWithBufferAndRetry(process func(ctx context.Context, result JobResultPipe) error, resultBufferSize, retries int) Job

func (*Service) NewJobWithRetry added in v1.15.0

func (s *Service) NewJobWithRetry(process func(ctx context.Context, result JobResultPipe) error, retries int) Job

func (*Service) Publish

func (s *Service) Publish(ctx context.Context, reference string, payload any) error

Publish Queue method to write a new message into the queue pre initialized with the supplied reference

func (*Service) RegisterForJwt added in v1.10.1

func (s *Service) RegisterForJwt(ctx context.Context) error

RegisterForJwt function hooks in jwt client registration to make sure service is authenticated

func (*Service) RegisterForJwtWithParams added in v1.8.1

func (s *Service) RegisterForJwtWithParams(ctx context.Context,
	oauth2ServiceAdminHost string, clientName string, clientSecret string,
	scope string, audienceList []string, metadata map[string]string) (map[string]any, error)

RegisterForJwtWithParams registers the supplied details for ability to generate access tokens. This is useful for situations where one may need to register external applications for access token generation

func (*Service) Run

func (s *Service) Run(ctx context.Context, address string) error

Run is used to actually instantiate the initialised components and keep them useful by handling incoming requests

func (*Service) Stop

func (s *Service) Stop(ctx context.Context)

Stop Used to gracefully run clean up methods ensuring all requests that were being handled are completed well without interuptions.

func (*Service) StreamAuthInterceptor added in v1.7.17

func (s *Service) StreamAuthInterceptor(audience string, issuer string) grpc.StreamServerInterceptor

StreamAuthInterceptor An authentication claims extractor that will always verify the information flowing in the streams as true jwt claims

func (*Service) SubmitJob added in v1.9.1

func (s *Service) SubmitJob(ctx context.Context, job Job) error

SubmitJob used to submit jobs to our worker pool for processing. Once a job is submitted the end user does not need to do any further tasks One can ideally also wait for the results of their processing for their specific job This is done by simply by listening to the jobs ErrChan. Be sure to also check for when its closed

err, ok := <- errChan

func (*Service) SubscriptionIsInitiated added in v1.7.13

func (s *Service) SubscriptionIsInitiated(path string) bool

func (*Service) TLSEnabled added in v1.13.0

func (s *Service) TLSEnabled() bool

func (*Service) Translate added in v1.1.9

func (s *Service) Translate(ctx context.Context, request any, messageId string) string

Translate performs a quick translation based on the supplied message id

func (*Service) TranslateWithMap added in v1.1.9

func (s *Service) TranslateWithMap(ctx context.Context, request any, messageId string, variables map[string]any) string

TranslateWithMap performs a translation with variables based on the supplied message id

func (*Service) TranslateWithMapAndCount added in v1.1.9

func (s *Service) TranslateWithMapAndCount(ctx context.Context, request any, messageId string, variables map[string]any, count int) string

TranslateWithMapAndCount performs a translation with variables based on the supplied message id and can pluralize

func (*Service) UnRegisterForJwt added in v1.8.9

func (s *Service) UnRegisterForJwt(ctx context.Context,
	oauth2ServiceAdminHost string, clientID string) error

UnRegisterForJwt utilizing client id we de register external applications for access token generation

func (*Service) UnaryAuthInterceptor added in v1.7.17

func (s *Service) UnaryAuthInterceptor(audience string, issuer string) grpc.UnaryServerInterceptor

UnaryAuthInterceptor Simple grpc interceptor to extract the jwt supplied via authorization bearer token and verify the authentication claims in the token

func (*Service) Version added in v1.7.13

func (s *Service) Version() string

Version gets the release version of the service.

type SubscribeWorker

type SubscribeWorker interface {
	Handle(ctx context.Context, metadata map[string]string, message []byte) error
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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