serv

package module
v3.0.0-...-91d9d01 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2023 License: Apache-2.0 Imports: 61 Imported by: 2

Documentation

Overview

Package serv provides an API to include and use the GraphJin service with your own code. For detailed documentation visit https://graphjin.com

Example usage:

package main

import (
	"database/sql"
	"fmt"
	"time"
	"github.com/dosco/graphjin/core/v3"
	_ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
	conf := serv.Config{ AppName: "Test App" }
	conf.DB.Host := "127.0.0.1"
	conf.DB.Port := 5432
	conf.DB.DBName := "test_db"
	conf.DB.User := "postgres"
	conf.DB.Password := "postgres"

	gjs, err := serv.NewGraphJinService(conf)
	if err != nil {
		log.Fatal(err)
	}

 	if err := gjs.Start(); err != nil {
		log.Fatal(err)
	}
}

Index

Constants

View Source
const (
	DeployRoute   = "/api/v1/deploy"
	RollbackRoute = "/api/v1/deploy/rollback"
)

Variables

This section is empty.

Functions

func GetConfigName

func GetConfigName() string

func InitAdmin

func InitAdmin(db *sql.DB, dbtype string) error

func InitTelemetry

func InitTelemetry(
	c context.Context,
	exp trace.SpanExporter,
	serviceName, serviceInstanceID string,
) error

func NewDB

func NewDB(conf *Config, openDB bool, log *zap.SugaredLogger, fs core.FS) (*sql.DB, error)

func SecretsCmd

func SecretsCmd(cmdName, fileName string, sa SecretArgs, args []string, log *zap.SugaredLogger) error

Types

type Admin

type Admin struct {
	// Enables the ability to hot-deploy a new configuration
	HotDeploy bool `mapstructure:"hot_deploy" jsonschema:"title=Enable Hot Deploy"`

	// Secret key used to control access to the admin api
	AdminSecretKey string `mapstructure:"admin_secret_key" jsonschema:"title=Admin API Secret Key"`
}

Configuration for admin service

type Auth

type Auth = auth.Auth

type Client

type Client struct {
	*resty.Client
}

func NewAdminClient

func NewAdminClient(host string, secret string) *Client

func (*Client) Deploy

func (c *Client) Deploy(name, confPath string) (*Resp, error)

func (*Client) Rollback

func (c *Client) Rollback() (*Resp, error)

type Config

type Config struct {

	// Configuration for the GraphJin compiler core
	Core `mapstructure:",squash" jsonschema:"title=Compiler Configuration"`

	// Configuration for the GraphJin Service
	Serv `mapstructure:",squash" jsonschema:"title=Service Configuration"`

	// Configuration for admin service
	Admin `mapstructure:",squash" jsonschema:"title=Admin Configuration"`
	// contains filtered or unexported fields
}

Configuration for the GraphJin service

func NewConfig

func NewConfig(config, format string) (*Config, error)

func ReadInConfig

func ReadInConfig(configFile string) (*Config, error)

ReadInConfig function reads in the config file for the environment specified in the GO_ENV environment variable. This is the best way to create a new GraphJin config.

func ReadInConfigFS

func ReadInConfigFS(configFile string, fs afero.Fs) (*Config, error)

ReadInConfigFS is the same as ReadInConfig but it also takes a filesytem as an argument

func (*Config) GetSecret

func (c *Config) GetSecret(k string) (string, bool)

func (*Config) GetSecretOrEnv

func (c *Config) GetSecretOrEnv(k string) string

func (*Config) RelPath

func (c *Config) RelPath(p string) string

func (*Config) SetHash

func (c *Config) SetHash(hash string)

func (*Config) SetName

func (c *Config) SetName(name string)

type Core

type Core = core.Config

type Database

type Database struct {
	ConnString string `mapstructure:"connection_string" jsonschema:"title=Connection String"`
	Type       string `jsonschema:"title=Type,enum=postgres,enum=mysql"`
	Host       string `jsonschema:"title=Host"`
	Port       uint16 `jsonschema:"title=Port"`
	DBName     string `jsonschema:"title=Database Name"`
	User       string `jsonschema:"title=User"`
	Password   string `jsonschema:"title=Password"`
	Schema     string `jsonschema:"title=Postgres Schema"`

	// Size of database connection pool
	PoolSize int `mapstructure:"pool_size" jsonschema:"title=Connection Pool Size"`

	// Max number of active database connections allowed
	MaxConnections int `mapstructure:"max_connections" jsonschema:"title=Maximum Connections"`

	// Max time after which idle database connections are closed
	MaxConnIdleTime time.Duration `mapstructure:"max_connection_idle_time" jsonschema:"title=Connection Idel Time"`

	// Max time after which database connections are not reused
	MaxConnLifeTime time.Duration `mapstructure:"max_connection_life_time" jsonschema:"title=Connection Life Time"`

	// Database ping timeout is used for db health checking
	PingTimeout time.Duration `mapstructure:"ping_timeout" jsonschema:"title=Healthcheck Ping Timeout"`

	// Set up an secure TLS encrypted database connection
	EnableTLS bool `mapstructure:"enable_tls" jsonschema:"title=Enable TLS"`

	// Required for TLS. For example with Google Cloud SQL it's
	// <gcp-project-id>:<cloud-sql-instance>
	ServerName string `mapstructure:"server_name" jsonschema:"title=TLS Server Name"`

	// Required for TLS. Can be a file path or the contents of the PEM file
	ServerCert string `mapstructure:"server_cert" jsonschema:"title=Server Certificate"`

	// Required for TLS. Can be a file path or the contents of the PEM file
	ClientCert string `mapstructure:"client_cert" jsonschema:"title=Client Certificate"`

	// Required for TLS. Can be a file path or the contents of the pem file
	ClientKey string `mapstructure:"client_key" jsonschema:"title=Client Key"`
}

Database configuration

type DeployReq

type DeployReq struct {
	Name   string `json:"name"`
	Bundle string `json:"bundle"`
}

type HookFn

type HookFn func(*core.Result)

type JWTConfig

type JWTConfig = auth.JWTConfig

type Mux

type Mux interface {
	Handle(string, http.Handler)
	ServeHTTP(http.ResponseWriter, *http.Request)
}

type Option

type Option func(*service) error

func OptionDeployActive

func OptionDeployActive() Option

OptionDeployActive caused the active config to be deployed on

func OptionSetDB

func OptionSetDB(db *sql.DB) Option

OptionSetDB sets a new db client

func OptionSetFS

func OptionSetFS(fs core.FS) Option

OptionSetFS sets service filesystem

func OptionSetHookFunc

func OptionSetHookFunc(fn HookFn) Option

OptionSetHookFunc sets a function to be called on every request

func OptionSetNamespace

func OptionSetNamespace(namespace string) Option

OptionSetNamespace sets service namespace

func OptionSetZapLogger

func OptionSetZapLogger(zlog *zap.Logger) Option

OptionSetZapLogger sets service structured logger

type Payload

type Payload struct {
	Data   json.RawMessage `json:"data,omitempty"`
	Errors []core.Error    `json:"errors,omitempty"`
}

type RateLimiter

type RateLimiter struct {
	// The number of events per second
	Rate float64 `jsonschema:"title=Connection Rate"`

	// Bucket a burst of at most 'bucket' number of events
	Bucket int `jsonschema:"title=Bucket Size"`

	// The header that contains the client ip
	IPHeader string `mapstructure:"ip_header" jsonschema:"title=IP From HTTP Header,example=X-Forwarded-For"`
}

RateLimiter sets the API rate limits

type Resp

type Resp struct {
	Msg string
}

type SecretArgs

type SecretArgs struct {
	KMS, KMSC, AWS, GCP, Azure, PGP string
}

type Serv

type Serv struct {
	// Application name is used in log and debug messages
	AppName string `mapstructure:"app_name" jsonschema:"title=Application Name"`

	// When enabled runs the service with production level security defaults.
	// For example allow lists are enforced.
	Production bool `jsonschema:"title=Production Mode,default=false"`

	// The default path to find all configuration files and scripts
	ConfigPath string `mapstructure:"config_path" jsonschema:"title=Config Path"`

	// The file for the secret key store. This must be a Mozilla SOPS file
	SecretsFile string `mapstructure:"secrets_file" jsonschema:"title=Secrets File"`

	// Logging level must be one of debug, error, warn, info
	LogLevel string `mapstructure:"log_level" jsonschema:"title=Log Level,enum=debug,enum=error,enum=warn,enum=info"`

	// Logging Format must me either json or simple
	LogFormat string `mapstructure:"log_format" jsonschema:"title=Logging Level,enum=json,enum=simple"`

	// The host and port the service runs on. Example localhost:8080
	HostPort string `mapstructure:"host_port" jsonschema:"title=Host and Port"`

	// Host to run the service on
	Host string `jsonschema:"title=Host"`

	// Port to run the service on
	Port string `jsonschema:"title=Port"`

	// Enables HTTP compression
	HTTPGZip bool `mapstructure:"http_compress" jsonschema:"title=Enable Compression,default=true"`

	// Sets the API rate limits
	RateLimiter RateLimiter `mapstructure:"rate_limiter" jsonschema:"title=Set API Rate Limiting"`

	// Enables the Server-Timing HTTP header
	ServerTiming bool `mapstructure:"server_timing" jsonschema:"title=Server Timing HTTP Header,default=true"`

	// Enable the web UI. Disabled in production
	WebUI bool `mapstructure:"web_ui" jsonschema:"title=Enable Web UI,default=false"`

	// Enable OpenTrace request tracing
	EnableTracing bool `mapstructure:"enable_tracing" jsonschema:"title=Enable Tracing,default=true"`

	// Enables reloading the service on config changes. Disabled in production
	WatchAndReload bool `mapstructure:"reload_on_config_change" jsonschema:"title=Reload Config"`

	// Enable blocking requests with a HTTP 401 on auth failure
	AuthFailBlock bool `mapstructure:"auth_fail_block" jsonschema:"title=Block Request on Authorization Failure"`

	// This is the path to the database migration files
	MigrationsPath string `mapstructure:"migrations_path" jsonschema:"title=Migrations Path"`

	// Sets the HTTP CORS Access-Control-Allow-Origin header
	AllowedOrigins []string `mapstructure:"cors_allowed_origins" jsonschema:"title=HTTP CORS Allowed Origins"`

	// Sets the HTTP CORS Access-Control-Allow-Headers header
	AllowedHeaders []string `mapstructure:"cors_allowed_headers" jsonschema:"title=HTTP CORS Allowed Headers"`

	// Enables debug logs for CORS
	DebugCORS bool `mapstructure:"cors_debug" jsonschema:"title=Log CORS"`

	// Sets the HTTP Cache-Control header
	CacheControl string `mapstructure:"cache_control" jsonschema:"title=Enable Cache-Control"`

	// Sets the default authentication used by the service
	Auth Auth `jsonschema:"title=Authentication"`

	// Database configuration
	DB Database `mapstructure:"database" jsonschema:"title=Database"`
}

Configuration for the GraphJin Service

type Service

type Service struct {
	atomic.Value
	// contains filtered or unexported fields
}

func NewGraphJinService

func NewGraphJinService(conf *Config, options ...Option) (*Service, error)

NewGraphJinService a new service

func (*Service) Attach

func (s *Service) Attach(mux Mux) error

Attach route to the internal http service

func (*Service) AttachWithNS

func (s *Service) AttachWithNS(mux Mux, namespace string) error

AttachWithNS a namespaced route to the internal http service

func (*Service) Deploy

func (s *Service) Deploy(conf *Config, options ...Option) error

Deploy a new configuration

func (*Service) GetDB

func (s *Service) GetDB() *sql.DB

GetDB fetching internal db client

func (*Service) GetGraphJin

func (s *Service) GetGraphJin() *core.GraphJin

GetGraphJin fetching internal GraphJin core

func (*Service) GraphQL

func (s *Service) GraphQL(ah auth.HandlerFunc) http.Handler

GraphQLis the http handler the GraphQL endpoint

func (*Service) GraphQLWithNS

func (s *Service) GraphQLWithNS(ah auth.HandlerFunc, ns string) http.Handler

GraphQLWithNS is the http handler the namespaced GraphQL endpoint

func (*Service) REST

func (s *Service) REST(ah auth.HandlerFunc) http.Handler

REST is the http handler the REST endpoint

func (*Service) RESTWithNS

func (s *Service) RESTWithNS(ah auth.HandlerFunc, ns string) http.Handler

RESTWithNS is the http handler the namespaced REST endpoint

func (*Service) Reload

func (s *Service) Reload() error

Reload re-runs database discover and reinitializes service.

func (*Service) Start

func (s *Service) Start() error

Start the service listening on the configured port

func (*Service) WebUI

func (s *Service) WebUI(routePrefix, gqlEndpoint string) http.Handler

WebUI is the http handler the web ui endpoint

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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