-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.go
More file actions
488 lines (422 loc) · 12.9 KB
/
lambda.go
File metadata and controls
488 lines (422 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// lambda.go
package dynamorm
import (
"context"
"fmt"
"log"
"net/http"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/pay-theory/dynamorm/pkg/core"
"github.com/pay-theory/dynamorm/pkg/session"
pkgTypes "github.com/pay-theory/dynamorm/pkg/types"
)
var (
// Global Lambda-optimized DB for connection reuse
globalLambdaDB *LambdaDB
lambdaOnce sync.Once
benchmarkLoadDefaultConfig = config.LoadDefaultConfig
benchmarkNewDynamoDBClient = dynamodb.NewFromConfig
)
// Package dynamorm provides Lambda-specific optimizations for DynamoDB operations.
//
// Best Practices for Lambda:
//
// 1. Initialize globally to reuse connections across invocations:
// var db *dynamorm.LambdaDB
// func init() {
// db, _ = dynamorm.LambdaInit(&User{}, &Post{})
// }
//
// 2. Use context with Lambda timeout:
// func handler(ctx context.Context, event Event) error {
// lambdaDB := db.WithLambdaTimeout(ctx)
// // Use lambdaDB for all operations
// }
//
// 3. Connection Pool Sizing:
// - 128MB-512MB: 5 connections
// - 512MB-1GB: 10 connections
// - 1GB+: 20 connections
//
// 4. Cold Start Optimization:
// - Pre-register all models in init()
// - Use LambdaInit() helper
// - Consider increasing Lambda memory for faster CPU
//
// 5. Monitoring:
// - Use GetMemoryStats() to track memory usage
// - Log cold start metrics in production
// - Monitor DynamoDB throttling
// LambdaDB wraps DB with Lambda-specific optimizations
type LambdaDB struct {
core.ExtendedDB
db *DB
modelCache *sync.Map
lambdaMemoryMB int
isLambda bool
xrayEnabled bool
}
// NewLambdaOptimized creates a Lambda-optimized DB instance
func NewLambdaOptimized() (*LambdaDB, error) {
// Use global instance if available (warm start)
if globalLambdaDB != nil {
return globalLambdaDB, nil
}
var err error
lambdaOnce.Do(func() {
globalLambdaDB, err = createLambdaDB()
})
return globalLambdaDB, err
}
// createLambdaDB creates the actual Lambda DB instance
func createLambdaDB() (*LambdaDB, error) {
// Detect Lambda environment
isLambda := IsLambdaEnvironment()
memoryMB := GetLambdaMemoryMB()
// Create optimized HTTP client for Lambda
httpClient := &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 10,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
DisableKeepAlives: false, // Keep connections alive for reuse
},
}
// Load AWS config with Lambda optimizations
awsConfigOptions := []func(*config.LoadOptions) error{
config.WithRegion(getRegion()),
config.WithHTTPClient(httpClient),
config.WithRetryMode(aws.RetryModeAdaptive),
config.WithRetryMaxAttempts(3),
}
// Enable X-Ray tracing automatically when running in Lambda. The AWS SDK picks up
// X-Ray configuration from the environment, so no explicit setup is required here.
cfg := session.Config{
Region: getRegion(),
MaxRetries: 3,
DefaultRCU: 5,
DefaultWCU: 5,
AutoMigrate: false,
EnableMetrics: isLambda,
AWSConfigOptions: awsConfigOptions,
}
// Optimize DynamoDB client options for Lambda
if isLambda {
cfg.DynamoDBOptions = append(cfg.DynamoDBOptions, func(o *dynamodb.Options) {
// Lambda-specific optimizations
o.RetryMode = aws.RetryModeAdaptive
})
}
db, err := New(cfg)
if err != nil {
return nil, err
}
// Type assert to get the concrete DB
concreteDB, ok := db.(*DB)
if !ok {
return nil, fmt.Errorf("failed to get concrete DB implementation")
}
ldb := &LambdaDB{
ExtendedDB: db,
db: concreteDB,
modelCache: &sync.Map{},
isLambda: isLambda,
lambdaMemoryMB: memoryMB,
xrayEnabled: os.Getenv("_X_AMZN_TRACE_ID") != "",
}
return ldb, nil
}
// PreRegisterModels registers models at init time to reduce cold starts
func (ldb *LambdaDB) PreRegisterModels(models ...any) error {
for _, model := range models {
if err := ldb.db.registry.Register(model); err != nil {
return err
}
// Cache the model type for fast lookup
modelType := reflect.TypeOf(model)
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
}
ldb.modelCache.Store(modelType, true)
}
return nil
}
// RegisterTypeConverter registers a custom converter on the underlying DB and
// clears any cached marshalers so the converter takes effect immediately.
func (ldb *LambdaDB) RegisterTypeConverter(typ reflect.Type, converter pkgTypes.CustomConverter) error {
if ldb == nil || ldb.db == nil {
return fmt.Errorf("lambda DB is not initialized")
}
return ldb.db.RegisterTypeConverter(typ, converter)
}
// IsModelRegistered checks if a model is already registered
func (ldb *LambdaDB) IsModelRegistered(model any) bool {
modelType := reflect.TypeOf(model)
if modelType.Kind() == reflect.Ptr {
modelType = modelType.Elem()
}
_, ok := ldb.modelCache.Load(modelType)
return ok
}
// WithLambdaTimeout creates a new DB instance with Lambda timeout handling
func (ldb *LambdaDB) WithLambdaTimeout(ctx context.Context) *LambdaDB {
deadline, ok := ctx.Deadline()
if !ok {
return ldb
}
// Leave 1 second buffer for Lambda cleanup
adjustedDeadline := deadline.Add(-1 * time.Second)
newDB := &DB{
session: ldb.db.session,
registry: ldb.db.registry,
converter: ldb.db.converter,
marshaler: ldb.db.marshaler,
ctx: ctx,
lambdaDeadline: adjustedDeadline,
}
return &LambdaDB{
ExtendedDB: newDB,
db: newDB,
modelCache: ldb.modelCache, // Share the same model cache pointer
isLambda: ldb.isLambda,
lambdaMemoryMB: ldb.lambdaMemoryMB,
xrayEnabled: ldb.xrayEnabled,
}
}
// OptimizeForMemory adjusts internal buffers based on available Lambda memory
func (ldb *LambdaDB) OptimizeForMemory() {
// Adjust batch sizes based on memory
memoryMB := ldb.lambdaMemoryMB
if memoryMB == 0 {
memoryMB = 512 // Default
}
// Scale timeout buffers with available memory
buffer := 100 * time.Millisecond
if memoryMB >= 2048 {
buffer = 50 * time.Millisecond
} else if memoryMB <= 512 {
buffer = 200 * time.Millisecond
}
if ldb.db != nil {
ldb.db.lambdaTimeoutBuffer = buffer
}
}
// OptimizeForColdStart reduces Lambda cold start time
func (ldb *LambdaDB) OptimizeForColdStart() {
// Pre-warm the connection pool
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("dynamorm: lambda pre-warm encountered panic: %v", r)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
// Perform a lightweight operation to establish connection
client, err := ldb.db.session.Client()
if err != nil {
// Connection pre-warming failed, but we continue normally
return
}
_, err = client.ListTables(ctx, &dynamodb.ListTablesInput{
Limit: aws.Int32(1),
})
if err != nil {
return
}
}()
// Pre-compile common expressions if using a query builder
if ldb.isLambda {
// Initialize expression builder cache
_ = ldb.Model(struct{}{})
}
}
// GetMemoryStats returns current memory usage statistics
func (ldb *LambdaDB) GetMemoryStats() LambdaMemoryStats {
var m runtime.MemStats
runtime.ReadMemStats(&m)
return LambdaMemoryStats{
Alloc: m.Alloc,
TotalAlloc: m.TotalAlloc,
Sys: m.Sys,
NumGC: m.NumGC,
AllocatedMB: float64(m.Alloc) / 1024 / 1024,
SystemMB: float64(m.Sys) / 1024 / 1024,
LambdaMemoryMB: ldb.lambdaMemoryMB,
MemoryPercent: (float64(m.Sys) / 1024 / 1024) / float64(ldb.lambdaMemoryMB) * 100,
}
}
// LambdaMemoryStats contains memory usage information
type LambdaMemoryStats struct {
Alloc uint64 // Bytes allocated and still in use
TotalAlloc uint64 // Bytes allocated (even if freed)
Sys uint64 // Bytes obtained from system
NumGC uint32 // Number of GC cycles
AllocatedMB float64 // MB currently allocated
SystemMB float64 // MB obtained from system
LambdaMemoryMB int // Total Lambda memory allocation
MemoryPercent float64 // Percentage of Lambda memory used
}
// Lambda environment helper functions
// IsLambdaEnvironment detects if running in AWS Lambda
func IsLambdaEnvironment() bool {
return os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != ""
}
// GetLambdaMemoryMB returns the allocated memory in MB
func GetLambdaMemoryMB() int {
memStr := os.Getenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")
if memStr == "" {
return 0
}
mem, err := strconv.Atoi(memStr)
if err != nil {
return 0
}
return mem
}
// EnableXRayTracing enables AWS X-Ray tracing for DynamoDB calls
func EnableXRayTracing() bool {
return os.Getenv("_X_AMZN_TRACE_ID") != ""
}
// getRegion returns the AWS region from environment
func getRegion() string {
if region := os.Getenv("AWS_REGION"); region != "" {
return region
}
// Fallback to default region
return "us-east-1"
}
// GetRemainingTimeMillis returns milliseconds until Lambda timeout
func GetRemainingTimeMillis(ctx context.Context) int64 {
deadline, ok := ctx.Deadline()
if !ok {
return -1
}
remaining := time.Until(deadline)
return remaining.Milliseconds()
}
// LambdaInit should be called in the init() function of your Lambda handler
// It performs one-time initialization to reduce cold start latency
func LambdaInit(models ...any) (*LambdaDB, error) {
// Create Lambda-optimized DB
db, err := NewLambdaOptimized()
if err != nil {
return nil, err
}
// Pre-register models
if len(models) > 0 {
if err := db.PreRegisterModels(models...); err != nil {
return nil, err
}
}
// Optimize for cold start
db.OptimizeForColdStart()
// Optimize based on Lambda memory
db.OptimizeForMemory() // Uses auto-detected memory
return db, nil
}
// BenchmarkColdStart measures cold start performance
func BenchmarkColdStart(models ...any) ColdStartMetrics {
start := time.Now()
// Track initialization phases
phases := make(map[string]time.Duration)
// Phase 1: AWS Config
phaseStart := time.Now()
cfg, err := benchmarkLoadDefaultConfig(context.Background())
phases["aws_config"] = time.Since(phaseStart)
if err != nil {
// If config loading fails, still track it but with error
phases["aws_config_error"] = time.Since(phaseStart)
return ColdStartMetrics{
TotalDuration: time.Since(start),
Phases: phases,
MemoryMB: GetLambdaMemoryMB(),
IsLambda: IsLambdaEnvironment(),
}
}
// Phase 2: DynamoDB Client
phaseStart = time.Now()
client := benchmarkNewDynamoDBClient(cfg)
phases["dynamodb_client"] = time.Since(phaseStart)
// Phase 3: DynamORM Setup
phaseStart = time.Now()
db, err := NewLambdaOptimized()
phases["dynamorm_setup"] = time.Since(phaseStart)
if err != nil {
phases["dynamorm_setup_error"] = phases["dynamorm_setup"]
return ColdStartMetrics{
TotalDuration: time.Since(start),
Phases: phases,
MemoryMB: GetLambdaMemoryMB(),
IsLambda: IsLambdaEnvironment(),
}
}
// Phase 4: Model Registration
if len(models) > 0 {
phaseStart = time.Now()
if err := db.PreRegisterModels(models...); err != nil {
// If model registration fails, still track it but with error
phases["model_registration_error"] = time.Since(phaseStart)
return ColdStartMetrics{
TotalDuration: time.Since(start),
Phases: phases,
MemoryMB: GetLambdaMemoryMB(),
IsLambda: IsLambdaEnvironment(),
}
}
phases["model_registration"] = time.Since(phaseStart)
}
// Phase 5: First Query (connection establishment)
phaseStart = time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if _, err := client.ListTables(ctx, &dynamodb.ListTablesInput{Limit: aws.Int32(1)}); err != nil {
duration := time.Since(phaseStart)
phases["first_connection_error"] = duration
phases["first_connection"] = duration
} else {
phases["first_connection"] = time.Since(phaseStart)
}
totalDuration := time.Since(start)
return ColdStartMetrics{
TotalDuration: totalDuration,
Phases: phases,
MemoryMB: GetLambdaMemoryMB(),
IsLambda: IsLambdaEnvironment(),
}
}
// ColdStartMetrics contains cold start performance data
type ColdStartMetrics struct {
Phases map[string]time.Duration
TotalDuration time.Duration
MemoryMB int
IsLambda bool
}
// String returns a formatted string of the metrics
func (m ColdStartMetrics) String() string {
var result strings.Builder
result.WriteString(fmt.Sprintf("Cold Start Metrics (Total: %v)\n", m.TotalDuration))
result.WriteString(fmt.Sprintf("Lambda Memory: %d MB\n", m.MemoryMB))
result.WriteString("Phases:\n")
// Sort phases for consistent output
phases := make([]string, 0, len(m.Phases))
for phase := range m.Phases {
phases = append(phases, phase)
}
sort.Strings(phases)
for _, phase := range phases {
result.WriteString(fmt.Sprintf(" %s: %v\n", phase, m.Phases[phase]))
}
return result.String()
}