utility

package
v0.0.0-...-2ec8670 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2024 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDecodeConf = errors.New("decode config")

Functions

func CtxGetGormTX

func CtxGetGormTX(ctx context.Context, database *gorm.DB) *gorm.DB

func CtxWithGormTX

func CtxWithGormTX(ctx context.Context, database *gorm.DB, tx *gorm.DB) context.Context

func EasyShutdown

func EasyShutdown(
	waitSeconds int, component string, stopAction func() error,
)

func EasyShutdownWithCtx

func EasyShutdownWithCtx(
	countdown context.Context,
	waitSeconds int,
	component string,
	stopAction func() error,
)

func InitO11YTracer

func InitO11YTracer(conf *O11YConfig, shutdown *Shutdown, svcName string) error

func LoadLocalConfigFromMultiSource

func LoadLocalConfigFromMultiSource[T any](
	decode Unmarshal,
	FilePath string,
	logger *slog.Logger,
) (
	conf *T,
	err error,
)

LoadLocalConfigFromMultiSource attempts to load a local configuration file from multiple sources. It tries to locate the configuration file using the following sources in order:

1. The specified FilePath parameter 2. The current directory 3. The path defined by the environment variable CONF_PATH 4. The user's home directory

Parameters: - decode: A function used to decode the content of the configuration file into an instance of type T. - FilePath: The explicit path to the configuration file.

func LoadLocalFile

func LoadLocalFile[T any](decode Unmarshal, FilePath string) (*T, error)

func MockTimeNow

func MockTimeNow(RFC3339 string) func() time.Time

MockTimeNow

Parameters: RFC3339 (string): The time value in RFC3339 format that will be used for simulation.

Example usage:

MockTimeNow("2023-08-19T12:00:00Z")
MockTimeNow("2023-08-19T20:00:00+08:00")

func NewUlid

func NewUlid() string

func ServeO11YMetric

func ServeO11YMetric(port string, shutdown *Shutdown, logger *slog.Logger)

Types

type CustomError

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

func UnwrapCustomError

func UnwrapCustomError(err error) (myErr *CustomError, ok bool)

func (*CustomError) Error

func (c *CustomError) Error() string

func (*CustomError) ErrorCode

func (c *CustomError) ErrorCode() int

func (*CustomError) HttpStatus

func (c *CustomError) HttpStatus() int

func (*CustomError) Unwrap

func (c *CustomError) Unwrap() error

type EasyTransaction

type EasyTransaction func(ctx context.Context, flow func(ctxTX context.Context) error) error

func NewGormEasyTransaction

func NewGormEasyTransaction(db *gorm.DB) EasyTransaction

NewGormEasyTransaction 把 tx *gorm.DB 放在 context.Context 進行參數傳遞, 如此一來, 在應用服務層就可以隱藏 tx 物件, 只依賴抽象的 repository, 而且在資料層也可以透過 CtxGetGormTX 取得 *gorm.DB

func NonEasyTransaction

func NonEasyTransaction() EasyTransaction

type ErrorRegistry

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

func NewErrorRegistry

func NewErrorRegistry() *ErrorRegistry

func (*ErrorRegistry) AddErrorCode

func (r *ErrorRegistry) AddErrorCode(errCode int) *ErrorRegistry

AddErrorCode ErrorCode is Must Field The correct call sequence starts with AddErrorCode and ends with NewError or WrapError.

Example:

ErrInvalidParam = ErrorRegistry.
	AddErrorCode(4000).
	HttpStatus(http.StatusBadRequest).
	NewError("invalid parameter")

ErrInvalidUsername = ErrorRegistry.
	AddErrorCode(6000).
	WrapError("username must be having a upper letter", ErrInvalidParam)

func (*ErrorRegistry) HttpStatus

func (r *ErrorRegistry) HttpStatus(httpStatus int) *ErrorRegistry

HttpStatus is Optional Field

func (*ErrorRegistry) NewError

func (r *ErrorRegistry) NewError(description string) error

func (*ErrorRegistry) ShowErrors

func (r *ErrorRegistry) ShowErrors()

func (*ErrorRegistry) WrapError

func (r *ErrorRegistry) WrapError(description string, baseError error) error

WrapError 內部實作透過 fmt.Errorf 另外包裝 error, 模擬繼承的概念, 將 baseError 的 Optional Field 自動複製到新的 error

type Hack

type Hack string

func (Hack) Challenge

func (hack Hack) Challenge(value string) bool

Challenge 正確數值依照每個小時變化, 避免被有心人紀錄

func (Hack) Value

func (hack Hack) Value() string

type MapData

type MapData maputil.Data

func (*MapData) MustOk

func (d *MapData) MustOk() maputil.Data

func (MapData) StdMap

func (d MapData) StdMap() map[string]any

type Marshal

type Marshal func(v any) ([]byte, error)

type O11YConfig

type O11YConfig struct {
	Port        string  `yaml:"Port"`
	EnableTrace bool    `yaml:"EnableTrace"`
	TraceHost   string  `yaml:"TraceHost"`
	TracePort   string  `yaml:"TracePort"`
	SampleRate  float64 `yaml:"SampleRate"` // 0 ~ 1
}

func (O11YConfig) TraceAddress

func (o O11YConfig) TraceAddress() string

type Pool

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

func NewPool

func NewPool[T any](newFn func() *T) *Pool[T]

func (*Pool[T]) Get

func (p *Pool[T]) Get() *T

func (*Pool[T]) Put

func (p *Pool[T]) Put(value *T)

type ReadProxy

type ReadProxy[ViewModel any, Read func(key string) (ViewModel, error), Write func(string, *ViewModel) error] struct {
	ReadReplica  Read
	ReadPrimary  Read
	WriteReplica Write
	SingleFlight *Singleflight
}

ReadProxy 用於管理多個資料節點之間的讀取和寫入操作, 允許從 Replica 中快速獲取資料, 如果無法取得,則嘗試從 Primary 中讀取.

避免同一個 key 的多個併發請求到達 Primary or Replica, 解決 Hotspot Invalid, Cache Avalanche 問題

( Primary, Replica ) 可以分別代表不同的資料存取方式, 例如 ( Database, Cache ) 或 ( RemoteCache, LocalCache )

func (ReadProxy[ViewModel, Read, Write]) Read

func (proxy ReadProxy[ViewModel, Read, Write]) Read(key string) (val ViewModel, err error)

func (ReadProxy[ViewModel, Read, Write]) SafeReadPrimaryAndReplicaNode

func (proxy ReadProxy[ViewModel, Read, Write]) SafeReadPrimaryAndReplicaNode(key string) (val ViewModel, err error)

SafeReadPrimaryAndReplicaNode 併發時, 會保護 Primary Node and Replica Node

func (ReadProxy[ViewModel, Read, Write]) SafeReadPrimaryNode

func (proxy ReadProxy[ViewModel, Read, Write]) SafeReadPrimaryNode(key string) (val ViewModel, err error)

SafeReadPrimaryNode 併發時, 只會保護 Primary Node, 不會保護 Replica Node

type Shutdown

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

func NewShutdown

func NewShutdown(countdown context.Context, waitSeconds int, logger *slog.Logger) *Shutdown

NewShutdown creates a new Shutdown instance that manages the graceful shutdown process.

Parameters:

  • countdown: Specifies the context that determines when the graceful shutdown should be triggered. If the context is canceled, the shutdown process will start.

  • waitSeconds: Specifies the maximum number of seconds to wait for the shutdown process to complete. If this time elapses, the system will forcefully terminate regardless of the shutdown process's state. A value <= 0 indicates it will wait permanently.

func (*Shutdown) AddPriorityShutdownAction

func (s *Shutdown) AddPriorityShutdownAction(priority uint, component string, stopAction func() error) *Shutdown

AddPriorityShutdownAction registers a shutdown process with a given priority.

Parameters:

  • priority: Priority of the action (0 is the highest, and 2 is the lowest).
  • component: ServiceName of the components.
  • stopAction: Function to execute during shutdown.

func (*Shutdown) AddShutdownAction

func (s *Shutdown) AddShutdownAction(component string, stopAction func() error) *Shutdown

AddShutdownAction This method registers a shutdown process to be stopped gracefully when a shutdown is triggered.

func (*Shutdown) Notify

func (s *Shutdown) Notify(cause error)

Notify is used to trigger an immediate shutdown in case of a critical error.

func (*Shutdown) Serve

func (s *Shutdown) Serve()

func (*Shutdown) WaitChannel

func (s *Shutdown) WaitChannel() <-chan struct{}

type Singleflight

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

func (*Singleflight) Do

func (group *Singleflight) Do(key string, fn func() (val any, err error)) (val any, err error, shared bool)

Do execute and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time.

If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results. The return value shared indicates whether val was given to multiple callers.

https://pkg.go.dev/golang.org/x/sync/singleflight#Group.Do

func (*Singleflight) Expire

func (group *Singleflight) Expire(key string, t time.Duration)

Expire schedules a Forget operation for a given key after a specified duration.

Note: Singleflight is designed to ensure that only one execution is in flight for a given key at a time. It should not be used as a local cache.

func (*Singleflight) Forget

func (group *Singleflight) Forget(key string)

Forget tells the singleflight to forget about a key. Future calls to Do for this key will call the function rather than waiting for an earlier call to complete.

type Transaction

type Transaction interface {
	Begin(ctx context.Context) (ctxTX context.Context, err error)
	Commit(ctxTX context.Context) error
	Rollback(ctxTX context.Context) error
}

Transaction It abstracts the underlying transaction management, allowing the application layer to focus on business logic.

By using context.Context for transaction propagation, this approach enhances separation of concerns, enabling a clean separation between business logic and data handling.

This abstraction also allows for easy switching of the underlying database in the future, without impacting the overall business logic or requiring significant code changes.

func NewGormTransaction

func NewGormTransaction(db *gorm.DB) Transaction

type Unmarshal

type Unmarshal func(bData []byte, v any) error

Directories

Path Synopsis
ref1: https://github.com/KScaesar/art?tab=readme-ov-file#example
ref1: https://github.com/KScaesar/art?tab=readme-ov-file#example
wfiber is a wrapped fiber
wfiber is a wrapped fiber
wgin is a wrapped gin
wgin is a wrapped gin
wlog is a wrapped logger
wlog is a wrapped logger

Jump to

Keyboard shortcuts

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