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
Show file tree
Hide file tree
Changes from 3 commits
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
29 changes: 15 additions & 14 deletions serverless/compiler-lambda/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import fetch from "node-fetch";
import { IVerificationService } from "../../services/VerificationService";
import { ContractMeta, ContractWrapper, getMatchStatus } from "../../common";
import { ISolidityCompiler } from "@ethereum-sourcify/lib-sourcify";
import { SolcLambda } from "../../services/compiler/lambda/SolcLambda";
import { SolcLambdaWithLocalFallback } from "../../services/compiler/lambda-with-fallback/SolcLambdaWithLocalFallback";
import { SolcLocal } from "../../services/compiler/local/SolcLocal";
import { StorageService } from "../../services/StorageService";
import logger from "../../../common/logger";
Expand All @@ -32,8 +32,8 @@ import { createHash } from "crypto";

let selectedSolidityCompiler: ISolidityCompiler;
if (config.get("lambdaCompiler.enabled")) {
logger.info("Using lambda solidity compiler");
selectedSolidityCompiler = new SolcLambda();
logger.info("Using lambda solidity compiler with local fallback");
selectedSolidityCompiler = new SolcLambdaWithLocalFallback();
} else {
logger.info("Using local solidity compiler");
selectedSolidityCompiler = new SolcLocal();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
CompilerOutput,
ISolidityCompiler,
JsonInput,
} from "@ethereum-sourcify/lib-sourcify";
import logger from "../../../../common/logger";
import { SolcLambda } from "../lambda/SolcLambda";
import { SolcLocal } from "../local/SolcLocal";

export class SolcLambdaWithLocalFallback implements ISolidityCompiler {
private solcLambda = new SolcLambda();
private solcLocal = new SolcLocal();

public async compile(
version: string,
solcJsonInput: JsonInput,
forceEmscripten: boolean = false
): Promise<CompilerOutput> {
let compilerOutput: CompilerOutput;
try {
compilerOutput = await this.solcLambda.compile(
version,
solcJsonInput,
forceEmscripten
);
} catch (e) {
logger.error(
Copy link
Member

@marcocastignoli marcocastignoli Apr 10, 2024

Choose a reason for hiding this comment

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

I think that here we need to run local compilation only on the specific "too big output" error not all the errors

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

(I pushed the new commit before I saw your comment update)

The problem with this is that I cannot really find out which error code is given by AWS in the case the response is too big. I was checking the docs and they were not very helpful (https://docs.aws.amazon.com/lambda/latest/api/API_InvokeWithResponseStreamCompleteEvent.html).

We could also try to find a contract whose compiler output is bigger than the response stream limit of 20 MB. I'm just not sure how to go about that.

Copy link
Member

@marcocastignoli marcocastignoli Apr 11, 2024

Choose a reason for hiding this comment

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

I'm thinking... Maybe on the lambda side you can find the output size and if it's more than 20mb send a specific response. Could this work?

Continues here: #1340 (comment)

"Lambda compilation error - Falling back to local compilation"
);
compilerOutput = await this.solcLocal.compile(
version,
solcJsonInput,
forceEmscripten
);
}
return compilerOutput;
}
}
69 changes: 46 additions & 23 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,
Expand Down Expand Up @@ -44,45 +44,68 @@ 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 });

let output;
try {
output = JSON.parse(streamResult);
} catch (e) {
logger.error("Error parsing Lambda function result", {
error: e,
lambdaRequestId: response.$metadata.requestId,
functionError: response.FunctionError,
});
throw new Error(
`AWS Lambda error: ${errorObj.errorType} - ${errorObj.errorMessage} - lamdbaRequestId: ${response.$metadata.requestId}`
`AWS Lambda error: ${e} - lamdbaRequestId: ${response.$metadata.requestId}`
);
}

return response;
}
if (output.error) {
logger.error("Error received from Lambda function", {
error: output.error,
lambdaRequestId: response.$metadata.requestId,
});
throw new Error(
`AWS Lambda error: ${output.error} - lamdbaRequestId: ${response.$metadata.requestId}`
);
}

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