server

package
v0.0.0-...-fd63c1f Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EC_NO_ROUTE = 1000 + iota
	EC_CONTENTTYPE_UNSUPPORTED
	EC_CONTENTTYPE_UNEXPECTED
	EC_MARSHAL_FAILED
	EC_DEMARSHAL_FAILED
	EC_BAD_URL_QUERY
	EC_PARAM_REQUIRED
	EC_PARAM_INVALID
	EC_PARAM_NOISOLANG
	EC_PARAM_NOISOCOUNTRY
	EC_PARAM_NOTEXPECTED
)

10xx - HTTP errors

View Source
const (
	EC_DATABASE = 1100 + iota
	EC_SERVER
	EC_RPC
	EC_NETWORK
)

11xx - internal server error codes

View Source
const (
	EC_ACCESS_HEADER_MISSING = 1200 + iota
	EC_ACCESS_APIKEY_MISSING
	EC_ACCESS_APIKEY_INVALID
	EC_ACCESS_APIKEY_INACTIVE
	EC_ACCESS_APIVERSION_INVALID
	EC_ACCESS_METHOD_UNSUPPORTED
	EC_ACCESS_ORIGIN_DENIED
	EC_ACCESS_TOKEN_MISSING
	EC_ACCESS_TOKEN_MALFORMED
	EC_ACCESS_TOKEN_INVALID
	EC_ACCESS_TOKEN_REVOKED
	EC_ACCESS_TOKEN_EXPIRED
	EC_ACCESS_SCOPES_INSUFFICIENT
	EC_ACCESS_RATE_LIMITED
	EC_ACCESS_READONLY
	EC_ACCESS_DENIED
)

12xx - Access errors

View Source
const (
	EC_RESOURCE_ID_MISSING = 1300 + iota
	EC_RESOURCE_ID_MALFORMED
	EC_RESOURCE_VERSION_MISMATCH
	EC_RESOURCE_TYPE_MISMATCH
	EC_RESOURCE_CONFLICT
	EC_RESOURCE_NOTFOUND
	EC_RESOURCE_EXISTS
	EC_RESOURCE_CREATE_FAILED
	EC_RESOURCE_UPDATE_FAILED
	EC_RESOURCE_DELETE_FAILED
	EC_RESOURCE_STATE_UNEXPECTED
)

13xx - Resource errors

Variables

View Source
var (
	EBadRequest         = NewWrappedError(http.StatusBadRequest, "incorrect request syntax")
	EUnauthorized       = NewWrappedError(http.StatusUnauthorized, "authentication required")
	EForbidden          = NewWrappedError(http.StatusForbidden, "access forbidden")
	ENotFound           = NewWrappedError(http.StatusNotFound, "resource not found")
	ENotAllowed         = NewWrappedError(http.StatusMethodNotAllowed, "method not allowed")
	ENotAcceptable      = NewWrappedError(http.StatusNotAcceptable, "unsupported response type")
	EBadMimetype        = NewWrappedError(http.StatusUnsupportedMediaType, "unsupported media type")
	EConflict           = NewWrappedError(http.StatusConflict, "resource state conflict")
	EInternal           = NewWrappedError(http.StatusInternalServerError, "internal server error")
	ERequestTooLarge    = NewWrappedError(http.StatusRequestEntityTooLarge, "request size exceeds our limits")
	ETooManyRequests    = NewWrappedError(http.StatusTooManyRequests, "request limit exceeded")
	EServiceUnavailable = NewWrappedError(http.StatusServiceUnavailable, "service temporarily unavailable")
	ENotImplemented     = NewWrappedError(http.StatusNotImplemented, "not implemented")
	EConnectionClosed   = NewWrappedError(499, "connection closed")
)

Server Error Reasons

View Source
var (
	UserAgent  = "Blockwatch-TzIndex/1.0"
	ApiVersion string
)

Functions

func C

func C(f ApiCall) func(http.ResponseWriter, *http.Request)

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func MapError

func MapError(scope, msg string, err error) error

func NewRouter

func NewRouter() *mux.Router

Generate a new API router with support for HTTP OPTIONS

func NotFound

func NotFound(ctx *Context) (interface{}, int)

func ParseErrorFromByte

func ParseErrorFromByte(b []byte, status int) error

func ParseErrorFromStream

func ParseErrorFromStream(i io.Reader, status int) error

func Query

func Query(ctx *Context, key string) (mode pack.FilterMode, val string, ok bool)

func Register

func Register(model RESTful)

func StateOptions

func StateOptions(ctx *Context) (interface{}, int)

Respond to requests with the OPTIONS Method.

func UseLogger

func UseLogger(logger logpkg.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type ApiCall

type ApiCall func(*Context) (interface{}, int)

type ApiErrorWrapper

type ApiErrorWrapper func(code int, detail string, err error) *Error

func NewWrappedApiError

func NewWrappedApiError(status int, msg string) ApiErrorWrapper

type Config

type Config struct {
	Crawler *etl.Crawler
	Indexer *etl.Indexer
	Client  *rpc.Client
	Http    HttpConfig
}

func (Config) ClampExplore

func (c Config) ClampExplore(count uint) uint

func (Config) ClampExplore64

func (c Config) ClampExplore64(count int64) int64

func (Config) ClampList

func (c Config) ClampList(count uint) uint

func (Config) ClampList64

func (c Config) ClampList64(count int64) int64

type Context

type Context struct {
	context.Context
	// request data
	Request        *http.Request
	ResponseWriter http.ResponseWriter
	RemoteIP       net.IP
	Cfg            *Config
	Server         *RestServer
	Crawler        *etl.Crawler
	Indexer        *etl.Indexer
	Client         *rpc.Client
	Tip            *model.ChainTip
	Params         *rpc.Params

	// QoS and Debugging
	RequestID string
	Log       logpkg.Logger

	// Statistics
	Now         time.Time
	Expires     time.Time
	Performance *PerformanceCounter
	// contains filtered or unexported fields
}

func NewContext

func NewContext(ctx context.Context, r *http.Request, w http.ResponseWriter, f ApiCall, srv *RestServer) *Context

func (*Context) ParseRequestArgs

func (api *Context) ParseRequestArgs(args interface{})

GET/POST/PATCH/PATCH load data or fail

func (*Context) RequestString

func (api *Context) RequestString() string

func (*Context) StreamResponseHeaders

func (api *Context) StreamResponseHeaders(status int, contentType string)

func (*Context) StreamTrailer

func (api *Context) StreamTrailer(cursor string, count int, err error)

type Dispatcher

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

func NewDispatcher

func NewDispatcher(maxWorkers int, maxQueue int) *Dispatcher

func (*Dispatcher) Run

func (d *Dispatcher) Run()

type Error

type Error struct {
	Code      int    `json:"code"`
	Status    int    `json:"status"`
	Message   string `json:"message"`
	Scope     string `json:"scope"`
	Detail    string `json:"detail"`
	RequestId string `json:"request_id,omitempty"`
	Cause     error  `json:"-"`
	Reason    string `json:"reason,omitempty"`
}

func (*Error) Complete

func (e *Error) Complete(code int, detail string, err error) error

func (*Error) CompleteApiError

func (e *Error) CompleteApiError(code int, detail string, err error) *Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) Marshal

func (e *Error) Marshal() []byte

func (*Error) MarshalIndent

func (e *Error) MarshalIndent() []byte

func (*Error) SetScope

func (e *Error) SetScope(s string)

func (*Error) String

func (e *Error) String() string

func (*Error) WithReason

func (e *Error) WithReason(r string) *Error

func (*Error) WithRequestId

func (e *Error) WithRequestId(i string) *Error

func (*Error) WithScope

func (e *Error) WithScope(s string) *Error

type ErrorList

type ErrorList []*Error

type ErrorResponse

type ErrorResponse struct {
	Errors ErrorList `json:"errors"`
}

type ErrorWrapper

type ErrorWrapper func(code int, detail string, err error) error

func NewWrappedError

func NewWrappedError(status int, msg string) ErrorWrapper

type HttpConfig

type HttpConfig struct {
	Addr                string        `json:"addr"`
	Port                int           `json:"port"`
	MaxWorkers          int           `json:"max_workers"`
	MaxQueue            int           `json:"max_queue"`
	TimeoutHeader       string        `json:"timeout_header"`
	FailHeader          string        `json:"fail_header"`
	DegradedHeader      string        `json:"degraded_header"`
	LimitHeader         string        `json:"limit_header"`
	ReadTimeout         time.Duration `json:"read_timeout"`
	HeaderTimeout       time.Duration `json:"header_timeout"`
	WriteTimeout        time.Duration `json:"write_timeout"`
	KeepAlive           time.Duration `json:"keep_alive"`
	ShutdownTimeout     time.Duration `json:"shutdown_timeout"`
	DefaultListCount    uint          `json:"default_list_count"`
	MaxListCount        uint          `json:"max_list_count"`
	DefaultExploreCount uint          `json:"default_explore_count"`
	MaxExploreCount     uint          `json:"max_explore_count"`
	MaxSeriesDuration   time.Duration `json:"max_series_duration"`
	CorsEnable          bool          `json:"cors_enable"`
	CorsOrigin          string        `json:"cors_origin"`
	CorsAllowHeaders    string        `json:"cors_allow_headers"`
	CorsExposeHeaders   string        `json:"cors_expose_headers"`
	CorsMethods         string        `json:"cors_methods"`
	CorsMaxAge          string        `json:"cors_maxage"`
	CorsCredentials     string        `json:"cors_credentials"`
	CacheEnable         bool          `json:"cache_enable"`
	CacheControl        string        `json:"cache_control"`
	CacheExpires        time.Duration `json:"cache_expires"`
	CacheMaxExpires     time.Duration `json:"cache_max"`
}

HTTP Server Configuration

func NewHttpConfig

func NewHttpConfig() HttpConfig

func (HttpConfig) Address

func (c HttpConfig) Address() string

func (*HttpConfig) Check

func (cfg *HttpConfig) Check() error

type Options

type Options interface {
	WithPrim() bool
	WithUnpack() bool
	WithHeight() int64
	WithMeta() bool
	WithRights() bool
	WithMerge() bool
	WithStorage() bool
}

type ParsableRequest

type ParsableRequest interface {
	Parse(ctx *Context)
}

type PerformanceCounter

type PerformanceCounter struct {
	Runtime time.Duration
	// contains filtered or unexported fields
}

func NewPerformanceCounter

func NewPerformanceCounter(now time.Time) *PerformanceCounter

func (*PerformanceCounter) EndCall

func (p *PerformanceCounter) EndCall()

func (*PerformanceCounter) Since

func (p *PerformanceCounter) Since() time.Duration

func (*PerformanceCounter) StartCall

func (p *PerformanceCounter) StartCall(now time.Time)

func (*PerformanceCounter) WriteResponseHeader

func (p *PerformanceCounter) WriteResponseHeader(w http.ResponseWriter)

func (*PerformanceCounter) WriteResponseTrailer

func (p *PerformanceCounter) WriteResponseTrailer(w http.ResponseWriter)

type RESTful

type RESTful interface {
	RESTPrefix() string
	RESTPath(r *mux.Router) string
	RegisterRoutes(r *mux.Router) error
	RegisterDirectRoutes(r *mux.Router) error
}

type Resource

type Resource interface {
	LastModified() time.Time
	Expires() time.Time
}

type RestServer

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

func New

func New(cfg *Config) (*RestServer, error)

func (*RestServer) IsOffline

func (s *RestServer) IsOffline() bool

func (*RestServer) IsShutdown

func (s *RestServer) IsShutdown() bool

func (*RestServer) SetOffline

func (s *RestServer) SetOffline(off bool)

func (*RestServer) Start

func (s *RestServer) Start()

func (*RestServer) Stop

func (s *RestServer) Stop()

type Worker

type Worker struct {
	WorkerPool chan chan *Context
	JobChannel chan *Context
	// contains filtered or unexported fields
}

func NewWorker

func NewWorker(workerPool chan chan *Context) Worker

func (Worker) Start

func (w Worker) Start()

func (Worker) Stop

func (w Worker) Stop()

Stop signals the worker to stop listening for work requests.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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