-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlambda-handler.js
More file actions
256 lines (214 loc) · 6.77 KB
/
lambda-handler.js
File metadata and controls
256 lines (214 loc) · 6.77 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
/**
* AWS Lambda Handler for Chronas API
*
* This handler provides optimized Lambda integration with connection caching,
* cold start optimization, and proper error handling.
*/
import { configure } from '@vendia/serverless-express';
import debug from 'debug';
import { initializeApp, setupLambdaContext, checkAppHealth } from './config/lambda-app.js';
import { trackColdStart, trackWarmStart, trackLambdaContext, getMetrics } from './config/performance.js';
const debugLog = debug('chronas-api:lambda-handler');
// Force cold start for debugging - v1.0.3 - Fixed serverless-express package version compatibility
// Cached serverless express instance for connection reuse
let serverlessExpressInstance = null;
let appInitialized = false;
/**
* Initialize serverless express instance with caching
*/
async function getServerlessExpressInstance() {
if (serverlessExpressInstance && appInitialized) {
debugLog('Using cached serverless express instance');
return serverlessExpressInstance;
}
try {
debugLog('Initializing serverless express instance...');
// Initialize the application
const appResult = await initializeApp();
if (!appResult || !appResult.app) {
throw new Error('Failed to initialize Express application');
}
// Create serverless express instance
serverlessExpressInstance = configure({
app: appResult.app,
logSettings: {
level: process.env.NODE_ENV === 'development' ? 'debug' : 'warn'
},
// Explicitly configure for API Gateway v2
eventSourceName: 'AWS_API_GATEWAY_V2',
// Lambda-specific optimizations
binaryMimeTypes: [
'application/octet-stream',
'font/eot',
'font/opentype',
'font/otf',
'image/jpeg',
'image/png',
'image/svg+xml'
]
});
appInitialized = true;
// Track cold start performance
trackColdStart(appResult.initTime);
debugLog(`Serverless express instance initialized (init time: ${appResult.initTime}ms)`);
debugLog(`Database connected: ${appResult.dbConnected}`);
return serverlessExpressInstance;
} catch (error) {
debugLog('Failed to initialize serverless express instance:', error.message);
// Reset cached instance on error
serverlessExpressInstance = null;
appInitialized = false;
throw error;
}
}
/**
* Handle warm-up requests
*/
function handleWarmUp(event) {
debugLog('Handling warm-up request');
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'X-Lambda-Warm-Up': 'true'
},
body: JSON.stringify({
message: 'Lambda function warmed up',
timestamp: new Date().toISOString(),
health: checkAppHealth(),
performance: getMetrics()
})
};
}
/**
* Handle health check requests
*/
function handleHealthCheck(event) {
debugLog('Handling health check request');
const health = checkAppHealth();
const statusCode = health.initialized && !health.hasError ? 200 : 503;
return {
statusCode,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
body: JSON.stringify({
status: health.initialized ? 'healthy' : 'unhealthy',
timestamp: new Date().toISOString(),
...health
})
};
}
/**
* Main Lambda handler
*/
export const handler = async (event, context) => {
// Prevent Lambda from waiting for empty event loop
context.callbackWaitsForEmptyEventLoop = false;
const startTime = Date.now();
try {
// Track Lambda context performance
const lambdaPerf = trackLambdaContext(context);
debugLog('Lambda handler invoked', {
httpMethod: event.httpMethod,
path: event.path,
requestId: context.awsRequestId,
remainingTime: lambdaPerf.remainingTime
});
// Track warm start if app is already initialized
if (appInitialized) {
trackWarmStart();
}
// Handle special requests
if (event.source === 'serverless-plugin-warmup' || event.warmup) {
return handleWarmUp(event);
}
if (event.path === '/health/lambda' || event.path === '/lambda-health') {
return handleHealthCheck(event);
}
// Set up Lambda context for the request
const lambdaContext = setupLambdaContext(event, context);
// Get or initialize serverless express instance
const serverlessApp = await getServerlessExpressInstance();
// Add Lambda context to the event for middleware access
event.lambdaContext = lambdaContext;
// Process the request
const response = await serverlessApp(event, context);
const processingTime = Date.now() - startTime;
debugLog(`Request processed in ${processingTime}ms`);
// Add Lambda-specific headers
if (response.headers) {
response.headers['X-Lambda-Request-Id'] = context.awsRequestId;
response.headers['X-Lambda-Processing-Time'] = processingTime.toString();
}
return response;
} catch (error) {
const processingTime = Date.now() - startTime;
debugLog('Lambda handler error:', {
error: error.message,
stack: error.stack,
processingTime,
requestId: context.awsRequestId
});
// Log error for monitoring
console.error('Lambda handler error:', {
message: error.message,
requestId: context.awsRequestId,
path: event.path,
method: event.httpMethod,
processingTime
});
// Return error response
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'X-Lambda-Request-Id': context.awsRequestId,
'X-Lambda-Processing-Time': processingTime.toString(),
'X-Lambda-Error': 'true'
},
body: JSON.stringify({
error: 'Internal Server Error',
message: process.env.NODE_ENV === 'development' ? error.message : 'An error occurred',
requestId: context.awsRequestId,
timestamp: new Date().toISOString()
})
};
}
};
/**
* Health check handler for ALB health checks
*/
export const healthHandler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
const health = checkAppHealth();
return {
statusCode: health.initialized && !health.hasError ? 200 : 503,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: health.initialized ? 'healthy' : 'unhealthy',
timestamp: new Date().toISOString(),
requestId: context.awsRequestId,
...health
})
};
} catch (error) {
return {
statusCode: 503,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
status: 'unhealthy',
error: error.message,
timestamp: new Date().toISOString(),
requestId: context.awsRequestId
})
};
}
};
export default { handler, healthHandler };