Documentation
¶
Overview ¶
Package uncommons provides shared infrastructure helpers used across Lerian services.
The package includes context helpers, validation utilities, error adapters, and cross-cutting primitives used by higher-level subpackages.
Typical usage at request ingress:
ctx = uncommons.ContextWithLogger(ctx, logger) ctx = uncommons.ContextWithTracer(ctx, tracer) ctx = uncommons.ContextWithHeaderID(ctx, requestID)
This package is intentionally dependency-light; specialized integrations live in subpackages such as opentelemetry, mongo, redis, rabbitmq, and server.
Index ¶
- Variables
- func AttributesFromContext(ctx context.Context) []attribute.KeyValue
- func CamelToSnakeCase(str string) string
- func CheckMetadataKeyAndValueLength(limit int, metadata map[string]any) error
- func Contains[T comparable](slice []T, item T) bool
- func ContextWithHeaderID(ctx context.Context, headerID string) context.Context
- func ContextWithLogger(ctx context.Context, logger log.Logger) context.Context
- func ContextWithMetricFactory(ctx context.Context, metricFactory *metrics.MetricsFactory) context.Context
- func ContextWithSpanAttributes(ctx context.Context, kv ...attribute.KeyValue) context.Context
- func ContextWithTracer(ctx context.Context, tracer trace.Tracer) context.Context
- func GenerateUUIDv7() (uuid.UUID, error)
- func GetCPUUsage(ctx context.Context, factory *metrics.MetricsFactory)
- func GetMapNumKinds() map[reflect.Kind]bool
- func GetMemUsage(ctx context.Context, factory *metrics.MetricsFactory)
- func GetenvBoolOrDefault(key string, defaultValue bool) bool
- func GetenvIntOrDefault(key string, defaultValue int64) int64
- func GetenvOrDefault(key string, defaultValue string) string
- func HashSHA256(input string) string
- func IsDateRangeWithinMonthLimit(initial, final time.Time, limit int) bool
- func IsInitialDateBeforeFinalDate(initial, final time.Time) bool
- func IsInternalLerianService(userAgent string) bool
- func IsNilOrEmpty(s *string) bool
- func IsUUID(s string) bool
- func IsValidDate(date string) bool
- func IsValidDateTime(date string) bool
- func MergeMaps(source, target map[string]any) map[string]any
- func NewLoggerFromContext(ctx context.Context) log.Logger
- func NewTrackingFromContext(ctx context.Context) (log.Logger, trace.Tracer, string, *metrics.MetricsFactory)
- func NormalizeDate(date time.Time, days *int) string
- func NormalizeDateTime(date time.Time, days *int, endOfDay bool) string
- func ParseDateTime(dateStr string, isEndDate bool) (time.Time, bool, error)
- func RegexIgnoreAccents(regex string) string
- func RemoveAccents(word string) (string, error)
- func RemoveChars(str string, chars map[string]bool) string
- func RemoveSpaces(word string) string
- func ReplaceAttributes(ctx context.Context, kv ...attribute.KeyValue) context.Context
- func ReplaceUUIDWithPlaceholder(path string) string
- func Reverse[T any](s []T) []T
- func SafeInt64ToInt(val int64) int
- func SafeIntToUint32(value int, defaultVal uint32, logger log.Logger, fieldName string) uint32
- func SafeIntToUint64(val int) uint64
- func SafeUintToInt(val uint) int
- func SetConfigFromEnvVars(s any) error
- func StringToInt(s string) intdeprecated
- func StringToIntOrDefault(s string, defaultVal int) int
- func StructToJSONString(s any) (string, error)
- func UUIDsToStrings(uuids []uuid.UUID) []string
- func ValidateBusinessError(err error, entityType string, args ...any) error
- func ValidateServerAddress(value string) string
- func WithTimeoutSafe(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc, error)
- type App
- type CustomContextKeyValue
- type Launcher
- type LauncherOption
- type LocalEnvConfig
- type Response
- type Syscmd
- type SyscmdI
- type TrackingComponents
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNilLauncher is returned when a launcher method is called on a nil receiver. ErrNilLauncher = errors.New("launcher is nil") // ErrEmptyApp is returned when an app name is empty or whitespace. ErrEmptyApp = errors.New("app name is empty") // ErrNilApp is returned when a nil app instance is provided. ErrNilApp = errors.New("app is nil") // ErrConfigFailed is returned when launcher option application collected errors. ErrConfigFailed = errors.New("launcher configuration failed") )
var CustomContextKey = customContextKey("custom_context")
CustomContextKey is the context key used to store CustomContextKeyValue.
var ErrInvalidDateFormat = errors.New("invalid date format")
ErrInvalidDateFormat indicates the date string could not be parsed by any known format.
var ErrLoggerNil = errors.New("logger is nil")
ErrLoggerNil is returned when the Logger is nil and cannot proceed.
var ErrNilParentContext = errors.New("cannot create context from nil parent")
ErrNilParentContext indicates that a nil parent context was provided
var ErrNotPointer = errors.New("argument must be a pointer")
ErrNotPointer indicates that a non-pointer value was passed where a pointer was required.
Functions ¶
func AttributesFromContext ¶
AttributesFromContext returns a shallow copy of the AttrBag slice, safe to reuse by processors.
func CamelToSnakeCase ¶
CamelToSnakeCase converts a given camelCase string to snake_case format.
func CheckMetadataKeyAndValueLength ¶
CheckMetadataKeyAndValueLength check the length of key and value to a limit pass by on field limit
func Contains ¶
func Contains[T comparable](slice []T, item T) bool
Contains checks if an item is in a slice. This function uses type parameters to work with any slice type.
func ContextWithHeaderID ¶
ContextWithHeaderID returns a context within a HeaderID in "headerID" value.
func ContextWithLogger ¶
ContextWithLogger returns a context within a Logger in "logger" value.
func ContextWithMetricFactory ¶
func ContextWithMetricFactory(ctx context.Context, metricFactory *metrics.MetricsFactory) context.Context
ContextWithMetricFactory returns a context within a MetricsFactory in "metricFactory" value.
func ContextWithSpanAttributes ¶
ContextWithSpanAttributes appends one or more attributes to the request's AttrBag. Call this once at the ingress (HTTP/gRPC middleware) and avoid per-layer duplication. Example keys: tenant.id, enduser.id, request.route, region, plan.
func ContextWithTracer ¶
ContextWithTracer returns a context within a trace.Tracer in "tracer" value.
func GenerateUUIDv7 ¶
GenerateUUIDv7 generates a new UUID v7 using the google/uuid package. Returns the generated UUID or an error if crypto/rand fails.
func GetCPUUsage ¶
func GetCPUUsage(ctx context.Context, factory *metrics.MetricsFactory)
GetCPUUsage reads the current CPU usage and records it through the MetricsFactory gauge.
func GetMapNumKinds ¶
GetMapNumKinds get the map of numeric kinds to use in validations and conversions.
The numeric kinds are: - int - int8 - int16 - int32 - int64 - float32 - float64
func GetMemUsage ¶
func GetMemUsage(ctx context.Context, factory *metrics.MetricsFactory)
GetMemUsage reads the current memory usage and records it through the MetricsFactory gauge.
func GetenvBoolOrDefault ¶
GetenvBoolOrDefault returns the value of os.Getenv(key string) value as bool or defaultValue if error Is the environment variable (key) is not defined, it returns the given defaultValue If the environment variable (key) is not a valid bool format, it returns the given defaultValue If any error occurring during bool parse, it returns the given defaultValue.
func GetenvIntOrDefault ¶
GetenvIntOrDefault returns the value of os.Getenv(key string) value as int or defaultValue if error If the environment variable (key) is not defined, it returns the given defaultValue If the environment variable (key) is not a valid int format, it returns the given defaultValue If any error occurring during int parse, it returns the given defaultValue.
func GetenvOrDefault ¶
GetenvOrDefault encapsulate built-in os.Getenv behavior but if key is not present it returns the defaultValue.
func HashSHA256 ¶
HashSHA256 generate a hash sha-256 to create idempotency on redis
func IsDateRangeWithinMonthLimit ¶
IsDateRangeWithinMonthLimit checks if the date range is within the permitted range in months.
func IsInitialDateBeforeFinalDate ¶
IsInitialDateBeforeFinalDate checks if the initial date is before or equal to the final date.
func IsInternalLerianService ¶
IsInternalLerianService reports whether a user-agent belongs to a Lerian internal service.
func IsNilOrEmpty ¶
IsNilOrEmpty returns a boolean indicating if a *string is nil or empty. It's use TrimSpace so, a string " " and "" and "null" and "nil" will be considered empty
func IsValidDate ¶
IsValidDate checks if the provided date string is in the format "YYYY-MM-DD".
func IsValidDateTime ¶
IsValidDateTime checks if the provided date string is in the format "YYYY-MM-DD HH:MM:SS".
func NewLoggerFromContext ¶
NewLoggerFromContext extract the Logger from "logger" value inside context
func NewTrackingFromContext ¶
func NewTrackingFromContext(ctx context.Context) (log.Logger, trace.Tracer, string, *metrics.MetricsFactory)
NewTrackingFromContext extracts tracking components from context with intelligent fallback. It follows the fail-safe principle: preserve valid components, provide sensible defaults for invalid ones.
func NormalizeDate ¶
NormalizeDate normalizes a date adding or subtracting days without time to make it match the query requirements and string format.
func NormalizeDateTime ¶
NormalizeDateTime normalizes a date adding or subtracting days with time. If the date already has a specific time (not at start/end of day), it preserves it. Otherwise, it normalizes to start (00:00:00) or end (23:59:59) of day.
func ParseDateTime ¶
ParseDateTime parses a date string that can be either: - Date only (YYYY-MM-DD): returns time with 00:00:00 for start, 23:59:59 for end - Date and time (ISO 8601 formats like YYYY-MM-DDTHH:MM:SS): returns exact time Returns the parsed time and a boolean indicating if time was specified
func RegexIgnoreAccents ¶
RegexIgnoreAccents receives a regex, then, for each char it's adds the accents variations to expression Ex: Given "a" -> "aáàãâ" Ex: Given "c" -> "ç"
func RemoveAccents ¶
RemoveAccents removes accents of a given word and returns it
func RemoveChars ¶
RemoveChars from a string
func RemoveSpaces ¶
RemoveSpaces removes spaces of a given word and returns it
func ReplaceAttributes ¶
ReplaceAttributes resets the current AttrBag with a new set (rarely needed; provided for completeness).
func ReplaceUUIDWithPlaceholder ¶
ReplaceUUIDWithPlaceholder replaces UUIDs with a placeholder in a given path string.
func SafeInt64ToInt ¶
SafeInt64ToInt safely converts int64 to int
func SafeIntToUint32 ¶
SafeIntToUint32 safely converts int to uint32 with overflow protection. Returns the converted value if in valid range [0, MaxUint32], otherwise returns defaultVal. This prevents G115 (CWE-190) integer overflow vulnerabilities.
func SafeIntToUint64 ¶
SafeIntToUint64 safe mode to converter int to uint64
func SafeUintToInt ¶
SafeUintToInt converts a uint to int64 safely by capping values at math.MaxInt64.
func SetConfigFromEnvVars ¶
SetConfigFromEnvVars builds a struct by setting it fields values using the "var" tag Constraints: s any - must be an initialized pointer Supported types: String, Boolean, Int, Int8, Int16, Int32 and Int64.
func StringToInt
deprecated
func StringToIntOrDefault ¶ added in v2.3.0
StringToIntOrDefault converts a string to an int, returning defaultVal on parse failure.
func StructToJSONString ¶
StructToJSONString convert a struct to json string
func UUIDsToStrings ¶
UUIDsToStrings converts a slice of UUIDs to a slice of strings. It's optimized to minimize allocations and iterations.
func ValidateBusinessError ¶
ValidateBusinessError validates the error and returns the appropriate business error code, title, and message.
Parameters:
- err: The error to be validated (ref: https://github.com/LerianStudio/midaz/common/constant/errors.go).
- entityType: The type of the entity related to the error.
- args: Additional arguments for formatting error messages.
Returns:
- error: The appropriate business error with code, title, and message.
func ValidateServerAddress ¶
ValidateServerAddress checks if the value matches the pattern <some-address>:<some-port> and returns the value if it does.
func WithTimeoutSafe ¶
func WithTimeoutSafe(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc, error)
WithTimeoutSafe creates a context with the specified timeout, but respects any existing deadline in the parent context. Returns an error if parent is nil.
The function returns three values (context, cancel, error) for explicit nil-parent error handling.
Note: When the parent's deadline is shorter than the requested timeout, this function returns a cancellable context that inherits the parent's deadline rather than creating a new deadline. The returned context's Deadline() will return the parent's deadline.
Types ¶
type App ¶
App represents an application that will run as a deployable component. It's an entrypoint at main.go. RedisRepository provides an interface for redis.
type CustomContextKeyValue ¶
type CustomContextKeyValue struct {
HeaderID string
Tracer trace.Tracer
Logger log.Logger
MetricFactory *metrics.MetricsFactory
// AttrBag holds request-wide attributes to be applied to every span.
// Keep low/medium cardinality attributes here (tenant.id, plan, region, request_id, route).
AttrBag []attribute.KeyValue
}
CustomContextKeyValue holds all request-scoped facilities we attach to context.
type Launcher ¶
Launcher manages apps.
func NewLauncher ¶
func NewLauncher(opts ...LauncherOption) *Launcher
NewLauncher create an instance of Launch.
func (*Launcher) Run ¶
func (l *Launcher) Run()
Run every application registered before with Run method. Maintains backward compatibility - logs error internally if Logger is nil. For explicit error handling, use RunWithError instead.
func (*Launcher) RunWithError ¶
RunWithError runs all applications and returns an error if Logger is nil or if any configuration errors were collected during option application. Safe to call on a Launcher created without NewLauncher (fields are lazy-initialized).
type LauncherOption ¶
type LauncherOption func(l *Launcher)
LauncherOption defines a function option for Launcher.
func RunApp ¶
func RunApp(name string, app App) LauncherOption
RunApp registers an application with the launcher. If registration fails, the error is collected and surfaced when RunWithError is called.
func WithLogger ¶
func WithLogger(logger log.Logger) LauncherOption
WithLogger adds a log.Logger component to launcher.
type LocalEnvConfig ¶
type LocalEnvConfig struct {
Initialized bool
}
LocalEnvConfig is used to automatically call the InitLocalEnvConfig method using Dependency Injection So, if a func parameter or a struct field depends on LocalEnvConfig, when DI starts, it will call InitLocalEnvConfig as the LocalEnvConfig provider.
func InitLocalEnvConfig ¶
func InitLocalEnvConfig() *LocalEnvConfig
InitLocalEnvConfig load a .env file to set up local environment vars. It's called once per application process. Version and environment are always logged in a plain startup banner format.
type Response ¶
type Response struct {
EntityType string `json:"entityType,omitempty"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
Err error `json:"err,omitempty"`
}
Response represents a business error with code, title, and message.
type TrackingComponents ¶
type TrackingComponents struct {
Logger log.Logger
Tracer trace.Tracer
HeaderID string
MetricFactory *metrics.MetricsFactory
}
TrackingComponents represents the complete set of tracking components extracted from context. This struct encapsulates all telemetry-related dependencies in a single, cohesive unit.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package assert provides always-on runtime assertions for detecting programming bugs.
|
Package assert provides always-on runtime assertions for detecting programming bugs. |
|
Package backoff provides retry delay helpers with exponential growth and jitter.
|
Package backoff provides retry delay helpers with exponential growth and jitter. |
|
Package circuitbreaker provides service-level circuit breaker orchestration and health-check-driven recovery helpers.
|
Package circuitbreaker provides service-level circuit breaker orchestration and health-check-driven recovery helpers. |
|
Package constant provides shared constant values used across the library.
|
Package constant provides shared constant values used across the library. |
|
Package cron parses standard 5-field cron expressions and computes next run times.
|
Package cron parses standard 5-field cron expressions and computes next run times. |
|
Package crypto provides hashing and symmetric encryption helpers.
|
Package crypto provides hashing and symmetric encryption helpers. |
|
Package errgroup coordinates goroutines that share a cancellation context.
|
Package errgroup coordinates goroutines that share a cancellation context. |
|
internal
|
|
|
Package jwt provides minimal HMAC-based JWT signing and verification.
|
Package jwt provides minimal HMAC-based JWT signing and verification. |
|
Package license provides helpers for license validation and management.
|
Package license provides helpers for license validation and management. |
|
Package log defines the v2 logging interface and typed logging fields.
|
Package log defines the v2 logging interface and typed logging fields. |
|
Package mongo provides resilient MongoDB connection and index management helpers.
|
Package mongo provides resilient MongoDB connection and index management helpers. |
|
net
|
|
|
http
Package http provides Fiber-oriented HTTP helpers, middleware, and error handling.
|
Package http provides Fiber-oriented HTTP helpers, middleware, and error handling. |
|
http/ratelimit
Package ratelimit provides rate-limiting helpers for the HTTP package.
|
Package ratelimit provides rate-limiting helpers for the HTTP package. |
|
Package opentelemetry provides tracing, metrics, propagation, and redaction helpers.
|
Package opentelemetry provides tracing, metrics, propagation, and redaction helpers. |
|
metrics
Package metrics provides a fluent factory for OpenTelemetry metric instruments.
|
Package metrics provides a fluent factory for OpenTelemetry metric instruments. |
|
Package outbox provides transactional outbox primitives.
|
Package outbox provides transactional outbox primitives. |
|
postgres
Package postgres provides PostgreSQL adapters for outbox repository contracts.
|
Package postgres provides PostgreSQL adapters for outbox repository contracts. |
|
Package pointers provides helpers for pointer creation and conversions.
|
Package pointers provides helpers for pointer creation and conversions. |
|
Package postgres provides shared PostgreSQL connection helpers.
|
Package postgres provides shared PostgreSQL connection helpers. |
|
Package rabbitmq provides AMQP connection, consumer, and producer helpers.
|
Package rabbitmq provides AMQP connection, consumer, and producer helpers. |
|
Package redis provides Redis/Valkey client helpers with topology and IAM support.
|
Package redis provides Redis/Valkey client helpers with topology and IAM support. |
|
Package runtime provides panic recovery utilities for services with full observability integration.
|
Package runtime provides panic recovery utilities for services with full observability integration. |
|
Package safe provides panic-free helpers for math, slices, and regex operations.
|
Package safe provides panic-free helpers for math, slices, and regex operations. |
|
Package security provides helpers for handling sensitive fields and data safety.
|
Package security provides helpers for handling sensitive fields and data safety. |
|
Package server provides server lifecycle and graceful shutdown helpers.
|
Package server provides server lifecycle and graceful shutdown helpers. |
|
Package transaction provides transaction intent planning and posting validations.
|
Package transaction provides transaction intent planning and posting validations. |
|
Package zap provides adapters and helpers around zap-based logging.
|
Package zap provides adapters and helpers around zap-based logging. |