Skip to content

Commit

Permalink
[cdk support] samp invoke
Browse files Browse the repository at this point in the history
  • Loading branch information
ljacobsson committed Jul 25, 2023
1 parent ad23ea9 commit 39ab04b
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 21 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "samp-cli",
"version": "1.0.24",
"version": "1.0.26",
"description": "CLI tool for extended productivity with AWS Serverless Application Model (SAM)",
"main": "index.js",
"scripts": {
Expand Down
30 changes: 28 additions & 2 deletions src/commands/invoke/invoke.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,35 @@ const link2aws = require('link2aws');
const open = import('open');
let region;
async function run(cmd) {
if (fs.existsSync("samconfig.toml")) {
if (fs.existsSync(".lambda-debug")) {
const envConfig = JSON.parse(fs.readFileSync(".lambda-debug", "utf8")).envConfig;
cmd.stackName = envConfig.stack_name;
cmd.profile = envConfig.profile;
cmd.region = envConfig.region;
} else if (fs.existsSync("cdk.out/manifest.json")) {
const manifest = JSON.parse(fs.readFileSync("cdk.out/manifest.json", "utf8"));
const stacks = Object.keys(manifest.artifacts).filter(key => manifest.artifacts[key].type === "aws:cloudformation:stack");
let stack = stacks[0];
if (stacks.length > 1) {
stack = await inputUtil.autocomplete("Select a stack", stacks);
}
const stackInfo = manifest.artifacts[stack];
cmd.stackName = stack;
const region = stackInfo.environment.split("/")[3];
if (!cmd.region && region === "unknown-region") {
console.log("Unable to determine region from manifest.json. Please specify using --region");
process.exit(1);
}
if (!cmd.region) {
cmd.region = region;
}
if (!cmd.profile) {
console.log("Using default profile. Override by setting --profile <your profile>");
}
}
else if (fs.existsSync("samconfig.toml")) {
const config = ini.parse(fs.readFileSync("samconfig.toml", "utf8"));
const params = { ...config?.default?.deploy?.parameters, ...(config?.default?.global?.parameters || {})};
const params = { ...config?.default?.deploy?.parameters, ...(config?.default?.global?.parameters || {}) };
if (!cmd.stackName && params.stack_name) {
console.log("Using stack name from config:", params.stack_name);
cmd.stackName = params.stack_name;
Expand Down
11 changes: 9 additions & 2 deletions src/commands/local/lib/cleanup.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ try {
const cfnClient = new CloudFormationClient({ region, credentials });
const lambdaClient = new LambdaClient({ region, credentials });
const templateResponse = await cfnClient.send(new GetTemplateCommand({ StackName: stackName, TemplateStage: "Processed" }));
const stack = await cfnClient.send(new ListStackResourcesCommand({ StackName: stackName }));

const stackResources = [];
let token;
do {
const response = await cfnClient.send(new ListStackResourcesCommand({ StackName: stackName, NextToken: token }));
stackResources.push(...response.StackResourceSummaries);
token = response.NextToken;
} while (token);

const template = JSON.parse(templateResponse.TemplateBody);

Expand All @@ -47,7 +54,7 @@ const updatePromises = functions.map(async functionName => {
do {
try {
const func = template.Resources[functionName];
const physicalId = stack.StackResourceSummaries.find(resource => resource.LogicalResourceId === functionName).PhysicalResourceId;
const physicalId = stackResources.find(resource => resource.LogicalResourceId === functionName).PhysicalResourceId;
console.log(`Restoring function: ${functionName}`);

await lambdaClient.send(new UpdateFunctionConfigurationCommand({
Expand Down
13 changes: 9 additions & 4 deletions src/commands/local/lib/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import ini from 'ini';
import getMac from 'getmac';
import archiver from 'archiver';
import { fileURLToPath } from 'url';
import { spawnSync } from 'child_process';
import { fork, spawnSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const mac = getMac();
Expand Down Expand Up @@ -283,9 +283,14 @@ client.on('connect', async function () {

client.on('message', async function (topic, message) {
const obj = JSON.parse(message.toString());
process.env = { ...obj.envVars, LOCAL_DEBUG: true };
const result = await routeEvent(obj.event, obj.context, stack, functionSources);
client.publish(`lambda-debug/callback/${mac}/${obj.sessionId}`, JSON.stringify(result || {}));
const frk = fork(path.join(__dirname, 'event-router.js'), [ JSON.stringify(obj), JSON.stringify(stack), JSON.stringify(functionSources)]);

frk.on('message', (result) => {
console.log(`Result: ${result}`);
client.publish(`lambda-debug/callback/${mac}/${obj.sessionId}`, result);
});

//
});

client.on('close', function () {
Expand Down
19 changes: 17 additions & 2 deletions src/commands/local/lib/event-router.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
export async function routeEvent(event, context, stack, functionSources) {
export async function routeEvent(obj, stack, functionSources) {
try {
const event = obj.event;
const context = obj.context;
process.env = { ...obj.envVars, LOCAL_DEBUG: true };

const logicalId = stack.StackResourceSummaries.find(resource => resource.PhysicalResourceId === context.functionName).LogicalResourceId;
const modulePath = functionSources[logicalId].module;
const modulePath = functionSources[logicalId].module;
const module = await import(modulePath);
return await module[functionSources[logicalId].handler](event, context);
} catch (error) {
console.log(error);
return { error: error.message };
}
}
if (process.argv.length > 3) {
const obj = JSON.parse(process.argv[2]);
const stack = JSON.parse(process.argv[3]);
const functionSources = JSON.parse(process.argv[4]);
routeEvent(obj, stack, functionSources).then((result) => {
const response = typeof result === "string" ? result : JSON.stringify(result, null, 2);
process.send(response || "");
process.exit(0);
}
);
}
30 changes: 20 additions & 10 deletions src/commands/local/lib/relay/relay.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,32 @@ export const handler = async (event, context) => {
});

client.on('message', function (topic, message) {
const payload = JSON.parse(message.toString());
if (payload.error) {
console.log('Error: ', payload.error);
reject(payload.error);
}
if (payload.event === 'exit') {
console.log('Debug session ended');
client.end();
resolve('exit');
let payload;
try {
payload = JSON.parse(message.toString());
if (payload.error) {
console.log('Error: ', payload.error);
reject(payload.error);
}
if (payload.event === 'exit') {
console.log('Debug session ended');
client.end();
resolve('exit');
}
} catch (e) {
// non-json payload
}

resolve(message.toString());
});
});

const message = await promise;
return JSON.parse(message);
try {
return JSON.parse(message);
} catch (e) {
return message;
}
};

function publishEvent(event, context) {
Expand Down

0 comments on commit 39ab04b

Please sign in to comment.