vhost

package
v0.0.0-...-3f54671 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2022 License: MIT Imports: 15 Imported by: 1

Documentation

Index

Examples

Constants

View Source
const (
	CommandChannelStart = iota
	CommandChannelStop
	CommandChannelPause
	CommandChannelResume
)
View Source
const (
	// gRPC status codes
	// https://grpc.github.io/grpc/core/md_doc_statuscodes.html
	StatusInvalidContent     = int32(-1) // Content is not available or is of the wrong type, usually found via unmarshalling
	StatusOk                 = int32(0)  // Not an error; returned on success.
	StatusCancelled          = int32(1)  // The operation was cancelled, typically by the caller.
	StatusUnknown            = int32(2)  // Unknown error. For example, this error may be returned when a Status value received from another address space belongs to an error space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
	StatusInvalidArgument    = int32(3)  // The client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
	StatusDeadlineExceeded   = int32(4)  // The deadline expired before the operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long
	StatusNotFound           = int32(5)  // Some requested entity (e.g., file or directory) was not found. Note to server developers: if a request is denied for an entire class of users, such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used. If a request is denied for some users within a class of users, such as user-based access control, PERMISSION_DENIED must be used.
	StatusAlreadyExists      = int32(6)  // The entity that a client attempted to create (e.g., file or directory) already exists.
	StatusPermissionDenied   = int32(7)  // The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors). This error code does not imply the request is valid or the requested entity exists or satisfies other pre-conditions.
	StatusResourceExhausted  = int32(8)  // Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
	StatusFailedPrecondition = int32(9)  // The operation was rejected because the system is not in a state required for the operation's execution. For example, the directory to be deleted is non-empty, an rmdir operation is applied to a non-directory, etc. Service implementors can use the following guidelines to decide between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: (a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level (e.g., when a client-specified test-and-set fails, indicating the client should restart a read-modify-write sequence). (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless the files are deleted from the directory.
	StatusAborted            = int32(10) // The operation was aborted, typically due to a concurrency issue such as a sequencer check failure or transaction abort. See the guidelines above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
	StatusOutOfRange         = int32(11) // The operation was attempted past the valid range. E.g., seeking or reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size. There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
	StatusUnimplemented      = int32(12) // The operation is not implemented or is not supported/enabled in this service.
	StatusInternal           = int32(13) // Internal errors. This means that some invariants expected by the underlying system have been broken. This error code is reserved for serious errors.
	StatusUnavailable        = int32(14) // The service is currently unavailable. This is most likely a transient condition, which can be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
	StatusDataLoss           = int32(15) // Unrecoverable data loss or corruption.
	StatusUnauthenticated    = int32(16) // The request does not have valid authentication credentials for the operation.
)

Variables

This section is empty.

Functions

func ContextContent

func ContextContent(ctx context.Context) any

func ContextRequestId

func ContextRequestId(ctx context.Context) string

ContextRequestId - return the requestId from a Context

func ContextWithContent

func ContextWithContent(ctx context.Context, content any) context.Context

ContextWithContent - creates a new Context with content

func ContextWithFSContent

func ContextWithFSContent(ctx context.Context, fs fs.FS, name string) context.Context

ContextWithFSContent - creates a new Context with FS content

func ContextWithRequestId

func ContextWithRequestId(ctx context.Context, requestId string) context.Context

ContextWithRequestId - creates a new Context with a request id

func CreateCredentialsMessage

func CreateCredentialsMessage(to, from, event string, fn Credentials) eventing.Message

CreateCredentialsMessage - functions

func CustomLoggingHandler

func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler

func GetEnv

func GetEnv() string

GetEnv - function to get the vhost runtime environment

func IsContextContent

func IsContextContent(ctx context.Context) bool

func IsDevEnv

func IsDevEnv() bool

func IsDevEnvironment

func IsDevEnvironment() bool

func IsPackageStartupSuccessful

func IsPackageStartupSuccessful(uri string) bool

IsPackageStartupSuccessful - determine if a package was successfully started

func MountFS

func MountFS(f fs.FS)

func NewgRPCStatus

func NewgRPCStatus(code int32, msg any) gRPCStatus

func OverrideIsDevEnv

func OverrideIsDevEnv(fn FuncBool)

OverrideIsDevEnv - function to override dev environment determination

func OverrideMaxStartupIterations

func OverrideMaxStartupIterations(count int)

func ReadFile

func ReadFile(name string) ([]byte, error)

ReadFile - read a file from the mounted fs, adding the resource directory as that is not known by the client

Example
package main

import (
	"embed"
	"fmt"
)

//go:embed resource/*
var content embed.FS

func init() {
	MountFS(content)
}

func _ExampleFileSystemNotMounted() {
	_, err := ReadFile("resource/readme.txt")
	fmt.Printf("Error : %v\n", err)

	//Output:
	// Error : invalid argument : file system has not been mounted
}

func main() {
	_, err0 := ReadFile("")
	fmt.Printf("Error : %v\n", err0)

	buf, err := ReadFile("bad-path/config_bad.txt")
	if err != nil {
		fmt.Printf("Error : %v\n", err)
	} else {
		fmt.Println(string(buf))
	}

	buf, err = ReadFile("postgresql/config_{env}.txt")
	if err != nil {
		fmt.Printf("Error : %v\n", err)
	} else {
		fmt.Println(string(buf))
	}

	// Should override and return config_test.txt
	/*
		lookupEnv = func(name string) (string, error) { return "stage", nil }
		buf, err = ReadFile("postgresql/config_{env}.txt")
		if err != nil {
			fmt.Printf("Error : %v\n", err)
		} else {
			fmt.Println(string(buf))
		}
	*/

}

func _ExampleReadMap() {
	_, err0 := ReadMap("")
	fmt.Printf("Error : %v\n", err0)

	m, err := ReadMap("postgresql/config_dev.txt")
	if err != nil {
		fmt.Printf("Error : %v\n", err)
	} else {
		fmt.Printf("Map [config_dev.txt]: %v\n", m)
	}

	m, err = ReadMap("postgresql/config_test.txt")
	if err != nil {
		fmt.Printf("Error : %v\n", err)
	} else {
		fmt.Printf("Map [config_test.txt]: %v\n", m)
	}

	// Should override and return config_test.txt
	lookupEnv = func(name string) (string, error) { return "stage", nil }
	m, err = ReadMap("postgresql/config_{env}.txt")
	if err != nil {
		fmt.Printf("Error : %v\n", err)
	} else {
		fmt.Printf("Map : %v\n", m)
	}

	
Output:

Error : invalid argument : file name is empty
Error : open resource/bad-path/config_bad.txt: file does not exist
Error : invalid argument : template variable is invalid: env

func ReadMap

func ReadMap(path string) (map[string]string, error)

func RegisterPackage

func RegisterPackage(uri string, c chan eventing.Message) error

RegisterPackage - function to register a package uri

func SendStartupFailureResponse

func SendStartupFailureResponse(from string)

func SendStartupSuccessfulResponse

func SendStartupSuccessfulResponse(from string)

func SetEnv

func SetEnv(s string)

SetEnv - function to set the vhost runtime environment

func Shutdown

func Shutdown()

Shutdown - virtual host shutdown

func TestDriver

func TestDriver() string

Types

type ClosableChannel

type ClosableChannel struct {
	C chan struct{}
}

func CreateClosableChannel

func CreateClosableChannel() *ClosableChannel

CreateClosableChannel : create a closable channel type, with a minimum channel capacity of 1, otherwise,

the routine will block waiting on a receive from the stop channel

func (*ClosableChannel) Close

func (c *ClosableChannel) Close()

type CommandChannel

type CommandChannel struct {
	C    chan int
	Tick *time.Duration
}

func CreateCommandChannel

func CreateCommandChannel(tick time.Duration) *CommandChannel

func (*CommandChannel) NewTicker

func (c *CommandChannel) NewTicker() *time.Ticker

func (*CommandChannel) Pause

func (c *CommandChannel) Pause()

func (*CommandChannel) Resume

func (c *CommandChannel) Resume()

func (*CommandChannel) Start

func (c *CommandChannel) Start()

func (*CommandChannel) Stop

func (c *CommandChannel) Stop()

type Credentials

type Credentials func() (username string, password string, err error)

func AccessCredentials

func AccessCredentials(msg *eventing.Message) Credentials

type Errors

type Errors interface {
	error
	IsError() bool
	Errors() []error
	Add(err error)
}

func NewErrors

func NewErrors(errs ...error) Errors
Example
errs := NewErrors(errors.New("first error"), errors.New("second error"))

fmt.Printf("IsError: %v\n", errs.IsError())
fmt.Printf("Error  : %v\n", errs)
fmt.Printf("Errors : %v\n", errs.Errors())
errs.Add(errors.New("third error"))
fmt.Printf("Errors : %v\n", errs.Errors())
//fmt.Printf("Cat    : %v\n", errs.Cat())
Output:

IsError: true
Error  : first error : second error
Errors : [first error second error]
Errors : [first error second error third error]

func NewErrorsAny

func NewErrorsAny(a any) Errors
Example
func ExampleNewErrorsHandled() {
	errs := NewErrorsList([]error{errors.New("first error"), errors.New("second error")})

	fmt.Printf("IsError: %v\n", errs.IsError())
	fmt.Printf("Error  : %v\n", errs)
	fmt.Printf("Errors : %v\n", errs.Errors())

	errs.Handled()
	fmt.Printf("IsError: %v\n", errs.IsError())
	//fmt.Printf("Error  : %v\n", errs)
	fmt.Printf("Errors : %v\n", errs.Errors())

	//Output:
	//IsError: true
	//Error  : first error : second error
	//Errors : [first error second error]
	//IsError: false
	//Errors : []

}

errs := NewErrorsAny("should not be an error")

fmt.Printf("IsError: %v\n", errs.IsError())
fmt.Printf("Errors : %v\n", errs.Errors())

errs = NewErrorsAny(errors.New("this should be an error"))
fmt.Printf("IsError: %v\n", errs.IsError())
fmt.Printf("Errors : %v\n", errs.Errors())
Output:

IsError: false
Errors : []
IsError: true
Errors : [this should be an error]

func NewErrorsList

func NewErrorsList(errs []error) Errors
Example
errs := NewErrorsList([]error{errors.New("first error"), errors.New("second error")})

fmt.Printf("IsError: %v\n", errs.IsError())
fmt.Printf("Error  : %v\n", errs)
fmt.Printf("Errors : %v\n", errs.Errors())
//fmt.Printf("Cat    : %v\n", errs.Cat())
Output:

IsError: true
Error  : first error : second error
Errors : [first error second error]

type FuncBool

type FuncBool func() bool

FuncBool - type for niladic functions, functions with no parameters

type LogFormatter

type LogFormatter func(writer io.Writer, params LogFormatterParams)

LogFormatter gives the signature of the formatter function passed to CustomLoggingHandler

type LogFormatterParams

type LogFormatterParams struct {
	Request    *http.Request
	URL        url.URL
	TimeStamp  time.Time
	StatusCode int
	Size       int
}

https://github.com/gorilla/handlers/blob/master/logging.go LogFormatterParams is the structure any formatter will be handed when time to log comes

type LookupVariable

type LookupVariable = func(name string) (value string, err error)

type MessageMap

type MessageMap map[string]eventing.Message

type ResponseChannel

type ResponseChannel struct {
	C    chan any
	Tick *time.Duration
}

func CreateResponseChannel

func CreateResponseChannel(tick time.Duration) *ResponseChannel

func (*ResponseChannel) NewTicker

func (c *ResponseChannel) NewTicker() *time.Ticker

type Status

type Status interface {
	fmt.Stringer

	Errors
	HttpStatus() int
	Handled() Status
	// contains filtered or unexported methods
}

func NewStatusAlreadyExists

func NewStatusAlreadyExists(a any) Status

func NewStatusCancelled

func NewStatusCancelled(a any) Status

func NewStatusCode

func NewStatusCode(code int32, a any) Status

func NewStatusDeadlineExceeded

func NewStatusDeadlineExceeded(a any) Status

func NewStatusError

func NewStatusError(err ...error) Status

func NewStatusGRPC

func NewStatusGRPC(grpcStatus gRPCStatus) Status

func NewStatusInProgress

func NewStatusInProgress() Status

func NewStatusInternal

func NewStatusInternal(a any) Status

func NewStatusInvalidArgument

func NewStatusInvalidArgument(a any) Status

func NewStatusNotFound

func NewStatusNotFound(a any) Status

func NewStatusOk

func NewStatusOk() Status

func NewStatusOkMessage

func NewStatusOkMessage(a any) Status

func NewStatusPermissionDenied

func NewStatusPermissionDenied(a any) Status

func NewStatusUnauthenticated

func NewStatusUnauthenticated(a any) Status

func NewStatusUnavailable

func NewStatusUnavailable(a any) Status

func ProcessContent

func ProcessContent[T any](content any) (T, Status)

func ProcessContextContent

func ProcessContextContent[T any](ctx context.Context) (T, Status)

func Startup

func Startup(ticks int, override MessageMap) Status

Startup - virtual host startup

Jump to

Keyboard shortcuts

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