Documentation
¶
Overview ¶
this middleware function is to revoke token jwt if status user blocked or suspend
Index ¶
- Constants
- Variables
- func AcquireLock(key string, ttl time.Duration) (bool, error)
- func AcquireLockWithRetry(key string, ttl time.Duration, maxRetries int, retryDelay time.Duration) (*redsync.Mutex, bool, error)
- func AddValidatorLibs()
- func ConfigureLogForwarding(cfg phlogger.LogForwardConfig)
- func ConfigureSentryLogging(enable bool)
- func DeleteRedis(id string) error
- func DeleteRedisWithContext(ctx context.Context, id string) error
- func FlushSentry(timeout time.Duration)
- func GetAppEnv() string
- func GetAppName() string
- func GetConfigurationStatus() map[string]interface{}
- func GetMutex(key string) *redsync.Mutex
- func GetOrGenerateRequestID(headerValue string) string
- func GetRedis(id string) (string, error)
- func GetRedisClient(redisHost, redisPort, redisPassword string, redisDb int) error
- func GetRedisOptions() *redis.Options
- func GetRedisPoolClient() (*redis.Client, error)
- func GetRedisWithContext(ctx context.Context, id string) (string, error)
- func GetSentryClient() *sentry.Client
- func GetSentryClientOptions() *sentry.ClientOptions
- func GetSentryData() *phsentry.SentryData
- func GetTrxRedisBackoff() int
- func GetTrxRedisLockTimeout() time.Duration
- func IncrementMetric(event string)
- func IncrementMetricBy(event string, n int64)
- func InitRedSyncOnce() error
- func InitRedisOptions(rawOpt redis.Options) *redis.Options
- func InitSentry(options phsentry.SentryOptions) *sentry.Client
- func InitSentryOptions(options phsentry.SentryOptions)
- func InitializeApp()
- func InitializeLogger()
- func InitializeRedis(opt redis.Options)
- func InitializeRedisWithRetry(opts RedisInitOptions) error
- func InitializeSampler(cfg SamplerConfig)
- func IsAuditTrailTrxEnabled() bool
- func JSONEncode(obj interface{}) string
- func JsonMinify(jsonB []byte) ([]byte, error)
- func LogAuditTrailTrx(data AuditTrailTrx)
- func LogAudittrailData(funcName, desc, source, commType string, key *[]string, ...)
- func LogAudittrailDataV2(funcName, desc, source, commType string, key *[]string, ...)
- func LogAudittrailProcess(funcName, desc, info string, key *[]string)
- func LogAudittrailProcessV2(funcName, desc, info string, key *[]string)
- func LogConfigurationWarnings()
- func LogCtx(ctx context.Context, fields ...string) *phtrace.LogContextCtx
- func LogD(format string, args ...interface{})
- func LogDCtx(ctx context.Context, format string, args ...interface{})
- func LogDRated(key string, format string, args ...interface{})
- func LogDRatedW(key string, window time.Duration, format string, args ...interface{})
- func LogE(format string, args ...interface{})
- func LogECtx(ctx context.Context, format string, args ...interface{})
- func LogERated(key string, format string, args ...interface{})
- func LogERatedW(key string, window time.Duration, format string, args ...interface{})
- func LogErr(err error)
- func LogF(format string, args ...interface{})
- func LogForwardConfigFromEnv() phlogger.LogForwardConfig
- func LogI(format string, args ...interface{})
- func LogICtx(ctx context.Context, format string, args ...interface{})
- func LogIRated(key string, format string, args ...interface{})
- func LogIRatedW(key string, window time.Duration, format string, args ...interface{})
- func LogJ(arg interface{})
- func LogJI(arg interface{})
- func LogSetLevel(levelName string)
- func LogW(format string, args ...interface{})
- func LogWCtx(ctx context.Context, format string, args ...interface{})
- func LogWRated(key string, format string, args ...interface{})
- func LogWRatedW(key string, window time.Duration, format string, args ...interface{})
- func LoggerErrorHub(err interface{}, args ...interface{})
- func NewAmqp(addr string, c *AmqpClient)
- func NewSentryData(dt *phsentry.SentryData)
- func ReadBody(c echo.Context, idem string) (map[string]interface{}, string, error)
- func RegisterMetricsHook(hook MetricsHook)
- func ReleaseLock(key string) error
- func ReleaseLockWithRetry(mutex *redsync.Mutex, maxRetries int) error
- func RemoveMutex(key string)
- func RevokeToken(next echo.HandlerFunc) echo.HandlerFunc
- func SendSentryDebug(err error, args ...string)
- func SendSentryError(err error, args ...string)
- func SendSentryErrorWithContext(ctx context.Context, err error, args ...string)
- func SendSentryEvent(event *sentry.Event, args ...string)
- func SendSentryMessage(msg string, args ...string)
- func SendSentryWarning(err error, args ...string)
- func SendToSentryDebug(err error, service, module, function string)
- func SendToSentryError(err error, service, module, function string)
- func SendToSentryEvent(event *sentry.Event, service, module, function string)
- func SendToSentryMessage(message string, service, module, function string)
- func SendToSentryWarning(err error, service, module, function string)
- func SentryEnabled() bool
- func SentryLoggingFromEnv() bool
- func SetAppEnv(v string)
- func SetAppName(v string)
- func StoreMutex(key string, mutex *redsync.Mutex)
- func StoreRedis(id string, data interface{}, duration time.Duration) error
- func StoreRedisWithContext(ctx context.Context, id string, data interface{}, duration time.Duration) error
- func StoreRedisWithLock(id string, data interface{}, duration time.Duration) (err error)
- func ToJson(data interface{}) string
- func ToJsonIndent(data interface{}) string
- func VerifCsrf(next echo.HandlerFunc) echo.HandlerFunc
- func VerifIdemKey(next echo.HandlerFunc) echo.HandlerFunc
- func VerifyMD5(idemKey string, request []byte) (string, error)
- type AmqpClient
- func (c *AmqpClient) AmqpConfig() amqp.Config
- func (c *AmqpClient) Cc() error
- func (c *AmqpClient) Channel() *amqp.Channel
- func (c *AmqpClient) Close() error
- func (c *AmqpClient) ConnName() string
- func (c *AmqpClient) Consume() (<-chan amqp.Delivery, error)
- func (c *AmqpClient) ErrLog() *log.Logger
- func (c *AmqpClient) InfoLog() *log.Logger
- func (c *AmqpClient) IsReady() bool
- func (c *AmqpClient) Push(data []byte) error
- func (c *AmqpClient) PushWithTTL(data []byte, ttl string) error
- func (c *AmqpClient) SetAmqpConfig(amqpConfig *amqp.Config)
- func (c *AmqpClient) UnsafePush(data []byte) error
- func (c *AmqpClient) WaitForReady(timeout time.Duration) bool
- type AuditPublisher
- func GetAuditPublisher() *AuditPublisher
- func GetAuditTrailTrxPublisher() *AuditPublisher
- func NewAuditPublisher(client *AmqpClient, opts ...AuditPublisherOption) *AuditPublisher
- func SetUpAuditTrailPublisher(host, port, vhost, username, password, queue, appName string, ...) *AuditPublisher
- func SetUpAuditTrailTrxPublisher(enabled bool, host, port, vhost, username, password, queue, appName string, ...) *AuditPublisher
- type AuditPublisherOption
- func WithBufferSize(n int) AuditPublisherOption
- func WithCircuitBreakerCooldown(d time.Duration) AuditPublisherOption
- func WithCircuitBreakerThreshold(n int) AuditPublisherOption
- func WithMaxRetries(n int) AuditPublisherOption
- func WithMessageTTL(ttl string) AuditPublisherOption
- func WithPublishTimeout(d time.Duration) AuditPublisherOption
- func WithWorkerCount(n int) AuditPublisherOption
- type AuditTrailData
- type AuditTrailProcess
- type AuditTrailTrx
- type ConfigError
- type DataAuditTrailProcess
- type Detail
- type Headers
- type HealthCheck
- type HealthStatus
- type IRqAutoConnect
- type KeyedLimiter
- type LockError
- type LogContext
- type MessagePayloadAudit
- type MetricsHook
- type RabbitMQConnection
- type RabbitMQDefaultPayload
- type RedisInitOptions
- type RedisMetricsDetailed
- type RedisPoolStats
- type Request
- type RequestAndResponse
- type ResponseApi
- func (r *ResponseApi) Accepted(data interface{})
- func (r *ResponseApi) BadRequest(message string, intenalCode string)
- func (r *ResponseApi) InternalServerError(err error)
- func (r *ResponseApi) Out(code int, message, internalCode string, status string, data interface{})
- func (r *ResponseApi) Success(message string, data interface{})
- func (r *ResponseApi) Unauthorized(message string, intenalCode string)
- type ResponseAudit
- type SamplerConfig
Constants ¶
const ( CmdAuditTrailProcess = "audit-trail-process" CmdAuditTrailData = "audit-trail-data" )
const ( AuditTrxStateRequestReceived = "request_received" AuditTrxStateRequestValidated = "request_validated" AuditTrxStateOrderCreated = "order_created" AuditTrxStateChannelSelected = "channel_selected" AuditTrxStateChannelProcessed = "channel_processed" AuditTrxStateVendorRequestSent = "vendor_request_sent" AuditTrxStateVendorTokenAcquired = "vendor_token_acquired" AuditTrxStateQrGenerated = "qr_generated" AuditTrxStateVendorRequestFailed = "vendor_request_failed" AuditTrxStateTransactionUpdated = "transaction_updated" AuditTrxStatePaymentNotified = "payment_notified" AuditTrxStateResponseReturned = "response_returned" AuditTrxStateOrderExpired = "order_expired" AuditTrxStatePaymentReceived = "payment_received" AuditTrxStateStatusChecked = "status_checked" )
const ( AuditTrxStatusProcessing = "processing" AuditTrxStatusSuccess = "success" AuditTrxStatusFailed = "failed" AuditTrxStatusExpired = "expired" )
const ( FieldTraceID = phtrace.FieldTraceID FieldSpanID = phtrace.FieldSpanID FieldTicketID = phtrace.FieldTicketID FieldReffNo = phtrace.FieldReffNo FieldMerchantID = phtrace.FieldMerchantID FieldOrderID = phtrace.FieldOrderID FieldTrxID = phtrace.FieldTrxID FieldTrxNo = phtrace.FieldTrxNo FieldService = phtrace.FieldService FieldRoute = phtrace.FieldRoute FieldVendor = phtrace.FieldVendor )
Standard log/span field keys re-exported from phtrace so callers can use pchelper.FieldTicketID instead of importing phtrace directly. Promoting these constants to the top-level package is part of Phase 2 Task 2.9 so the field names can't drift across services.
const ( Numeric string = "^-?[0-9]+$" Key string = "^[-a-zA-Z0-9_-]+$" )
const CmdAuditTrailTrx = "audit-trail-trx"
Variables ¶
var ( PushMaxRetries = 3 // max retry attempts for Push() PushTimeout = 15 * time.Second // total timeout for a single Push() call )
Push retry and timeout configuration. Package-level vars allow consumer services to override before calling SetUpRabbitMq.
var (
DefaultRedisTimeout = 1000 * time.Millisecond
)
Functions ¶
func AcquireLock ¶ added in v1.6.3
AcquireLock acquires a distributed lock using RedSync
func AcquireLockWithRetry ¶ added in v1.6.3
func AcquireLockWithRetry(key string, ttl time.Duration, maxRetries int, retryDelay time.Duration) (*redsync.Mutex, bool, error)
AcquireLockWithRetry attempts to acquire a distributed lock with retries key: the lock key ttl: lock time-to-live maxRetries: maximum number of retry attempts retryDelay: delay between retries Returns: - mutex: the lock mutex (nil if not acquired) - acquired: whether the lock was acquired - err: any error that occurred
func AddValidatorLibs ¶
func AddValidatorLibs()
func ConfigureLogForwarding ¶ added in v1.8.0
func ConfigureLogForwarding(cfg phlogger.LogForwardConfig)
ConfigureLogForwarding registers Sentry forwarding hooks based on cfg. Call once at startup AFTER InitSentry(). Safe to call multiple times — each call adds hooks cumulatively; use phlogger.ClearLogHooks() if you need a reset.
Example (startup):
pch.InitSentry(pch.SentryOptions{...})
pch.ConfigureLogForwarding(pch.LogForwardConfigFromEnv())
func ConfigureSentryLogging ¶ added in v1.8.0
func ConfigureSentryLogging(enable bool)
ConfigureSentryLogging enables or disables forwarding of all log levels to Sentry. When enabled (true), all logs emitted via LogI, LogE, LogW, LogD, LogF are forwarded to Sentry as structured events and breadcrumbs.
Call once at startup AFTER InitSentry() has completed. This is the recommended simpler API compared to ConfigureLogForwarding for basic setup.
Example (startup):
pch.InitSentry(pch.SentryOptions{...})
pch.ConfigureSentryLogging(true) // enable all log levels to Sentry
pch.LogE("[Main] startup error: %v", err) // forwarded to Sentry
To enable via environment variable (default):
// In your service
enableSentryLogging := os.Getenv("SENTRY_LOGGING") == "true"
pch.ConfigureSentryLogging(enableSentryLogging)
func DeleteRedis ¶
DeleteRedis deletes data from Redis (backward compatible wrapper)
func DeleteRedisWithContext ¶ added in v1.8.0
DeleteRedisWithContext deletes data from Redis with a custom context
func FlushSentry ¶ added in v1.8.0
FlushSentry waits up to timeout for buffered Sentry events to drain. Call before process shutdown to avoid losing queued errors.
func GetAppName ¶ added in v1.4.0
func GetAppName() string
func GetConfigurationStatus ¶ added in v1.8.0
func GetConfigurationStatus() map[string]interface{}
GetConfigurationStatus returns a summary of configuration validation Useful for health check endpoints
func GetOrGenerateRequestID ¶ added in v1.8.0
GetOrGenerateRequestID extracts X-Request-ID header or generates a new one
func GetRedisClient ¶
func GetRedisOptions ¶ added in v1.4.0
func GetRedisPoolClient ¶ added in v1.4.0
func GetRedisWithContext ¶ added in v1.8.0
GetRedisWithContext retrieves data from Redis with a custom context
func GetSentryClient ¶ added in v1.5.1
func GetSentryClientOptions ¶ added in v1.5.1
func GetSentryClientOptions() *sentry.ClientOptions
func GetSentryData ¶ added in v1.5.1
func GetSentryData() *phsentry.SentryData
func GetTrxRedisBackoff ¶ added in v1.6.3
func GetTrxRedisBackoff() int
func GetTrxRedisLockTimeout ¶ added in v1.6.3
func IncrementMetric ¶ added in v1.8.0
func IncrementMetric(event string)
IncrementMetric records one occurrence of a named event via the registered hook.
func IncrementMetricBy ¶ added in v1.8.0
IncrementMetricBy records `n` occurrences of a named event via the registered hook.
func InitRedSyncOnce ¶ added in v1.6.3
func InitRedSyncOnce() error
InitRedSyncOnce initializes the redSync instance once
func InitSentry ¶ added in v1.5.0
func InitSentry(options phsentry.SentryOptions) *sentry.Client
InitSentry initializes the global Sentry client from options; nil when Dsn is empty. Debug enables sentry-go SDK diagnostic logs (not the same as SendSentryDebug events).
func InitSentryOptions ¶ added in v1.5.1
func InitSentryOptions(options phsentry.SentryOptions)
InitSentryOptions prepares merged Sentry client options without instantiating the client. See phsentry.SentryOptions (including Debug / service-level SENTRY_DEBUG wiring).
func InitializeApp ¶ added in v1.5.1
func InitializeApp()
func InitializeLogger ¶ added in v1.4.0
func InitializeLogger()
func InitializeRedis ¶ added in v1.6.3
InitializeRedis initializes Redis with default retry behavior (backward compatible wrapper) For advanced retry configuration, use InitializeRedisWithRetry instead
func InitializeRedisWithRetry ¶ added in v1.8.0
func InitializeRedisWithRetry(opts RedisInitOptions) error
InitializeRedisWithRetry initializes Redis connection with configurable retry logic This provides better resilience against transient connection failures during startup
func InitializeSampler ¶ added in v1.8.0
func InitializeSampler(cfg SamplerConfig)
InitializeSampler sets the global sampler config. Called automatically by InitializeLogger() with env-aware defaults. Use to override defaults at startup.
func IsAuditTrailTrxEnabled ¶ added in v1.8.1
func IsAuditTrailTrxEnabled() bool
func JSONEncode ¶
func JSONEncode(obj interface{}) string
func JsonMinify ¶
func LogAuditTrailTrx ¶ added in v1.8.1
func LogAuditTrailTrx(data AuditTrailTrx)
LogAuditTrailTrx publishes one transaction audit event to the dedicated queue.
func LogAudittrailData ¶
func LogAudittrailData(funcName, desc, source, commType string, key *[]string, data *RequestAndResponse)
LogAudittrailData add audittrail data
func LogAudittrailDataV2 ¶ added in v1.8.0
func LogAudittrailDataV2(funcName, desc, source, commType string, key *[]string, data *RequestAndResponse)
LogAudittrailDataV2 publishes an audit trail data event via the worker pool. Falls back to the legacy LogAudittrailData if the publisher is not set up.
func LogAudittrailProcess ¶
LogAudittrailProcess add audittrail process
func LogAudittrailProcessV2 ¶ added in v1.8.0
LogAudittrailProcessV2 publishes an audit trail process event via the worker pool. Falls back to the legacy LogAudittrailProcess if the publisher is not set up.
func LogConfigurationWarnings ¶ added in v1.8.0
func LogConfigurationWarnings()
LogConfigurationWarnings logs all configuration validation warnings This is a convenience function to log validation results at startup
func LogCtx ¶ added in v1.9.0
func LogCtx(ctx context.Context, fields ...string) *phtrace.LogContextCtx
LogCtx is an alias alphabet — returns a ctx-bound logger that lets you add standard fields (ticket_id, reff_no, merchant_id, order_id, trx_no, etc.) once and have them appear on every log line. See phtrace.WithFields.
func LogD ¶ added in v1.4.0
func LogD(format string, args ...interface{})
LogD logs at Debug level (delegates to phlogger wrapper with hooks).
func LogDRated ¶ added in v1.8.0
LogDRated logs at Debug level with rate limiting using key and the default 50ms window.
func LogDRatedW ¶ added in v1.8.0
LogDRatedW logs at Debug level with rate limiting using key and an explicit window.
func LogE ¶ added in v1.4.0
func LogE(format string, args ...interface{})
LogE logs at Error level (delegates to phlogger wrapper with hooks).
func LogECtx ¶ added in v1.9.0
LogECtx logs at Error level with trace context prefix and records an exception event on the active span (if any).
func LogERated ¶ added in v1.8.0
LogERated logs at Error level with rate limiting using key and the default 50ms window.
func LogERatedW ¶ added in v1.8.0
LogERatedW logs at Error level with rate limiting using key and an explicit window.
func LogF ¶ added in v1.4.0
func LogF(format string, args ...interface{})
LogF logs at Fatal level (process exits after hook execution).
func LogForwardConfigFromEnv ¶ added in v1.8.0
func LogForwardConfigFromEnv() phlogger.LogForwardConfig
LogForwardConfigFromEnv returns a LogForwardConfig loaded from environment variables. See phlogger.LogForwardConfigFromEnv for variable names and defaults.
func LogI ¶ added in v1.4.0
func LogI(format string, args ...interface{})
LogI logs at Info level (delegates to phlogger wrapper with hooks).
func LogIRated ¶ added in v1.8.0
LogIRated logs at Info level with rate limiting using key and the default 50ms window.
func LogIRatedW ¶ added in v1.8.0
LogIRatedW logs at Info level with rate limiting using key and an explicit window.
func LogSetLevel ¶ added in v1.4.0
func LogSetLevel(levelName string)
func LogW ¶ added in v1.4.0
func LogW(format string, args ...interface{})
LogW logs at Warning level (delegates to phlogger wrapper with hooks).
func LogWRated ¶ added in v1.8.0
LogWRated logs at Warning level with rate limiting using key and the default 50ms window.
func LogWRatedW ¶ added in v1.8.0
LogWRatedW logs at Warning level with rate limiting using key and an explicit window.
func LoggerErrorHub ¶
func LoggerErrorHub(err interface{}, args ...interface{})
func NewAmqp ¶ added in v1.6.0
func NewAmqp(addr string, c *AmqpClient)
NewAmqp creates a new consumer state instance, and automatically attempts to connect to the server.
func NewSentryData ¶ added in v1.5.0
func NewSentryData(dt *phsentry.SentryData)
func RegisterMetricsHook ¶ added in v1.8.0
func RegisterMetricsHook(hook MetricsHook)
RegisterMetricsHook sets the global metrics callback for high-frequency events. Consumers wire their own backend (prometheus, statsd, etc.).
func ReleaseLock ¶ added in v1.6.3
func ReleaseLockWithRetry ¶ added in v1.6.3
ReleaseLockWithRetry releases a previously acquired lock with retry mechanism
func RemoveMutex ¶ added in v1.6.3
func RemoveMutex(key string)
RemoveMutex removes a mutex from the map
func RevokeToken ¶
func RevokeToken(next echo.HandlerFunc) echo.HandlerFunc
func SendSentryDebug ¶ added in v1.5.0
func SendSentryError ¶ added in v1.5.0
func SendSentryErrorWithContext ¶ added in v1.8.0
SendSentryErrorWithContext captures an error with request context (e.g. from Echo). Extra string args are passed through to phsentry for breadcrumb metadata.
func SendSentryEvent ¶ added in v1.5.0
func SendSentryMessage ¶ added in v1.5.0
func SendSentryWarning ¶ added in v1.5.0
func SendToSentryDebug ¶ added in v1.5.1
func SendToSentryError ¶ added in v1.5.1
func SendToSentryEvent ¶ added in v1.5.1
func SendToSentryMessage ¶ added in v1.5.1
func SendToSentryWarning ¶ added in v1.5.1
func SentryEnabled ¶ added in v1.8.0
func SentryEnabled() bool
SentryEnabled returns true if Sentry has been initialized.
func SentryLoggingFromEnv ¶ added in v1.8.0
func SentryLoggingFromEnv() bool
SentryLoggingFromEnv loads the SENTRY_LOGGING environment variable and returns its boolean value. Parses common boolean formats: "1", "t", "T", "true", "TRUE", "True", "0", "f", "F", "false", "FALSE", "False". Returns false for invalid or unset values (default behavior).
Call once at startup AFTER InitSentry() has completed, then pass result to ConfigureSentryLogging. This is the recommended pattern for environment-driven sentry logging control.
Example (typical service startup):
pch.InitSentry(pch.SentryOptions{Dsn: os.Getenv("SENTRY_DSN"), ...})
pch.ConfigureSentryLogging(pch.SentryLoggingFromEnv())
Environment variable examples:
SENTRY_LOGGING=true → enable SENTRY_LOGGING=1 → enable SENTRY_LOGGING=false → disable (default) SENTRY_LOGGING=0 → disable (default) (unset) → disable (default)
func SetAppName ¶ added in v1.4.0
func SetAppName(v string)
func StoreMutex ¶ added in v1.6.3
StoreMutex stores a mutex in the map for later release
func StoreRedis ¶
StoreRedis stores data to Redis (backward compatible wrapper)
func StoreRedisWithContext ¶ added in v1.8.0
func StoreRedisWithContext(ctx context.Context, id string, data interface{}, duration time.Duration) error
StoreRedisWithContext stores data to Redis with a custom context Allows caller to control cancellation and timeout behavior
func StoreRedisWithLock ¶ added in v1.6.3
func ToJson ¶ added in v1.4.0
func ToJson(data interface{}) string
ToJson Encode json from object to JSON and beautify the output.
func ToJsonIndent ¶ added in v1.4.0
func ToJsonIndent(data interface{}) string
ToJsonIndent Encode json from object to JSON and beautify the output.
func VerifCsrf ¶
func VerifCsrf(next echo.HandlerFunc) echo.HandlerFunc
func VerifIdemKey ¶
func VerifIdemKey(next echo.HandlerFunc) echo.HandlerFunc
Types ¶
type AmqpClient ¶ added in v1.6.0
type AmqpClient struct {
// contains filtered or unexported fields
}
AmqpClient is the base struct for handling connection recovery, consumption and publishing. Note that this struct has an internal mutex to safeguard against data races. As you develop and iterate over this example, you may need to add further locks, or safeguards, to keep your application safe from data races
func NewAmqpClient ¶ added in v1.6.0
func NewAmqpClient(queueName, connName, addr string, config *amqp.Config) *AmqpClient
NewAmqpClient creates a new consumer state instance, and automatically attempts to connect to the server.
func SetUpRabbitMq ¶
func SetUpRabbitMq(host, port, vhost, username, password, auditTrailQue, appName string) *AmqpClient
SetUpRabbitMq service must call this func in main function NOTE : for audittrail purpose
func (*AmqpClient) AmqpConfig ¶ added in v1.6.0
func (c *AmqpClient) AmqpConfig() amqp.Config
func (*AmqpClient) Cc ¶ added in v1.6.0
func (c *AmqpClient) Cc() error
Cc For debug purpose TODO : debugging close channel
func (*AmqpClient) Channel ¶ added in v1.6.0
func (c *AmqpClient) Channel() *amqp.Channel
func (*AmqpClient) Close ¶ added in v1.6.0
func (c *AmqpClient) Close() error
Close will cleanly shut down the channel and connection.
func (*AmqpClient) ConnName ¶ added in v1.6.0
func (c *AmqpClient) ConnName() string
func (*AmqpClient) Consume ¶ added in v1.6.0
func (c *AmqpClient) Consume() (<-chan amqp.Delivery, error)
Consume will continuously put queue items on the channel. It is required to call delivery.Ack when it has been successfully processed, or delivery.Nack when it fails. Ignoring this will cause data to build up on the server.
func (*AmqpClient) ErrLog ¶ added in v1.6.0
func (c *AmqpClient) ErrLog() *log.Logger
func (*AmqpClient) InfoLog ¶ added in v1.6.0
func (c *AmqpClient) InfoLog() *log.Logger
func (*AmqpClient) IsReady ¶ added in v1.8.0
func (c *AmqpClient) IsReady() bool
IsReady returns true if the AMQP client has an active connection and channel.
func (*AmqpClient) Push ¶ added in v1.6.0
func (c *AmqpClient) Push(data []byte) error
Push will push data onto the queue, and wait for a confirmation. Retries up to PushMaxRetries times with a total timeout of PushTimeout. Returns an error if all retries are exhausted or the timeout is reached.
func (*AmqpClient) PushWithTTL ¶ added in v1.8.0
func (c *AmqpClient) PushWithTTL(data []byte, ttl string) error
PushWithTTL pushes data to the queue with a configurable TTL. An empty ttl means the message never expires in the queue.
func (*AmqpClient) SetAmqpConfig ¶ added in v1.6.0
func (c *AmqpClient) SetAmqpConfig(amqpConfig *amqp.Config)
func (*AmqpClient) UnsafePush ¶ added in v1.6.0
func (c *AmqpClient) UnsafePush(data []byte) error
UnsafePush will push to the queue without checking for confirmation. It returns an error if it fails to connect. No guarantees are provided for whether the server will receive the message.
func (*AmqpClient) WaitForReady ¶ added in v1.8.0
func (c *AmqpClient) WaitForReady(timeout time.Duration) bool
WaitForReady blocks until the client is ready or the timeout expires. Returns true if ready, false if timed out.
type AuditPublisher ¶ added in v1.8.0
type AuditPublisher struct {
// contains filtered or unexported fields
}
AuditPublisher provides production-grade audit message publishing with bounded concurrency via a worker pool, backpressure via a buffered channel, and a circuit breaker to avoid wasting resources when RabbitMQ is down.
func GetAuditPublisher ¶ added in v1.8.0
func GetAuditPublisher() *AuditPublisher
GetAuditPublisher returns the package-level AuditPublisher, or nil if not initialized.
func GetAuditTrailTrxPublisher ¶ added in v1.8.1
func GetAuditTrailTrxPublisher() *AuditPublisher
func NewAuditPublisher ¶ added in v1.8.0
func NewAuditPublisher(client *AmqpClient, opts ...AuditPublisherOption) *AuditPublisher
NewAuditPublisher creates an AuditPublisher with the given AMQP client and options. Call Start() to launch worker goroutines.
func SetUpAuditTrailPublisher ¶ added in v1.8.0
func SetUpAuditTrailPublisher(host, port, vhost, username, password, queue, appName string, opts ...AuditPublisherOption) *AuditPublisher
SetUpAuditTrailPublisher creates an AmqpClient and AuditPublisher with a production-grade worker pool. Returns the publisher for lifecycle management. Existing SetUpRabbitMq is unchanged — services can migrate at their own pace.
func SetUpAuditTrailTrxPublisher ¶ added in v1.8.1
func SetUpAuditTrailTrxPublisher( enabled bool, host, port, vhost, username, password, queue, appName string, opts ...AuditPublisherOption, ) *AuditPublisher
SetUpAuditTrailTrxPublisher initializes dedicated transaction-audit publishing.
func (*AuditPublisher) Start ¶ added in v1.8.0
func (p *AuditPublisher) Start()
Start launches the worker goroutines. Call Stop() to shut down gracefully.
func (*AuditPublisher) Stop ¶ added in v1.8.0
func (p *AuditPublisher) Stop()
Stop gracefully shuts down the publisher: closes the channel, waits for workers to drain remaining messages, and returns.
func (*AuditPublisher) Submit ¶ added in v1.8.0
func (p *AuditPublisher) Submit(payload MessagePayloadAudit)
Submit adds a message to the worker pool. Non-blocking: if the buffer is full or the circuit breaker is open, the message is dropped with a warning log.
type AuditPublisherOption ¶ added in v1.8.0
type AuditPublisherOption func(*AuditPublisher)
AuditPublisherOption configures an AuditPublisher via functional options.
func WithBufferSize ¶ added in v1.8.0
func WithBufferSize(n int) AuditPublisherOption
WithBufferSize sets the channel buffer size (default 1000).
func WithCircuitBreakerCooldown ¶ added in v1.8.0
func WithCircuitBreakerCooldown(d time.Duration) AuditPublisherOption
WithCircuitBreakerCooldown sets the cooldown duration when circuit is open (default 30s).
func WithCircuitBreakerThreshold ¶ added in v1.8.0
func WithCircuitBreakerThreshold(n int) AuditPublisherOption
WithCircuitBreakerThreshold sets consecutive failures before circuit opens (default 10).
func WithMaxRetries ¶ added in v1.8.0
func WithMaxRetries(n int) AuditPublisherOption
WithMaxRetries sets the maximum push retry count per message (default 3).
func WithMessageTTL ¶ added in v1.8.0
func WithMessageTTL(ttl string) AuditPublisherOption
WithMessageTTL sets the message TTL for published audit messages. Empty string means no expiration (recommended for audit data).
func WithPublishTimeout ¶ added in v1.8.0
func WithPublishTimeout(d time.Duration) AuditPublisherOption
WithPublishTimeout sets the total timeout for a single push call (default 15s).
func WithWorkerCount ¶ added in v1.8.0
func WithWorkerCount(n int) AuditPublisherOption
WithWorkerCount sets the number of worker goroutines (default 10).
type AuditTrailData ¶ added in v1.6.0
type AuditTrailData struct {
Subject string `json:"Subject,omitempty"`
Function string `json:"Function,omitempty"`
Description string `json:"Description,omitempty"`
Key []string `json:"Key"` //
Source string `json:"Source"` // internal or external
CommunicationType string `json:"CommunicationType"`
Data *RequestAndResponse `json:"Data"`
}
type AuditTrailProcess ¶ added in v1.6.0
type AuditTrailProcess struct {
Subject string `json:"Subject,omitempty"`
Function string `json:"Function,omitempty"`
Description string `json:"Description,omitempty"`
Key []string `json:"Key"`
Data DataAuditTrailProcess `json:"Data"`
}
type AuditTrailTrx ¶ added in v1.8.1
type AuditTrailTrx struct {
ReffNo string `json:"reffNo"`
OrderNo string `json:"orderNo"`
TicketId string `json:"ticketId,omitempty"`
Status string `json:"status"`
State string `json:"state"`
Message string `json:"message"`
Service string `json:"service"`
Function string `json:"function"`
Description string `json:"description"`
CommunicationType string `json:"communicationType"`
EventTime string `json:"eventTime"`
DurationMs int64 `json:"durationMs,omitempty"`
Amount string `json:"amount,omitempty"`
Currency string `json:"currency,omitempty"`
MerchantNo string `json:"merchantNo,omitempty"`
PaymentCode string `json:"paymentCode,omitempty"`
QrValue string `json:"qrValue,omitempty"`
Rrn string `json:"rrn,omitempty"`
ErrorCode string `json:"errorCode,omitempty"`
VendorName string `json:"vendorName,omitempty"`
Request interface{} `json:"request,omitempty"`
Response interface{} `json:"response,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
}
AuditTrailTrx represents one transaction lifecycle event.
type ConfigError ¶ added in v1.8.0
type ConfigError struct {
Field string `json:"field"`
Message string `json:"message"`
Level string `json:"level"` // "warning" or "error"
}
ConfigError represents a configuration validation error
func ValidateConfiguration ¶ added in v1.8.0
func ValidateConfiguration() []ConfigError
ValidateConfiguration validates the runtime configuration Returns a slice of ConfigError for any issues found
type DataAuditTrailProcess ¶ added in v1.6.0
type Headers ¶
type Headers struct {
IdempotencyKey string `json:"idem_key"`
Session string `json:"session"`
Csrf string `json:"csrf"`
RequestID string `json:"request_id"` // Request ID for tracing
}
func (*Headers) ValiadateHeaderCsrf ¶
func (h *Headers) ValiadateHeaderCsrf() interface{}
func (*Headers) ValiadateHeaderIdem ¶
func (h *Headers) ValiadateHeaderIdem() interface{}
type HealthCheck ¶ added in v1.8.0
type HealthCheck struct {
AppName string `json:"app_name"`
AppEnv string `json:"app_env"`
Timestamp time.Time `json:"timestamp"`
Overall string `json:"overall_status"`
Checks []HealthStatus `json:"checks"`
}
HealthCheck represents the overall health check result
func CheckHealth ¶ added in v1.8.0
func CheckHealth() *HealthCheck
CheckHealth performs health checks on all initialized components Returns comprehensive health status for Redis, RabbitMQ, and other components This is backward compatible - safe to call even if components aren't initialized
type HealthStatus ¶ added in v1.8.0
type HealthStatus struct {
Component string `json:"component"`
Status string `json:"status"` // "healthy", "degraded", "unhealthy"
Message string `json:"message,omitempty"`
Latency int64 `json:"latency_ms,omitempty"`
}
HealthStatus represents the health status of a component
type IRqAutoConnect ¶ added in v1.5.0
type IRqAutoConnect interface {
StartConnection(username, password, host, port, vhost string) (c *amqp.Connection, err error)
DeclareQueues(queues ...string) (err error)
GetRqChannel() *amqp.Channel
Stop()
// contains filtered or unexported methods
}
IRqAutoConnect is interface defining method of rabbit mq auto connect
type KeyedLimiter ¶ added in v1.8.0
type KeyedLimiter = phlogger.KeyedLimiter
KeyedLimiter provides per-key token bucket rate limiting. See phlogger.KeyedLimiter for full documentation.
func NewKeyedLimiter ¶ added in v1.8.0
func NewKeyedLimiter(r float64, burst int) *KeyedLimiter
NewKeyedLimiter creates a per-key token bucket limiter. r is events/second, burst is max burst per key.
type LockError ¶ added in v1.8.0
type LockError struct {
Key string // The lock key
Op string // Operation: "acquire" or "release"
Reason string // Human-readable reason for the error
Err error // Underlying error (if any)
}
LockError represents a distributed lock operation error with context
type LogContext ¶ added in v1.8.0
type LogContext = phlogger.LogContext
LogContext is a child logger with key-value context prefix. See phlogger.LogContext for full documentation.
func NewLogContext ¶ added in v1.8.0
func NewLogContext(fields ...string) *LogContext
NewLogContext creates a child logger with key-value context fields. Fields are prepended as [key=value key2=value2] to every message.
type MessagePayloadAudit ¶
type MetricsHook ¶ added in v1.8.0
type MetricsHook = phlogger.MetricsHook
MetricsHook is a callback for high-frequency event counting. See phlogger.MetricsHook for full documentation.
type RabbitMQConnection ¶ added in v1.5.0
type RabbitMQConnection struct {
Host, Port, Username, Password, VirtualHost, QueueName string
}
func (*RabbitMQConnection) GlobalConn ¶ added in v1.5.0
func (connection *RabbitMQConnection) GlobalConn()
func (*RabbitMQConnection) QueueConn ¶ added in v1.5.0
func (connection *RabbitMQConnection) QueueConn(RQ_QUEUE string)
type RabbitMQDefaultPayload ¶ added in v1.5.0
type RabbitMQDefaultPayload struct {
Route string `json:"command"`
Param interface{} `json:"param"`
Data interface{} `json:"data"`
}
type RedisInitOptions ¶ added in v1.8.0
type RedisInitOptions struct {
Options redis.Options
MaxRetries int // Maximum number of retry attempts (default: 3)
RetryDelay time.Duration // Base delay between retries (default: 1s, uses exponential backoff)
FailFast bool // If true, return error on failure; if false, log but continue (default: false for backward compat)
}
RedisInitOptions provides advanced configuration for Redis initialization with retry logic
type RedisMetricsDetailed ¶ added in v1.8.0
type RedisMetricsDetailed struct {
PoolStats *RedisPoolStats `json:"pool_stats"`
HitRate float64 `json:"hit_rate_percent"` // Cache hit rate percentage
ActiveConns int `json:"active_conns"` // TotalConns - IdleConns
PoolUtilized float64 `json:"pool_utilized_percent"` // Percentage of pool in use
}
RedisMetricsDetailed provides extended Redis metrics including calculated ratios
func GetRedisMetricsDetailed ¶ added in v1.8.0
func GetRedisMetricsDetailed() *RedisMetricsDetailed
GetRedisMetricsDetailed returns enhanced metrics with calculated statistics Useful for monitoring and capacity planning
type RedisPoolStats ¶ added in v1.8.0
type RedisPoolStats struct {
TotalConns int `json:"total_conns"`
IdleConns int `json:"idle_conns"`
StaleConns int `json:"stale_conns"`
Hits uint32 `json:"hits"`
Misses uint32 `json:"misses"`
Timeouts uint32 `json:"timeouts"`
}
RedisPoolStats represents Redis connection pool statistics
func GetRedisMetrics ¶ added in v1.8.0
func GetRedisMetrics() *RedisPoolStats
GetRedisMetrics is an alias for GetRedisPoolStats for API consistency Returns comprehensive Redis connection pool metrics
func GetRedisPoolStats ¶ added in v1.8.0
func GetRedisPoolStats() *RedisPoolStats
GetRedisPoolStats returns Redis connection pool statistics Safe to call - returns nil if Redis not initialized
type Request ¶
type Request struct {
Time string `json:"Time"`
Path string `json:"Path,omitempty"`
QueryString interface{} `json:"QueryString,omitempty"`
Header interface{} `json:"Header,omitempty"`
Param interface{} `json:"Param,omitempty"`
Body interface{} `json:"Body,omitempty"`
IpAddress string `json:"IpAddress,omitempty"`
BrowserId int `json:"BrowserId,omitempty"`
Latitude string `json:"Latitude,omitempty"`
Longitude string `json:"Longitude,omitempty"`
}
type RequestAndResponse ¶
type RequestAndResponse struct {
Request Request `json:"Request"`
Response ResponseAudit `json:"Response"`
}
type ResponseApi ¶
type ResponseApi struct {
Code int `json:"code"`
Status string `json:"status"`
Message string `json:"message"`
InternalCode string `json:"internal_code,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func (*ResponseApi) Accepted ¶
func (r *ResponseApi) Accepted(data interface{})
Accepted in process response
func (*ResponseApi) BadRequest ¶
func (r *ResponseApi) BadRequest(message string, intenalCode string)
BadRequest is method for bad request
func (*ResponseApi) InternalServerError ¶
func (r *ResponseApi) InternalServerError(err error)
InternalServerError is method for internal server error
func (*ResponseApi) Out ¶
func (r *ResponseApi) Out(code int, message, internalCode string, status string, data interface{})
func (*ResponseApi) Success ¶
func (r *ResponseApi) Success(message string, data interface{})
func (*ResponseApi) Unauthorized ¶
func (r *ResponseApi) Unauthorized(message string, intenalCode string)
Unauthorized unauthorized user
type ResponseAudit ¶
type SamplerConfig ¶ added in v1.8.0
type SamplerConfig = phlogger.SamplerConfig
SamplerConfig controls log sampling behavior per key per period. See phlogger.SamplerConfig for full documentation.
func SamplerConfigForEnv ¶ added in v1.8.0
func SamplerConfigForEnv(env string) SamplerConfig
SamplerConfigForEnv returns production-tuned sampler defaults for the given environment.
func SamplerConfigFromAppEnv ¶ added in v1.8.0
func SamplerConfigFromAppEnv() SamplerConfig
SamplerConfigFromAppEnv returns a SamplerConfig based on APP_ENV.
Source Files
¶
- amqp.go
- audittrail-entities.go
- audittrail.go
- audittrail_publisher.go
- audittrail_trx.go
- audittrail_trx_entities.go
- audittrail_v2.go
- config.go
- csrf.go
- headers.go
- health.go
- helpers.go
- idempotency-key.go
- init.go
- log_prefix.go
- logger.go
- mutex.go
- redis.go
- response.go
- revoke-token.go
- rmq-autoconnect.go
- rmq.go
- sentry.go
- validator.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package phtrace provides OpenTelemetry tracing and metrics helpers for PayCloud services.
|
Package phtrace provides OpenTelemetry tracing and metrics helpers for PayCloud services. |
|
sdk
|
|
|
services/s3minio/facade
Package facade provides stable constructors for service-scoped S3MinIO SDK usage.
|
Package facade provides stable constructors for service-scoped S3MinIO SDK usage. |
|
services/s3minio/grpc
Package grpc exposes the service-scoped S3MinIO gRPC transport adapter.
|
Package grpc exposes the service-scoped S3MinIO gRPC transport adapter. |
|
services/s3minio/helper
Package helper exposes the service-scoped S3MinIO SDK contracts.
|
Package helper exposes the service-scoped S3MinIO SDK contracts. |
|
services/s3minio/http
Package http exposes the service-scoped S3MinIO HTTP bridge adapter.
|
Package http exposes the service-scoped S3MinIO HTTP bridge adapter. |
|
services/s3minio/pb
Package pb exposes the service-scoped S3MinIO protobuf compatibility surface.
|
Package pb exposes the service-scoped S3MinIO protobuf compatibility surface. |
|
shared/errors
Package errors holds shared SDK error normalization helpers for future service packages.
|
Package errors holds shared SDK error normalization helpers for future service packages. |
|
shared/observability
Package observability holds shared SDK instrumentation helpers for future service packages.
|
Package observability holds shared SDK instrumentation helpers for future service packages. |
|
shared/transport
Package transport holds cross-service transport primitives for future SDK migrations.
|
Package transport holds cross-service transport primitives for future SDK migrations. |