cypress

package module
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2023 License: MIT Imports: 46 Imported by: 0

README

cypress

An integrated web server and websocket framework

features

  1. pipeline based request handlers
  2. security as a request handler
  3. logging as a request handler
  4. MVC support
  5. Redis based session store support
  6. context for all, supports cancellation and correlation logging
  7. horizental database partitioning
  8. XA transaction support

XA transaction support requirements

  • User privileges

For MySQL 8.0 XA_RECOVER_ADMIN is required

  • Unique key generator

There is a default database based unique key generator, since the tables requires by the generator would not exceed a few hundreds of rows, there is no sharding support for this version of unique key generator. The following data table is required for DB based unique key generator.

create table `id_generator` (
    `name` varchar(200) not null,
    `partition` int not null,
    `pooled_id` int not null,
    constraint `pk_id_generator` primary key (`name`, `partition`)
  ) engine=InnoDB default charset=utf8;
  • Cluster transaction state store

A cluster transaction state store is required to support distributed transactions, the store is used to provide transaction states for unknown transaction state resolver to decide how to move on with outstanding but timeout transactions.

There is a DB based transaction store implementation provided, which requires the following data tables,

  create table `cluster_txn` (
      `id` varchar(40) auto_increment not null primary key,
      `state` int not null default 0,
      `timestamp` bigint not null,
      `lease_expiration` bigint not null default 0
  ) engine=InnoDB default charset=utf8 auto_increment=10001;
  create table `txn_participant` (
      `txn_id` varchar(40) not null,
      `partition` int not null,
      `state` int not null default 0,
      constraint `pk_txn_participant` primary key (`txn_id`, `partition`)
  ) engine=InnoDB default charset=utf8;

Documentation

Index

Constants

View Source
const (
	// ClusterTxnStateNone nil state
	ClusterTxnStateNone = iota

	// ClusterTxnStateCommitted state committed
	ClusterTxnStateCommitted

	// ClusterTxnStateRollback state rollback
	ClusterTxnStateRollback
)
View Source
const (
	// XAStateUnknown state unknown
	XAStateUnknown = iota

	// XAStateActive state active
	XAStateActive

	// XAStateIdle state idle
	XAStateIdle

	// XAStatePrepared state prepared
	XAStatePrepared

	// XAStateRollback state rollback
	XAStateRollback

	// XAStateCommitted state committed
	XAStateCommitted
)
View Source
const (
	// EntityTagsDTags dtags tag
	EntityTagsDTags = "dtags"

	// EntityTagsDTagsKey key flag in dtags
	EntityTagsDTagsKey = "key"

	// EntityTagsDTagsSecure secure flag in dtags
	EntityTagsDTagsSecure = "secure"

	// EntityTagsDTagsNoUpdate noupdate flag in dtags
	EntityTagsDTagsNoUpdate = "noupdate"

	// EntityTagsDTagsNoGen nogen flag in dtags
	EntityTagsDTagsNoGen = "nogen"

	// EntityTagsDTagsMultiKey multikey flag in dtags
	EntityTagsDTagsMultiKey = "multikey"

	// EntityTagsDTagsAutoInc autoinc flag in dtags
	EntityTagsDTagsAutoInc = "autoinc"

	// EntityTagsDTagsPartition partition flag in dtags
	EntityTagsDTagsPartition = "partition"

	// EntityTagsCol col tag
	EntityTagsCol = "col"

	// EntityTagsAlias alias tag
	EntityTagsAlias = "alias"

	// EntityTagsPrefix prefix tag
	EntityTagsPrefix = "prefix"

	PagingNext = "next"
	PagingPrev = "prev"
	PagingNone = "none"
)
View Source
const (
	TraceActivityIDKey = "TraceActivityID"
	UserPrincipalKey   = "UserPrincipal"
	SessionKey         = "UserSession"
)

Context keys

View Source
const (
	DefaultJwtProviderName = "JWT"
	BackupKeyNameSuffix    = "$backup"
)
View Source
const (
	// PartitionKeyBitWidth bits for partition value
	PartitionKeyBitWidth = 5

	// PartitionKeyMask partition value mask
	PartitionKeyMask = 0x1f

	// SegmentedIDBitWidth segmented id value bit width
	SegmentedIDBitWidth = 7

	// SegmentedIDMask segmented id value mask
	SegmentedIDMask = 0x7f

	// PooledIDBitWidth pooled id value bit width
	PooledIDBitWidth = PartitionKeyBitWidth + SegmentedIDBitWidth

	// MaxPooledID maximum pooled id
	MaxPooledID = (int64(1) << (64 - PooledIDBitWidth)) - 1

	// MaxSegmentedID max segmented id
	MaxSegmentedID = int64(1 << SegmentedIDBitWidth)
)

Variables

View Source
var (
	//EntityToTableNameMapper entity name to table name mapper
	EntityToTableNameMapper = TableNameResolverFunc(ToSnakeCase)

	// SQLIdentifierQuoteLeft sql identifier quote left
	SQLIdentifierQuoteLeft = "`"

	// SQLIdentifierQuoteRight sql identifier quote right
	SQLIdentifierQuoteRight = "`"
)
View Source
var (
	// ErrDirectoryRequired a directory is expected but file is seen
	ErrDirectoryRequired = errors.New("a directory is required")

	// ErrFileRequired a file is expected but directory is seen
	ErrFileRequired = errors.New("a file is required")

	// ErrBadSessionFile failed to read session data from session file
	ErrBadSessionFile = errors.New("bad session file")
)
View Source
var (
	//ErrNoFile no file given for Creating a template
	ErrNoFile = errors.New("no template file")

	//SkinDefault default skin name
	SkinDefault = "default"
)
View Source
var (
	// ErrDupActionName mulitple actions are having the same name for the same controller
	ErrDupActionName = errors.New("action name duplicated")

	// ServerName name of the app
	ServerName = "cypress"

	// ServerVersion version of the server
	ServerVersion = "v0.1.1110"

	// CaptchaKey captcha key in session
	CaptchaKey = "captcha"

	// CaptchaSessionKey captcha alternative session key parameter name
	CaptchaSessionKey = "sessid"

	// NotFoundMsg message to be shown when resource not found
	NotFoundMsg = "Sorry, we are not able to find the resource you requested"
)
View Source
var (
	// ErrLockFailed failed to lock
	ErrLockFailed = errors.New("failed to lock")

	// ErrLockCancelled not able to acquire the lock before context has cancelled
	ErrLockCancelled = errors.New("context cancelled before lock is acquired")
)
View Source
var (
	// CorrelationIDHeader http header name for correlation id header
	CorrelationIDHeader = http.CanonicalHeaderKey("x-correlation-id")
)
View Source
var (
	// ErrOutOfRange value out of range
	ErrOutOfRange = errors.New("value out of range")
)
View Source
var (
	// ErrPointerRequired a pointer is required
	ErrPointerRequired = errors.New("a pointer is required")
)
View Source
var (
	// ErrSessionNotFound a session with the specified key cannot be found
	ErrSessionNotFound = errors.New("session not found")
)
View Source
var (
	ZkLock2MaxConcurrentThreads int64 = int64(math.MaxInt32) / 2
)

Functions

func AccessorGetOne

func AccessorGetOne[T any](ctx context.Context, accessor *DbAccessor, proto *T) (*T, error)

func AccessorGetOneByKey

func AccessorGetOneByKey[T any](ctx context.Context, accessor *DbAccessor, key interface{}) (*T, error)

func AccessorQueryAll

func AccessorQueryAll[T any](ctx context.Context, accessor *DbAccessor, sql string, mapper RowMapper, args ...interface{}) ([]*T, error)

func AccessorQueryOne

func AccessorQueryOne[T any](ctx context.Context, accessor *DbAccessor, sql string, mapper RowMapper, args ...interface{}) (*T, error)

func Aes256Decrypt

func Aes256Decrypt(key, iv, data []byte) ([]byte, error)

Aes256Decrypt decrypts the data with given key and iv using AES256/CBC/PKCS5Padding

func Aes256Encrypt

func Aes256Encrypt(key, iv, data []byte) ([]byte, error)

Aes256Encrypt encrypts the data with given key and iv using AES256/CBC/PKCS5Padding

func CalculateMd5PartitionKey

func CalculateMd5PartitionKey(key string) int32

CalculateMd5PartitionKey Md5 based partition key calculator

func CalculateMd5PartitionKey2

func CalculateMd5PartitionKey2(key string) int32

CalculateMd5PartitionKey2 Md5 based partition key calculator, a fixed version to CalculateMd5PartitionKey

func ClusterGetAll

func ClusterGetAll[T any](ctx context.Context, cluster *MyCluster, query string, args ...interface{}) ([][]*T, error)

func ClusterGetOne

func ClusterGetOne[T any](ctx context.Context, cluster *MyCluster, query string, aggregator func(*T, *T) *T, args ...interface{}) (*T, error)

func ClusterGetPage

func ClusterGetPage[T any](ctx context.Context, cluster *MyCluster, query string, merger *PageMerger[any], args ...interface{}) ([]*T, error)

func ClusterQueryAll

func ClusterQueryAll[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, args ...interface{}) ([][]*T, error)

func ClusterQueryOne

func ClusterQueryOne[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, aggregator func(*T, *T) *T, args ...interface{}) (*T, error)

func ClusterQueryPage

func ClusterQueryPage[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, merger *PageMerger[any], args ...interface{}) ([]*T, error)

func ConvertToEpochMillis

func ConvertToEpochMillis(t time.Time) int64

ConvertToEpochMillis convert a time object to epoch in milliseconds

func DecodeRsaPrivateKey

func DecodeRsaPrivateKey(payload []byte) (*rsa.PrivateKey, error)

DecodeRsaPrivateKey decode rsa private key from pem payload

func DecodeRsaPublicKey

func DecodeRsaPublicKey(payload []byte) (*rsa.PublicKey, error)

DecodeRsaPublicKey decodes rsa public key from pem payload

func GetEpochMillis

func GetEpochMillis() int64

GetEpochMillis get epoch milliseconds for now

func GetFieldValueGetters

func GetFieldValueGetters(t reflect.Type) map[string]*FieldValueGetter

GetFieldValueGetters gets all possible FieldValueGetters for the give type t

func GetPartitionKey

func GetPartitionKey(id int64) int32

GetPartitionKey gets the partition key from the given unique ID value

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID get the trace ID related to the context

func LoadRsaPrivateKey

func LoadRsaPrivateKey(pemFile string) (*rsa.PrivateKey, error)

LoadRsaPrivateKey load rsa private key from pem file

func LoadRsaPublicKey

func LoadRsaPublicKey(pemFile string) (*rsa.PublicKey, error)

LoadRsaPublicKey load rsa public key from pem file

func LogExec

func LogExec(activityID string, start time.Time, err error)

LogExec log the sql Exec call result

func LogOperation

func LogOperation(ctx context.Context, operation string, operator func() error) error

LogOperation emit latency and error (if any) for the given operation

func LoggingHandler

func LoggingHandler(handler http.Handler) http.Handler

LoggingHandler http incoming logging handler

func Max added in v1.4.11

func Max[T Ordered](v1, v2 T) T

func Md5

func Md5(data []byte) []byte

Md5 returns the md5 checksum of the data

func Min added in v1.4.11

func Min[T Ordered](v1, v2 T) T

func NewRollingLogWriter

func NewRollingLogWriter(fileName string, maxSizeInMegaBytes, maxRotationFiles int) io.Writer

NewRollingLogWriter returns a new file based rolling log writer maxSizeInMegaBytes specifies the maximum size of each log file, while maxRotationFiles tells the maximum files to keep

func NewSessionHandler

func NewSessionHandler(pipeline http.Handler, store SessionStore, timeout time.Duration, valueTypes ...interface{}) http.Handler

NewSessionHandler creates a new session handler with registering the session object types

func NewSessionID

func NewSessionID() string

NewSessionID creates a new session ID

func OrderedCompare added in v1.4.9

func OrderedCompare[T Ordered](lh T, rh T) int

func QueryAll

func QueryAll(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) ([]interface{}, error)

QueryAll query all rows and map them to objects

func QueryAllEntities

func QueryAllEntities[TEntity any](ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) ([]*TEntity, error)

func QueryAllWithCollector

func QueryAllWithCollector(ctx context.Context, queryable Queryable, mapper RowMapper, query string, collector DataCollector, args ...interface{}) error

func QueryOne

func QueryOne(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) (interface{}, error)

QueryOne query one object

func QueryOneEntity

func QueryOneEntity[TEntity any](ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) (*TEntity, error)

func SendError

func SendError(writer http.ResponseWriter, statusCode int, errorMsg string)

SendError complete the request by sending an error message to the client

func SetupLogger

func SetupLogger(level LogLevel, writer io.Writer)

SetupLogger setup the global logger with specified log writer and log level this must be called before the logging can actually work

func Sha1

func Sha1(data []byte) []byte

Sha1 returns the sha1 checksum of the data

func Sha256

func Sha256(data []byte) []byte

Sha256 returns the sha256 checksum of the data

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase maps CamelCase to SnakeCase

func TxnGetOne

func TxnGetOne[T any](txn Txn, proto *T) (*T, error)

func TxnGetOneByKey

func TxnGetOneByKey[T any](txn Txn, key interface{}) (*T, error)

func TxnQueryAll

func TxnQueryAll[T any](txn Txn, sql string, mapper RowMapper, args ...interface{}) ([]*T, error)

func TxnQueryOne

func TxnQueryOne[T any](txn Txn, sql string, mapper RowMapper, args ...interface{}) (*T, error)

Types

type Action

type Action struct {
	Name    string
	Handler ActionHandler
}

Action a named http.Handler

type ActionHandler

type ActionHandler func(request *http.Request, response *Response)

ActionHandler action handler for standard routing

type AuthorizationManager

type AuthorizationManager interface {
	// CheckAccess check the user to see if the user has permission to access
	// path with the given http method
	CheckAccess(user *UserPrincipal, method, path string) bool

	// CheckAnonymousAccessible checks the given path can be accessed by anonymous
	// user with the given http method
	CheckAnonymousAccessible(method, path string) bool
}

AuthorizationManager an interface used by the security handler to check if the given user has permission to use the specified method and access the given path

type BufferedWriter

type BufferedWriter struct {
	Buffer [][]byte
}

BufferedWriter writes everything into memory

func NewBufferWriter

func NewBufferWriter() *BufferedWriter

NewBufferWriter creates a new buffer based writer

func (*BufferedWriter) Write

func (w *BufferedWriter) Write(p []byte) (n int, err error)

Write save the data into buffer

type ClusterTxn

type ClusterTxn struct {
	ID              string `col:"id" dtags:"key,nogen"`
	State           int    `col:"state"`
	Timestamp       int64  `col:"timestamp"`
	LeaseExpiration int64  `col:"lease_expiration"`
}

ClusterTxn cluster transaction entity

type CollectorCreatorFunc

type CollectorCreatorFunc func() DataCollector

func (CollectorCreatorFunc) Create

func (creator CollectorCreatorFunc) Create() DataCollector

type CompareFunc

type CompareFunc[T any] func(T, T) int

CompareFunc function implements Comparer

func (CompareFunc[T]) Compare

func (f CompareFunc[T]) Compare(lh T, rh T) int

Compare implements Comparer

type Comparer

type Comparer[T any] interface {
	Compare(lh T, rh T) int
}

Comparer interface for comparing objects

type Complex added in v1.4.9

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type ConcurrentMap

type ConcurrentMap[TKey comparable, TValue any] struct {
	// contains filtered or unexported fields
}

ConcurrentMap a concurrent map

func NewConcurrentMap

func NewConcurrentMap[TKey comparable, TValue any]() *ConcurrentMap[TKey, TValue]

NewConcurrentMap creates a new instance of ConcurrentMap

func (*ConcurrentMap[TKey, TValue]) Delete

func (m *ConcurrentMap[TKey, TValue]) Delete(key TKey)

Delete deletes the specified key from the map

func (*ConcurrentMap[TKey, TValue]) Foreach

func (m *ConcurrentMap[TKey, TValue]) Foreach(f func(key TKey, value TValue))

Foreach iterates the map and passes the key and value to the given function

func (*ConcurrentMap[TKey, TValue]) Get

func (m *ConcurrentMap[TKey, TValue]) Get(key TKey) (TValue, bool)

Get gets a value for the given key if it exists

func (*ConcurrentMap[TKey, TValue]) GetOrCompute

func (m *ConcurrentMap[TKey, TValue]) GetOrCompute(key TKey, generator func() TValue) TValue

GetOrCompute gets a value from map if it does not exist compute the value from the given generator

func (*ConcurrentMap[TKey, TValue]) Len

func (m *ConcurrentMap[TKey, TValue]) Len() int

Len gets the length of the underlying values

func (*ConcurrentMap[TKey, TValue]) Put

func (m *ConcurrentMap[TKey, TValue]) Put(key TKey, value TValue) (TValue, bool)

Put puts a value to the map associate to the map and return the old value

func (*ConcurrentMap[TKey, TValue]) RemoveIf

func (m *ConcurrentMap[TKey, TValue]) RemoveIf(evaluator func(key TKey, value TValue) bool) int

RemoveIf iterates the map and delete all items that the evaluator returns true returns number of items that were removed

type Controller

type Controller interface {
	ListActions() []Action
}

Controller a request controller that could provide a set of http.Handler to handle http requests based on the action name

type ControllerFunc

type ControllerFunc func() []Action

ControllerFunc a function that implements Controller interface

func AsController

func AsController(c interface{}) ControllerFunc

AsController enumerates all accessible member functions of c which has two parameters and *http.Request as the first one while *Response as the second one as Actions

func (ControllerFunc) ListActions

func (f ControllerFunc) ListActions() []Action

ListActions adapt the ControllerFunc to Controller interface

type CustomHandler

type CustomHandler interface {
	// PipelineWith returns a http.Handler that will execute the given handler
	// after the custom handler code is done.
	PipelineWith(handler http.Handler) http.Handler
}

CustomHandler a handler that is executed after session is setup/restored

type CustomHandlerFunc

type CustomHandlerFunc func(handler http.Handler) http.Handler

CustomHandlerFunc a function that implements CustomHandler

func (CustomHandlerFunc) PipelineWith

func (h CustomHandlerFunc) PipelineWith(handler http.Handler) http.Handler

PipelineWith implements CustomHandler interface

type DataCollector

type DataCollector interface {
	Collect(item interface{})
}

Data collector to collect query results

type DataCollectorCreator

type DataCollectorCreator interface {
	Create() DataCollector
}

Data collectors creator to create data collectors for query results

type DataCollectorFunc

type DataCollectorFunc[T any] func(item *T)

func (DataCollectorFunc[T]) Collect

func (collector DataCollectorFunc[T]) Collect(item interface{})

type DataPage added in v1.4.9

type DataPage[T any] struct {
	Page         int         `json:"page"`
	TotalRecords int64       `json:"totalRecords"`
	TotalPages   int         `json:"totalPages"`
	Records      []T         `json:"records"`
	PageToken    string      `json:"pageToken"`
	Summary      interface{} `json:"summary,omitempty"`
}

type DataRow

type DataRow interface {
	ColumnTypes() ([]*sql.ColumnType, error)
	Columns() ([]string, error)
	Scan(dest ...interface{}) error
}

DataRow data row, which can be used to scan values or get column information

type DbAccessor

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

DbAccessor database accessor

func NewDbAccessor

func NewDbAccessor(db *sql.DB) *DbAccessor

NewDbAccessor create a new instance of data accessor for the given db

func (*DbAccessor) BeginTxn

func (accessor *DbAccessor) BeginTxn(ctx context.Context) (*DbTxn, error)

BeginTxn starts a new transaction with RepeatableRead isolation

func (*DbAccessor) BeginTxnWithIsolation

func (accessor *DbAccessor) BeginTxnWithIsolation(ctx context.Context, isolation sql.IsolationLevel) (*DbTxn, error)

BeginTxnWithIsolation starts a new transaction

func (*DbAccessor) Conn

func (accessor *DbAccessor) Conn(ctx context.Context) (*sql.Conn, error)

Conn gets a connection to the DB

func (*DbAccessor) Delete

func (accessor *DbAccessor) Delete(ctx context.Context, entity interface{}) (sql.Result, error)

Delete delete entity from db

func (*DbAccessor) Execute

func (accessor *DbAccessor) Execute(ctx context.Context, command string, args ...interface{}) (sql.Result, error)

Execute execute command towards db

func (*DbAccessor) GetOne

func (accessor *DbAccessor) GetOne(ctx context.Context, proto interface{}) (interface{}, error)

GetOne query one entity based on the prototype

func (*DbAccessor) GetOneByKey

func (accessor *DbAccessor) GetOneByKey(ctx context.Context, ty reflect.Type, key interface{}) (interface{}, error)

GetOneByKey query one entity based on the given key, the entity must have a single dimension primary key

func (*DbAccessor) Insert

func (accessor *DbAccessor) Insert(ctx context.Context, entity interface{}) (sql.Result, error)

Insert insert entity to db

func (*DbAccessor) QueryAll

func (accessor *DbAccessor) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)

QueryAll execute sql query and return all entities based on the mapper

func (*DbAccessor) QueryAllWithCollector

func (accessor *DbAccessor) QueryAllWithCollector(ctx context.Context, query string, mapper RowMapper, collector DataCollector, args ...interface{}) error

func (*DbAccessor) QueryOne

func (accessor *DbAccessor) QueryOne(ctx context.Context, query string, mapper RowMapper, args ...interface{}) (interface{}, error)

QueryOne execute sql query and return one entity based on the mapper

func (*DbAccessor) Update

func (accessor *DbAccessor) Update(ctx context.Context, entity interface{}) (sql.Result, error)

Update update entity with db

type DbClusterTxnStore

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

DbClusterTxnStore an database based cluster transaction store implementation

func NewDbClusterTxnStore

func NewDbClusterTxnStore(db *DbAccessor) *DbClusterTxnStore

NewDbClusterTxnStore create a new database based cluster transaction store

func (*DbClusterTxnStore) AddTxnParticipant

func (store *DbClusterTxnStore) AddTxnParticipant(ctx context.Context, txnID string, partition int) error

AddTxnParticipant add a participant to a transaction

func (*DbClusterTxnStore) Close

func (store *DbClusterTxnStore) Close() error

Close close all resources used by store

func (*DbClusterTxnStore) CreateTxn

func (store *DbClusterTxnStore) CreateTxn(ctx context.Context, txnID string, t time.Time) (*ClusterTxn, error)

CreateTxn create a transaction

func (*DbClusterTxnStore) DeleteTxn

func (store *DbClusterTxnStore) DeleteTxn(ctx context.Context, txnID string) error

DeleteTxn delete partition from store

func (*DbClusterTxnStore) GetTxn

func (store *DbClusterTxnStore) GetTxn(ctx context.Context, txnID string) (*ClusterTxn, error)

GetTxn get transaction by ID

func (*DbClusterTxnStore) LeaseExpiredTxns

func (store *DbClusterTxnStore) LeaseExpiredTxns(ctx context.Context, expireTime, leaseTimeout time.Time, items int) ([]*ClusterTxn, error)

LeaseExpiredTxns lease expired transactions, only expired and lease expired (or not lease) transactions are visible

func (*DbClusterTxnStore) ListParticipants

func (store *DbClusterTxnStore) ListParticipants(ctx context.Context, txnID string) ([]*TxnParticipant, error)

ListParticipants list all participants in transaction

func (*DbClusterTxnStore) UpdateTxnState

func (store *DbClusterTxnStore) UpdateTxnState(ctx context.Context, txnID string, state int) error

UpdateTxnState update transaction state

type DbTxn

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

DbTxn db transaction wrapper with context

func (*DbTxn) Close

func (txn *DbTxn) Close()

Close commit or rollback transaction and close conn

func (*DbTxn) Commit

func (txn *DbTxn) Commit() error

Commit commit the transaction

func (*DbTxn) Delete

func (txn *DbTxn) Delete(entity interface{}) (sql.Result, error)

Delete delete entity from db

func (*DbTxn) Execute

func (txn *DbTxn) Execute(command string, args ...interface{}) (sql.Result, error)

Execute execute command towards db

func (*DbTxn) GetOne

func (txn *DbTxn) GetOne(proto interface{}) (interface{}, error)

GetOne query one entity based on the key fields set in the prototype

func (*DbTxn) GetOneByKey

func (txn *DbTxn) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)

GetOneByKey query one entity based on the key, the entity must have a sinle dimension key

func (*DbTxn) Insert

func (txn *DbTxn) Insert(entity interface{}) (sql.Result, error)

Insert insert entity to db

func (*DbTxn) QueryAll

func (txn *DbTxn) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)

QueryAll execute sql query and return all entities based on the mapper

func (*DbTxn) QueryAllWithCollector

func (txn *DbTxn) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error

func (*DbTxn) QueryOne

func (txn *DbTxn) QueryOne(query string, mapper RowMapper, args ...interface{}) (interface{}, error)

QueryOne execute sql query and return one entity based on the mapper

func (*DbTxn) Rollback

func (txn *DbTxn) Rollback() error

Rollback rollback the transaction

func (*DbTxn) Update

func (txn *DbTxn) Update(entity interface{}) (sql.Result, error)

Update update entity with db

type DbUniqueIDGenerator

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

DbUniqueIDGenerator database based unique id generator

func NewDbUniqueIDGenerator

func NewDbUniqueIDGenerator(dbAccessor *DbAccessor) *DbUniqueIDGenerator

NewDbUniqueIDGenerator creates a db based unique id generator

func (*DbUniqueIDGenerator) NextUniqueID

func (generator *DbUniqueIDGenerator) NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error)

NextUniqueID generate a next unique id

type DistributedLocker

type DistributedLocker interface {
	Lock(ctx context.Context) (LockContext, error)
	Unlock(lockCtx LockContext)
}

type DistributedSharedLocker

type DistributedSharedLocker interface {
	RLock(ctx context.Context) (LockContext, error)
	RUnlock(lockCtx LockContext)
	Lock(ctx context.Context) (LockContext, error)
	Unlock(lockCtx LockContext)
}

type DummyWriter

type DummyWriter struct{}

DummyWriter drops all data to be written

func (*DummyWriter) Write

func (w *DummyWriter) Write(p []byte) (n int, err error)

Write drops the data

type EntityDescriptor

type EntityDescriptor struct {
	InsertSQL string
	UpdateSQL string
	DeleteSQL string
	GetOneSQL string
	// contains filtered or unexported fields
}

EntityDescriptor entity descriptor

func GetOrCreateEntityDescriptor

func GetOrCreateEntityDescriptor(entityType reflect.Type) *EntityDescriptor

GetOrCreateEntityDescriptor get or create EntityDescriptor for the given type

func (*EntityDescriptor) GetInsertValues

func (descriptor *EntityDescriptor) GetInsertValues(entity interface{}) []interface{}

GetInsertValues get insert values for the given entity

func (*EntityDescriptor) GetKeyValues

func (descriptor *EntityDescriptor) GetKeyValues(entity interface{}) []interface{}

GetKeyValues get key value for the given entity

func (*EntityDescriptor) GetUpdateValues

func (descriptor *EntityDescriptor) GetUpdateValues(entity interface{}) []interface{}

GetUpdateValues get update values for the given entity

type FieldValueGetter

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

FieldValueGetter the field value pointer retriever

func NewFieldValueGetter

func NewFieldValueGetter(fieldName string) *FieldValueGetter

NewFieldValueGetter creates a new FieldValueGetter object

func (*FieldValueGetter) Get

func (getter *FieldValueGetter) Get(value reflect.Value) reflect.Value

Get gets the field value object, the field value object should be settable which means if the value's type is an pointer, then it should be pointing to a valid memory

type Float added in v1.4.9

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type Integer added in v1.4.9

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type JwtKeyMap

type JwtKeyMap map[string]*rsa.PublicKey

JwtKeyMap maps issuer to a public key

func (JwtKeyMap) GetBackupKey

func (m JwtKeyMap) GetBackupKey(_ context.Context, issuer string) *rsa.PublicKey

func (JwtKeyMap) GetKey

func (m JwtKeyMap) GetKey(_ context.Context, issuer string) *rsa.PublicKey

type JwtKeyProvider

type JwtKeyProvider interface {
	GetKey(ctx context.Context, issuer string) *rsa.PublicKey
	GetBackupKey(ctx context.Context, issuer string) *rsa.PublicKey
}

JwtKeyProvider RSA public key provider for retrieving issuer public keys

type JwtUserClaims

type JwtUserClaims struct {
	jwt.Claims
	Sid           string   `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid,omitempty"`
	Name          string   `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name,omitempty"`
	AccountName   string   `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn,omitempty"`
	Roles         []string `json:"http://schemas.microsoft.com/ws/2008/06/identity/claims/role,omitempty"`
	Domain        string   `json:"TenantId,omitempty"`
	SecurityToken string   `json:"sectok,omitempty"`
	Parent        string   `json:"ParentAccountName,omitempty"`
}

JwtUserClaims Microsoft claims spec compatible user claims

type JwtUserPrincipal

type JwtUserPrincipal struct {
	UserPrincipal
	SecurityToken string
	DisplayName   string
	Parent        string
	Source        string
}

JwtUserPrincipal a user principal created from JWT token

type JwtUserProvider

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

JwtUserProvider jwt token based user provider

func NewJwtUserProvider

func NewJwtUserProvider(keyProvider JwtKeyProvider, userLoader UserPrincipalLoader) *JwtUserProvider

NewJwtUserProvider creates a new instances of jwt user provider

func (*JwtUserProvider) Authenticate

func (provider *JwtUserProvider) Authenticate(request *http.Request) *UserPrincipal

func (*JwtUserProvider) GetName

func (provider *JwtUserProvider) GetName() string

func (*JwtUserProvider) Load

func (provider *JwtUserProvider) Load(domain, id string) *UserPrincipal

type KeepAliveMessageHandler

type KeepAliveMessageHandler interface {
	// OnPingMessage when a ping message is received, no need to send back pong message,
	// which is done right after this handler
	OnPingMessage(session *WebSocketSession, text string) error

	// OnPongMessage when a pong message is received, this API will be called to notify the application
	OnPongMessage(session *WebSocketSession, text string) error
}

KeepAliveMessageHandler websocket message handler to handle ping/pong messages for ping message, a pong message will be sent back after OnPingMessage is returned.

type LockContext

type LockContext map[string]interface{}

type LogLevel

type LogLevel int32

LogLevel logging level

const (
	// LogLevelDebug debug logging level
	LogLevelDebug LogLevel = 1 + iota

	// LogLevelInfo info logging level
	LogLevelInfo

	// LogLevelWarn warnning level
	LogLevelWarn

	// LogLevelError error level
	LogLevelError
)

type MyCluster

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

MyCluster MySQL based database cluster, up to 32 physical partitions, for cluster that requires more than 32 partitions, consider tidb or similar distributed database

func NewMyCluster

func NewMyCluster(master *DbAccessor, partitions []*DbAccessor, txnTimeout int, idGen UniqueIDGenerator, partitionCalc PartitionCalculator) *MyCluster

NewMyCluster creates an instance of MyCluster

func NewMyClusterWithTxnStore

func NewMyClusterWithTxnStore(txnStore TxnStore, partitions []*DbAccessor, txnTimeout int, idGen UniqueIDGenerator, partitionCalc PartitionCalculator) *MyCluster

NewMyClusterWithTxnStore create a new instance of MyCluster with given TxnStore

func (*MyCluster) Close

func (cluster *MyCluster) Close()

Close close all resources that acquired by current instance

func (*MyCluster) CreateTransaction

func (cluster *MyCluster) CreateTransaction(ctx context.Context) (*MyClusterTxn, error)

CreateTransaction creates a cluster transaction

func (*MyCluster) Delete

func (cluster *MyCluster) Delete(ctx context.Context, entity interface{}) (sql.Result, error)

Delete delete the given entity

func (*MyCluster) ExecuteOnAll

func (cluster *MyCluster) ExecuteOnAll(ctx context.Context, query string, args ...interface{}) error

ExecuteOnAll execute query on all partitions

func (*MyCluster) GenerateKey

func (cluster *MyCluster) GenerateKey(ctx context.Context, entity interface{}) error

GenerateKey generates and assign an unique id for the given entity

func (*MyCluster) GetAll

func (cluster *MyCluster) GetAll(ctx context.Context, ty reflect.Type, query string, args ...interface{}) ([][]interface{}, error)

GetAll get all entities from all partition by the given prototype

func (*MyCluster) GetAllPartitions

func (cluster *MyCluster) GetAllPartitions() []*DbAccessor

GetAllPartitions gets all physical partitions in cluster

func (*MyCluster) GetAllReduced

func (cluster *MyCluster) GetAllReduced(
	ctx context.Context,
	ty reflect.Type,
	query string,
	reducer func([][]interface{}) []interface{},
	args ...interface{}) ([]interface{}, error)

GetAllReduced get all entries and apply the reduce

func (*MyCluster) GetAllWithCollector

func (cluster *MyCluster) GetAllWithCollector(
	ctx context.Context,
	ty reflect.Type,
	query string,
	creator DataCollectorCreator,
	args ...interface{}) error

func (*MyCluster) GetAnyPartition

func (cluster *MyCluster) GetAnyPartition() *DbAccessor

GetAnyPartition gets a random partition from physical partitions

func (*MyCluster) GetDbAccessor

func (cluster *MyCluster) GetDbAccessor(partition int32) *DbAccessor

GetDbAccessor get DbAccessor by partition

func (*MyCluster) GetDbAccessorByID

func (cluster *MyCluster) GetDbAccessorByID(id int64) *DbAccessor

GetDbAccessorByID get DbAccessor by unique ID

func (*MyCluster) GetDbAccessorByKey

func (cluster *MyCluster) GetDbAccessorByKey(partitionKey string) *DbAccessor

GetDbAccessorByKey get DbAccessor by partition key

func (*MyCluster) GetOne

func (cluster *MyCluster) GetOne(
	ctx context.Context,
	ty reflect.Type,
	query string,
	aggregator func(interface{}, interface{}) interface{},
	args ...interface{}) (interface{}, error)

GetOne query one entity by the given prototype

func (*MyCluster) GetPage

func (cluster *MyCluster) GetPage(
	ctx context.Context,
	ty reflect.Type,
	query string,
	merger *PageMerger[any],
	args ...interface{}) ([]interface{}, error)

GetPage get a page of entities by the given prototype

func (*MyCluster) GetPartitionByKey

func (cluster *MyCluster) GetPartitionByKey(key string) int32

GetPartitionByKey calculates the partition ID by the given partition key

func (*MyCluster) GetUniqueID

func (cluster *MyCluster) GetUniqueID(ctx context.Context, entity interface{}, partition int32) (int64, error)

GetUniqueID gets a unique id for the given entity prototype

func (*MyCluster) GetUniqueIDByName

func (cluster *MyCluster) GetUniqueIDByName(ctx context.Context, entityName string, partition int32) (int64, error)

GetUniqueIDByName gets a unique id from cluster for the given entity name and partition

func (*MyCluster) Insert

func (cluster *MyCluster) Insert(ctx context.Context, entity interface{}) error

Insert insert the entity to db based on the tagged partition key

func (*MyCluster) InsertAt

func (cluster *MyCluster) InsertAt(ctx context.Context, partition int32, entity interface{}) error

InsertAt insert entity to specific partition

func (*MyCluster) InsertByKey

func (cluster *MyCluster) InsertByKey(ctx context.Context, partitionKey string, entity interface{}) error

InsertByKey insert entity to db based on given partition key

func (*MyCluster) InsertToAll

func (cluster *MyCluster) InsertToAll(ctx context.Context, entity interface{}) error

InsertToAll insert entity to all partitions

func (*MyCluster) QueryAll

func (cluster *MyCluster) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([][]interface{}, error)

QueryAll query all entities from all partitions by the given mapper

func (*MyCluster) QueryAllReduced

func (cluster *MyCluster) QueryAllReduced(
	ctx context.Context,
	query string,
	mapper RowMapper,
	reducer func([][]interface{}) []interface{},
	args ...interface{}) ([]interface{}, error)

QueryAllReduced query all entities and apply the reducer

func (*MyCluster) QueryAllWithCollector

func (cluster *MyCluster) QueryAllWithCollector(
	ctx context.Context,
	query string,
	mapper RowMapper,
	creator DataCollectorCreator,
	args ...interface{}) error

func (*MyCluster) QueryOne

func (cluster *MyCluster) QueryOne(
	ctx context.Context,
	query string,
	mapper RowMapper,
	aggregator func(interface{}, interface{}) interface{},
	args ...interface{}) (interface{}, error)

QueryOne query one entity with the given mapper

func (*MyCluster) QueryPage

func (cluster *MyCluster) QueryPage(
	ctx context.Context,
	query string,
	mapper RowMapper,
	merger *PageMerger[any],
	args ...interface{}) ([]interface{}, error)

QueryPage query a page of entities by the given page merger

func (*MyCluster) Update

func (cluster *MyCluster) Update(ctx context.Context, entity interface{}) error

Update update the entity based on the key in the entity

func (*MyCluster) UpdateAt

func (cluster *MyCluster) UpdateAt(ctx context.Context, partition int32, entity interface{}) error

UpdateAt update entity at the specific partition

func (*MyCluster) UpdateToAll

func (cluster *MyCluster) UpdateToAll(ctx context.Context, entity interface{}) error

UpdateToAll update entity to all partitions

type MyClusterTxn

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

MyClusterTxn cluster supported 2PC transaction

func (*MyClusterTxn) Close

func (txn *MyClusterTxn) Close()

Close close and release all transactions

func (*MyClusterTxn) Commit

func (txn *MyClusterTxn) Commit() error

Commit commit all participants

func (*MyClusterTxn) Delete

func (txn *MyClusterTxn) Delete(entity interface{}) (sql.Result, error)

Delete delete the entity from database

func (*MyClusterTxn) DeleteAt

func (txn *MyClusterTxn) DeleteAt(partition int32, entity interface{}) (sql.Result, error)

DeleteAt delete the specified entry from the given partition

func (*MyClusterTxn) DeleteFromAll

func (txn *MyClusterTxn) DeleteFromAll(entity interface{}) ([]sql.Result, error)

DeleteFromAll delete the entry from all partitions

func (*MyClusterTxn) ExecuteAt

func (txn *MyClusterTxn) ExecuteAt(partition int32, sql string, args ...interface{}) (sql.Result, error)

ExecuteAt execute the given query on a specific partition

func (*MyClusterTxn) ExecuteOnAll

func (txn *MyClusterTxn) ExecuteOnAll(query string, args ...interface{}) ([]sql.Result, error)

ExecuteOnAll execute the given query on all partitions

func (*MyClusterTxn) GetTxnByID

func (txn *MyClusterTxn) GetTxnByID(id int64) (*XATransaction, error)

GetTxnByID get an XATransaction by unique ID

func (*MyClusterTxn) GetTxnByPartition

func (txn *MyClusterTxn) GetTxnByPartition(partition int32) (*XATransaction, error)

GetTxnByPartition get an XATransaction by partition number

func (*MyClusterTxn) InsertAt

func (txn *MyClusterTxn) InsertAt(partition int32, entity interface{}) (sql.Result, error)

InsertAt insert an entity to the given partition

func (*MyClusterTxn) InsertToAll

func (txn *MyClusterTxn) InsertToAll(entity interface{}) ([]sql.Result, error)

InsertToAll insert an entry to all partitions

func (*MyClusterTxn) Rollback

func (txn *MyClusterTxn) Rollback() error

Rollback rollback all participants

func (*MyClusterTxn) Update

func (txn *MyClusterTxn) Update(entity interface{}) (sql.Result, error)

Update update entity to database

func (*MyClusterTxn) UpdateAt

func (txn *MyClusterTxn) UpdateAt(partition int32, entity interface{}) (sql.Result, error)

UpdateAt update entity at the specific partition

func (*MyClusterTxn) UpdateToAll

func (txn *MyClusterTxn) UpdateToAll(entity interface{}) ([]sql.Result, error)

UpdateToAll update entity to all partitions

type Ordered added in v1.4.9

type Ordered interface {
	Integer | Float | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type PageMerger

type PageMerger[T any] struct {
	// contains filtered or unexported fields
}

PageMerger a tool to merge multiple paged query results into one page

func NewPageMerger

func NewPageMerger[T any](pageSize int, comparer Comparer[T]) *PageMerger[T]

NewPageMerger create a new page merger

func (*PageMerger[T]) Merge

func (m *PageMerger[T]) Merge(lists ...[]T) []T

Merge merge lists into a single sorted list and only return the top `pageSize` items of all lists

type PageQuery added in v1.4.9

type PageQuery[T any, TPrimaryKey any, TSecondaryKey any] struct {
	Cluster                     *MyCluster
	CountingQueryText           string
	CountingQueryArgsConfigurer func() []interface{}
	QuerySetup                  func(sql *strings.Builder) ([]interface{}, bool)
	PrimaryKeyName              string
	SecondaryKeyName            string
	PrimaryKeyParser            func(value string) (TPrimaryKey, bool)
	SecondaryKeyParser          func(value string) (TSecondaryKey, bool)
	PrimaryKeyGetter            func(t *T) TPrimaryKey
	SecondaryKeyGetter          func(t *T) TSecondaryKey
	PrimaryKeyComparer          Comparer[TPrimaryKey]
	SecondaryKeyComparer        Comparer[TSecondaryKey]
}

func (*PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQuery added in v1.4.9

func (q *PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQuery(ctx context.Context, paging, pageToken string, pageSize int) (*DataPage[*T], error)

func (*PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQueryWithCustomPageToken added in v1.4.10

func (q *PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQueryWithCustomPageToken(ctx context.Context, paging, pagingToken string, pageSize int, rangeSeparator, keySeparator string) (*DataPage[*T], error)

type PartitionCalculateFunc

type PartitionCalculateFunc func(key string) int32

PartitionCalculateFunc partition calculate function, implements PartitionCalculator

func (PartitionCalculateFunc) GetPartition

func (calc PartitionCalculateFunc) GetPartition(key string) int32

GetPartition implements PartitionCalculator

type PartitionCalculator

type PartitionCalculator interface {
	GetPartition(key string) int32
}

PartitionCalculator partition key calculator

type PooledID

type PooledID struct {
	Name      string `col:"name" dtags:"key,nogen"`
	Partition int32  `col:"partition"`
	PooledID  int64  `col:"pooled_id"`
}

PooledID unique id pooled ID record, requires the following table / create table `pooled_id` ( / `name` varchar(200) not null, / `partition` int not null, / `pooled_id` bigint not null, / constraint `pk_id_generator` primary key (`name`, `partition`) / );

type Queryable

type Queryable interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}

Queryable a queryable object that could be a Connection, DB or Tx

type Response

type Response struct {
	Writer http.ResponseWriter
	// contains filtered or unexported fields
}

Response web response

func (*Response) DoneWithContent

func (r *Response) DoneWithContent(statusCode int, contentType string, content []byte)

DoneWithContent sets the status, content-type header and writes the content to response

func (*Response) DoneWithError

func (r *Response) DoneWithError(statusCode int, msg string)

DoneWithError response an error page based on errorTemplate to the client

func (*Response) DoneWithJSON

func (r *Response) DoneWithJSON(statusCode int, obj interface{})

DoneWithJSON sets the status and write the model as json

func (*Response) DoneWithRedirect

func (r *Response) DoneWithRedirect(req *http.Request, url string, status int)

DoneWithRedirect redirects to the specified url

func (*Response) DoneWithTemplate

func (r *Response) DoneWithTemplate(statusCode int, name string, model interface{})

DoneWithTemplate sets the status and write the model with the given template name as response, the content type is defaulted to text/html

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

SetCookie add cookie to response

func (*Response) SetHeader

func (r *Response) SetHeader(name, value string)

SetHeader sets a header value for response

func (*Response) SetNoCache

func (r *Response) SetNoCache()

SetNoCache sets headers for the client not to cache the response

func (*Response) SetStatus

func (r *Response) SetStatus(statusCode int)

SetStatus sets the response status

func (*Response) Write

func (r *Response) Write(content []byte) (int, error)

Write writes content to response, compatible with writer

type RowMapper

type RowMapper interface {
	Map(row DataRow) (interface{}, error)
}

RowMapper maps a row to an object

func NewSmartMapper

func NewSmartMapper(ty reflect.Type) RowMapper

NewSmartMapper creates a smart row mapper for data row

type RowMapperFunc

type RowMapperFunc func(row DataRow) (interface{}, error)

RowMapperFunc a function that implements RowMapper

func (RowMapperFunc) Map

func (mapper RowMapperFunc) Map(row DataRow) (interface{}, error)

Map implements the RowMapper interface

type SecurityHandler

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

SecurityHandler a http handler to do both authentication and authorization for requests

func NewSecurityHandler

func NewSecurityHandler() *SecurityHandler

NewSecurityHandler creates an instance of SecurityHandler object without any user providers and with nil AuthorizationManager

func (*SecurityHandler) AddUserProvider

func (handler *SecurityHandler) AddUserProvider(userProvider UserProvider) *SecurityHandler

AddUserProvider add a user provider to the security handler

func (*SecurityHandler) ServeHTTP

func (handler *SecurityHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP implements the http.Handler interface

func (*SecurityHandler) WithAuthz

func (handler *SecurityHandler) WithAuthz(authz AuthorizationManager) *SecurityHandler

WithAuthz specify the AuthorizationManager to be used by this handler

func (*SecurityHandler) WithLoginURL

func (handler *SecurityHandler) WithLoginURL(loginURL string) *SecurityHandler

WithLoginURL the URL to redirect if the access is denied

func (*SecurityHandler) WithPipeline

func (handler *SecurityHandler) WithPipeline(h http.Handler) *SecurityHandler

WithPipeline specify the http.Handler to be called if the request passes the security check

type Session

type Session struct {
	ID      string
	IsValid bool
	// contains filtered or unexported fields
}

Session a HTTP session

func GetSession

func GetSession(request *http.Request) *Session

GetSession helper function for getting session from request

func NewSession

func NewSession(id string) *Session

NewSession creates a new session

func (*Session) Deserialize

func (session *Session) Deserialize(data []byte)

Deserialize de-serializes the bytes into session data

func (*Session) GetAsFlashValue

func (session *Session) GetAsFlashValue(key string) (interface{}, bool)

GetAsFlashValue gets the value that is associated with the key and remove the value if the key existing, this returns the value and the key existing indicator

func (*Session) GetValue

func (session *Session) GetValue(key string) (interface{}, bool)

GetValue gets the value which is associated with the key, returns the value and key existing indicator

func (*Session) NeedSave

func (session *Session) NeedSave() bool

NeedSave checks if the session needs to be saved back to store or not

func (*Session) Serialize

func (session *Session) Serialize() []byte

Serialize serializes the session data into bytes

func (*Session) SetValue

func (session *Session) SetValue(key string, value interface{}) (interface{}, bool)

SetValue sets a value to the session, returns the old value if the key has a value before

type SessionStore

type SessionStore interface {
	// Save saves the session with timeout, the session cannot be
	// returned by Get after the give timeout duration passed, while the
	// timeout need to be reset at each time the session is saved.
	// if the session's IsValid is set to false, after saved, the
	// session should never be returned by Get.
	Save(session *Session, timeout time.Duration) error

	// Get gets the session with the given ID, returns the session
	// if the session is still valid, otherwise, (nil, ErrSessionNotFound)
	// will be returned
	Get(id string) (*Session, error)

	// Close closes the session store and release the resources that
	// the session store owns
	Close()
}

SessionStore interface for storing sessions

func NewFileSessionStore

func NewFileSessionStore(directory string) (SessionStore, error)

NewFileSessionStore creates a file session store

func NewInMemorySessionStore

func NewInMemorySessionStore() SessionStore

NewInMemorySessionStore creates an in memory session store

func NewRedisSessionStore

func NewRedisSessionStore(cli *redis.Client) SessionStore

NewRedisSessionStore creates a new redis based session store

type SharedTemplateDetector

type SharedTemplateDetector func(string) bool

SharedTemplateDetector detector used to check if the given path is a shared template or not

type Signed added in v1.4.9

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type SkinManager

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

SkinManager a TemplateManager is mapped to a skin, skin manager manages TemplateManagers by names.

func NewSkinManager

func NewSkinManager(defaultSkin *TemplateManager) *SkinManager

NewSkinManager creates a skin manager object

func (*SkinManager) AddSkin

func (skinMgr *SkinManager) AddSkin(name string, tmplMgr *TemplateManager)

AddSkin adds a skin

func (*SkinManager) ApplySelector

func (skinMgr *SkinManager) ApplySelector(request *http.Request) (*TemplateManager, string)

ApplySelector find skin by applying selector, if selector is not configured default skin will be returned, if the skin name returned by the selector cannot be found, this returns nil

func (*SkinManager) GetDefaultSkin

func (skinMgr *SkinManager) GetDefaultSkin() *TemplateManager

GetDefaultSkin gets the default skin

func (*SkinManager) GetSkin

func (skinMgr *SkinManager) GetSkin(name string) (*TemplateManager, bool)

GetSkin find skin by name

func (*SkinManager) GetSkinOrDefault

func (skinMgr *SkinManager) GetSkinOrDefault(name string) *TemplateManager

GetSkinOrDefault gets the skin with the given name if it's not found return the default skin

func (*SkinManager) RemoveSkin

func (skinMgr *SkinManager) RemoveSkin(name string)

RemoveSkin removes a skin

func (*SkinManager) WithSelector

func (skinMgr *SkinManager) WithSelector(selector SkinSelector)

WithSelector sets the skin selector for the skin manager

type SkinSelector

type SkinSelector interface {
	GetSkin(request *http.Request) string
}

SkinSelector returns a skin name based on the request object

type SkinSelectorFunc

type SkinSelectorFunc func(*http.Request) string

SkinSelectorFunc converts a function to SkinSelector interface

type SliceCollector

type SliceCollector[T any] struct {
	Results []*T
}

func NewSliceCollector

func NewSliceCollector[T any]() *SliceCollector[T]

func (*SliceCollector[T]) Collect

func (collector *SliceCollector[T]) Collect(item interface{})

type SliceCollectorCreator

type SliceCollectorCreator[T any] struct {
	Collectors []*SliceCollector[T]
}

func NewSliceCollectorCreator

func NewSliceCollectorCreator[T any]() *SliceCollectorCreator[T]

func (*SliceCollectorCreator[T]) Create

func (creator *SliceCollectorCreator[T]) Create() DataCollector

func (*SliceCollectorCreator[T]) GetResults

func (creator *SliceCollectorCreator[T]) GetResults() [][]*T

func (*SliceCollectorCreator[T]) MergeResults

func (creator *SliceCollectorCreator[T]) MergeResults(merger *PageMerger[*T]) []*T

type Stringify added in v1.4.9

type Stringify interface {
	String() string
}

type TableNameResolver

type TableNameResolver interface {
	Resolve(structName string) string
}

TableNameResolver resolves a struct name to table name

type TableNameResolverFunc

type TableNameResolverFunc func(structName string) string

TableNameResolverFunc a function that implements TableNameResolver

func (TableNameResolverFunc) Resolve

func (resolver TableNameResolverFunc) Resolve(name string) string

Resolve resolves struct name to table name

type TemplateConfigFunc

type TemplateConfigFunc func(*template.Template)

TemplateConfigFunc shared templates config function

type TemplateManager

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

TemplateManager manages the templates by groups and update template group on-demand based on the template file update timestamp

func NewTemplateManager

func NewTemplateManager(dir, suffix string, refreshInterval time.Duration, configFunc TemplateConfigFunc, sharedTemplateDetector SharedTemplateDetector) *TemplateManager

NewTemplateManager creates a template manager for the given dir

func (*TemplateManager) Close

func (manager *TemplateManager) Close()

Close closes the template manager and release all resources

func (*TemplateManager) GetTemplate

func (manager *TemplateManager) GetTemplate(name string) (*template.Template, bool)

GetTemplate retrieve a template with the specified name from template manager, this returns the template and a boolean value to indicate if the template is found or not

type Txn

type Txn interface {
	Insert(entity interface{}) (sql.Result, error)

	Update(entity interface{}) (sql.Result, error)

	Delete(entity interface{}) (sql.Result, error)

	Execute(sql string, args ...interface{}) (sql.Result, error)

	GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)

	GetOne(proto interface{}) (interface{}, error)

	QueryOne(sql string, mapper RowMapper, args ...interface{}) (interface{}, error)

	QueryAll(sql string, mapper RowMapper, args ...interface{}) ([]interface{}, error)

	QueryAllWithCollector(sql string, mapper RowMapper, collector DataCollector, args ...interface{}) error
}

Txn an abstraction for db transaction as well as cluster based db transaction

type TxnParticipant

type TxnParticipant struct {
	TxnID     string `col:"txn_id" dtags:"multikey"`
	Partition int    `col:"partition" dtags:"multikey"`
	State     int    `col:"state"`
}

TxnParticipant cluster transaction participant

type TxnStore

type TxnStore interface {
	// CreateTxn create a transaction entity
	CreateTxn(ctx context.Context, txnID string, t time.Time) (*ClusterTxn, error)

	// GetTxn get transaction entity by ID
	GetTxn(ctx context.Context, txnID string) (*ClusterTxn, error)

	// UpdateTxnState update transaction state
	UpdateTxnState(ctx context.Context, txnID string, state int) error

	// AddTxnParticipant add a participant to a transaction
	AddTxnParticipant(ctx context.Context, txnID string, partition int) error

	// DeleteTxn delete partition from store
	DeleteTxn(ctx context.Context, txnID string) error

	// LeaseExpiredTxns lease expired transactions, only expired and lease expired (or not lease) transactions are visible
	LeaseExpiredTxns(ctx context.Context, expireTime, leaseTimeout time.Time, items int) ([]*ClusterTxn, error)

	// ListParticipants list all participants in transaction
	ListParticipants(ctx context.Context, txnID string) ([]*TxnParticipant, error)

	// Close close all resources used by store
	Close() error
}

TxnStore a cluster transaction entity store to keep cluster transaction states

type UniqueID

type UniqueID struct {
	Value int64 // format [PooledID][Partition][SegmentedID]
}

UniqueID global unique id for a given namespace in cluster

func NewUniqueID

func NewUniqueID(pooledID int64, partition int32, segmentedID int32) (UniqueID, error)

NewUniqueID create a new unique id based on the pooledID, partition and segmentedID

func (UniqueID) Partition

func (id UniqueID) Partition() int32

Partition gets the partition for the unique id

type UniqueIDGenerator

type UniqueIDGenerator interface {
	NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error)
}

UniqueIDGenerator unique id generator interface

type UniqueIDPool

type UniqueIDPool struct {
	Lock *sync.Mutex
	// contains filtered or unexported fields
}

UniqueIDPool unique id pool

func NewUniqueIDPool

func NewUniqueIDPool() *UniqueIDPool

NewUniqueIDPool creates a new ID pool

func (*UniqueIDPool) NextID

func (pool *UniqueIDPool) NextID(ctx context.Context, partition int32) (int64, error)

NextID generate a new id from pool

func (*UniqueIDPool) UpdatePooledID

func (pool *UniqueIDPool) UpdatePooledID(partition int32, pooledID int64) error

UpdatePooledID update pooled id for the given partition

type Unsigned added in v1.4.9

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type UserPrincipal

type UserPrincipal struct {
	// ID user id
	ID string

	// Domain the domain of the user principal
	Domain string

	// Name user's printable name
	Name string

	// Provider user provider
	Provider string

	// Roles roles for the user
	Roles []string

	// Self pointing to the object that owns this object
	// this makes the UserPrincipal extensible and embeddable
	// The container object can put its pointer into this field
	// and could be deferenced by the application code
	Self interface{}
}

UserPrincipal the security principal of the http session

func GetUser

func GetUser(request *http.Request) *UserPrincipal

GetUser gets the UserPrincipal for the request

type UserPrincipalLoader

type UserPrincipalLoader interface {
	Load(domain, id string) *UserPrincipal
}

UserPrincipalLoader loads a user principal by user domain and id

type UserPrincipalLoaderFunc

type UserPrincipalLoaderFunc func(domain, id string) *UserPrincipal

UserPrincipalLoaderFunc delegates function to UserPrincipalLoader interface

func (UserPrincipalLoaderFunc) Load

func (f UserPrincipalLoaderFunc) Load(domain, id string) *UserPrincipal

type UserProvider

type UserProvider interface {
	// GetName gets the name of the provider
	GetName() string

	// Authenticate authenticates the incoming request and
	// returns the UserPrincipal object if security token
	// is found and resolvable by the user provider or nil
	// if nothing can be resolved
	Authenticate(request *http.Request) *UserPrincipal

	//Load loads the user by the specified domain and id
	Load(domain, id string) *UserPrincipal
}

UserProvider an interface used by the framework to resolve UserPrincipal from incoming request and also used by loading the UserPrincipal in authorized mode by given user id and user domain

type WebServer

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

WebServer a web server that supports auth & authz, logging, session and web sockets

func NewWebServer

func NewWebServer(listenAddr string, skinMgr *SkinManager) *WebServer

NewWebServer creates a web server instance to listen on the specified address

func (*WebServer) AddStaticResource

func (server *WebServer) AddStaticResource(prefix, dir string) *WebServer

AddStaticResource adds a static resource folder to the server with the given prefix, the prefix must be in format of "/prefix/"

func (*WebServer) AddUserProvider

func (server *WebServer) AddUserProvider(provider UserProvider) *WebServer

AddUserProvider adds a user provider to security handler

func (*WebServer) AddWsEndoint

func (server *WebServer) AddWsEndoint(endpoint string, listener WebSocketListener) *WebServer

AddWsEndoint adds a web socket endpoint to the server

func (*WebServer) AddWsHandler

func (server *WebServer) AddWsHandler(endpoint string, handler *WebSocketHandler) *WebServer

AddWsHandler adds a web socket handler to server

func (*WebServer) HandleFunc

func (server *WebServer) HandleFunc(path string, f func(w http.ResponseWriter, r *http.Request)) *WebServer

HandleFunc register a handle function for a path pattern

func (*WebServer) RegisterController

func (server *WebServer) RegisterController(name string, controller Controller) error

RegisterController register a controller for the standard routing

func (*WebServer) Shutdown

func (server *WebServer) Shutdown()

Shutdown shutdown the web server

func (*WebServer) Start

func (server *WebServer) Start() error

Start starts the web server

func (*WebServer) WithAuthz

func (server *WebServer) WithAuthz(authz AuthorizationManager) *WebServer

WithAuthz specify the AuthorizationManager to be used by this handler

func (*WebServer) WithCORS

func (server *WebServer) WithCORS(handler func(http.Handler) http.Handler) *WebServer

WithCORS setup cors handler for the web server

func (*WebServer) WithCaptcha

func (server *WebServer) WithCaptcha(path string) *WebServer

WithCaptcha setup a captcha generator at the given "path" in a 240 x 80 image with six digits chanllege

func (*WebServer) WithCaptchaCustom

func (server *WebServer) WithCaptchaCustom(path string, digits, width, height int) *WebServer

WithCaptchaCustom setup a captcha generator at the given path with custom digits, width and height

func (*WebServer) WithCustomHandler

func (server *WebServer) WithCustomHandler(handler CustomHandler) *WebServer

WithCustomHandler set or chains a handler to custom handlers chain, the new CustomHandler will be added to the tail of custom handlers chain.

func (*WebServer) WithLoginURL

func (server *WebServer) WithLoginURL(loginURL string) *WebServer

WithLoginURL the URL to redirect if the access is denied

func (*WebServer) WithRequestTimeout

func (server *WebServer) WithRequestTimeout(timeout int)

WithRequestTimeout set request timeout in seconds for each individual requests

func (*WebServer) WithSessionOptions

func (server *WebServer) WithSessionOptions(store SessionStore, timeout time.Duration, valueTypes ...interface{}) *WebServer

WithSessionOptions setup the session options including the session store and session timeout interval

func (*WebServer) WithStandardRouting

func (server *WebServer) WithStandardRouting(prefix string) *WebServer

WithStandardRouting setup a routing as "prefix" + "/{controller:[_a-zA-Z][_a-zA-Z0-9]*}/{action:[_a-zA-Z][_a-zA-Z0-9]*}" and the web server will route the requests based on the registered controllers.

type WebSocketHandler

type WebSocketHandler struct {
	MessageLimit     int64
	ReadTimeout      time.Duration
	WriteTimeout     time.Duration
	Listener         WebSocketListener
	WriteCompression bool
	CheckOrigin      func(*http.Request) bool
}

WebSocketHandler Web socket handler have handler.Handle for router to enable web socket endpoints

func (*WebSocketHandler) Handle

func (handler *WebSocketHandler) Handle(writer http.ResponseWriter, request *http.Request)

Handle handles the incomping web requests and try to upgrade the request into a websocket connection

type WebSocketListener

type WebSocketListener interface {
	// OnConnect when a connection is established
	OnConnect(session *WebSocketSession)

	// OnTextMessage when a text message is available in the channel
	OnTextMessage(session *WebSocketSession, text string)

	// OnBinaryMessage when a binary message is available in the channel
	OnBinaryMessage(session *WebSocketSession, data []byte)

	// OnClose when the channel is broken or closed by remote
	OnClose(session *WebSocketSession, reason int)
}

WebSocketListener web socket listener that could be used to listen on a specific web socket endpoint

type WebSocketSession

type WebSocketSession struct {
	RemoteAddr string
	User       *UserPrincipal
	Session    *Session
	Context    map[string]interface{}
	// contains filtered or unexported fields
}

WebSocketSession a connected web socket session

func (*WebSocketSession) Close

func (session *WebSocketSession) Close() error

Close close the underlying connection of the WebSocketSession

func (*WebSocketSession) SendBinaryMessage

func (session *WebSocketSession) SendBinaryMessage(data []byte) error

SendBinaryMessage sends a binary message to the remote, a more convenient version of SendMessage

func (*WebSocketSession) SendMessage

func (session *WebSocketSession) SendMessage(msgType int, data []byte) error

SendMessage sends a message with the given type

func (*WebSocketSession) SendTextMessage

func (session *WebSocketSession) SendTextMessage(text string) error

SendTextMessage sends a text message to the remote, a more convenient version of SendMessage

type XATransaction

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

XATransaction MySQL XA transaction support

func (*XATransaction) Begin

func (xa *XATransaction) Begin() error

Begin begins the transaction

func (*XATransaction) Close

func (xa *XATransaction) Close()

Close release xa transaction

func (*XATransaction) Delete

func (xa *XATransaction) Delete(entity interface{}) (sql.Result, error)

Delete delete entity from db

func (*XATransaction) Execute

func (xa *XATransaction) Execute(command string, args ...interface{}) (sql.Result, error)

Execute execute command towards db

func (*XATransaction) GetOne

func (xa *XATransaction) GetOne(proto interface{}) (interface{}, error)

GetOne query one entity based on the keys in prototype

func (*XATransaction) GetOneByKey

func (xa *XATransaction) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)

GetOneByKey query one entity based on the prototype and the single dimension key

func (*XATransaction) Insert

func (xa *XATransaction) Insert(entity interface{}) (sql.Result, error)

Insert insert entity to db

func (*XATransaction) QueryAll

func (xa *XATransaction) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)

QueryAll execute sql query and return all entities based on the mapper

func (*XATransaction) QueryAllWithCollector

func (xa *XATransaction) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error

func (*XATransaction) QueryOne

func (xa *XATransaction) QueryOne(query string, mapper RowMapper, args ...interface{}) (interface{}, error)

QueryOne execute sql query and return one entity based on the mapper

func (*XATransaction) Update

func (xa *XATransaction) Update(entity interface{}) (sql.Result, error)

Update update entity with db

type XaTxnID

type XaTxnID struct {
	FormatID       int    `col:"formatID"`
	GlobalIDLength int    `col:"gtrid_length"`
	BranchIDLength int    `col:"bqual_length"`
	Data           string `col:"data"`
}

XaTxnID xa transaction id format

type ZkLock

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

ZkLock zookeeper based distributed lock This lock does not rely on sequential numbers, but may lead to starvation issue

func NewZkLock

func NewZkLock(conn *zk.Conn, path string) *ZkLock

NewZkLock creates a new ZkLock on the given path

func (*ZkLock) Lock

func (lock *ZkLock) Lock(ctx context.Context) (LockContext, error)

Lock lock or return error if not able to lock

func (*ZkLock) Release

func (lock *ZkLock) Release()

Release release the lock, ignore all errors

func (*ZkLock) Unlock

func (lock *ZkLock) Unlock(lockCtx LockContext)

Unlock release the lock, alias of Release

type ZkLock2

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

ZkLock zookeeper based distributed lock

func NewZkLock2

func NewZkLock2(conn *zk.Conn, path string) (*ZkLock2, error)

NewZkLock creates a new ZkLock2 on the given path

func (*ZkLock2) Lock

func (lock *ZkLock2) Lock(ctx context.Context) (LockContext, error)

func (*ZkLock2) Unlock

func (lock *ZkLock2) Unlock(lockCtx LockContext)

type ZkRWLock

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

ZkRWLock zookeeper based reader/writer lock

func NewZkRWLock

func NewZkRWLock(conn *zk.Conn, path string) (*ZkRWLock, error)

NewZkRWLock creates a zookeeper reader/writer lock on the given path

func (*ZkRWLock) Lock

func (rwLock *ZkRWLock) Lock(ctx context.Context) (LockContext, error)

Lock acquires writer lock

func (*ZkRWLock) RLock

func (rwLock *ZkRWLock) RLock(ctx context.Context) (LockContext, error)

RLock try to acquire reader lock

func (*ZkRWLock) RUnlock

func (rwLock *ZkRWLock) RUnlock(lockCtx LockContext)

RUnlock release reader lock that is acquired

func (*ZkRWLock) Unlock

func (rwLock *ZkRWLock) Unlock(lockCtx LockContext)

Unlock release writer lock

type ZkRWLock2

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

func NewZkRWLock2

func NewZkRWLock2(conn *zk.Conn, path string) (*ZkRWLock2, error)

func (*ZkRWLock2) Lock

func (lock *ZkRWLock2) Lock(ctx context.Context) (LockContext, error)

func (*ZkRWLock2) RLock

func (lock *ZkRWLock2) RLock(ctx context.Context) (LockContext, error)

func (*ZkRWLock2) RUnlock

func (lock *ZkRWLock2) RUnlock(lockCtx LockContext)

func (*ZkRWLock2) Unlock

func (lock *ZkRWLock2) Unlock(lockCtx LockContext)

Jump to

Keyboard shortcuts

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