vostok

package module
v0.0.0-...-d427cfa Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2021 License: MIT Imports: 46 Imported by: 0

README

Go Report Card

Vostok


What Vostok can do

  • Vostok's core services
  • The REST layer
  • The Admin functionalities

Top


If you do not have Go yet

There are several ways to setup Go.

With macOS, a straightforward way is the following:

  • Install brew, if you do not already have it. Learn a bit how to use it.
  • Then: brew install go
  • Create a common folder for all your Go projects (mandatory), for example: mkdir -p ~/Git/Go
  • Then, add to your bash env file (providing you followed the same paths - else just adapt this):
export GOROOT=/usr/local/opt/go/libexec
export GOPATH=$HOME/Git/Go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

Top


How to install Vostok's dev environment

cd $GOPATH/src
mkdir -p bitbucket.org/oscaroscar && cd bitbucket.org/oscaroscar

And then git clone vostok here.

Finally, to be able to use Vostok in another Go program:

go install -v bitbucket.org/oscaroscar/vostok

To build Vostok while developing it:

go build -i -v bitbucket.org/oscaroscar/vostok

Unless you already have you preferences, you really should consider the Atom editor, with the go-plus package, to have quite an IDE for Go.

Top


Using the examples


1. The 'simple' example

What we want to do here is to install a very very simple application server and to make it run so we can send HTTP resquests to it and see something in return.

Simple webapp: building

Let's build it:

go build -i -o $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simple/examples_vostok_simple -v bitbucket.org/oscaroscar/vostok/examples/simple/go

Explanations:

  • -i: to automatically install the dependencies if needed
  • -o $GOPATH/src/bitbucket.org/oscaroscar/vostok/bin/examples/simple/examples_vostok_simple: the output is a binary file named examples_vostok_simple
  • -v: a kind of verbose mode, to see what needs to be rebuilt along the way
  • bitbucket.org/oscaroscar/vostok/examples/simple/go: the path to the Go files to build

Top

Simple webapp: running

To run the webapp, we need a config file - such as the one you can find in the /conf folder, that you can duplicate and adapt:

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simple && ./examples_vostok_simple -config=conf/examples.vostok.simple.test.mymachine.json

Depending on where the log is done - which is configured within the given config file - you might need to sudo the running of the server (which we do in the example above).

To look at the logs - which is highly recommended - you can tail -f the logging file.

To check that it works, open this URL in your web browser: http://localhost:64900/examples/vostok/simple, setting the host and port corresponding to the config file you're using.

Top

Simple webapp: 'forever running'

You can write scripts that will basically run the server as seen below in a never ending loop. An example is given here:

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simple && scripts/forever.test.mymachine.sh

Top


2. The 'simple JSON' example

This example shows Vostok's ability to return JSON responses.

If you've gone through the 'simple' example, we can go quicker here. To build:

go build -i -o $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleJSON/examples_vostok_simpleJSON -v bitbucket.org/oscaroscar/vostok/examples/simpleJSON/go

To run:

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleJSON && ./examples_vostok_simpleJSON -config=conf/examples.vostok.simpleJSON.test.mymachine.json

To test, open http://localhost:64901/examples/vostok/simpleJSON in your navigator.

Top


3. The 'simple DB' example

The simpleDB application makes use of vostok and shows how to build an application connected to a database.

In order to demonstrate its capacity to use various DB manager, we have written two sets of config files and two sets of database creation scripts so the app can connect PostgreSQL or MySQL.

The instructions can be found here.

To build:

go build -i -o $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleDB/examples_vostok_simpleDB -v bitbucket.org/oscaroscar/vostok/examples/simpleDB/go

To run (MySQL):

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleDB && ./examples_vostok_simpleDB -config=conf/examples.vostok.simpleDB.mysql.test.mymachine.json

Or (PostgreSQL):

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleDB && sudo ./examples_vostok_simpleDB -config=conf/examples.vostok.simpleDB.postgres.test.mymachine.json

To "forever run":

cd $GOPATH/src/bitbucket.org/oscaroscar/vostok/examples/simpleDB && sudo scripts/forever.test.mymachine.sh

To test, open http://localhost:64901/examples/vostok/simple in your navigator.

Top


4. The 'REST' example

If can be found here.

Top


5. The 'routine' example

If can be found here.

Top


Some coding principles

Some rules are applied to ensure code homogeneity inside this lib, and preferably in all projects using it:

Top


Need some tools ?

  • You can try Atom, with the go-plus plugin. To use the bundled plugin go-debug, you'll need to install delve.
  • [Give other possible methods here (Vim, Vscode, etc.)]

Top

Documentation

Overview

------------------------------------------------------------------------------

Utils for all cookie based auth method (session or stateless)

------------------------------------------------------------------------------ Copyright © Oscar Ayoun, Julien Wan, Audréa Malialin ------------------------------------------------------------------------------

------------------------------------------------------------------------------

Code handling Session Authentication with cookies

------------------------------------------------------------------------------ Copyright © Oscar Ayoun, Julien Wan, Audréa Malialin ------------------------------------------------------------------------------

------------------------------------------------------------------------------

Code handling Session Authentication with cookies utils

------------------------------------------------------------------------------ Copyright © Oscar Ayoun, Julien Wan ------------------------------------------------------------------------------

------------------------------------------------------------------------------

Code handling Stateless Authentication with cookies

------------------------------------------------------------------------------ Copyright © Audréa Malialin, Julien Wan ------------------------------------------------------------------------------

Index

Constants

View Source
const (

	// LocalCacheNOEXPIRATION is used for items that have no reason to expire in the cache
	LocalCacheNOEXPIRATION = goca.NoExpiration

	// LocalCacheDEFEXPIRATION is used for items that should use the default cache expiration time (set in config)
	LocalCacheDEFEXPIRATION = goca.DefaultExpiration
)
View Source
const (

	// GlobalCacheDurationNEVER is used for items that should not be cached
	GlobalCacheDurationNEVER = -2

	// GlobalCacheDurationFOREVER is used for items that have no reason to expire in the cache
	GlobalCacheDurationFOREVER = goca.NoExpiration

	// GlobalCacheDurationDEFAULT is used for items that should use the default cache expiration time (set in config)
	GlobalCacheDurationDEFAULT = goca.DefaultExpiration
)
View Source
const (

	// DbMgrPOSTGRES : the name of the PostgreSQL DB manager
	DbMgrPOSTGRES = "postgres"

	// DbMgrMYSQL : the name of the MysQL DB manager
	DbMgrMYSQL = "mysql"

	// SQLLibSQLX : when not using the default sql lib for DB connection, but sqlx instead
	SQLLibSQLX = "sqlx"

	// CountersTableName the name of the table for holding counters
	CountersTableName = "vostok_counters"

	// CountersTableNameConstraint is the name of the constraints that should be put on the counter table's name column
	CountersTableNameConstraint = "uk_" + CountersTableName + "_name"

	// DBDefaultIDValue is the value that we associate with the NULL value for a
	// database index. 0 is complicated because we could imagine the ID could be 0
	// this is reason why we choose -1.
	DBDefaultIDValue int64 = -1
)
View Source
const (

	// RootPathREST is the path root for REST resources
	RootPathREST = "/rest/"

	// RootPathOAUTH is the path root for oauth requests
	RootPathOAUTH = "/oauth/"

	// RootPathSESSIONAUTH is the path root for session auth requests
	RootPathSESSIONAUTH = "/sessionauth/"

	// RootPathSTATELESSAUTH is the path root for stateless auth requests
	RootPathSTATELESSAUTH = "/statelessauth/"
)
View Source
const DateFormatMICROSEC = "2006-01-02 15:04:05.999999"

DateFormatMICROSEC is the time format we use for timestamps

View Source
const DateFormatSECONDS = "2006/01/02 15:04:05"

DateFormatSECONDS is a format for date that looks like this "2017/12/25 19:56:42"

View Source
const DateFormatYYYYsMMsDD = "2006/01/02"

DateFormatYYYYsMMsDD is a format for date that looks like this 2017/12/25

Variables

View Source
var URICutOAUTH int

URICutOAUTH is the index at which to cut a OAuth URI to get the 'action'

View Source
var URICutREST int

URICutREST is the index at which to cut a Rest URI to get the resource & action from it

View Source
var URICutSESSIONAUTH int

URICutSESSIONAUTH is the index at which to cut a Session Auth URI to get the 'action'

View Source
var URICutSTATELESSAUTH int

URICutSTATELESSAUTH is the index at which to cut a Stateless Auth URI to get the 'action'

Functions

func Abs

func Abs(num int) int

Abs returns the absolute value of a given integer

func BatchFunctionSet

func BatchFunctionSet(name BatchFuncName, function BatchFunction, checkFn batchFunctionConfigCheckFn)

BatchFunctionSet allows to bind a batch function to a name which serves as a unique ID, and a to a function that helps check the configuration for the compartments that are to be dealt with by the given batch function.

func BuildConfigWith

func BuildConfigWith(pConfigFilePath string, pConfigFileObject IConfigFile) (*ServerConfig, ICustomConfig, error)

BuildConfigWith reads a configuration file and hydrates a server configuration object. This expects the configuration file to be a JSON file.

Arguments

pConfigFilePath:   the name of the config item for which we want the value
pConfigFileObject: the object that will bear the configuration items

Returns

  • the root config object for the server
  • the application custom configuration object
  • the error if there is one

func CamelToShort

func CamelToShort(camelCasedString string) string

CamelToShort converts a camelCasedString to a "short" version, i.e. camCasStr

func CamelToSnake

func CamelToSnake(camelCasedString string) string

CamelToSnake converts the givenCamelString to snake case version i.e. given_camel_string

func CheckAndAcquireTimestamp

func CheckAndAcquireTimestamp(pString string) (string, error)

CheckAndAcquireTimestamp checks the format and tries to complete the string if it is not a full timestamp using the format YYYY-MM-DD HH:MM:SS.uuuuuu

Arguments

pRegExpPattern: the regular expression pattern to use when trying to
                check the string.

Returns

  • the extracted value
  • an error if something has failed

func Count

func Count(db IDB, table string, wherePart string, whereValues ...interface{}) (int, error)

Count : returns the number of rows in the given table

func DateStringToTime

func DateStringToTime(dateString string, format string) (*time.Time, error)

DateStringToTime returns a Time object from a given date string, and a given date format

func DayToTime

func DayToTime(simpleDayString string) *time.Time

DayToTime transform a day date given as "2006/01/02" to a pointer to a Time object. Panics if the day format is wrong

func FindCountryA2CodeStr

func FindCountryA2CodeStr(codeOrTranslation string) string

FindCountryA2CodeStr is a shortcut to quickly have an alpha 2 code from a code or translation

func Float64FromNullFloat64

func Float64FromNullFloat64(pNf64 *sql.NullFloat64) float64

Float64FromNullFloat64 returns the default value for a float64 float when the value was NULL in the result of the SQL request. The default value is 0.0.

Arguments

pNi64: a NullInt64 object

Returns

  • the corresponding int64 integer

func GenerateRandomString

func GenerateRandomString(source rand.Source, n int) string

GenerateRandomString creates a random string of a given size, from a given rand.Source, with characters in [0-9a-zA-Z] This should be quite an effective way. See benchmark here (to reproduce in a test file): cf. http://stackoverflow.com/a/31832326/7745451

func GetAppToken

func GetAppToken(tokenRespObj ITokenResponse, appName string, tokenURL string, user string, password string, timeout time.Duration, body interface{}) (string, error)

GetAppToken retrieves a token to access another app

func GetFileContent

func GetFileContent(pFile *os.File) (string, error)

GetFileContent returns a string representation of a file.

Arguments

pFilename : the name of the file for which we want the content

Returns

  • the file's content as a string
  • an error if there is a problem

func GetIP

func GetIP(r *http.Request) string

GetIP gets a requests IP address by reading off the forwarded-for header (for proxies) and falls back to use the remote address.

func GetJSONExample

func GetJSONExample() string

GetJSONExample returns a json string example

func GetPwdHashingFunc

func GetPwdHashingFunc() func(pwd []byte, salt []byte) ([]byte, error)

GetPwdHashingFunc returns the hashing function currently used

func GetPwdMatchingFunc

func GetPwdMatchingFunc() func(hashedPwd []byte, pwd []byte, salt []byte) error

GetPwdMatchingFunc returns the hashing function currently used

func GetScopeSignature

func GetScopeSignature(scope LoggingScope) string

GetScopeSignature builds a string from the given scope's ID, and the IDs of its parent and all its grandparent, separated by a pipe "|". Example: "01|009765|044"

func GetUserAgent

func GetUserAgent(r *http.Request) string

GetUserAgent gets a requests User Agent

func IDFromNullID

func IDFromNullID(pNID64 *sql.NullInt64) int64

IDFromNullID returns the default value for a database ID which is an int64 int and can be NULL. THe reason why we use this procedure instead of the more generic Int64FromNullInt64 is that for database IDs 0 could potentially be a not null value.

Arguments

pNID64: a NullInt64 object

Returns

  • the corresponding int64 integer

func InitGlobalCacheFromConfig

func InitGlobalCacheFromConfig(globalCacheConfig *applicationGlobalCacheConfig)

InitGlobalCacheFromConfig : initialising the main global cache instance - or its partitioned version (if NoPartition = false in the config) - with a given global cache config

func InitLocalCacheForTests

func InitLocalCacheForTests(localDefaultExpiration time.Duration, localCleanupInterval time.Duration)

InitLocalCacheForTests : initialising the main local cache with given cache parameters

func InitLocalCacheFromConfig

func InitLocalCacheFromConfig(localCacheConfig *applicationLocalCacheConfig)

InitLocalCacheFromConfig : initialising the main local cache instance with a given local cache config

func Int64FromNullInt64

func Int64FromNullInt64(pNi64 *sql.NullInt64) int64

Int64FromNullInt64 returns the default value for an int64 integer when the value was NULL in the result of the SQL request. The default value is 0.

Arguments

pNi64: a NullInt64 object

Returns

  • the corresponding int64 integer

func IntLen

func IntLen(num int) int

IntLen returns the length of a given integer, i.e. the number of chars it takes

func LeftPad

func LeftPad(s string, pad string, length int) string

LeftPad left-pads a given string with a padding string, until a given length is reached

func MaxDuration

func MaxDuration(a, b time.Duration) time.Duration

MaxDuration returns the min between the 2 given integers

func MaxInt

func MaxInt(a, b int) int

MaxInt returns the min between the 2 given integers

func MaxInt64

func MaxInt64(a, b int64) int64

MaxInt64 returns the min between the 2 given integers

func MinDuration

func MinDuration(a, b time.Duration) time.Duration

MinDuration returns the min between the 2 given integers

func MinInt

func MinInt(a, b int) int

MinInt returns the min between the 2 given integers

func MinInt64

func MinInt64(a, b int64) int64

MinInt64 returns the min between the 2 given integers

func NewRandSource

func NewRandSource() rand.Source

NewRandSource is our "standard" way of creating a new rand source

func NormalizeAndCapOnce

func NormalizeAndCapOnce(str string) (result string, err error)

NormalizeAndCapOnce normalizes and upper caps a given string. I.e. Jean-Vincent Placé => JEAN-VINCENT PLACE For multiple successive calls to this function, it is recommended to use the ToUpper method on the same IStringNormalizer instance.

func NormalizeStringOnce

func NormalizeStringOnce(str string) (result string, err error)

NormalizeStringOnce removes accents from a given string. Example: "Yoùr Śtring šđč枊ĐČĆŽ Ötzi's Nationalität èàì" => "Your String sđcczSĐCCZ Otzi's Nationalitat eai" For multiple successive calls to this function, it is recommended to use the String method on the same IStringNormalizer instance.

func Now

func Now() *time.Time

Now returns the current time as a pointer to a time.Time instance, in UTC zone

func PascalToCamel

func PascalToCamel(pascalCasedString string) string

PascalToCamel returns the given string lowerCamelCased. Ex: KickYourAss => kickYourAss

func PascalToSnake

func PascalToSnake(pascalCasedString string) string

PascalToSnake converts the GivenPascalString to its snake case version i.e. given_camel_string

func PurgeAuthTokens

func PurgeAuthTokens(expiredSince time.Duration, doClean bool) (totalSize int, detected int, treated int, err error)

PurgeAuthTokens cleans the entities in the "authTableACCESS" table, that expired since a longer time that the argument. This argument should not be less than the configured token expiration time, i.e. calling this function MUST NEVER prune valid tokens.

func RandBool

func RandBool(source rand.Source) bool

RandBool returns a random boolean value

func RandDate

func RandDate(source rand.Source, withMicrosec bool) *time.Time

RandDate returns a random date, as a pointer to a time.Time value

func RandDigit

func RandDigit(source rand.Source) int64

RandDigit returns a random digit, between 0 and 9

func RandDuration

func RandDuration(source rand.Source, maxduration string) time.Duration

RandDuration returns a random duration, from 0 to a given maximum duration

func RandFloatString

func RandFloatString(source rand.Source, minlength int, maxlength int, maxdecimals int) string

RandFloatString generates a random string representing a real number, with a given maximum length

func RandInt

func RandInt(source rand.Source, min int, max int) int

RandInt does the same as RandNum, but returns an int

func RandIntByte

func RandIntByte(source rand.Source) byte

RandIntByte returns a random digit, between 0 and 9, as a byte

func RandIntString

func RandIntString(source rand.Source, minlength int, maxlength int) string

RandIntString generates a random string representing an integer, with a given maximum length NB: this is a maximum length, not a maximum int !!

func RandNum

func RandNum(source rand.Source, min int, max int) int64

RandNum returns a random number, between min and max

func RandSampleInt

func RandSampleInt(source rand.Source, fromIntValues []int) (sample []int)

RandSampleInt returns a randomly chosen subset of a given int array

func RandString

func RandString(source rand.Source, minlength int, maxlength int) string

RandString generates a random string with at most a given number of characters

func RightPad

func RightPad(s string, pad string, length int) string

RightPad left-pads a given string with a padding string, until a given length is reached

func Round

func Round(num float64) int64

Round rounds a given real number to the nearest integer

func Round1f32

func Round1f32(num float32) float32

Round1f32 rounds a given real 64-bits number to the nearest float, at the first decimal place

func Round1f64

func Round1f64(num float64) float64

Round1f64 rounds a given real 64-bits number to the nearest float, at the first decimal place

func Round2f32

func Round2f32(num float32) float32

Round2f32 rounds a given real 64-bits number to the nearest float, at the second decimal place

func Round2f64

func Round2f64(num float64) float64

Round2f64 rounds a given real 64-bits number to the nearest float, at the second decimal place

func Round32

func Round32(num float32) int64

Round32 rounds a given real number to the nearest integer

func SaveAuthClient

func SaveAuthClient(authClient osin.Client) error

SaveAuthClient saves - i.e. inserts or updates - a user into the auth DB

func SetNeededCountryCodes

func SetNeededCountryCodes(alpha2Code ...string)

SetNeededCountryCodes is used to specify the country codes (FR, GB, IT, etc) that the application can restrict to

func SetPwdHashingFunc

func SetPwdHashingFunc(daFunc func(pwd []byte, salt []byte) ([]byte, error))

SetPwdHashingFunc allows to set a hashing function to hash the passwords

func SetPwdMatchingFunc

func SetPwdMatchingFunc(daFunc func(hashedPwd []byte, pwd []byte, salt []byte) error)

SetPwdMatchingFunc allows to set a hashing function to hash the passwords

func SnakeToShort

func SnakeToShort(snakeCasedString string) string

SnakeToShort converts a snake_case_string to a "short" version, i.e. snaCasStr

func StringFromNullString

func StringFromNullString(pNs *sql.NullString) string

StringFromNullString returns the default value for an string when the value was NULL in the result of the SQL request. The default value is the empty string.

Arguments

pNs: a NullString object

Returns

  • the corresponding string

func StringInSlice

func StringInSlice(str string, slice []string) bool

StringInSlice tells if a given string is in the given slice

func TimeToSimpleString

func TimeToSimpleString(time *time.Time) string

TimeToSimpleString formats a time as a date with format "2006/12/25"

func ToDuration32

func ToDuration32(timeInFloat float32) time.Duration

ToDuration32 returns a duration from a time, given as a 64-bits float - when it comes from an operation for instance

func ToDuration64

func ToDuration64(timeInFloat float64) time.Duration

ToDuration64 returns a duration from a time, given as a 64-bits float - when it comes from an operation for instance

func ToDurationStr

func ToDurationStr(str string) time.Duration

ToDurationStr returns a duration from a given string, like 1d, 30s, 5000us, etc

func ToMicrosec

func ToMicrosec(nanoseconds time.Duration) int64

ToMicrosec outputs the time given in nanoseconds, in microseconds; the result cannot be a duration since it's not nanosecs

func ToMillisec

func ToMillisec(nanoseconds time.Duration) int64

ToMillisec outputs the time given in nanoseconds, in milliseconds; the result cannot be a duration since it's not nanosecs

func TrimIfLong

func TrimIfLong(s string, maxlength int) string

TrimIfLong cuts the given string at the maximal size, if it exceeds it

Types

type Amount

type Amount float64

Amount is used for all the amounts of money

func (Amount) MarshalJSON

func (a Amount) MarshalJSON() ([]byte, error)

MarshalJSON for amounts, allowing us to marshall amounts with max 4 decimals

type AppMode

type AppMode int

AppMode helps configure in which environment type the app is running

const (
	AppModeTEST    AppMode = -1 // for automated TESTS
	AppModeDEV     AppMode = 0  // for DEV environments
	AppModePRELIVE AppMode = 1  // for PRELIVE environments
	AppModeLIVE    AppMode = 9  // for LIVE environments
)

Defining app modes

type Appserv

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

Appserv carries the vostok application server. From this root object you will get access to the config, the registered actions which are the HTTP handlers, the cached templates, the children processes, the DB connections and also the Job schedulers.

func NewAppserv

func NewAppserv(pRootPath string, pConfigFilePath string, instanceID int) (*Appserv, error)

NewAppserv reads the JSON config file and builds the configuration of the app server.

Arguments

pRootPath:       location from which to find all the resources; "" by default
pConfigFilePath: location of the config file

Returns

  • the newly created application server object
  • the error if something not expected happened

func NewAppservWithConfig

func NewAppservWithConfig(pRootPath string, pConfigFilePath string, pConfigFileObject IConfigFile, instanceID int) (*Appserv, error)

NewAppservWithConfig reads the JSON config file and builds the configuration of the app server.

Arguments

pRootPat:          location from which to find all the resources; "" by default
pConfigFilePath:   location of the config file
pConfigFileObject: type of the config file

Returns

  • the newly created application server object
  • the error if something not expected happened

func (*Appserv) AddActionHandler

func (sAppserv *Appserv) AddActionHandler(pAction string, pNeedLogin bool, pCall AppservCall)

AddActionHandler stores a new action handler to the application server. An action handler is basically an HTTP handler triggered by an action set using the HTTP parameter "action".

Arguments

pAction:    the name of the action
pNeedLogin: boolean to specify whether the action requires login
pCall:      a function which will handle the action

func (*Appserv) AddLoggerHook

func (sAppserv *Appserv) AddLoggerHook(loggerHook logrus.Hook)

AddLoggerHook allows to set a logrus logger, even if one is already set

func (*Appserv) Batcher

func (sAppserv *Appserv) Batcher() *Batcher

Batcher : IBatcher implem

func (*Appserv) BeginDbTransaction

func (sAppserv *Appserv) BeginDbTransaction() (*sql.Tx, error)

BeginDbTransaction starts an sql transaction using the base SQL library Begin().

Returns

  • the transaction started
  • the error

func (*Appserv) BindOriginalFunction

func (sAppserv *Appserv) BindOriginalFunction(name string, jfunc interface{})

BindOriginalFunction allows to keep in memory that we use a certain name, for a given function

func (*Appserv) Exec

func (sAppserv *Appserv) Exec(pQuery string, pParams ...interface{}) (sql.Result, error)

Exec executes a SQL query on the primary database using the base SQL library Exec() procedure. This should be used when you are not expecting any resulting row being selected. Classic examples are INSERT and UPDATE.

Arguments

pQuery: a SQL query to execute (INSERT or UPDATE)

Returns

  • the result (this is just information like last index for instance)
  • the error

func (*Appserv) GetAppName

func (sAppserv *Appserv) GetAppName() string

GetAppName returns a string representing the appname as it appears in the config

func (*Appserv) GetAppPath

func (sAppserv *Appserv) GetAppPath() string

GetAppPath returns the current app path, as configured

func (*Appserv) GetAppURL

func (sAppserv *Appserv) GetAppURL() string

GetAppURL the app's URL

func (*Appserv) GetBox

func (sAppserv *Appserv) GetBox() string

GetBox returns a string representing the box as it appears in the config.

func (*Appserv) GetCustomConfig

func (sAppserv *Appserv) GetCustomConfig() ICustomConfig

GetCustomConfig returns the custom config from an app server. The custom config's role is to bring to an application its specific config which has nothing to do with the base Vostok application configuration items.

func (*Appserv) GetDbName

func (sAppserv *Appserv) GetDbName() string

GetDbName returns the primary database name as it was provided into the configuration file.

Returns

  • the name of the currently preimary DB the App Server is connected to

func (*Appserv) GetDescription

func (sAppserv *Appserv) GetDescription() string

GetDescription returns a string representing the description as it appears in the config.

func (*Appserv) GetLogger

func (sAppserv *Appserv) GetLogger() *logrus.Logger

GetLogger indicates how to get the logger from this scope

func (*Appserv) GetMode

func (sAppserv *Appserv) GetMode() AppMode

GetMode is an accessor to get the application mode / environnement (live, prelive, dev, ...)

Returns

  • the application mode

func (*Appserv) GetNotAuthenticatedCode

func (sAppserv *Appserv) GetNotAuthenticatedCode() int

GetNotAuthenticatedCode returns the code to return to the client when it/he/she fails to authenticate

func (*Appserv) GetOriginalJobConfig

func (sAppserv *Appserv) GetOriginalJobConfig(jobID string, doPanicIfNotFound bool) *JobConfig

GetOriginalJobConfig returns a jobConfig instance if it exists

func (*Appserv) GetParentScope

func (sAppserv *Appserv) GetParentScope() LoggingScope

GetParentScope returns the parent scope

func (*Appserv) GetRoutinePoolCapacity

func (sAppserv *Appserv) GetRoutinePoolCapacity() int

GetRoutinePoolCapacity tells us how many routines we can have running in parallel.

Returns

  • the routine pool capacity

func (*Appserv) GetRoutineStats

func (sAppserv *Appserv) GetRoutineStats() (currentUse, maxParaUse, totalUse int)

GetRoutineStats : implementation for Appserv

func (*Appserv) GetScheduledFunction

func (sAppserv *Appserv) GetScheduledFunction(name string) interface{}

GetScheduledFunction returns the function scheduled with the given name

func (*Appserv) GetScopeID

func (sAppserv *Appserv) GetScopeID() string

GetScopeID returns this scope's ID; scope IDs for sibling scopes should have the same length, for better readability

func (*Appserv) GetSecondaryDB

func (sAppserv *Appserv) GetSecondaryDB(pDbID string, pCheck bool) (*sql.DB, error)

GetSecondaryDB gets a hangle to the named secondary database as a *sql.DB instance if it exists and has been initialised.

Arguments

pDbID:  the DB ID
pCheck: if true, then a check is performed, to see if the DB is open

Returns

  • the DB corresponding to the given name
  • an error, if the DB does not exist, or is not open

func (*Appserv) GetSecondaryDBx

func (sAppserv *Appserv) GetSecondaryDBx(pDbID string, pCheck bool) (*sqlx.DB, error)

GetSecondaryDBx gets a handle to the named secondary database as a *sqlx.DB instance if it exists and has been initialised.

Arguments

pDbID:  the DB ID
pCheck: if true, then a check is performed, to see if the DB is open

Returns

  • the DB corresponding to the given name
  • an error, if the DB does not exist, or is not open

func (*Appserv) GetSecondaryDbName

func (sAppserv *Appserv) GetSecondaryDbName(id string) string

GetSecondaryDbName returns the secondary database name as it was provided into the configuration file with its ID.

Returns

  • the name of the referred secondary DB the App Server is connected to

func (*Appserv) GetSeparator

func (sAppserv *Appserv) GetSeparator() string

GetSeparator returns the separator to use after the scope ID; Most of the time it should be "|", but it could be "]["

func (*Appserv) GetSignature

func (sAppserv *Appserv) GetSignature() string

GetSignature : the scope must retain the result of GetScopeSignature(this) and return it through this method

func (*Appserv) GetSqlLogThreshold

func (sAppserv *Appserv) GetSqlLogThreshold() time.Duration

GetSqlLogThreshold returns the time above which we automatically log the SQL request executions; -1 means always

Returns

  • the configured duration; if nothing configured

func (*Appserv) GetTokenExp

func (sAppserv *Appserv) GetTokenExp() time.Duration

GetTokenExp the configured token expiration as a duration; it panics if the configured value cannot be parsed as a valid duration.

func (*Appserv) GetUniqueID

func (sAppserv *Appserv) GetUniqueID(counterName string) (int, error)

GetUniqueID allows to get a unique value associated to the given counter name

Returns

  • the unique value
  • the error

func (*Appserv) GetVersion

func (sAppserv *Appserv) GetVersion() string

GetVersion returns a string representing the version as it appears in the config.

func (*Appserv) GetVostokAppToken

func (sAppserv *Appserv) GetVostokAppToken(appName string, appURL string, user string, password string, timeout time.Duration) (string, error)

GetVostokAppToken retrieves a token to access another Vostok-based app

func (*Appserv) HasDb

func (sAppserv *Appserv) HasDb() bool

HasDb tells if a main app DB has been configured and initialised.

Returns

  • true if a DB instance has been created; false otherwise

func (*Appserv) InitAppDB

func (sAppserv *Appserv) InitAppDB() (vDbManager string, vDbUsername string, vDbName string, vEnableDbConnection bool)

InitAppDB initialises the app DB, if the related config items have been provided in the current config file.

func (*Appserv) InitAuth

func (sAppserv *Appserv) InitAuth()

InitAuth initialises the authentication server along with its authentication DB

func (*Appserv) InitBatcher

func (sAppserv *Appserv) InitBatcher()

InitBatcher initialises a Batcher instance for the App server

func (*Appserv) InitGlobalCache

func (sAppserv *Appserv) InitGlobalCache()

InitGlobalCache : initialising the main global cache (partitioned or not) with the appserv config

func (*Appserv) InitLocalCache

func (sAppserv *Appserv) InitLocalCache()

InitLocalCache : initialising the main local cache with the appserv config

func (*Appserv) InitLoggers

func (sAppserv *Appserv) InitLoggers()

Init logger if needed

func (*Appserv) InitRoutinePool

func (sAppserv *Appserv) InitRoutinePool()

InitRoutinePool initialises the routine pool

func (*Appserv) IsDBOpen

func (sAppserv *Appserv) IsDBOpen() bool

IsDBOpen returns a boolean telling you whether there is an open connection to the main (primary) database. It is making use of the Ping() procedure implemented by the SQL driver.

Returns

  • true if the primary DB associated with the given App Server is open

func (*Appserv) IsHideFunctionName

func (sAppserv *Appserv) IsHideFunctionName() bool

IsHideFunctionName tells if the caller function should be hidden or not

func (*Appserv) IsTestMode

func (sAppserv *Appserv) IsTestMode() bool

IsTestMode tells whether the application mode is test.

Returns

  • true is the mode is Test, false otherwise

func (*Appserv) IsVerbose

func (sAppserv *Appserv) IsVerbose() bool

IsVerbose tells if the log is being verbose, as per its configuration

func (*Appserv) Log

func (sAppserv *Appserv) Log() LogEntry

Log creates a prefixed log entry with no frame skipped, and no field

func (*Appserv) LogF

func (sAppserv *Appserv) LogF(skip int, fields logrus.Fields) LogEntry

LogF creates a prefixed log entry with fields, with a given number of frames skipped

func (*Appserv) NewBatchRoutineContext

func (sAppserv *Appserv) NewBatchRoutineContext(scopeID string) IBatchRoutineContext

func (*Appserv) NewRoutine

func (sAppserv *Appserv) NewRoutine(scopeID string) Routine

NewRoutine : implementation for Appserv

func (*Appserv) OpenAndTweakDBConnection

func (sAppserv *Appserv) OpenAndTweakDBConnection(c *applicationDBConfig) (db IDB, errOpen error)

OpenAndTweakDBConnection calls OpenDBConnection with arguments coming from a DB config, and also sets some properties about the connection.

Arguments

dbConfig: an applicationDBConfig instance containing the info needed to
          open and tweak a DB connection

Returns

  • same as OpenDBConnection

Comments

The same comments as for OpenDBConnection apply here.

func (*Appserv) OpenDBConnection

func (sAppserv *Appserv) OpenDBConnection(pDriverName string, pDbName string, pDbHost string, pUsername string, pPassword string, pSQLLib string) (IDB, error)

OpenDBConnection opens a database connection using the appropriate driver. The caller does not need to know exactly which lib takes which parameters, the procedure does it for him.

Arguments

pDriverName: the driver name to use
pDbName:     the database name
pDbHost:     the database host. Empty string should be used to connect to local host
pUsername:   the username to use
pPassword:   the password
pSQLLib:     the library used for DB connection; if void, the native one is used

Returns

  • the database handle
  • the error if something not expected happened

Comments

It opens connection according to the DB manager. The format for opening the
connection varies and here are the references :
    PostgreSQL: https://godoc.org/github.com/lib/pq
        "user=%s dbname=%s password=%s sslmode=disable", pUsername, pDbName, pPassword
    MySQL: https://github.com/go-sql-driver/mysql/
        "%s:%s@%s/%s", pUsername, pPassword, pDbHost, pDbName

func (*Appserv) PullJobWorker

func (sAppserv *Appserv) PullJobWorker() (*JobWorker, error)

PullJobWorker retrieves a job worker from the pool

func (*Appserv) QueryRow

func (sAppserv *Appserv) QueryRow(pQuery string, pParams ...interface{}) *sql.Row

QueryRow sends a SQL request to the primary database and returns the result set. This encapsulate the base SQL library QueryRow() procedure to allow some login. The difference with QuerySQL() is that it is expecting only one row in return.

Arguments

pQuery:  the query to execute
pParams: the parameters to pass to the statement

Returns

  • the resulting row

func (*Appserv) QuerySQL

func (sAppserv *Appserv) QuerySQL(pQuery string, pParams ...interface{}) (*sql.Rows, error)

QuerySQL sends a SQL request to the primary database and returns the result set. This encapsulate the base SQL library Query() procedure to allow some login.

Arguments

pQuery:  the query to execute
pParams: the parameters to pass to the statement

Returns

  • the resulting rows
  • the error

func (*Appserv) ReleaseJobWorker

func (sAppserv *Appserv) ReleaseJobWorker(jobWorker *JobWorker)

ReleaseJobWorker puts a job worker back intp the pool

func (*Appserv) RemoveFunction

func (sAppserv *Appserv) RemoveFunction(name string)

RemoveFunction removes a function that has been put into the scheduler

func (*Appserv) ScheduleFunction

func (sAppserv *Appserv) ScheduleFunction(name string, schedule string, fn interface{}, args ...interface{}) error

ScheduleFunction puts a named function into the scheduler, with a given schedule, and the function's arguments. This is a low level method that do not use the app server's job configurations. Also, the app server's workers are not involved here. This method should never be used in applicative packages, cf. ScheduleJob instead, or rest.ScheduleAndTrackJob, which allow to run functions that have contexts with DB access and logging functionalities passed to them. WARNING : functions directly scheduled this way are not protected against server shutdowns! Meaning they can be interrupted (by a CTRL+C for example), and leave things in an indeterminate state.

func (*Appserv) ScheduleJob

func (sAppserv *Appserv) ScheduleJob(jobID string, jobFunc scheduledJobFunc) error

ScheduleJob puts a function into the scheduler, with a job ID. The function is run with a job worker, that provider functionalities such as DB access and logging.

func (*Appserv) ServeHTTP

func (sAppserv *Appserv) ServeHTTP(pResponseWriter http.ResponseWriter, pRequest *http.Request)

ServeHTTP picks a free child and makes it serve the request. It will wait if none is available, and until one is free to pick up the request. This is the entry point of all request handling process.

Arguments

pResponseWriter: the HTTP connection
pRequest:        the HTTP request which has been sent

func (*Appserv) SetAuthClientGetterFn

func (sAppserv *Appserv) SetAuthClientGetterFn(fn AuthClientGetterFn)

SetAuthClientGetterFn set the getter function which extract the auth client data

func (*Appserv) SetMainLogger

func (sAppserv *Appserv) SetMainLogger(logger *logrus.Logger)

SetMainLogger allows to set a logrus logger, even if one is already set

func (*Appserv) Start

func (sAppserv *Appserv) Start()

Start actually starts the server using the configuration information which has been read at creation time.

func (*Appserv) StartBatchJob

func (sAppserv *Appserv) StartBatchJob(batchUID BatchUID)

StartBatchJob starts a batch function, as configured by the item in the 'Batcher' section of the config with the given batch job UID;

type AppservCall

type AppservCall func(pAppservChild *AppservChild)

AppservCall is the type of the functions which are actually triggered by an HTTP request. For this reason it has two parameters which are the child of the application server, serving the request and also virtual parameters which are here to call programmatically HTTP handlers when there are no actual HTTP parameters.

type AppservChild

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

AppservChild is the application server child process. Children actually handle the requests. This is the reason why it provides access to the current HTTP request and also a link to the application server.

func (*AppservChild) Batcher

func (sAppservChild *AppservChild) Batcher() *Batcher

Batcher : IBatcher implem

func (*AppservChild) BeginDbTransaction

func (sAppservChild *AppservChild) BeginDbTransaction() (*sql.Tx, error)

BeginDbTransaction App Server Child version

func (*AppservChild) BindOriginalFunction

func (sAppservChild *AppservChild) BindOriginalFunction(name string, jfunc interface{})

BindOriginalFunction : implementation for appserv children

func (*AppservChild) DecryptData

func (sAppservChild *AppservChild) DecryptData(pEncryptedData []byte) ([]byte, error)

DecryptData decrypts the data using NaCl SecretBox feature. The nonce is stored into the message itself as shown as an example in the package doc https://godoc.org/golang.org/x/crypto/nacl/secretbox

Arguments

pENcryptedData: the string / data we want to decrypt

Returns

  • the decrypted version of the string

func (*AppservChild) EncryptData

func (sAppservChild *AppservChild) EncryptData(pData []byte) ([]byte, error)

EncryptData encrypts the data using NaCl SecretBox feature. The nonce is stored into the message itself as shown as an example in the package doc https://godoc.org/golang.org/x/crypto/nacl/secretbox

Arguments

pData: the string / data we want to encrypt

Returns

  • the encrypted version of the string

func (*AppservChild) EscapeStringJavascript

func (sAppservChild *AppservChild) EscapeStringJavascript(pString string) string

EscapeStringJavascript escapes javascript strings. For the moment it escapes the following characters: ', " and \

Arguments

pString: the string you want to escape

Returns

  • the string escaped so it can be inserted as a Javascript string

func (*AppservChild) Exec

func (sAppservChild *AppservChild) Exec(pQuery string, pParams ...interface{}) (sql.Result, error)

Exec App Server Child version

func (*AppservChild) ExecuteStatement

func (sAppservChild *AppservChild) ExecuteStatement(pName string, pParams ...interface{}) (sql.Result, error)

ExecuteStatement executes the named statement expecting no row in result.

Arguments

pName:   the name of the statement to execute
pParams: the parameters to pass to the statement

Returns

  • the result (this is just information)
  • the error

func (*AppservChild) GetAction

func (sAppservChild *AppservChild) GetAction() string

GetAction returns the action currently performed

func (*AppservChild) GetAppName

func (sAppservChild *AppservChild) GetAppName() string

GetAppName App Server Child version

func (*AppservChild) GetAppPath

func (sAppservChild *AppservChild) GetAppPath() string

GetAppPath App Server Child version

func (*AppservChild) GetAppURL

func (sAppservChild *AppservChild) GetAppURL() string

GetAppURL App Server Child version

func (*AppservChild) GetBox

func (sAppservChild *AppservChild) GetBox() string

GetBox App Server Child version

func (*AppservChild) GetChildNumber

func (sAppservChild *AppservChild) GetChildNumber() int

GetChildNumber returns a string representing the child number.

func (*AppservChild) GetCookie

func (sAppservChild *AppservChild) GetCookie(pName string) ([]byte, error)

GetCookie returns the value for the cookie named. If no cookie with this name is found an error ErrNoCookie will be returned. If multiple cookies have the same name, only one will be returned. We assumed the content has been encoded with base64 so we decode the content before returning it.

Arguments

pName: the name of the cookie

Returns

  • the value of the cookie if found, nil otherwise
  • the error if something not expected happened

func (*AppservChild) GetCurrentHTTPRequest

func (sAppservChild *AppservChild) GetCurrentHTTPRequest() *http.Request

GetCurrentHTTPRequest returns the current http request object the child is processing. It could be useful if you want to get the FormValue values for instance.

Returns

  • the current request

func (*AppservChild) GetCurrentResponseWriter

func (sAppservChild *AppservChild) GetCurrentResponseWriter() http.ResponseWriter

GetCurrentResponseWriter returns the current response writer object the child is processing. It could be useful if you want to write some stuff straight away.

Returns

  • the current response writer

func (*AppservChild) GetCurrentURL

func (sAppservChild *AppservChild) GetCurrentURL() *url.URL

GetCurrentURL tells the time the current request has started.

func (*AppservChild) GetCustomConfig

func (sAppservChild *AppservChild) GetCustomConfig() ICustomConfig

GetCustomConfig App Server Child version

func (*AppservChild) GetDbName

func (sAppservChild *AppservChild) GetDbName() string

GetDbName App Server Child version

func (*AppservChild) GetDescription

func (sAppservChild *AppservChild) GetDescription() string

GetDescription App Server Child version

func (*AppservChild) GetHTTPMethod

func (sAppservChild *AppservChild) GetHTTPMethod() string

GetHTTPMethod returns the currently used HTTP method

func (*AppservChild) GetIPAddress

func (sAppservChild *AppservChild) GetIPAddress() string

GetIPAddress returns the IP address of the client from which the request has originated. It could be IPv4 as well as IPv6. Since we are working behind a proxy, we need to use the X-Forwarded-For Header property and forget about the RemoteAddress since this will always be the local host 127.0.0.1.

func (*AppservChild) GetLogger

func (sAppservChild *AppservChild) GetLogger() *logrus.Logger

GetLogger indicates how to get the logger from this scope

func (*AppservChild) GetLogin

func (sAppservChild *AppservChild) GetLogin() bool

GetLogin returns the login state for the request.

func (*AppservChild) GetMode

func (sAppservChild *AppservChild) GetMode() AppMode

GetMode App Server Child version

func (*AppservChild) GetOriginalJobConfig

func (sAppservChild *AppservChild) GetOriginalJobConfig(jobID string, doPanicIfNotFound bool) *JobConfig

GetOriginalJobConfig returns a jobConfig instance if it exists

func (*AppservChild) GetParentScope

func (sAppservChild *AppservChild) GetParentScope() LoggingScope

GetParentScope returns the parent scope

func (*AppservChild) GetRoutinePoolCapacity

func (sAppservChild *AppservChild) GetRoutinePoolCapacity() int

func (*AppservChild) GetRoutineStats

func (sAppservChild *AppservChild) GetRoutineStats() (currentUse, maxParaUse, totalUse int)

GetRoutineStats : implementation for AppservChild

func (*AppservChild) GetScheduledFunction

func (sAppservChild *AppservChild) GetScheduledFunction(name string) interface{}

GetScheduledFunction returns the function scheduled with the given name

func (*AppservChild) GetScopeID

func (sAppservChild *AppservChild) GetScopeID() string

GetScopeID returns this scope's ID; scope IDs for sibling scopes should have the same length, for better readibiliy

func (*AppservChild) GetSecondaryDB

func (sAppservChild *AppservChild) GetSecondaryDB(pDbID string, pCheck bool) (*sql.DB, error)

GetSecondaryDB App Server Child version

func (*AppservChild) GetSecondaryDBx

func (sAppservChild *AppservChild) GetSecondaryDBx(pDbID string, pCheck bool) (*sqlx.DB, error)

GetSecondaryDBx App Server Child version

func (*AppservChild) GetSecondaryDbName

func (sAppservChild *AppservChild) GetSecondaryDbName(id string) string

GetSecondaryDbName App Server Child version

func (*AppservChild) GetSeparator

func (sAppservChild *AppservChild) GetSeparator() string

GetSeparator returns the separator to use after the scope ID; Most of the time it should be "|", but it could be "]["

func (*AppservChild) GetSignature

func (sAppservChild *AppservChild) GetSignature() string

GetSignature : the scope must retain the result of GetScopeSignature(this) and return it through this method

func (*AppservChild) GetSqlLogThreshold

func (sAppservChild *AppservChild) GetSqlLogThreshold() time.Duration

GetSqlLogThreshold App Server Child version

func (*AppservChild) GetStartTime

func (sAppservChild *AppservChild) GetStartTime() time.Time

GetStartTime tells the time the current request has started.

func (*AppservChild) GetStatement

func (sAppservChild *AppservChild) GetStatement(pName string) *sql.Stmt

GetStatement is a simple getter to retrieve a statement already prepared using its name.

Arguments

pName: the name of the statement the aller wants to get

Returns

  • the statement of nil if it does not exist

func (*AppservChild) GetTokenExp

func (sAppservChild *AppservChild) GetTokenExp() time.Duration

GetTokenExp App Server Child version

func (*AppservChild) GetUniqueID

func (sAppservChild *AppservChild) GetUniqueID(counterName string) (int, error)

GetUniqueID App Server Child version

func (*AppservChild) GetUserInfo

func (sAppservChild *AppservChild) GetUserInfo() *UserInfo

GetUserInfo returns the base user information object.

func (*AppservChild) GetVersion

func (sAppservChild *AppservChild) GetVersion() string

GetVersion App Server Child version

func (*AppservChild) GetVostokAppToken

func (sAppservChild *AppservChild) GetVostokAppToken(appName string, appURL string, user string, password string, timeout time.Duration) (string, error)

GetVostokAppToken : child version

func (*AppservChild) IsDBOpen

func (sAppservChild *AppservChild) IsDBOpen() bool

IsDBOpen App Server Child version

func (*AppservChild) IsHideFunctionName

func (sAppservChild *AppservChild) IsHideFunctionName() bool

IsHideFunctionName tells if the caller function should be hidden or not

func (*AppservChild) IsTestMode

func (sAppservChild *AppservChild) IsTestMode() bool

IsTestMode App Server Child version

func (*AppservChild) IsVerbose

func (sAppservChild *AppservChild) IsVerbose() bool

IsVerbose tells if the log is being verbose, as per its configuration

func (*AppservChild) Log

func (sAppservChild *AppservChild) Log() LogEntry

Log creates a prefixed log entry with no frame skipped, and no field

func (*AppservChild) LogF

func (sAppservChild *AppservChild) LogF(skip int, fields logrus.Fields) LogEntry

LogF creates a prefixed log entry with fields, with a given number of frames skipped

func (*AppservChild) NewRoutine

func (sAppservChild *AppservChild) NewRoutine(scopeID string) Routine

NewRoutine : implementation for AppservChild

func (*AppservChild) PlayJSON

func (sAppservChild *AppservChild) PlayJSON(pJSONObject interface{}, pIndent bool)

PlayJSON does the same as PlayJSONIndent, with the tab character as the default indentation.

func (*AppservChild) PlayJSONError

func (sAppservChild *AppservChild) PlayJSONError(pCallName string, pCallVersion string, pErrorCode string, pErrorTitle string, pErrorMessage string)

PlayJSONError plays the JSON corresponding to the Marshalling of the object. It includes the JSON into the Vostok JSON envelope.

Arguments

pCallName:     the name of the call the response is for
pCallVersion:  the version of the call
pErrorCode:    error code
pErrorTitle:   error title
pErrorMessage: error message

func (*AppservChild) PlayJSONIndent

func (sAppservChild *AppservChild) PlayJSONIndent(pJSONObject interface{}, pIndentString string)

PlayJSONIndent does the same as PlayJSONIndentWithCode, with a default OK code

func (*AppservChild) PlayJSONIndentWithCode

func (sAppservChild *AppservChild) PlayJSONIndentWithCode(pJSONObject interface{}, pIndentString string, pCode int)

PlayJSONIndentWithCode sends the exact representation of the JSON object to the output with a HTTP code defined by the parameter pCode.

Arguments

pJSONObject: the JSON object to send.
pIndent:     tells the JSON Marshaller to indent the JSON if set to true.
pCode:       the HTTP code to use in the response.

func (*AppservChild) PlayJSONResponse

func (sAppservChild *AppservChild) PlayJSONResponse(pCallName string, pCallVersion string, pDataObject interface{})

PlayJSONResponse plays the JSON corresponding to the Marshalling of the object. It includes the JSON into the Vostok JSON envelope.

Arguments

pCallName:    the name of the call the response is for
pCallVersion: the version of the call
pDataObject:  the data object to use to play the template

func (*AppservChild) PlayJSONStatus

func (sAppservChild *AppservChild) PlayJSONStatus()

PlayJSONStatus provides information about the current state of the application server. It is encapsulated into a standard Vostok response.

func (*AppservChild) PlayTemplate

func (sAppservChild *AppservChild) PlayTemplate(pTemplateName string, pTemplateType string, pTemplateData interface{})

PlayTemplate plays the template using either the object it has created in a previous call or parsing the template for the first time. It allows to cache the template so we dont load twice the same template.

Arguments

pTemplateName: the name of the template we want to play
pTemplateType: file type
pTemplateData: the data object to use to play the template

func (*AppservChild) PullJobWorker

func (sAppservChild *AppservChild) PullJobWorker() (*JobWorker, error)

PullJobWorker retrieves a job worker from the pool

func (*AppservChild) QueryRow

func (sAppservChild *AppservChild) QueryRow(pQuery string, pParams ...interface{}) *sql.Row

QueryRow App Server Child version

func (*AppservChild) QuerySQL

func (sAppservChild *AppservChild) QuerySQL(pQuery string, pParams ...interface{}) (*sql.Rows, error)

QuerySQL App Server Child version

func (*AppservChild) QueryStatement

func (sAppservChild *AppservChild) QueryStatement(pName string, pParams ...interface{}) (*sql.Rows, error)

QueryStatement queries the named statement expecting rows in return.

Arguments

pName:   the name of the statement to execute
pParams: the parameters to pass to the statement

Returns

  • the resulting rows
  • the error

func (*AppservChild) Redirect

func (sAppservChild *AppservChild) Redirect(pURL string)

Redirect issues a 303 redirection to a given url. We expect a Redirection after each POST.

Arguments

pURL: the url to redirect the client to

func (*AppservChild) ReleaseJobWorker

func (sAppservChild *AppservChild) ReleaseJobWorker(jobWorker *JobWorker)

ReleaseJobWorker puts a job worker back intp the pool

func (*AppservChild) RemoveFunction

func (sAppservChild *AppservChild) RemoveFunction(name string)

RemoveFunction : implementation for appserv children

func (*AppservChild) ScheduleFunction

func (sAppservChild *AppservChild) ScheduleFunction(name string, schedule string, fn interface{}, args ...interface{}) error

ScheduleFunction : implementation for appserv children

func (*AppservChild) SetCookie

func (sAppservChild *AppservChild) SetCookie(pName string, pValue []byte)

SetCookie sets a cookie in the current response's header. It will encode the content using base64 algorithm so there is no issue with the original format. There are other procedures to allow setting more parameters for the cookie.

Arguments:

pName:  the name of the cookie
pValue: the value we want to store

func (*AppservChild) SetLogin

func (sAppservChild *AppservChild) SetLogin(pLoginState bool)

SetLogin is use to set the login state

func (*AppservChild) SetUserInfo

func (sAppservChild *AppservChild) SetUserInfo(pUserInfo *UserInfo)

SetUserInfo stored the user information.

type AppservError

type AppservError struct {
	Title      string
	Message    string
	LogMessage string
}

AppservError is the generic Application server error object

type AuthClientGetterFn

type AuthClientGetterFn func(appServChild *AppservChild, id string) (*UserInfo, error)

AuthClientGetterFn is the generic method to get an AuthClient

type AuthLoginRequest

type AuthLoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type AuthLoginResponse

type AuthLoginResponse struct {
	UserInfo *UserInfo  `json:"userData,omitempty"`
	Error    *authError `json:"error,omitempty"`
	Expires  time.Time  `json:"expires,omitempty"`
}

type BaseUser

type BaseUser struct {
	Username    string `db:"username,64"     json:"username"              i*:"the user's username; if physical, it MUST be an email address"`
	Password    string `db:"password,255"    json:"password"              i*:"the user's password (should be a kind of hash)"`
	Physical    bool   `db:"physical"        json:"physical"              in:"if true, then the user is a person, else an application"`
	FirstName   string `db:"firstName,20"    json:"firstName,omitempty"   in:"the user's first name, if physical"`
	LastName    string `db:"lastName,20"     json:"lastName,omitempty"    in:"the user's last name, if physical"`
	Active      bool   `db:"active"          json:"active"                in:"makes the user account active or not"`
	Admin       bool   `db:"admin"           json:"admin"                 in:"tells if the user has admin rights or not"`
	SuperUser   bool   `db:"superUser"       json:"superUser"             in:"tells if the user has super user rights or not"`
	RedirectURI string `db:"redirectURI,255" json:"redirectURI,omitempty" in:"the user's redirect URI, when the user is a client app"`
}

BaseUser defines the minimal info we need for all kinds of 'User' concepts

func (*BaseUser) ClientSecretMatches

func (thisUser *BaseUser) ClientSecretMatches(secret string) bool

ClientSecretMatches : implementing the ClientSecretMatcher interface

func (*BaseUser) GetId

func (thisUser *BaseUser) GetId() string

GetId returns a BaseUser's username as it's 'client ID'

func (*BaseUser) GetRedirectUri

func (thisUser *BaseUser) GetRedirectUri() string

GetRedirectUri returns "<unknown>", because a 'BaseUser' does not provide a "redirect URI" for now

func (*BaseUser) GetSecret

func (thisUser *BaseUser) GetSecret() string

GetSecret returns the BaseUser's password as a 'client secret'

func (*BaseUser) GetUserData

func (thisUser *BaseUser) GetUserData() interface{}

GetUserData returns a copy of base user with only a few fields

type BatchCompartment

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

BatchCompartment : a compartment stores all the similar units that must be treated altogether, by the same batch

func (*BatchCompartment) ApplyBatchFunction

func (thisCompartment *BatchCompartment) ApplyBatchFunction(batchFnCtx IBatchFunctionContext, batchFn BatchFunction, doPurge bool) (nbTreated, nbUnitsTot int, err error)

ApplyBatchFunction applies the batch function to all of the batches contained in the given compartment; the basket is also included, if it's old enough: Returns the total number of units in the compartment, the number of units treated at the end, and / or an error if one happens. If purge = true, then we ignore the max number of batches to treat at once + we purge the basket

func (*BatchCompartment) GetBatchCompartmentID

func (thisCompartment *BatchCompartment) GetBatchCompartmentID() BatchCompartmentID

GetBatchKey : shortcut to know a compartment's configured ID

func (*BatchCompartment) GetBatchesSize

func (thisCompartment *BatchCompartment) GetBatchesSize() int

GetBatchesSize : shortcut to know a compartment's configured batchSize

func (*BatchCompartment) GetConfig

func (thisCompartment *BatchCompartment) GetConfig() IBatchCompartmentConfig

GetConfig returns the configuration associated with this compartment

func (*BatchCompartment) GetContext

func (thisCompartment *BatchCompartment) GetContext() interface{}

GetCompartmentContext returns the object serving as a specific context for this compartment

func (*BatchCompartment) GetParams

func (thisCompartment *BatchCompartment) GetParams() map[string]string

GetParams : shortcut to know a compartment's configured job parameters

func (*BatchCompartment) SetContext

func (thisCompartment *BatchCompartment) SetContext(compartmentContext IBatchCompartmentContext)

GetCompartmentContext returns the object serving as a specific context for this compartment

type BatchCompartmentID

type BatchCompartmentID string

BatchCompartmentID is a key that should help us uniquely identify a compartment

func BatchInsertCompartmentID

func BatchInsertCompartmentID(db string, table string) BatchCompartmentID

BatchInsertCompartmentID builds a BatchCompartmentID for the insert batch

type BatchFuncName

type BatchFuncName string

BatchFuncName is used to uniquely refer to batch function

const (
	BatchFunctionBULKINSERTLINES BatchFuncName = "bulkInsertLines"
)

type BatchFunction

type BatchFunction func(ctx IBatchFunctionContext, compartment *BatchCompartment, units []IBatchUnit) error

BatchFunction defines the signature of a function that knows what to do of a set of units, coming from a given compartment

type BatchUID

type BatchUID string

BatchUID is used to uniquely refer to a set of batch compartments treated with the same batch function

type BatchUnitAutoSign

type BatchUnitAutoSign struct{}

BatchUnitAutoSign is a signature for batch units and compartment which does not really need one

func (*BatchUnitAutoSign) Matches

func (thisSign *BatchUnitAutoSign) Matches(compartmentSignature IBatchSignature) error

Matches : implementing IBatchSignature

func (*BatchUnitAutoSign) ToString

func (thisSign *BatchUnitAutoSign) ToString() string

ToString : implementing IBatchSignature

type Batcher

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

Batcher : an instance of this struct can be attached to the app server and provide services; such as piling work elements to be asynchronously treated in batches, through scheduled jobs

func (*Batcher) GetCompartments

func (thisBatcher *Batcher) GetCompartments(handleWithJob BatchUID) map[BatchCompartmentID]*BatchCompartment

GetCompartments returns the compartments for a given job name, mapped by their batch keys

func (*Batcher) HasPendingWork

func (thisBatcher *Batcher) HasPendingWork() bool

HasPendingWork tells us if there is at least 1 unit waiting for treatment

func (*Batcher) IsShut

func (thisBatcher *Batcher) IsShut() bool

tells if the scheduler is shut or not

func (*Batcher) Push

func (thisBatcher *Batcher) Push(handleWithJob BatchUID, unit IBatchUnit) (nbInBasket, nbBatches, batchSize int, err error)

Push : pushing the unit in one of the batcher's compartment, to be treated later on; returns the number of units accumulated in the basket, or an error if something went south

func (*Batcher) Shut

func (thisBatcher *Batcher) Shut()

shutting down the scheduler

type BulkInsertionsContext

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

a context for each compartment we'll push stuff into

type CountryCode

type CountryCode struct {
	Alpha2Code   string
	Alpha3Code   string
	NumCode      int
	Translations map[Lang]*Translation
}

CountryCode : a country code, with its translations

func FindCountryCode

func FindCountryCode(codeOrTranslation string) *CountryCode

FindCountryCode retrieves a country code by a code or a translation

type Currency

type Currency struct {
	Code  CurrencyCode `json:"code"`
	Num   int          `json:"num"`
	Label string       `json:"label"`
}

Currency is a structure made to contain the code, the number, and the label of a Currency

func GetCurrency

func GetCurrency(currencyCode string) *Currency

GetCurrency returns the current for the given currency code, if it exists

type CurrencyCode

type CurrencyCode string

CurrencyCode defines an enum for the type of currencies

const (
	CurrencyCodeEUR CurrencyCode = "EUR"
	CurrencyCodeGBP CurrencyCode = "GBP"
	CurrencyCodeUSD CurrencyCode = "USD"
	CurrencyCodeCHF CurrencyCode = "CHF"
)

For the codes, check this page: https://en.wikipedia.org/wiki/ISO_4217

func (CurrencyCode) Label

func (thisCurrencyCode CurrencyCode) Label() string

Label returns the currency label associated with the given currency label

func (CurrencyCode) Num

func (thisCurrencyCode CurrencyCode) Num() int

Num returns the currency number associated with the given currency code

func (CurrencyCode) String

func (thisCurrencyCode CurrencyCode) String() string

type Email

type Email string

Email helps define an email address

type ErrorMessage

type ErrorMessage struct {
	Valid   bool
	Title   string
	Message string
}

ErrorMessage is a simple error message TODO _OA$0: checking it is still needed.

type IAppservSibling

type IAppservSibling interface {

	// Loggers
	IsVerbose() bool
	LogF(skip int, fields logrus.Fields) LogEntry
	Log() LogEntry

	// DB
	// QueryRow uses the Appserv version of QueryRow
	QueryRow(pQuery string, pParams ...interface{}) *sql.Row
	// QuerySQL uses the Appserv version of QuerySQL
	QuerySQL(pQuery string, pParams ...interface{}) (*sql.Rows, error)
	// Exec uses the Appserv version of Exec
	Exec(pQuery string, pParams ...interface{}) (sql.Result, error)
	// GetSecondaryDB retrieve the secondary SQL DB connector
	GetSecondaryDB(pDbID string, pCheck bool) (*sql.DB, error)
	// GetSecondaryDBx retrieve the secondary SQLx DB connector
	GetSecondaryDBx(pDbID string, pCheck bool) (*sqlx.DB, error)
	// BeginDbTransaction starts an sql transaction using the base SQL library
	BeginDbTransaction() (*sql.Tx, error)
	// GetDbName returns the name of the current DB we're connected to
	GetDbName() string
	// GetSecondaryDbName returns the name of the given secondary DB we're connected to
	GetSecondaryDbName(id string) string
	// IsDBOpen tells if the DB has been initialized, or not
	IsDBOpen() bool
	// GetUniqueID allows to get a unique value associated to the given counter name
	GetUniqueID(counterName string) (int, error)
	// GetSqlLogThreshold returns the time above which we automatically log the SQL request executions; 0 means always
	GetSqlLogThreshold() time.Duration

	// Config
	GetCustomConfig() ICustomConfig
	GetAppName() string
	GetAppPath() string
	GetDescription() string
	GetVersion() string
	GetMode() AppMode
	IsTestMode() bool

	// WS
	GetVostokAppToken(appName string, appURL string, user string, password string, timeout time.Duration) (string, error)

	// Batch processing
	IBatcherOwner
}

IAppservSibling is an interface allowing procedure shared by both AppservChild and JobWorker to be executed in both contexts.

type IBatchCompartmentConfig

type IBatchCompartmentConfig interface {
	GetBatchUID() BatchUID                     // the unique ID for the batch job this config belongs to
	GetBatchCompartmentID() BatchCompartmentID // the compartment identifier
	GetBatchesSize() int                       // the maximal number of units to treat at the same time
	GetNbBatchesAtOnce() int                   // the maximal number of batches to treat at each tick of the scheduler; 0 means : no limit
	GetPurgeBasketAfter() time.Duration        // the maximal duration a basket can stay opened without receiving new batch unit
	GetParams() map[string]string              // the compartment's additional parameters
	// contains filtered or unexported methods
}

IBatchCompartmentConfig : defines some characteristics for a batch compartment : an identifier, the batches batchSize, etc.

type IBatchCompartmentContext

type IBatchCompartmentContext interface{}

IBatchCompartmentContext : a context used to persist additional data on a compartment

type IBatchFunctionContext

type IBatchFunctionContext interface {
	IAppservSibling                                             // we should be able to do pretty much everything while treating batches
	NewBatchRoutineContext(scopeID string) IBatchRoutineContext // this is the context passed for the treatment of a batch, associated with a new routine
}

IBatchFunctionContext gathers all the services needed to perform the batch treatments

type IBatchInsertUnit

type IBatchInsertUnit interface {
	IBatchUnit
	GetInsertColumns() []string     // a list of the columns to insert for a given unit; MUST be the same list for the units of the same compartment
	GetInsertValues() []interface{} // a list of values corresponding to the columns
}

IBatchInsertUnit is a particular IBatchUnit, made for (you guessed it) batch inserts

type IBatchRoutineContext

type IBatchRoutineContext interface {
	IBatchFunctionContext // we should be able to do pretty much everything while treating a batch
	Release()             // we must be able to release this routine-based context
}

IBatchRoutineContext is the context needed for the treatment of a set of units within a new routine

type IBatchSignature

type IBatchSignature interface {
	Matches(compartmentSignature IBatchSignature) error // checks if this signature matches the targeted compartment's signature
	ToString() string                                   // builds a string from that signature for logging purposes
}

IBatchSignature : a batch signature allow to check that batch units have the same form. By sharing the same signature, batch units can be treated altogether. A batch unit that has a different signature has to be rejected.

type IBatchUnit

type IBatchUnit interface {
	GetBatchCompartmentID() BatchCompartmentID     // returns the key that must uniquely identify the compartment this unit must land into, before it is treated by the corresponding batch
	IsAllowed(compartment *BatchCompartment) error // can this unit enter the given compartment ? must return an error if not
	GetSignature() IBatchSignature                 // a signature - of simple or complex type (object) - that should be shared by all the batch units pushed into a given compartment
}

IBatchUnit designates a unit treated in batch, along with other similar units

type IBatcherOwner

type IBatcherOwner interface {
	Batcher() *Batcher
}

IBatcherOwner defines the capacity to give an access to an IBatcher instance

type ICache

type ICache interface {

	// Get is the method that allows to retrieve an object from the cache, given a corresponding key
	Get(key string) (interface{}, bool)

	// Set is the method that allows to put an object into the cache, with an expiration time
	Set(key string, object interface{}, expiration time.Duration)

	// SetDefault is the method that allows to put an object into the cache, with the default configured expiration time
	SetDefault(key string, object interface{})

	// Delete the entry corresponding to the given key
	Delete(key string)

	// Add is the method to put an object into the cache if it is not there yet, or is expired,
	// and returns an error if there's already something with this key
	Add(key string, object interface{}, expiration time.Duration) error

	// Flush removes all the entries from the cache
	Flush()
}

ICache defines what services a cache should provide

type ICachePartition

type ICachePartition interface {

	// PartitionName returns the partition's name
	PartitionName() string
}

ICachePartition is the type for objects used to identify cache spaces

func NewPartition

func NewPartition(partitionName string) ICachePartition

NewPartition can be used to create a new cache partition, while ensuring there's not an existing partition with the same name created THIS WAY. WARNING : this does NOT ensure that there isn't a partition created through another method with the same name ! i.e. this function does not completely prevent name collisions. So stay aware of all the partitions you have !

type IConfigFile

type IConfigFile interface {
	GetServerConfig() *ServerConfig
	GetCustomConfig() ICustomConfig
}

IConfigFile defines the generic services provided by a config file

type ICustomConfig

type ICustomConfig interface {
}

ICustomConfig gives a handle to a custom part of the server config

type IDB

type IDB interface {
	// Ping verifies a connection to the database is still alive,
	// establishing a connection if necessary.
	Ping() error
	// Exec executes a query without returning any rows.
	// The args are for any placeholder parameters in the query.
	Exec(query string, args ...interface{}) (sql.Result, error)
	// Query executes a query that returns rows, typically a SELECT.
	// The args are for any placeholder parameters in the query.
	Query(query string, args ...interface{}) (*sql.Rows, error)
	// QueryRow executes a query that is expected to return at most one row.
	// QueryRow always returns a non-nil value. Errors are deferred until
	// Row's Scan method is called.
	// If the query selects no rows, the *Row's Scan will return ErrNoRows.
	// Otherwise, the *Row's Scan scans the first selected row and discards
	// the rest.
	QueryRow(query string, args ...interface{}) *sql.Row
	// Begin starts a transaction. The default isolation level
	// is dependent on the driver.
	Begin() (*sql.Tx, error)
	// Prepare creates a prepared statement for use within a transaction.
	// The returned statement operates within the transaction and can no longer
	// be used once the transaction has been committed or rolled back.
	// To use an existing prepared statement on this transaction, see Tx.Stmt.
	Prepare(query string) (*sql.Stmt, error)
	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	// Expired connections may be closed lazily before reuse.
	// If d <= 0, connections are reused forever.
	SetConnMaxLifetime(d time.Duration)
	// SetMaxOpenConns sets the maximum number of open connections to the database.
	// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
	// MaxIdleConns, then MaxIdleConns will be reduced to match the new
	// MaxOpenConns limit.
	// If n <= 0, then there is no limit on the number of open connections.
	// The default is 0 (unlimited).
	SetMaxOpenConns(n int)
	// SetMaxIdleConns sets the maximum number of connections in the idle
	// connection pool.
	// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
	// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
	// If n <= 0, no idle connections are retained.
	// The default max idle connections is currently 2. This may change in
	// a future release.
	SetMaxIdleConns(n int)
	// Stats returns database statistics.
	Stats() sql.DBStats
}

IDB defines the common methods we're using on a DB connection manager

type IGlobalCache

type IGlobalCache interface {
	ICache // a global cache is a cache...

}

IGlobalCache defines what services a global (-as opposed to global) cache should provide TODO : put a cache server behind this, like gomemcache.

func GetGlobalCache

func GetGlobalCache() IGlobalCache

GetGlobalCache returns the global cache associated with the given Appserv instance if the global cache has not been initialised we naturally panic telling whoever reads the log that the calling code need to InitGlobalCache() before. WARNING: can be used only if NoPartition = true in the config.

type ILocalCache

type ILocalCache interface {
	ICache // a local cache is a cache...

}

ILocalCache defines what services a local (-as opposed to global) cache should provide TODO _JW$0: maybe we should remove the local cache ?? or at least, consider it only for "static" objects like entity schemas TODO _JW$0: for everything that can be changed - from the webapp for instance -> caching in a Shared Cache

func GetLocalCache

func GetLocalCache() ILocalCache

GetLocalCache returns the local cache associated with the given Appserv instance if the local cache has not been initialised we naturally panic telling whoever reads the log that the calling code need to InitLocalCache() before.

func NewLocalCache

func NewLocalCache(localDefaultExpiration time.Duration, localCleanupInterval time.Duration) ILocalCache

NewLocalCache returns a new instance implementing the interface ILocalCache

type IPartitionedCache

type IPartitionedCache interface {

	// Get is the method that allows to retrieve an object from the cache, given a corresponding key
	Get(partition ICachePartition, key string) (interface{}, bool)

	// Set is the method that allows to put an object into the cache, with an expiration time
	Set(partition ICachePartition, key string, object interface{}, expiration time.Duration)

	// SetDefault is the method that allows to put an object into the cache, with the default configured expiration time
	SetDefault(partition ICachePartition, key string, object interface{})

	// Delete the entry corresponding to the given key
	Delete(partition ICachePartition, key string)

	// Add is the method to put an object into the cache if it is not there yet, or is expired,
	// and returns an error if there's already something with this key
	Add(partition ICachePartition, key string, object interface{}, expiration time.Duration) error

	// AllItems returns a map of all the items cached in one cache partition, with their original keys
	// WARNING : should be used with caution since this can lead to performance issues.
	AllItems(partition ICachePartition) map[string]interface{}

	// Flush deletes all the entries from the given cache partition
	Flush(partition ICachePartition)

	// Partitions lists all the partitions currently in use
	Partitions() map[string]ICachePartition
}

IPartitionedCache helps dealing with a partitioned global cache

func GetPartitionedCache

func GetPartitionedCache() IPartitionedCache

GetPartitionedCache returns the global cache associated with the given Appserv instance if the global cache has not been initialised we naturally panic telling whoever reads the log that the calling code need to InitGlobalCache() before. WARNING: can be used only if NoPartition = true in the config.

type IStringNormalizer

type IStringNormalizer interface {
	String(str string) (result string, err error)  // basic normalization function: "Yoùr Śtring šđč枊ĐČĆŽ Ötzi's Nationalität èàì" => "Your String sđcczSĐCCZ Otzi's Nationalitat eai"
	ToUpper(str string) (result string, err error) // normalizes and capitalizes: Jean-Vincent Placé => JEAN-VINCENT PLACE
}

IStringNormalizer defines the functions our string normalizer should expose

func NewStringNormalizer

func NewStringNormalizer() IStringNormalizer

IStringNormalizer returns a non-thread-safe string normalizer instance

type ITokenResponse

type ITokenResponse interface {
	GetToken() string
	GetExpirationInSeconds() int
}

type JSONConfigFile

type JSONConfigFile struct {
	VostokInfo map[string]string `json:"vostok"`
	Config     *ServerConfig     `json:"configuration"`
}

JSONConfigFile represents the structure of a config file used by a Vostok app

func (*JSONConfigFile) GetCustomConfig

func (thisFile *JSONConfigFile) GetCustomConfig() ICustomConfig

GetCustomConfig helps implement the IConfigFile interface

func (*JSONConfigFile) GetServerConfig

func (thisFile *JSONConfigFile) GetServerConfig() *ServerConfig

GetServerConfig helps implement the IConfigFile interface

type JSONResponse

type JSONResponse struct {
	VostokHeader *JSONResponseHeader `json:"VostokHeader"`
	VostokData   interface{}         `json:"VostokData"`
}

JSONResponse is the root object on which are based the base vostok JSON responses.

type JSONResponseError

type JSONResponseError struct {
	Code    string `json:"Code"`
	Title   string `json:"Title"`
	Message string `json:"Message"`
}

JSONResponseError the JSON error

type JSONResponseHeader

type JSONResponseHeader struct {
	VostokVersion string `json:"VostokVersion"`
	Box           string `json:"Box"`
	AppName       string `json:"AppName"`
	AppVersion    string `json:"AppVersion"`
	CallName      string `json:"CallName"`
	ResponseType  string `json:"ResponseType"`
}

JSONResponseHeader the JSON response header

type JSONResponseStatus

type JSONResponseStatus struct {
	NbRequests uint64                    `json:"NbRequests"`
	CGIURL     string                    `json:"CGIURL"`
	Port       int                       `json:"Port"`
	Memory     *responseStatusMemory     `json:"Memory"`
	Children   []*responseStatusChildren `json:"Children"`
}

JSONResponseStatus correspond to the object which will be sent back by the Status special request.

type JSONString

type JSONString string

JSONString helps define a stringified json object

type JSONTime

type JSONTime time.Time

JSONTime correspond to a time.Time field compatible with JSON Marshalling.

func (JSONTime) MarshalJSON

func (sTime JSONTime) MarshalJSON() ([]byte, error)

MarshalJSON is called implicitly when Marshalling a JSONTime object.

type JobConfig

type JobConfig struct {
	UID         string            `json:"UID"`         // the job config unique identifier
	Description string            `json:"Description"` // description of the job
	Schedule    string            `json:"Schedule"`    // the schedule, set as a cron task; can be overridden in a REST application
	Active      bool              `json:"Active"`      // if true, then jobs are triggered with this config; else, nothing happen with this config
	UseConfig   bool              `json:"UseConfig"`   // if true, then the values of the parameters contained in the config files are used over other versions of these values (in a DB for instance)
	Params      map[string]string `json:"Params"`      // additional params for the job
}

JobConfig holds the configuration for workers

type JobWorker

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

JobWorker gives access to the scheduler and the app server, and their methods

func (*JobWorker) Batcher

func (thisWorker *JobWorker) Batcher() *Batcher

Batcher : IBatcher implem

func (*JobWorker) BeginDbTransaction

func (thisWorker *JobWorker) BeginDbTransaction() (*sql.Tx, error)

BeginDbTransaction start an sql transaction

func (*JobWorker) Exec

func (thisWorker *JobWorker) Exec(queryAsString string, values ...interface{}) (sql.Result, error)

Exec should allow to perform a query to update the DB

func (*JobWorker) GetAppName

func (thisWorker *JobWorker) GetAppName() string

GetAppName : returns the current app name

func (*JobWorker) GetAppPath

func (thisWorker *JobWorker) GetAppPath() string

GetAppPath : returns the current app path

func (*JobWorker) GetCustomConfig

func (thisWorker *JobWorker) GetCustomConfig() ICustomConfig

GetCustomConfig : returns the current custom config, i.e. the config belonging to a specific app

func (*JobWorker) GetDbName

func (thisWorker *JobWorker) GetDbName() string

GetDbName : the name of the currently configured DB we're connected to

func (*JobWorker) GetDescription

func (thisWorker *JobWorker) GetDescription() string

GetDescription : returns the current app description

func (*JobWorker) GetLogger

func (thisWorker *JobWorker) GetLogger() *logrus.Logger

GetLogger indicates how to get the logger from this scope

func (*JobWorker) GetMode

func (thisWorker *JobWorker) GetMode() AppMode

GetMode : tells is the current mode is: live, prelive, dev, etc...

func (*JobWorker) GetParentScope

func (thisWorker *JobWorker) GetParentScope() LoggingScope

GetParentScope returns the parent scope

func (*JobWorker) GetRoutineStats

func (thisWorker *JobWorker) GetRoutineStats() (currentUse, maxParaUse, totalUse int)

GetRoutineStats : implementation for JobWorker

func (*JobWorker) GetScopeID

func (thisWorker *JobWorker) GetScopeID() string

GetScopeID returns this scope's ID; scope IDs for sibling scopes should have the same length, for better readibiliy

func (*JobWorker) GetSecondaryDB

func (thisWorker *JobWorker) GetSecondaryDB(dbID string, check bool) (*sql.DB, error)

GetSecondaryDB returns a secondary DB, as a *sql.DB instance, if it exists, and has been initialised

func (*JobWorker) GetSecondaryDBx

func (thisWorker *JobWorker) GetSecondaryDBx(dbID string, check bool) (*sqlx.DB, error)

GetSecondaryDBx returns a secondary DB, as a *sqlx.DB instance, if it exists, and has been initialised

func (*JobWorker) GetSecondaryDbName

func (thisWorker *JobWorker) GetSecondaryDbName(id string) string

GetSecondaryDbName : the name of a secondary DB identified by its ID

func (*JobWorker) GetSeparator

func (thisWorker *JobWorker) GetSeparator() string

GetSeparator returns the separator to use after the scope ID; Most of the time it should be "|", but it could be "]["

func (*JobWorker) GetSignature

func (thisWorker *JobWorker) GetSignature() string

GetSignature : the scope must retain the result of GetScopeSignature(this) and return it through this method

func (*JobWorker) GetSqlLogThreshold

func (thisWorker *JobWorker) GetSqlLogThreshold() time.Duration

GetSqlLogThreshold returns the duration above which SQL executions are logged

func (*JobWorker) GetUniqueID

func (thisWorker *JobWorker) GetUniqueID(counterName string) (int, error)

GetUniqueID allows to get a unique value associated to the given counter name

func (*JobWorker) GetVersion

func (thisWorker *JobWorker) GetVersion() string

GetVersion : returns the current app version

func (*JobWorker) GetVostokAppToken

func (thisWorker *JobWorker) GetVostokAppToken(appName string, appURL string, user string, password string, timeout time.Duration) (string, error)

GetVostokAppToken retrieves a token to access another Vostok-based app

func (*JobWorker) GetWorkerID

func (thisWorker *JobWorker) GetWorkerID() int

GetWorkerID returns the worker ID

func (*JobWorker) GetWorkerUses

func (thisWorker *JobWorker) GetWorkerUses() int

GetWorkerUses returns the number of jobs this worker has been treated

func (*JobWorker) IsDBOpen

func (thisWorker *JobWorker) IsDBOpen() bool

IsDBOpen : true if the DB associated with the given App Server or Child is open

func (*JobWorker) IsHideFunctionName

func (thisWorker *JobWorker) IsHideFunctionName() bool

IsHideFunctionName tells if the caller function should be hidden or not

func (*JobWorker) IsTestMode

func (thisWorker *JobWorker) IsTestMode() bool

IsTestMode : tells if we're in test mode or not

func (*JobWorker) IsVerbose

func (thisWorker *JobWorker) IsVerbose() bool

IsVerbose : tells if we're in verbose mode; a logger can tell since it has to know to chose what to log

func (*JobWorker) Log

func (thisWorker *JobWorker) Log() LogEntry

Log creates a prefixed log entry with no frame skipped, and no field

func (*JobWorker) LogF

func (thisWorker *JobWorker) LogF(skip int, fields logrus.Fields) LogEntry

LogF creates a prefixed log entr, with fiel, y with a given number of frames skippds

func (*JobWorker) NewBatchRoutineContext

func (thisWorker *JobWorker) NewBatchRoutineContext(scopeID string) IBatchRoutineContext

func (*JobWorker) NewRoutine

func (thisWorker *JobWorker) NewRoutine(scopeID string) Routine

NewRoutine : implementation for JobWorker

func (*JobWorker) QueryRow

func (thisWorker *JobWorker) QueryRow(queryAsString string, values ...interface{}) *sql.Row

QueryRow should execute a query bringing back rows from the DB

func (*JobWorker) QuerySQL

func (thisWorker *JobWorker) QuerySQL(queryAsString string, values ...interface{}) (*sql.Rows, error)

QuerySQL should execute a query bringing back rows from the DB

type Lang

type Lang string

Lang helps listing languages

const (
	LangDE Lang = "DE"
	LangEN Lang = "EN"
	LangES Lang = "ES"
	LangFR Lang = "FR"
	LangIT Lang = "IT"
	LangNL Lang = "NL"
)

The languages managed by vostok apps

type LogEntry

type LogEntry interface {
	Trace(format string, args ...interface{})
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
	Fatal(format string, args ...interface{})
	Panic(format string, args ...interface{})
}

LogEntry is the interface we want to expose

func NewEntry

func NewEntry(scope LoggingScope, skip int, fields logrus.Fields) LogEntry

NewEntry helps instantiate a new entry proxy

type LoggingScope

type LoggingScope interface {

	// LogF creates a prefixed log entry wither of frames skipped, with fields
	LogF(skip int, fields logrus.Fields) LogEntry

	// Log_ creates a prefixed log entry with no frame skipped, and no field
	Log() LogEntry

	// GetParentScope returns the parent scope
	GetParentScope() LoggingScope

	// GetLogger indicates how to get the logger from this scope
	GetLogger() *logrus.Logger

	// GetScopeID returns this scope's ID; scope IDs for sibling scopes
	// should have the same length, for better readibiliy
	GetScopeID() string

	// GetSignature : the scope must retain the result of GetScopeSignature(this)
	// and return it through this method
	GetSignature() string

	// GetSeparator returns the separator to use after the scope ID;
	// Most of the time it should be "|", but it could be "]["
	GetSeparator() string

	// IsVerbose tells if the log is being verbose, as per its configuration
	IsVerbose() bool

	// IsHideFunctionName tells if the caller function should be hidden or not
	IsHideFunctionName() bool
}

LoggingScope helps use define what is a scope in terms of logging.

type OAuthAction

type OAuthAction string

OAuthAction allows use to list the available OAuth actions

type RegExpPattern

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

RegExpPattern provide both the object used to match the regexp and the string definition

var (
	// VOSTOK_REGEXP_UINT matches unsigned integers
	VOSTOK_REGEXP_UINT *RegExpPattern

	// VOSTOK_REGEXP_INT matches signed integers
	VOSTOK_REGEXP_INT *RegExpPattern

	// VOSTOK_REGEXP_FLOAT matches floating points numbers
	VOSTOK_REGEXP_FLOAT *RegExpPattern

	// VOSTOK_REGEXP_TIMESTAMP matches Mysql types timestamps YYYY-MM-DD HH:MM:SS.uuuuuu
	VOSTOK_REGEXP_TIMESTAMP *RegExpPattern

	// VOSTOK_REGEXP_TIMESTAMP_LONG matches Mysql types timestamps YYYY-MM-DD HH:MM:SS
	VOSTOK_REGEXP_TIMESTAMP_LONG *RegExpPattern

	// VOSTOK_REGEXP_TIMESTAMP_MEDIUM matches Mysql types timestamps YYYY-MM-DD HH:MM
	VOSTOK_REGEXP_TIMESTAMP_MEDIUM *RegExpPattern

	// VOSTOK_REGEXP_TIMESTAMP_SHORT matches Mysql types timestamps YYYY-MM-DD
	VOSTOK_REGEXP_TIMESTAMP_SHORT *RegExpPattern

	// VOSTOK_REGEXP_TIMESTAMP_YEAR matches a four chars Year
	VOSTOK_REGEXP_TIMESTAMP_YEAR *RegExpPattern

	// VOSTOK_REGEXP_MD5 matches the MD5 32 hex digits format
	VOSTOK_REGEXP_MD5 *RegExpPattern

	// VOSTOK_REGEXP_NAME matches names with letters and underscore and dash
	VOSTOK_REGEXP_NAME *RegExpPattern

	// VOSTOK_REGEXP_IP matches IPv4 or IPv6 IP addresses
	VOSTOK_REGEXP_IP *RegExpPattern
)

func NewRegExpPattern

func NewRegExpPattern(pPattern string) *RegExpPattern

NewRegExpPattern returns a new RegExpPattern object by compiling the string definition provides as an parameter.

Arguments

pPattern: the pattern as a string

func (*RegExpPattern) MatchString

func (sRegExpPattern *RegExpPattern) MatchString(pString string) bool

MatchString does nothing clever but just reuse the MatchString from Go package regexp.

Arguments

pString: the string you want to test against the regexp pattern.

Returns

  • true if it matches, false otherwise.

type Routine

type Routine interface {
	Release()    // this should make the inner routine go back into the pool
	RoutineOwner // we should be able to start a routine from a routine!
}

Routine is an interface for the objects that should: - wrap a routine - offer the same services as the appserv, its children, or workers

type RoutineOwner

type RoutineOwner interface {
	LoggingScope    // it should allow scoped logs
	IAppservSibling // it should exposes the services we need while doing stuff inside a routine
	IBatcherOwner   // it should be able to pile on stuff to treat in batches
	// contains filtered or unexported methods
}

RoutineOwner is the type of the objects that can start a new routine, log, and access the DB

type ServerConfig

type ServerConfig struct {
	Box         string             `json:"Box"`
	AppName     string             `json:"AppName"`
	Description string             `json:"Description"`
	Version     string             `json:"Version"`
	Application *applicationConfig `json:"Application"`
	Items       map[string]string  `json:"Items"`
	Flags       map[string]bool    `json:"Flags"`
	Custom      ICustomConfig      `json:"Custom"`
}

ServerConfig is the root object holding the configuration items

func BuildConfig

func BuildConfig(pConfigFilePath string) (rConfig *ServerConfig, rErr error)

BuildConfig read a configuration file and hydrates a Server configuration object. This expects the configuration file to be a JSON file. This procedure doesn't use any specific configuration object as an argument which means it will not generate any custom configuration.

Arguments

pConfigFilePath:   the name of the config item for which we want the value
pConfigFileObject: the object that will bear the configuration items

Returns

  • the root config object for the server
  • the error if there is one

type SessionAuthAction

type SessionAuthAction string

SessionAuthAction allows use to list the available Session Authentication actions

const (
	// SessionAuthLOGIN: the action performed to log in an user
	SessionAuthLOGIN SessionAuthAction = "login"

	// SessionAuthLOGOUT: the action performed to log out an user
	SessionAuthLOGOUT SessionAuthAction = "logout"
)

type StatelessAuthAction

type StatelessAuthAction string

StatelessAuthAction allows use to list the available Stateless Authentication actions

const (
	// StatelessAuthLOGIN: the action performed to log in an user
	StatelessAuthLOGIN StatelessAuthAction = "login"

	// StatelessAuthLOGOUT: the action performed to log out an user
	StatelessAuthLOGOUT StatelessAuthAction = "logout"
)

type SuccessMessage

type SuccessMessage struct {
	Valid   bool
	Title   string
	Message string
}

SuccessMessage is a simple success message TODO _OA$0: checking it is still needed.

type Translation

type Translation struct {
	Language Lang
	Short    string
	Long     string
}

Translation helps keeping a translation for a given language

type URL

type URL string

URL helps define an internet URL

type UserInfo

type UserInfo struct {
	BaseUser
	UserID      int
	IPAddress   string
	Permissions map[string]bool
}

UserInfo is the base structure to store a logged in user

Jump to

Keyboard shortcuts

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