micro--go-micro
cae6fbbe76
* fix: remove deprecated rand.Seed calls Go 1.20+ automatically seeds the global random number generator. These calls are no-ops and generate warnings with newer Go versions. Removed from: - selector/strategy.go - registry/cache/cache.go - broker/memory.go - broker/http.go - cmd/cmd.go - transport/memory.go Co-authored-by: Shelley <shelley@exe.dev> * fix: handle previously ignored errors - MySQL store: properly handle prepared statement errors in initDB() - Consul registry: handle client creation errors in Client() method These silent failures could cause hard-to-debug issues in production. Co-authored-by: Shelley <shelley@exe.dev> * feat(genai): improve provider interface with context and streaming Breaking changes: - Generate() and Stream() now require context.Context as first parameter - Stream.Close() added for proper resource cleanup Improvements: - Proper context support for cancellation and timeouts - Real SSE streaming for OpenAI and Gemini text generation - Better error handling with wrapped errors and API error responses - Thread-safe provider registry with sync.RWMutex - New options: WithMaxTokens, WithTemperature, WithTimeout - Stream has proper Close() method for cleanup - Results can include Error field for per-chunk errors Provider updates: - OpenAI: true streaming with SSE parsing, proper HTTP client with timeout - Gemini: true streaming with streamGenerateContent endpoint - Default model updated to gpt-4o-mini (OpenAI) and gemini-2.0-flash (Gemini) Co-authored-by: Shelley <shelley@exe.dev> * feat(tls): make TLS secure by default, configurable via environment BREAKING: TLS now verifies certificates by default. Set MICRO_TLS_INSECURE=true to restore previous behavior (NOT recommended for production). Changes: - Add util/tls.Config(), SecureConfig(), InsecureConfig(), ConfigFromEnv() helpers - Update all components to use ConfigFromEnv() instead of hardcoded InsecureSkipVerify - Set MinVersion to TLS 1.2 for all TLS configs Affected components: - broker/http - broker/rabbitmq - registry/etcd - registry/consul - transport/grpc This improves security posture while allowing opt-out for development environments. Co-authored-by: Shelley <shelley@exe.dev> * feat(tls): add TLS helpers with opt-in secure mode NOT a breaking change - keeps InsecureSkipVerify=true as default for local development compatibility. New util/tls helpers: - Config() - returns config based on MICRO_TLS_SECURE env var - SecureConfig() - certificate verification enabled - InsecureConfig() - certificate verification disabled (dev only) For production security, use one of: - Set MICRO_TLS_SECURE=true with proper CA-signed certs - Use a service mesh (Istio, Linkerd) for automatic mTLS - Configure TLSConfig directly with your certificates Also: Changed CLI alias from 'g' to 'gen' for clarity - micro generate handler -> micro gen handler Co-authored-by: Shelley <shelley@exe.dev> * refactor(cli): rename generate directory to gen for consistency Directory name now matches the command alias: cmd/micro/cli/gen/ -> micro gen handler Co-authored-by: Shelley <shelley@exe.dev> --------- Co-authored-by: Shelley <shelley@exe.dev>
Registry Cache
Cache is a library that provides a caching layer for the go-micro registry.
If you're looking for caching in your microservices use the selector.
Features
- Caching: Caches registry lookups with configurable TTL
- Stale Cache Fallback: Returns stale cached data when registry is unavailable
- Singleflight Protection: Deduplicates concurrent requests for the same service
- Adaptive Throttling: Rate limits failed lookups to prevent cache penetration (new in v5)
Interface
// Cache is the registry cache interface
type Cache interface {
// embed the registry interface
registry.Registry
// stop the cache watcher
Stop()
}
Usage
Basic Usage
import (
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/cache"
)
r := registry.NewRegistry()
cache := cache.New(r)
services, _ := cache.GetService("my.service")
Advanced Configuration
import (
"time"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/cache"
)
r := registry.NewRegistry()
// Configure cache with custom options
cache := cache.New(r,
cache.WithTTL(2*time.Minute), // Cache TTL
cache.WithMinimumRetryInterval(10*time.Second), // Throttle failed lookups
)
services, _ := cache.GetService("my.service")
Adaptive Throttling
The cache implements rate limiting on ALL cache refresh attempts (not just errors) to prevent overwhelming the registry. This protects against multiple scenarios:
- Registry failures: When etcd is down/overloaded
- Rolling deployments: When all caches expire simultaneously under high QPS
- Cache expiration storms: When many services expire at once
How It Works
- Rate limiting: Refresh attempts are throttled per-service using
MinimumRetryInterval(default 5s) - Stale cache preference: If stale cache exists (even if expired), return it instead of calling registry
- No cache fallback: If no cache exists, return
ErrNotFoundand rely on gRPC retry - Singleflight deduplication: Concurrent requests are still deduplicated
- Recovery: Throttling is reset on successful registry lookup
Example Scenarios
Scenario 1: Registry Failure with Stale Cache
cache := cache.New(etcdRegistry, cache.WithMinimumRetryInterval(10*time.Second))
// Initial lookup populates cache
services, _ := cache.GetService("api") // → Calls etcd, caches result
// Cache expires after TTL
time.Sleep(2 * time.Minute)
// Etcd fails, but we have stale cache
services, err := cache.GetService("api") // → Returns stale cache WITHOUT calling etcd
// err == nil, services contains stale data
Scenario 2: Rolling Deployment Cache Storm
// Scenario: All 1000 upstream pods watch downstream service
// Downstream does rolling deployment - last pod updated
// All 1000 upstream caches expire simultaneously
// High QPS hits the system at this moment
// First request after cache expiration
services, _ := cache.GetService("downstream") // → Calls etcd, updates lastRefreshAttempt
// Next 999 requests arrive within MinimumRetryInterval
services, _ := cache.GetService("downstream") // → Returns stale cache, NO etcd call
// Rate limiting prevents 999 stampede requests to etcd
Scenario 3: No Cache Available
// First lookup when etcd is down (no cache exists yet)
_, err := cache.GetService("new-service") // → Calls etcd, fails, records attempt time
// err != nil
// Immediate retry (< 10s later, still no cache)
_, err = cache.GetService("new-service") // → Throttled, returns ErrNotFound immediately
// err == ErrNotFound
// After MinimumRetryInterval
time.Sleep(10 * time.Second)
_, err = cache.GetService("new-service") // → Allowed to retry, calls etcd again
This prevents cache penetration scenarios where thousands of concurrent requests hammer a failing or overloaded registry.