Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream lambda function compiler responses #1340

Merged
merged 6 commits into from
Apr 16, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Stream lambda function compiler responses
manuelwedler committed Apr 10, 2024

Verified

This commit was signed with the committer’s verified signature.
alvasw Alva Swanson
commit 9285615ba6f58d7dd8f18bb4d943892144d691a8
29 changes: 15 additions & 14 deletions serverless/compiler-lambda/index.js
Original file line number Diff line number Diff line change
@@ -5,6 +5,8 @@ const { exec, spawnSync } = require("child_process");
const solc = require("solc");
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
const pipeline = require("util").promisify(require("stream").pipeline);
const { Blob } = require('buffer');

async function fetchWithTimeout(resource, options = {}) {
const { timeout = 30000 } = options;
@@ -298,23 +300,22 @@ function asyncExecSolc(inputStringified, solcPath) {
});
}

exports.handler = async (event) => {
exports.handler = awslambda.streamifyResponse(async (event, responseStream, _context) => {
let output;
try {
return {
success: true,
body: await useCompiler(
event.version,
event.solcJsonInput,
event.forceEmscripten
),
};
output = await useCompiler(
event.version,
event.solcJsonInput,
event.forceEmscripten
);
} catch (e) {
return {
success: true,
body: e.message,
};
output = { error: e.message };
}
};
console.debug("Compilation output: ", output);

const outputBlob = new Blob([JSON.stringify(output)]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Continuing this comment: #1340 (comment)

like this:

if (weight(outputBlob) > 20MB ) {
  output = { error: "specific error for this case" }
  return or throw
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah nice idea! That should work out! Thanks for the hint

await pipeline(outputBlob.stream(), responseStream);
});

/* exports
.handler({
59 changes: 35 additions & 24 deletions services/server/src/server/services/compiler/lambda/SolcLambda.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
LambdaClient,
InvokeCommand,
InvokeCommandInput,
InvokeWithResponseStreamCommand,
InvokeWithResponseStreamCommandInput,
} from "@aws-sdk/client-lambda";
import {
CompilerOutput,
@@ -44,45 +44,56 @@ export class SolcLambda implements ISolidityCompiler {
logger.debug("Compiling with Lambda", { version });
const response = await this.invokeLambdaFunction(param);
logger.debug("Compiled with Lambda", { version });
const responseObj = this.parseCompilerOutput(response);
logger.silly("Lambda function response", { responseObj });
return responseObj;
logger.silly("Lambda function response", { response });
return response;
}

private async invokeLambdaFunction(payload: string): Promise<any> {
const params: InvokeCommandInput = {
private async invokeLambdaFunction(payload: string): Promise<CompilerOutput> {
const params: InvokeWithResponseStreamCommandInput = {
FunctionName: config.get("lambdaCompiler.functionName") || "compile",
Payload: payload,
};

const command = new InvokeCommand(params);
const command = new InvokeWithResponseStreamCommand(params);
const response = await this.lambdaClient.send(command);

if (!response.Payload) {
if (!response.EventStream) {
throw new Error(
"Error: No response payload received from Lambda function"
"Error: No response stream received from Lambda function"
);
}

if (response.FunctionError) {
const errorObj: { errorMessage: string; errorType: string } = JSON.parse(
Buffer.from(response.Payload).toString("utf8")
);
logger.error("Error invoking Lambda function", {
errorObj,
let streamResult = "";
for await (const event of response.EventStream) {
if (event.InvokeComplete?.ErrorCode) {
logger.error("Error invoking Lambda function", {
errorCode: event.InvokeComplete.ErrorCode,
errorDetails: event.InvokeComplete.ErrorDetails,
logResult: event.InvokeComplete.LogResult,
lambdaRequestId: response.$metadata.requestId,
});
throw new Error(
`AWS Lambda error: ${event.InvokeComplete.ErrorCode} - ${event.InvokeComplete.ErrorDetails} - lamdbaRequestId: ${response.$metadata.requestId}`
);
} else if (event.PayloadChunk?.Payload) {
streamResult += Buffer.from(event.PayloadChunk.Payload).toString(
"utf8"
);
}
}
logger.silly("Received stream response", { streamResult });

const output = JSON.parse(streamResult);
manuelwedler marked this conversation as resolved.
Show resolved Hide resolved
if (output.error) {
logger.error("Error received from Lambda function", {
error: output.error,
lambdaRequestId: response.$metadata.requestId,
functionError: response.FunctionError,
});
throw new Error(
`AWS Lambda error: ${errorObj.errorType} - ${errorObj.errorMessage} - lamdbaRequestId: ${response.$metadata.requestId}`
`AWS Lambda error: ${output.error} - lamdbaRequestId: ${response.$metadata.requestId}`
);
}

return response;
}

private parseCompilerOutput(response: any): CompilerOutput {
const res = JSON.parse(Buffer.from(response.Payload).toString("utf8"));
return res.body as CompilerOutput;
return output;
}
}