lib-uncommons

module
v2.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT

README

lib-uncommons

lib-uncommons is Lerian's shared Go toolkit for service primitives, connectors, observability, and runtime safety.

The current major API surface is v2. If you are migrating from older code, see MIGRATION_MAP.md.


Migrating from lib-commons?
Read the migration guide for a full comparison of improvements, new packages, and breaking changes:


Requirements

  • Go 1.25.7 or newer

Installation

go get github.com/LerianStudio/lib-uncommons/v2

What is in this library

Core (uncommons)
  • app.go: Launcher for concurrent app lifecycle management with NewLauncher(opts...) and RunApp options
  • context.go: request-scoped logger/tracer/metrics/header-id tracking via ContextWith* helpers, safe timeout with WithTimeoutSafe, span attribute propagation
  • errors.go: standardized business error mapping with ValidateBusinessError
  • utils.go: UUID generation (GenerateUUIDv7 returns error), struct-to-JSON, map merging, CPU/memory metrics, internal service detection
  • stringUtils.go: accent removal, case conversion, UUID placeholder replacement, SHA-256 hashing, server address validation
  • time.go: date/time validation, range checking, parsing with end-of-day support
  • os.go: environment variable helpers (GetenvOrDefault, GetenvBoolOrDefault, GetenvIntOrDefault), struct population from env tags via SetConfigFromEnvVars
  • uncommons/constants: shared constants for datasource status, errors, headers, metadata, pagination, transactions, OTEL attributes, obfuscation values, and SanitizeMetricLabel utility
Observability and logging
  • uncommons/opentelemetry: telemetry bootstrap (NewTelemetry), propagation (HTTP/gRPC/queue), span helpers, redaction (Redactor with RedactionRule patterns), struct-to-attribute conversion
  • uncommons/opentelemetry/metrics: fluent metrics factory (NewMetricsFactory, NewNopFactory) with Counter/Gauge/Histogram builders, explicit error returns, convenience recorders for accounts/transactions
  • uncommons/log: v2 logging interface (Logger with Log/With/WithGroup/Enabled/Sync), typed Field constructors (String, Int, Bool, Err, Any), GoLogger with CWE-117 log-injection prevention, sanitizer (SafeError, SanitizeExternalResponse)
  • uncommons/zap: zap adapter for uncommons/log with OTEL bridge, Config-based construction via New(), direct zap convenience methods (Debug/Info/Warn/Error), underlying access via Raw() and Level()
Data and messaging connectors
  • uncommons/postgres: Config-based constructor (New), Resolver(ctx) for dbresolver access, Primary() for raw *sql.DB, NewMigrator for schema migrations, backoff-based lazy-connect
  • uncommons/mongo: Config-based client with functional options (NewClient), URI builder (BuildURI), Client(ctx)/ResolveClient(ctx) for access, EnsureIndexes (variadic), TLS support, credential clearing
  • uncommons/redis: topology-based Config (standalone/sentinel/cluster), GCP IAM auth with token refresh, distributed locking via LockManager interface (NewRedisLockManager, LockHandle), SetPackageLogger for diagnostics, TLS defaults to a TLS1.2 minimum floor with AllowLegacyMinVersion as an explicit temporary compatibility override
  • uncommons/rabbitmq: connection/channel/health helpers for AMQP with *Context() variants, HealthCheck() (bool, error), Close()/CloseContext(), confirmable publisher with broker acks and auto-recovery, DLQ topology utilities, and health-check hardening (AllowInsecureHealthCheck, HealthCheckAllowedHosts, RequireHealthCheckAllowedHosts)
HTTP and server utilities
  • uncommons/net/http: Fiber HTTP helpers -- response (Respond/RespondStatus/RespondError/RenderError), health (Ping/HealthWithDependencies), SSRF-protected reverse proxy (ServeReverseProxy with ReverseProxyPolicy), pagination (offset/opaque cursor/timestamp cursor/sort cursor), validation (ParseBodyAndValidate/ValidateStruct/ValidateSortDirection/ValidateLimit), context/ownership (ParseAndVerifyTenantScopedID/ParseAndVerifyResourceScopedID), middleware (WithHTTPLogging/WithGrpcLogging/WithCORS/WithBasicAuth/NewTelemetryMiddleware), FiberErrorHandler
  • uncommons/net/http/ratelimit: Redis-backed rate limit storage (NewRedisStorage) with WithRedisStorageLogger option
  • uncommons/server: ServerManager-based graceful shutdown with WithHTTPServer/WithGRPCServer/WithShutdownChannel/WithShutdownTimeout/WithShutdownHook, StartWithGracefulShutdown()/StartWithGracefulShutdownWithError(), ServersStarted() for test coordination
Resilience and safety
  • uncommons/circuitbreaker: Manager interface with error-returning constructors (NewManager), config validation, preset configs (DefaultConfig/AggressiveConfig/ConservativeConfig/HTTPServiceConfig/DatabaseConfig), health checker (NewHealthCheckerWithValidation), metrics via WithMetricsFactory
  • uncommons/backoff: exponential backoff with jitter (ExponentialWithJitter) and context-aware sleep (WaitContext)
  • uncommons/errgroup: error-group concurrency with panic recovery (WithContext, Go, Wait), configurable logger via SetLogger
  • uncommons/runtime: panic recovery (RecoverAndLog/RecoverAndCrash/RecoverWithPolicy with *WithContext variants), safe goroutines (SafeGo/SafeGoWithContext/SafeGoWithContextAndComponent), panic metrics (InitPanicMetrics), span recording (RecordPanicToSpan), error reporter (SetErrorReporter/GetErrorReporter), production mode (SetProductionMode/IsProductionMode)
  • uncommons/assert: production-safe assertions (New + That/NotNil/NotEmpty/NoError/Never/Halt), assertion metrics (InitAssertionMetrics), domain predicates (Positive/ValidUUID/ValidAmount/DebitsEqualCredits/TransactionCanTransitionTo/BalanceSufficientForRelease and more)
  • uncommons/safe: panic-safe math (Divide/DivideRound/Percentage on decimal.Decimal, DivideFloat64), regex with caching (Compile/MatchString/FindString), slices (First/Last/At with *OrDefault variants)
  • uncommons/security: sensitive field detection (IsSensitiveField), default field lists (DefaultSensitiveFields/DefaultSensitiveFieldsMap)
Domain and support packages
  • uncommons/transaction: intent-based transaction planning (BuildIntentPlan), balance eligibility validation (ValidateBalanceEligibility), posting flow (ApplyPosting), operation resolution (ResolveOperation), typed domain errors (NewDomainError)
  • uncommons/outbox: transactional outbox contracts, dispatcher, sanitizer, and PostgreSQL adapters for schema-per-tenant or column-per-tenant models (schema resolver requires tenant context by default; column migration uses composite key (tenant_id, id))
  • uncommons/crypto: hashing (GenerateHash) and symmetric encryption (InitializeCipher/Encrypt/Decrypt) with credential-safe fmt output (String()/GoString() redact secrets)
  • uncommons/jwt: HS256/384/512 JWT signing (Sign), signature verification (Parse), combined signature + time-claim validation (ParseAndValidate), standalone time-claim validation (ValidateTimeClaims/ValidateTimeClaimsAt)
  • uncommons/license: license validation with functional options (New(opts...), WithLogger), handler management (SetHandler), termination (Terminate/TerminateWithError/TerminateSafe)
  • uncommons/pointers: pointer conversion helpers (String, Bool, Time, Int, Int64, Float64)
  • uncommons/cron: cron expression parser (Parse) and scheduler (Schedule.Next)
Build and shell
  • uncommons/shell/: Makefile include helpers (makefile_colors.mk, makefile_utils.mk), shell scripts (colors.sh, ascii.sh), ASCII art (logo.txt)

Minimal v2 usage

import (
    "context"

    "github.com/LerianStudio/lib-uncommons/v2/uncommons/log"
    "github.com/LerianStudio/lib-uncommons/v2/uncommons/opentelemetry"
)

func bootstrap() error {
    logger := log.NewNop()

    tl, err := opentelemetry.NewTelemetry(opentelemetry.TelemetryConfig{
        LibraryName:               "my-service",
        ServiceName:               "my-service-api",
        ServiceVersion:            "2.0.0",
        DeploymentEnv:             "local",
        CollectorExporterEndpoint: "localhost:4317",
        EnableTelemetry:           false, // Set to true when collector is available
        InsecureExporter:          true,
        Logger:                    logger,
    })
    if err != nil {
        return err
    }
    defer tl.ShutdownTelemetry()

    tl.ApplyGlobals()

    _ = context.Background()

    return nil
}

Environment Variables

The following environment variables are recognized by lib-uncommons:

Variable Type Default Package Description
VERSION string "NO-VERSION" uncommons Application version, printed at startup by InitLocalEnvConfig
ENV_NAME string "local" uncommons Environment name; when "local", a .env file is loaded automatically
ENV string (none) uncommons/assert When set to "production", stack traces are omitted from assertion failures
GO_ENV string (none) uncommons/assert Fallback production check (same behavior as ENV)
LOG_LEVEL string "debug" (dev/local) / "info" (other) uncommons/zap Log level override (debug, info, warn, error); Config.Level takes precedence if set
LOG_ENCODING string "console" (dev/local) / "json" (other) uncommons/zap Log output format: "json" for structured JSON, "console" for human-readable colored output
LOG_OBFUSCATION_DISABLED bool false uncommons/net/http Set to "true" to disable sensitive-field obfuscation in HTTP access logs (not recommended in production)
METRICS_COLLECTION_INTERVAL duration "5s" uncommons/net/http Background system-metrics collection interval (Go duration format, e.g. "10s", "1m")
ACCESS_CONTROL_ALLOW_CREDENTIALS bool "false" uncommons/net/http CORS Access-Control-Allow-Credentials header value
ACCESS_CONTROL_ALLOW_ORIGIN string "*" uncommons/net/http CORS Access-Control-Allow-Origin header value
ACCESS_CONTROL_ALLOW_METHODS string "POST, GET, OPTIONS, PUT, DELETE, PATCH" uncommons/net/http CORS Access-Control-Allow-Methods header value
ACCESS_CONTROL_ALLOW_HEADERS string "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization" uncommons/net/http CORS Access-Control-Allow-Headers header value
ACCESS_CONTROL_EXPOSE_HEADERS string "" uncommons/net/http CORS Access-Control-Expose-Headers header value

Additionally, uncommons.SetConfigFromEnvVars populates any struct using env:"VAR_NAME" field tags, supporting string, bool, and integer types. Consuming applications define their own variable names through these tags.

Development commands

Core
  • make build -- build all packages
  • make clean -- clean build artifacts and caches
  • make tidy -- clean dependencies (go mod tidy)
  • make format -- format code with gofmt
  • make help -- display all available commands
Testing
  • make test -- run unit tests (uses gotestsum if available)
  • make test-unit -- run unit tests excluding integration
  • make test-integration -- run integration tests with testcontainers (requires Docker)
  • make test-all -- run all tests (unit + integration)
Coverage
  • make coverage-unit -- unit tests with coverage report (respects .ignorecoverunit)
  • make coverage-integration -- integration tests with coverage
  • make coverage -- run all coverage targets
Code quality
  • make lint -- run lint checks (read-only)
  • make lint-fix -- auto-fix lint issues
  • make sec -- run security checks using gosec (make sec SARIF=1 for SARIF output)
  • make check-tests -- verify test coverage for packages
Test flags
  • LOW_RESOURCE=1 -- reduces parallelism and disables race detector for constrained machines
  • RETRY_ON_FAIL=1 -- retries failed tests once
  • RUN=<pattern> -- filter integration tests by name pattern
  • PKG=<path> -- filter to specific package(s)
Git hooks
  • make setup-git-hooks -- install and configure git hooks
  • make check-hooks -- verify git hooks installation
  • make check-envs -- check hooks + environment file security
Tooling and release
  • make tools -- install test tools (gotestsum)
  • make goreleaser -- create release snapshot

Project Rules

For coding standards, architecture patterns, testing requirements, and development guidelines, see docs/PROJECT_RULES.md.

License

This project is licensed under the terms in LICENSE.

Directories

Path Synopsis
Package uncommons provides shared infrastructure helpers used across Lerian services.
Package uncommons provides shared infrastructure helpers used across Lerian services.
assert
Package assert provides always-on runtime assertions for detecting programming bugs.
Package assert provides always-on runtime assertions for detecting programming bugs.
backoff
Package backoff provides retry delay helpers with exponential growth and jitter.
Package backoff provides retry delay helpers with exponential growth and jitter.
circuitbreaker
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.
constants
Package constant provides shared constant values used across the library.
Package constant provides shared constant values used across the library.
cron
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.
crypto
Package crypto provides hashing and symmetric encryption helpers.
Package crypto provides hashing and symmetric encryption helpers.
errgroup
Package errgroup coordinates goroutines that share a cancellation context.
Package errgroup coordinates goroutines that share a cancellation context.
jwt
Package jwt provides minimal HMAC-based JWT signing and verification.
Package jwt provides minimal HMAC-based JWT signing and verification.
license
Package license provides helpers for license validation and management.
Package license provides helpers for license validation and management.
log
Package log defines the v2 logging interface and typed logging fields.
Package log defines the v2 logging interface and typed logging fields.
mongo
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.
net/http/ratelimit
Package ratelimit provides rate-limiting helpers for the HTTP package.
Package ratelimit provides rate-limiting helpers for the HTTP package.
opentelemetry
Package opentelemetry provides tracing, metrics, propagation, and redaction helpers.
Package opentelemetry provides tracing, metrics, propagation, and redaction helpers.
opentelemetry/metrics
Package metrics provides a fluent factory for OpenTelemetry metric instruments.
Package metrics provides a fluent factory for OpenTelemetry metric instruments.
outbox
Package outbox provides transactional outbox primitives.
Package outbox provides transactional outbox primitives.
outbox/postgres
Package postgres provides PostgreSQL adapters for outbox repository contracts.
Package postgres provides PostgreSQL adapters for outbox repository contracts.
pointers
Package pointers provides helpers for pointer creation and conversions.
Package pointers provides helpers for pointer creation and conversions.
postgres
Package postgres provides shared PostgreSQL connection helpers.
Package postgres provides shared PostgreSQL connection helpers.
rabbitmq
Package rabbitmq provides AMQP connection, consumer, and producer helpers.
Package rabbitmq provides AMQP connection, consumer, and producer helpers.
redis
Package redis provides Redis/Valkey client helpers with topology and IAM support.
Package redis provides Redis/Valkey client helpers with topology and IAM support.
runtime
Package runtime provides panic recovery utilities for services with full observability integration.
Package runtime provides panic recovery utilities for services with full observability integration.
safe
Package safe provides panic-free helpers for math, slices, and regex operations.
Package safe provides panic-free helpers for math, slices, and regex operations.
security
Package security provides helpers for handling sensitive fields and data safety.
Package security provides helpers for handling sensitive fields and data safety.
server
Package server provides server lifecycle and graceful shutdown helpers.
Package server provides server lifecycle and graceful shutdown helpers.
transaction
Package transaction provides transaction intent planning and posting validations.
Package transaction provides transaction intent planning and posting validations.
zap
Package zap provides adapters and helpers around zap-based logging.
Package zap provides adapters and helpers around zap-based logging.

Jump to

Keyboard shortcuts

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