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
| // 云原生Lambda函数示例
const AWS = require('aws-sdk');
const { DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb');
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
const { CloudWatchClient, PutMetricDataCommand } = require('@aws-sdk/client-cloudwatch');
// 初始化AWS服务客户端
const dynamoClient = new DynamoDBDocumentClient({});
const s3Client = new S3Client({});
const cloudWatchClient = new CloudWatchClient({});
// 环境变量
const {
TABLE_NAME,
S3_BUCKET_NAME,
REGION,
ENVIRONMENT
} = process.env;
// 主处理函数
exports.handler = async (event, context) => {
try {
// 记录请求开始时间
const startTime = Date.now();
// 解析请求
const { httpMethod, pathParameters, body, headers } = event;
const requestId = context.awsRequestId;
// 构建响应对象
const response = {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'X-Request-ID': requestId
}
};
// 路由处理
switch (httpMethod) {
case 'GET':
if (pathParameters?.id) {
response.body = await handleGetItem(pathParameters.id, requestId);
} else {
response.body = await handleListItems(headers);
}
break;
case 'POST':
response.body = await handleCreateItem(JSON.parse(body), requestId);
response.statusCode = 201;
break;
case 'PUT':
response.body = await handleUpdateItem(
pathParameters.id,
JSON.parse(body),
requestId
);
break;
case 'DELETE':
await handleDeleteItem(pathParameters.id, requestId);
response.statusCode = 204;
response.body = '';
break;
default:
response.statusCode = 405;
response.body = JSON.stringify({ error: 'Method not allowed' });
}
// 记录性能指标
const duration = Date.now() - startTime;
await recordMetrics('APIRequest', duration, response.statusCode);
return response;
} catch (error) {
console.error('Lambda execution error:', error);
// 记录错误指标
await recordErrorMetrics(error);
// 返回错误响应
return {
statusCode: error.statusCode || 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: error.message || 'Internal server error',
requestId: context.awsRequestId
})
};
}
};
// 处理获取单个项目
async function handleGetItem(id, requestId) {
try {
const command = new GetCommand({
TableName: TABLE_NAME,
Key: { id }
});
const result = await dynamoClient.send(command);
if (!result.Item) {
throw {
statusCode: 404,
message: 'Item not found'
};
}
// 记录访问日志
console.log(`Item accessed: ${id}`, {
requestId,
timestamp: new Date().toISOString()
});
return JSON.stringify(result.Item);
} catch (error) {
console.error('Get item error:', error);
throw error;
}
}
// 处理获取项目列表
async function handleListItems(headers) {
try {
// 支持分页和过滤
const limit = parseInt(headers['x-limit']) || 20;
const nextToken = headers['x-next-token'];
const params = {
TableName: TABLE_NAME,
Limit: Math.min(limit, 100)
};
if (nextToken) {
params.ExclusiveStartKey = JSON.parse(Buffer.from(nextToken, 'base64').toString());
}
const command = new ScanCommand(params);
const result = await dynamoClient.send(command);
const response = {
items: result.Items,
count: result.Count
};
if (result.LastEvaluatedKey) {
response.nextToken = Buffer.from(
JSON.stringify(result.LastEvaluatedKey)
).toString('base64');
}
return JSON.stringify(response);
} catch (error) {
console.error('List items error:', error);
throw error;
}
}
// 处理创建项目
async function handleCreateItem(itemData, requestId) {
try {
// 数据验证
if (!itemData.name || !itemData.type) {
throw {
statusCode: 400,
message: 'Missing required fields'
};
}
const item = {
id: generateId(),
...itemData,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
status: 'active',
requestId
};
const command = new PutCommand({
TableName: TABLE_NAME,
Item: item,
ConditionExpression: 'attribute_not_exists(id)'
});
await dynamoClient.send(command);
// 发送事件通知
await publishEvent('item_created', item);
return JSON.stringify(item);
} catch (error) {
console.error('Create item error:', error);
if (error.name === 'ConditionalCheckFailedException') {
throw {
statusCode: 409,
message: 'Item already exists'
};
}
throw error;
}
}
// 处理更新项目
async function handleUpdateItem(id, updateData, requestId) {
try {
const updateExpression = [];
const expressionAttributeNames = {};
const expressionAttributeValues = {};
Object.keys(updateData).forEach(key => {
if (key !== 'id' && key !== 'createdAt') {
updateExpression.push(`#${key} = :${key}`);
expressionAttributeNames[`#${key}`] = key;
expressionAttributeValues[`:${key}`] = updateData[key];
}
});
// 添加更新时间
updateExpression.push('#updatedAt = :updatedAt');
expressionAttributeNames['#updatedAt'] = 'updatedAt';
expressionAttributeValues[':updatedAt'] = new Date().toISOString();
const command = new UpdateCommand({
TableName: TABLE_NAME,
Key: { id },
UpdateExpression: `SET ${updateExpression.join(', ')}`,
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: expressionAttributeValues,
ReturnValues: 'ALL_NEW'
});
const result = await dynamoClient.send(command);
// 发送事件通知
await publishEvent('item_updated', result.Attributes);
return JSON.stringify(result.Attributes);
} catch (error) {
console.error('Update item error:', error);
throw error;
}
}
// 处理删除项目
async function handleDeleteItem(id, requestId) {
try {
const command = new DeleteCommand({
TableName: TABLE_NAME,
Key: { id },
ReturnValues: 'ALL_OLD'
});
const result = await dynamoClient.send(command);
if (!result.Attributes) {
throw {
statusCode: 404,
message: 'Item not found'
};
}
// 归档到S3
await archiveToS3(result.Attributes);
// 发送事件通知
await publishEvent('item_deleted', result.Attributes);
} catch (error) {
console.error('Delete item error:', error);
throw error;
}
}
// 工具函数
function generateId() {
return `item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
// 归档到S3
async function archiveToS3(item) {
const key = `archive/${ENVIRONMENT}/${item.id}.json`;
const command = new PutObjectCommand({
Bucket: S3_BUCKET_NAME,
Key: key,
Body: JSON.stringify(item),
ContentType: 'application/json',
Metadata: {
original-table: TABLE_NAME,
deleted-at: new Date().toISOString()
}
});
await s3Client.send(command);
}
// 发布事件
async function publishEvent(eventType, data) {
const event = {
eventType,
data,
timestamp: new Date().toISOString(),
source: 'cloud-native-app',
environment: ENVIRONMENT
};
// 这里可以集成EventBridge或其他事件总线
console.log('Event published:', event);
}
// 记录性能指标
async function recordMetrics(metricName, value, statusCode) {
const command = new PutMetricDataCommand({
Namespace: 'CloudNativeApp',
MetricData: [
{
MetricName: metricName,
Value: value,
Unit: 'Milliseconds',
Dimensions: [
{
Name: 'Environment',
Value: ENVIRONMENT
},
{
Name: 'StatusCode',
Value: statusCode.toString()
}
]
}
]
});
try {
await cloudWatchClient.send(command);
} catch (error) {
console.error('Failed to record metrics:', error);
}
}
// 记录错误指标
async function recordErrorMetrics(error) {
const command = new PutMetricDataCommand({
Namespace: 'CloudNativeApp',
MetricData: [
{
MetricName: 'Errors',
Value: 1,
Unit: 'Count',
Dimensions: [
{
Name: 'Environment',
Value: ENVIRONMENT
},
{
Name: 'ErrorType',
Value: error.name || 'Unknown'
}
]
}
]
});
try {
await cloudWatchClient.send(command);
} catch (metricsError) {
console.error('Failed to record error metrics:', metricsError);
}
}
|