@gugananuvem/aws-local-simulator 1.0.31 → 1.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +834 -834
- package/aws-config +153 -153
- package/bin/aws-local-simulator.js +63 -63
- package/package.json +3 -2
- package/src/config/config-loader.js +114 -114
- package/src/config/default-config.js +79 -79
- package/src/config/env-loader.js +68 -68
- package/src/index.js +146 -146
- package/src/index.mjs +123 -123
- package/src/server.js +463 -463
- package/src/services/apigateway/index.js +75 -75
- package/src/services/apigateway/server.js +607 -607
- package/src/services/apigateway/simulator.js +1405 -1405
- package/src/services/athena/index.js +75 -75
- package/src/services/athena/server.js +101 -101
- package/src/services/athena/simulador.js +998 -998
- package/src/services/athena/simulator.js +346 -346
- package/src/services/cloudformation/index.js +106 -106
- package/src/services/cloudformation/server.js +417 -417
- package/src/services/cloudformation/simulador.js +1020 -1020
- package/src/services/cloudtrail/index.js +84 -84
- package/src/services/cloudtrail/server.js +235 -235
- package/src/services/cloudtrail/simulador.js +719 -719
- package/src/services/cloudwatch/index.js +84 -84
- package/src/services/cloudwatch/server.js +366 -366
- package/src/services/cloudwatch/simulador.js +1173 -1173
- package/src/services/cognito/index.js +79 -79
- package/src/services/cognito/server.js +297 -297
- package/src/services/cognito/simulator.js +1992 -1761
- package/src/services/config/index.js +96 -96
- package/src/services/config/server.js +215 -215
- package/src/services/config/simulador.js +1260 -1260
- package/src/services/dynamodb/index.js +74 -74
- package/src/services/dynamodb/server.js +139 -139
- package/src/services/dynamodb/simulator.js +1005 -982
- package/src/services/dynamodb/sqlite-store.js +722 -0
- package/src/services/ecs/index.js +65 -65
- package/src/services/ecs/server.js +235 -235
- package/src/services/ecs/simulator.js +844 -844
- package/src/services/eventbridge/index.js +89 -89
- package/src/services/eventbridge/server.js +209 -209
- package/src/services/eventbridge/simulator.js +684 -684
- package/src/services/index.js +45 -45
- package/src/services/kms/index.js +75 -75
- package/src/services/kms/server.js +81 -81
- package/src/services/kms/simulator.js +344 -344
- package/src/services/lambda/handler-loader.js +183 -183
- package/src/services/lambda/index.js +81 -81
- package/src/services/lambda/route-registry.js +274 -274
- package/src/services/lambda/server.js +191 -191
- package/src/services/lambda/simulator.js +364 -364
- package/src/services/parameter-store/index.js +80 -80
- package/src/services/parameter-store/server.js +50 -50
- package/src/services/parameter-store/simulator.js +201 -201
- package/src/services/s3/index.js +73 -73
- package/src/services/s3/server.js +350 -350
- package/src/services/s3/simulator.js +568 -568
- package/src/services/secret-manager/index.js +80 -80
- package/src/services/secret-manager/server.js +51 -51
- package/src/services/secret-manager/simulator.js +182 -182
- package/src/services/sns/index.js +89 -89
- package/src/services/sns/server.js +607 -607
- package/src/services/sns/simulator.js +1482 -1482
- package/src/services/sqs/index.js +98 -98
- package/src/services/sqs/server.js +360 -360
- package/src/services/sqs/simulator.js +509 -509
- package/src/services/sts/index.js +37 -37
- package/src/services/sts/server.js +144 -144
- package/src/services/sts/simulator.js +69 -69
- package/src/services/xray/index.js +83 -83
- package/src/services/xray/server.js +308 -308
- package/src/services/xray/simulador.js +994 -994
- package/src/template/aws-config-template.js +87 -87
- package/src/template/aws-config-template.mjs +90 -90
- package/src/template/config-template.json +203 -203
- package/src/utils/aws-config.js +91 -91
- package/src/utils/cloudtrail-audit.js +129 -129
- package/src/utils/local-store.js +83 -83
- package/src/utils/logger.js +59 -59
|
@@ -1,364 +1,364 @@
|
|
|
1
|
-
const LocalStore = require("../../utils/local-store");
|
|
2
|
-
const path = require("path");
|
|
3
|
-
const fs = require("fs");
|
|
4
|
-
const HandlerLoader = require("./handler-loader");
|
|
5
|
-
const logger = require("../../utils/logger");
|
|
6
|
-
const { CloudTrailAudit } = require("../../utils/cloudtrail-audit");
|
|
7
|
-
|
|
8
|
-
class LambdaSimulator {
|
|
9
|
-
constructor(config) {
|
|
10
|
-
this.config = config;
|
|
11
|
-
this.dataDir = path.join(process.env.AWS_LOCAL_SIMULATOR_DATA_DIR, "lambda");
|
|
12
|
-
this.store = new LocalStore(this.dataDir);
|
|
13
|
-
this.lambdas = new Map(); // functionName -> { handler, env, config }
|
|
14
|
-
this.environment = { ...process.env };
|
|
15
|
-
this.audit = new CloudTrailAudit("lambda.amazonaws.com");
|
|
16
|
-
this.cloudwatchSimulator = null; // injected via injectDependencies
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
async initialize() {
|
|
20
|
-
logger.debug("Inicializando Lambda Simulator...");
|
|
21
|
-
|
|
22
|
-
// Build global lambda defaults from config.global
|
|
23
|
-
const globalDefaults = this.config.global || {};
|
|
24
|
-
this.globalEnv = globalDefaults.env || {};
|
|
25
|
-
this.globalTimeout = globalDefaults.timeout || null;
|
|
26
|
-
this.globalMemorySize = globalDefaults.memorySize || null;
|
|
27
|
-
|
|
28
|
-
// Carrega do config.lambdas (fixo)
|
|
29
|
-
if (this.config.lambdas && this.config.lambdas.length > 0) {
|
|
30
|
-
for (const lambdaConfig of this.config.lambdas) {
|
|
31
|
-
await this.registerLambda(lambdaConfig);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// Carrega lambdas dinâmicas do disco
|
|
36
|
-
const savedLambdas = this.store.read("__functions__");
|
|
37
|
-
if (savedLambdas && Array.isArray(savedLambdas)) {
|
|
38
|
-
for (const lambdaConfig of savedLambdas) {
|
|
39
|
-
if (!this.lambdas.has(lambdaConfig.name)) {
|
|
40
|
-
await this.registerLambda(lambdaConfig);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
logger.debug(`✅ ${this.lambdas.size} Lambdas registradas`);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
async registerLambda(lambdaConfig) {
|
|
50
|
-
try {
|
|
51
|
-
const { name, handler: handlerPath, type = "auto" } = lambdaConfig;
|
|
52
|
-
|
|
53
|
-
if (!name) {
|
|
54
|
-
logger.warn(`Lambda sem nome ignorada: ${JSON.stringify(lambdaConfig)}`);
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Merge: global env as base, lambda-specific env overrides
|
|
59
|
-
const env = {
|
|
60
|
-
...(this.globalEnv || {}),
|
|
61
|
-
...(lambdaConfig.env || {}),
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
const timeout = lambdaConfig.timeout ?? this.globalTimeout ?? 30;
|
|
65
|
-
const memorySize = lambdaConfig.memorySize ?? this.globalMemorySize ?? 128;
|
|
66
|
-
|
|
67
|
-
const handler = await HandlerLoader.load(handlerPath, type);
|
|
68
|
-
let codeSize = 0;
|
|
69
|
-
try {
|
|
70
|
-
const info = await HandlerLoader.getInfo(handlerPath);
|
|
71
|
-
codeSize = info.size;
|
|
72
|
-
} catch (err) {
|
|
73
|
-
// Ignore size errors
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
if (handler != undefined) {
|
|
77
|
-
this.lambdas.set(name, {
|
|
78
|
-
name,
|
|
79
|
-
handler,
|
|
80
|
-
handlerPath,
|
|
81
|
-
handlerName: handler.name || "anonymous",
|
|
82
|
-
env,
|
|
83
|
-
timeout,
|
|
84
|
-
memorySize,
|
|
85
|
-
codeSize,
|
|
86
|
-
type,
|
|
87
|
-
registeredAt: new Date().toISOString(),
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
logger.debug(`✅ Lambda registrada: ${name} -> ${handlerPath}`);
|
|
91
|
-
} catch (error) {
|
|
92
|
-
if (error.message.indexOf("Handler não encontrado") == -1){
|
|
93
|
-
logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`, error);
|
|
94
|
-
throw error;
|
|
95
|
-
}else{
|
|
96
|
-
logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async invoke(functionName, event, invocationType = "RequestResponse") {
|
|
102
|
-
const lambda = this.lambdas.get(functionName);
|
|
103
|
-
|
|
104
|
-
if (!lambda) {
|
|
105
|
-
throw new Error(`Function not found: ${functionName}`);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
this.applyEnvironment(lambda.env);
|
|
109
|
-
logger.debug(`🎯 Invocando Lambda: ${functionName}`);
|
|
110
|
-
|
|
111
|
-
if (invocationType === "Event") {
|
|
112
|
-
this.executeHandler(lambda, functionName, event).catch((err) => logger.error(`❌ Async Lambda error (${functionName}):`, err));
|
|
113
|
-
return { StatusCode: 202 };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
let result;
|
|
117
|
-
try {
|
|
118
|
-
result = await this.executeHandler(lambda, functionName, event);
|
|
119
|
-
} catch (error) {
|
|
120
|
-
logger.error(`❌ Lambda handler error (${functionName}):`, error);
|
|
121
|
-
throw error;
|
|
122
|
-
}
|
|
123
|
-
this.audit.record({
|
|
124
|
-
eventName: "Invoke",
|
|
125
|
-
readOnly: false,
|
|
126
|
-
resources: [{ ARN: `arn:aws:lambda:local:000000000000:function:${functionName}`, type: "AWS::Lambda::Function" }],
|
|
127
|
-
requestParameters: { functionName, invocationType },
|
|
128
|
-
});
|
|
129
|
-
return { StatusCode: result.statusCode || 200, Payload: result };
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
async executeHandler(lambda, functionName, event) {
|
|
133
|
-
const requestId = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
|
|
134
|
-
const capturedLogs = [];
|
|
135
|
-
|
|
136
|
-
const context = this.createContext(functionName, requestId);
|
|
137
|
-
|
|
138
|
-
// Intercept console output during handler execution
|
|
139
|
-
const origLog = console.log;
|
|
140
|
-
const origError = console.error;
|
|
141
|
-
const origWarn = console.warn;
|
|
142
|
-
const origInfo = console.info;
|
|
143
|
-
|
|
144
|
-
const capture = (...args) => {
|
|
145
|
-
const line = args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ');
|
|
146
|
-
capturedLogs.push(line);
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
console.log = (...args) => { capture(...args); origLog(...args); };
|
|
150
|
-
console.error = (...args) => { capture(`[ERROR] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origError(...args); };
|
|
151
|
-
console.warn = (...args) => { capture(`[WARN] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origWarn(...args); };
|
|
152
|
-
console.info = (...args) => { capture(`[INFO] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origInfo(...args); };
|
|
153
|
-
|
|
154
|
-
let result;
|
|
155
|
-
let execError;
|
|
156
|
-
try {
|
|
157
|
-
result = await lambda.handler(event, context);
|
|
158
|
-
} catch (err) {
|
|
159
|
-
execError = err;
|
|
160
|
-
capturedLogs.push(`[ERROR] ${err.message}`);
|
|
161
|
-
} finally {
|
|
162
|
-
console.log = origLog;
|
|
163
|
-
console.error = origError;
|
|
164
|
-
console.warn = origWarn;
|
|
165
|
-
console.info = origInfo;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Send logs to CloudWatch asynchronously (non-blocking)
|
|
169
|
-
if (this.cloudwatchSimulator) {
|
|
170
|
-
this.cloudwatchSimulator
|
|
171
|
-
.putLambdaLogs(functionName, requestId, capturedLogs)
|
|
172
|
-
.catch((err) => logger.debug(`[CloudWatch] Failed to store Lambda logs: ${err.message}`));
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
if (execError) throw execError;
|
|
176
|
-
return result;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
createContext(functionName = "local-lambda", requestId = null) {
|
|
180
|
-
const reqId = requestId || Math.random().toString(36).substring(2, 18);
|
|
181
|
-
return {
|
|
182
|
-
awsRequestId: reqId,
|
|
183
|
-
functionName,
|
|
184
|
-
functionVersion: "$LATEST",
|
|
185
|
-
invokedFunctionArn: `arn:aws:lambda:local:000000000000:function:${functionName}`,
|
|
186
|
-
memoryLimitInMB: "1024",
|
|
187
|
-
logGroupName: `/aws/lambda/${functionName}`,
|
|
188
|
-
logStreamName: `${new Date().toISOString().slice(0, 10).replace(/-/g, '/')}/${reqId.slice(0, 8)}`,
|
|
189
|
-
getRemainingTimeInMillis: () => 30000,
|
|
190
|
-
callbackWaitsForEmptyEventLoop: true,
|
|
191
|
-
identity: null,
|
|
192
|
-
clientContext: null,
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
applyEnvironment(env) {
|
|
197
|
-
for (const [key, value] of Object.entries(env)) {
|
|
198
|
-
process.env[key] = value;
|
|
199
|
-
this.environment[key] = value;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
setEnvironmentVariable(key, value) {
|
|
204
|
-
process.env[key] = value;
|
|
205
|
-
this.environment[key] = value;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
getEnvironmentVariables() {
|
|
209
|
-
return { ...this.environment };
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
listLambdas() {
|
|
213
|
-
return Array.from(this.lambdas.values()).map((l) => {
|
|
214
|
-
let code = "";
|
|
215
|
-
try {
|
|
216
|
-
if (fs.existsSync(l.handlerPath)) {
|
|
217
|
-
code = fs.readFileSync(l.handlerPath, "utf8");
|
|
218
|
-
}
|
|
219
|
-
} catch (err) {
|
|
220
|
-
logger.error(`Erro ao ler código da lambda ${l.name}:`, err);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
return {
|
|
224
|
-
name: l.name,
|
|
225
|
-
handlerName: l.handlerName,
|
|
226
|
-
handlerPath: l.handlerPath,
|
|
227
|
-
type: l.type,
|
|
228
|
-
env: l.env,
|
|
229
|
-
timeout: l.timeout,
|
|
230
|
-
memorySize: l.memorySize,
|
|
231
|
-
codeSize: l.codeSize,
|
|
232
|
-
registeredAt: l.registeredAt,
|
|
233
|
-
code: code
|
|
234
|
-
};
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
getLambda(name) {
|
|
240
|
-
return this.lambdas.get(name);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
getLambdasCount() {
|
|
244
|
-
return this.lambdas.size;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
async reloadLambdas() {
|
|
248
|
-
logger.info("🔄 Recarregando Lambdas...");
|
|
249
|
-
|
|
250
|
-
for (const [name, lambda] of this.lambdas.entries()) {
|
|
251
|
-
try {
|
|
252
|
-
const newHandler = await HandlerLoader.reload(lambda.handlerPath, lambda.type);
|
|
253
|
-
lambda.handler = newHandler;
|
|
254
|
-
lambda.handlerName = newHandler.name || "anonymous";
|
|
255
|
-
logger.debug(`✅ Lambda recarregada: ${name}`);
|
|
256
|
-
} catch (error) {
|
|
257
|
-
logger.error(`❌ Erro ao recarregar Lambda ${name}:`, error);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
logger.info(`✅ ${this.lambdas.size} Lambdas recarregadas`);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
async createFunction(lambdaConfig) {
|
|
265
|
-
const { name, code, runtime, handler, timeout, memorySize, environment } = lambdaConfig;
|
|
266
|
-
|
|
267
|
-
if (!name) throw new Error("Function name is required");
|
|
268
|
-
|
|
269
|
-
// Define o caminho do arquivo (dentro do dataDir/functions)
|
|
270
|
-
const functionsDir = path.join(this.dataDir, "functions");
|
|
271
|
-
if (!fs.existsSync(functionsDir)) fs.mkdirSync(functionsDir, { recursive: true });
|
|
272
|
-
|
|
273
|
-
const fileName = `${name}.js`;
|
|
274
|
-
const filePath = path.join(functionsDir, fileName);
|
|
275
|
-
|
|
276
|
-
// Salva o código no disco
|
|
277
|
-
fs.writeFileSync(filePath, code || "// Hello Lambda");
|
|
278
|
-
|
|
279
|
-
// Registra a lambda
|
|
280
|
-
const config = {
|
|
281
|
-
name,
|
|
282
|
-
handler: filePath,
|
|
283
|
-
runtime: runtime || "nodejs18.x",
|
|
284
|
-
timeout: timeout || 30,
|
|
285
|
-
memorySize: memorySize || 128,
|
|
286
|
-
env: environment || {},
|
|
287
|
-
type: "commonjs"
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
await this.registerLambda(config);
|
|
291
|
-
this.persistLambdas();
|
|
292
|
-
|
|
293
|
-
return this.lambdas.get(name);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
async updateFunction(name, lambdaConfig) {
|
|
297
|
-
const lambda = this.lambdas.get(name);
|
|
298
|
-
if (!lambda) throw new Error(`Function not found: ${name}`);
|
|
299
|
-
|
|
300
|
-
const { code, runtime, handler, timeout, memorySize, environment } = lambdaConfig;
|
|
301
|
-
|
|
302
|
-
// Se houver código novo, sobrescreve o arquivo
|
|
303
|
-
if (code !== undefined) {
|
|
304
|
-
fs.writeFileSync(lambda.handlerPath, code);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// Atualiza a configuração
|
|
308
|
-
const updatedConfig = {
|
|
309
|
-
name,
|
|
310
|
-
handler: lambda.handlerPath,
|
|
311
|
-
runtime: runtime || lambda.runtime,
|
|
312
|
-
timeout: timeout || lambda.timeout,
|
|
313
|
-
memorySize: memorySize || lambda.memorySize,
|
|
314
|
-
env: environment || lambda.env,
|
|
315
|
-
type: lambda.type
|
|
316
|
-
};
|
|
317
|
-
|
|
318
|
-
await this.registerLambda(updatedConfig);
|
|
319
|
-
this.persistLambdas();
|
|
320
|
-
|
|
321
|
-
return this.lambdas.get(name);
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
async deleteFunction(name) {
|
|
325
|
-
|
|
326
|
-
if (this.lambdas.has(name)) {
|
|
327
|
-
this.lambdas.delete(name);
|
|
328
|
-
this.persistLambdas();
|
|
329
|
-
return true;
|
|
330
|
-
}
|
|
331
|
-
return false;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
persistLambdas() {
|
|
335
|
-
const functionsToSave = Array.from(this.lambdas.values())
|
|
336
|
-
.filter(l => l.handlerPath.includes(this.dataDir)) // Apenas as dinâmicas
|
|
337
|
-
.map(l => ({
|
|
338
|
-
name: l.name,
|
|
339
|
-
handler: l.handlerPath,
|
|
340
|
-
type: l.type,
|
|
341
|
-
env: l.env,
|
|
342
|
-
timeout: l.timeout,
|
|
343
|
-
memorySize: l.memorySize,
|
|
344
|
-
}));
|
|
345
|
-
|
|
346
|
-
this.store.write("__functions__", functionsToSave);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
getStats() {
|
|
350
|
-
return {
|
|
351
|
-
totalLambdas: this.lambdas.size,
|
|
352
|
-
lambdas: this.listLambdas().map((l) => ({ name: l.name, handler: l.handlerName })),
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
async reset() {
|
|
358
|
-
await this.reloadLambdas();
|
|
359
|
-
this.environment = { ...process.env };
|
|
360
|
-
logger.debug("Lambda: Estado resetado");
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
module.exports = LambdaSimulator;
|
|
1
|
+
const LocalStore = require("../../utils/local-store");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const HandlerLoader = require("./handler-loader");
|
|
5
|
+
const logger = require("../../utils/logger");
|
|
6
|
+
const { CloudTrailAudit } = require("../../utils/cloudtrail-audit");
|
|
7
|
+
|
|
8
|
+
class LambdaSimulator {
|
|
9
|
+
constructor(config) {
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.dataDir = path.join(process.env.AWS_LOCAL_SIMULATOR_DATA_DIR, "lambda");
|
|
12
|
+
this.store = new LocalStore(this.dataDir);
|
|
13
|
+
this.lambdas = new Map(); // functionName -> { handler, env, config }
|
|
14
|
+
this.environment = { ...process.env };
|
|
15
|
+
this.audit = new CloudTrailAudit("lambda.amazonaws.com");
|
|
16
|
+
this.cloudwatchSimulator = null; // injected via injectDependencies
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async initialize() {
|
|
20
|
+
logger.debug("Inicializando Lambda Simulator...");
|
|
21
|
+
|
|
22
|
+
// Build global lambda defaults from config.global
|
|
23
|
+
const globalDefaults = this.config.global || {};
|
|
24
|
+
this.globalEnv = globalDefaults.env || {};
|
|
25
|
+
this.globalTimeout = globalDefaults.timeout || null;
|
|
26
|
+
this.globalMemorySize = globalDefaults.memorySize || null;
|
|
27
|
+
|
|
28
|
+
// Carrega do config.lambdas (fixo)
|
|
29
|
+
if (this.config.lambdas && this.config.lambdas.length > 0) {
|
|
30
|
+
for (const lambdaConfig of this.config.lambdas) {
|
|
31
|
+
await this.registerLambda(lambdaConfig);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Carrega lambdas dinâmicas do disco
|
|
36
|
+
const savedLambdas = this.store.read("__functions__");
|
|
37
|
+
if (savedLambdas && Array.isArray(savedLambdas)) {
|
|
38
|
+
for (const lambdaConfig of savedLambdas) {
|
|
39
|
+
if (!this.lambdas.has(lambdaConfig.name)) {
|
|
40
|
+
await this.registerLambda(lambdaConfig);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
logger.debug(`✅ ${this.lambdas.size} Lambdas registradas`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async registerLambda(lambdaConfig) {
|
|
50
|
+
try {
|
|
51
|
+
const { name, handler: handlerPath, type = "auto" } = lambdaConfig;
|
|
52
|
+
|
|
53
|
+
if (!name) {
|
|
54
|
+
logger.warn(`Lambda sem nome ignorada: ${JSON.stringify(lambdaConfig)}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Merge: global env as base, lambda-specific env overrides
|
|
59
|
+
const env = {
|
|
60
|
+
...(this.globalEnv || {}),
|
|
61
|
+
...(lambdaConfig.env || {}),
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const timeout = lambdaConfig.timeout ?? this.globalTimeout ?? 30;
|
|
65
|
+
const memorySize = lambdaConfig.memorySize ?? this.globalMemorySize ?? 128;
|
|
66
|
+
|
|
67
|
+
const handler = await HandlerLoader.load(handlerPath, type);
|
|
68
|
+
let codeSize = 0;
|
|
69
|
+
try {
|
|
70
|
+
const info = await HandlerLoader.getInfo(handlerPath);
|
|
71
|
+
codeSize = info.size;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
// Ignore size errors
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (handler != undefined) {
|
|
77
|
+
this.lambdas.set(name, {
|
|
78
|
+
name,
|
|
79
|
+
handler,
|
|
80
|
+
handlerPath,
|
|
81
|
+
handlerName: handler.name || "anonymous",
|
|
82
|
+
env,
|
|
83
|
+
timeout,
|
|
84
|
+
memorySize,
|
|
85
|
+
codeSize,
|
|
86
|
+
type,
|
|
87
|
+
registeredAt: new Date().toISOString(),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
logger.debug(`✅ Lambda registrada: ${name} -> ${handlerPath}`);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.message.indexOf("Handler não encontrado") == -1){
|
|
93
|
+
logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`, error);
|
|
94
|
+
throw error;
|
|
95
|
+
}else{
|
|
96
|
+
logger.error(`Erro ao registrar Lambda ${lambdaConfig.name}:`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async invoke(functionName, event, invocationType = "RequestResponse") {
|
|
102
|
+
const lambda = this.lambdas.get(functionName);
|
|
103
|
+
|
|
104
|
+
if (!lambda) {
|
|
105
|
+
throw new Error(`Function not found: ${functionName}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
this.applyEnvironment(lambda.env);
|
|
109
|
+
logger.debug(`🎯 Invocando Lambda: ${functionName}`);
|
|
110
|
+
|
|
111
|
+
if (invocationType === "Event") {
|
|
112
|
+
this.executeHandler(lambda, functionName, event).catch((err) => logger.error(`❌ Async Lambda error (${functionName}):`, err));
|
|
113
|
+
return { StatusCode: 202 };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let result;
|
|
117
|
+
try {
|
|
118
|
+
result = await this.executeHandler(lambda, functionName, event);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
logger.error(`❌ Lambda handler error (${functionName}):`, error);
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
this.audit.record({
|
|
124
|
+
eventName: "Invoke",
|
|
125
|
+
readOnly: false,
|
|
126
|
+
resources: [{ ARN: `arn:aws:lambda:local:000000000000:function:${functionName}`, type: "AWS::Lambda::Function" }],
|
|
127
|
+
requestParameters: { functionName, invocationType },
|
|
128
|
+
});
|
|
129
|
+
return { StatusCode: result.statusCode || 200, Payload: result };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async executeHandler(lambda, functionName, event) {
|
|
133
|
+
const requestId = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
|
|
134
|
+
const capturedLogs = [];
|
|
135
|
+
|
|
136
|
+
const context = this.createContext(functionName, requestId);
|
|
137
|
+
|
|
138
|
+
// Intercept console output during handler execution
|
|
139
|
+
const origLog = console.log;
|
|
140
|
+
const origError = console.error;
|
|
141
|
+
const origWarn = console.warn;
|
|
142
|
+
const origInfo = console.info;
|
|
143
|
+
|
|
144
|
+
const capture = (...args) => {
|
|
145
|
+
const line = args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ');
|
|
146
|
+
capturedLogs.push(line);
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
console.log = (...args) => { capture(...args); origLog(...args); };
|
|
150
|
+
console.error = (...args) => { capture(`[ERROR] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origError(...args); };
|
|
151
|
+
console.warn = (...args) => { capture(`[WARN] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origWarn(...args); };
|
|
152
|
+
console.info = (...args) => { capture(`[INFO] ${args.map(a => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ')}`); origInfo(...args); };
|
|
153
|
+
|
|
154
|
+
let result;
|
|
155
|
+
let execError;
|
|
156
|
+
try {
|
|
157
|
+
result = await lambda.handler(event, context);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
execError = err;
|
|
160
|
+
capturedLogs.push(`[ERROR] ${err.message}`);
|
|
161
|
+
} finally {
|
|
162
|
+
console.log = origLog;
|
|
163
|
+
console.error = origError;
|
|
164
|
+
console.warn = origWarn;
|
|
165
|
+
console.info = origInfo;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Send logs to CloudWatch asynchronously (non-blocking)
|
|
169
|
+
if (this.cloudwatchSimulator) {
|
|
170
|
+
this.cloudwatchSimulator
|
|
171
|
+
.putLambdaLogs(functionName, requestId, capturedLogs)
|
|
172
|
+
.catch((err) => logger.debug(`[CloudWatch] Failed to store Lambda logs: ${err.message}`));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (execError) throw execError;
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
createContext(functionName = "local-lambda", requestId = null) {
|
|
180
|
+
const reqId = requestId || Math.random().toString(36).substring(2, 18);
|
|
181
|
+
return {
|
|
182
|
+
awsRequestId: reqId,
|
|
183
|
+
functionName,
|
|
184
|
+
functionVersion: "$LATEST",
|
|
185
|
+
invokedFunctionArn: `arn:aws:lambda:local:000000000000:function:${functionName}`,
|
|
186
|
+
memoryLimitInMB: "1024",
|
|
187
|
+
logGroupName: `/aws/lambda/${functionName}`,
|
|
188
|
+
logStreamName: `${new Date().toISOString().slice(0, 10).replace(/-/g, '/')}/${reqId.slice(0, 8)}`,
|
|
189
|
+
getRemainingTimeInMillis: () => 30000,
|
|
190
|
+
callbackWaitsForEmptyEventLoop: true,
|
|
191
|
+
identity: null,
|
|
192
|
+
clientContext: null,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
applyEnvironment(env) {
|
|
197
|
+
for (const [key, value] of Object.entries(env)) {
|
|
198
|
+
process.env[key] = value;
|
|
199
|
+
this.environment[key] = value;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
setEnvironmentVariable(key, value) {
|
|
204
|
+
process.env[key] = value;
|
|
205
|
+
this.environment[key] = value;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
getEnvironmentVariables() {
|
|
209
|
+
return { ...this.environment };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
listLambdas() {
|
|
213
|
+
return Array.from(this.lambdas.values()).map((l) => {
|
|
214
|
+
let code = "";
|
|
215
|
+
try {
|
|
216
|
+
if (fs.existsSync(l.handlerPath)) {
|
|
217
|
+
code = fs.readFileSync(l.handlerPath, "utf8");
|
|
218
|
+
}
|
|
219
|
+
} catch (err) {
|
|
220
|
+
logger.error(`Erro ao ler código da lambda ${l.name}:`, err);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
name: l.name,
|
|
225
|
+
handlerName: l.handlerName,
|
|
226
|
+
handlerPath: l.handlerPath,
|
|
227
|
+
type: l.type,
|
|
228
|
+
env: l.env,
|
|
229
|
+
timeout: l.timeout,
|
|
230
|
+
memorySize: l.memorySize,
|
|
231
|
+
codeSize: l.codeSize,
|
|
232
|
+
registeredAt: l.registeredAt,
|
|
233
|
+
code: code
|
|
234
|
+
};
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
getLambda(name) {
|
|
240
|
+
return this.lambdas.get(name);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
getLambdasCount() {
|
|
244
|
+
return this.lambdas.size;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async reloadLambdas() {
|
|
248
|
+
logger.info("🔄 Recarregando Lambdas...");
|
|
249
|
+
|
|
250
|
+
for (const [name, lambda] of this.lambdas.entries()) {
|
|
251
|
+
try {
|
|
252
|
+
const newHandler = await HandlerLoader.reload(lambda.handlerPath, lambda.type);
|
|
253
|
+
lambda.handler = newHandler;
|
|
254
|
+
lambda.handlerName = newHandler.name || "anonymous";
|
|
255
|
+
logger.debug(`✅ Lambda recarregada: ${name}`);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
logger.error(`❌ Erro ao recarregar Lambda ${name}:`, error);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
logger.info(`✅ ${this.lambdas.size} Lambdas recarregadas`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async createFunction(lambdaConfig) {
|
|
265
|
+
const { name, code, runtime, handler, timeout, memorySize, environment } = lambdaConfig;
|
|
266
|
+
|
|
267
|
+
if (!name) throw new Error("Function name is required");
|
|
268
|
+
|
|
269
|
+
// Define o caminho do arquivo (dentro do dataDir/functions)
|
|
270
|
+
const functionsDir = path.join(this.dataDir, "functions");
|
|
271
|
+
if (!fs.existsSync(functionsDir)) fs.mkdirSync(functionsDir, { recursive: true });
|
|
272
|
+
|
|
273
|
+
const fileName = `${name}.js`;
|
|
274
|
+
const filePath = path.join(functionsDir, fileName);
|
|
275
|
+
|
|
276
|
+
// Salva o código no disco
|
|
277
|
+
fs.writeFileSync(filePath, code || "// Hello Lambda");
|
|
278
|
+
|
|
279
|
+
// Registra a lambda
|
|
280
|
+
const config = {
|
|
281
|
+
name,
|
|
282
|
+
handler: filePath,
|
|
283
|
+
runtime: runtime || "nodejs18.x",
|
|
284
|
+
timeout: timeout || 30,
|
|
285
|
+
memorySize: memorySize || 128,
|
|
286
|
+
env: environment || {},
|
|
287
|
+
type: "commonjs"
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
await this.registerLambda(config);
|
|
291
|
+
this.persistLambdas();
|
|
292
|
+
|
|
293
|
+
return this.lambdas.get(name);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async updateFunction(name, lambdaConfig) {
|
|
297
|
+
const lambda = this.lambdas.get(name);
|
|
298
|
+
if (!lambda) throw new Error(`Function not found: ${name}`);
|
|
299
|
+
|
|
300
|
+
const { code, runtime, handler, timeout, memorySize, environment } = lambdaConfig;
|
|
301
|
+
|
|
302
|
+
// Se houver código novo, sobrescreve o arquivo
|
|
303
|
+
if (code !== undefined) {
|
|
304
|
+
fs.writeFileSync(lambda.handlerPath, code);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Atualiza a configuração
|
|
308
|
+
const updatedConfig = {
|
|
309
|
+
name,
|
|
310
|
+
handler: lambda.handlerPath,
|
|
311
|
+
runtime: runtime || lambda.runtime,
|
|
312
|
+
timeout: timeout || lambda.timeout,
|
|
313
|
+
memorySize: memorySize || lambda.memorySize,
|
|
314
|
+
env: environment || lambda.env,
|
|
315
|
+
type: lambda.type
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
await this.registerLambda(updatedConfig);
|
|
319
|
+
this.persistLambdas();
|
|
320
|
+
|
|
321
|
+
return this.lambdas.get(name);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async deleteFunction(name) {
|
|
325
|
+
|
|
326
|
+
if (this.lambdas.has(name)) {
|
|
327
|
+
this.lambdas.delete(name);
|
|
328
|
+
this.persistLambdas();
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
persistLambdas() {
|
|
335
|
+
const functionsToSave = Array.from(this.lambdas.values())
|
|
336
|
+
.filter(l => l.handlerPath.includes(this.dataDir)) // Apenas as dinâmicas
|
|
337
|
+
.map(l => ({
|
|
338
|
+
name: l.name,
|
|
339
|
+
handler: l.handlerPath,
|
|
340
|
+
type: l.type,
|
|
341
|
+
env: l.env,
|
|
342
|
+
timeout: l.timeout,
|
|
343
|
+
memorySize: l.memorySize,
|
|
344
|
+
}));
|
|
345
|
+
|
|
346
|
+
this.store.write("__functions__", functionsToSave);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
getStats() {
|
|
350
|
+
return {
|
|
351
|
+
totalLambdas: this.lambdas.size,
|
|
352
|
+
lambdas: this.listLambdas().map((l) => ({ name: l.name, handler: l.handlerName })),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
async reset() {
|
|
358
|
+
await this.reloadLambdas();
|
|
359
|
+
this.environment = { ...process.env };
|
|
360
|
+
logger.debug("Lambda: Estado resetado");
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
module.exports = LambdaSimulator;
|