Skip to content

Commit 28f2f4c

Browse files
authored
Use Cargo Lambda (#8)
* Use Cargo Lambda Remove directory structure generation, since that tools gives you that for free. Signed-off-by: David Calavera <david.calavera@gmail.com> * Update name references Signed-off-by: David Calavera <david.calavera@gmail.com>
1 parent 77ab0f5 commit 28f2f4c

File tree

6 files changed

+40
-71
lines changed

6 files changed

+40
-71
lines changed

README.md

Lines changed: 12 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@
2121

2222
This library provides a construct for a Rust Lambda function.
2323

24-
It uses [`cargo-zigbuild`] under the hood, and follows best practices as outlined
24+
It uses [`cargo-lambda`] under the hood, and follows best practices as outlined
2525
in the [official AWS documentation].
2626

27-
[`cargo-zigbuild`]: https://github.com/messense/cargo-zigbuild
27+
[`cargo-lambda`]: https://crates.io/crates/cargo-lambda
2828
[official aws documentation]: https://github.com/awslabs/aws-lambda-rust-runtime#building-and-deploying-your-lambda-functions
2929

3030
## Rust Function
@@ -33,10 +33,10 @@ The `RustFunction` construct creates a Lambda function with automatic bundling a
3333

3434
## Getting Started
3535

36-
1. Install the [npm] package:
36+
1. Install this [npm] package, and [zig]:
3737

3838
```shell
39-
$ npm i rust.aws-cdk-lambda
39+
$ npm i rust.aws-cdk-lambda --save-optional
4040
```
4141

4242
2. Install the **aarch64-unknown-linux-gnu** toolchain with Rustup by running:
@@ -45,31 +45,16 @@ The `RustFunction` construct creates a Lambda function with automatic bundling a
4545
$ rustup target add aarch64-unknown-linux-gnu
4646
```
4747

48-
3) Install [Zig], using the instructions in their [installation guide] or via one of the options below.
49-
50-
1. Using [pip] (Python 3 required):
51-
52-
```shell
53-
$ pip install ziglang
54-
```
55-
56-
2. Using [npm]:
57-
58-
```shell
59-
$ npm install -g @ziglang/cli
60-
```
61-
62-
4) Use [`cargo`] to install _messense/cargo-zigbuild_:
48+
4) Use [`cargo`] to install _cargo-lambda_:
6349

6450
```shell
65-
$ cargo install cargo-zigbuild
51+
$ cargo install cargo-lambda
6652
```
6753

6854
[npm]: https://nodejs.org/
6955
[pip]: https://pip.pypa.io/en/stable/
7056
[`cargo`]: https://www.rust-lang.org/
7157
[zig]: https://ziglang.org/
72-
[installation guide]: https://ziglang.org/learn/getting-started/#installing-zig
7358

7459
## Examples
7560

@@ -120,9 +105,7 @@ All other properties of `lambda.Function` are supported, see also the [AWS Lambd
120105
121106
When bundling the code, the `RustFunction` runs the following steps in order:
122107
123-
- First it runs `cargo zigbuild`, and passes in the `--release` and `--target` flags, so it compiles for a Lambda environment - which defaults to the **aarch64-unknown-linux-gnu** target, as mentioned above. Note that _zigbuild_ does initially confirm that the Rust code can compile.
124-
125-
- Next, it copies the release app binary from the `target/` folder to a file named `bootstrap`, which the Lambda custom runtime environment looks for. It adds this new file under the _build directory_, which defaults to a `.build/` folder under the directory where `cdk` was invoked.
108+
- First it runs `cargo lambda`, and passes in the `--release` and `--target` flags, so it compiles for a Lambda environment - which defaults to the **aarch64-unknown-linux-gnu** target, as mentioned above. Note that _cargo lambda_ does initially confirm that the Rust code can compile.
126109
127110
- The directory path to the executable is then passed in to `lambda.Code.fromAsset`, which creates a _zip file_ from the release binary asset.
128111
@@ -132,7 +115,7 @@ If you instead prefer to use [Docker] and [`cross`] for deployment, as outlined
132115
in the [official AWS docs], you can install and use the [latest `v0.x`] release instead:
133116
134117
```shell
135-
$ npm i rust.aws-cdk-lambda@0.4.0
118+
$ npm i rust.aws-cdk-lambda@0.4.0 --save-optional
136119
```
137120
138121
[docker]: https://www.docker.com/get-started
@@ -294,8 +277,8 @@ Below lists some commonly used properties you can pass in to the `RustFunction`
294277
| `setupLogging` | Determines whether we want to set up [library logging](https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html) - i.e. set the `RUST_LOG` environment variable - for the lambda function.<br><br>The format defaults to `warn,module_name=debug`, which means that the default log level is `warn`, and the executable or library's log level is `debug`. |
295278
| |
296279
| `features` | A list of features to activate when compiling Rust code. These must also be added to the `Cargo.toml` file. |
297-
| `buildEnvironment` | Key-value pairs that are passed in at compile time, i.e. to `cargo build` or `cargo zigbuild`. This differs from `environment`, which determines the environment variables which are set on the AWS Lambda function itself. |
298-
| `extraBuildArgs` | Additional arguments that are passed in at build time to `cargo zigbuild`. For example, [`--all-features`]. |
280+
| `buildEnvironment` | Key-value pairs that are passed in at compile time, i.e. to `cargo build` or `cargo lambda`. This differs from `environment`, which determines the environment variables which are set on the AWS Lambda function itself. |
281+
| `extraBuildArgs` | Additional arguments that are passed in at build time to `cargo lambda`. For example, [`--all-features`]. |
299282
300283
## Settings
301284
@@ -314,5 +297,5 @@ Below are some useful _global_ defaults which can be set for all Rust Lambda Fun
314297
| `MODULE_LOG_LEVEL` | Log Level for a module (i.e. the executable). Note that this value is only used when `RustFunctionProps.setupLogging` is enabled. Defaults to `debug`. |
315298
| `WORKSPACE_DIR` | Sets the root workspace directory. By default, the workspace directory is assumed to be the directory where `cdk` was invoked.<br><br>This directory should contain at the minimum a `Cargo.toml` file which defines the workspace members. |
316299
| `FEATURES` | A list of features to activate when compiling Rust code. These must also be added to the `Cargo.toml` file. |
317-
| `BUILD_ENVIRONMENT` | Key-value pairs that are passed in at compile time, i.e. to `cargo build` or `cargo zigbuild`. This differs from `environment`, which determines the environment variables which are set on the AWS Lambda function itself. |
318-
| `EXTRA_BUILD_ARGS` | Additional arguments that are passed in at build time to both `cargo zigbuild`. For example, [`--all-features`]. |
300+
| `BUILD_ENVIRONMENT` | Key-value pairs that are passed in at compile time, i.e. to `cargo build` or `cargo lambda`. This differs from `environment`, which determines the environment variables which are set on the AWS Lambda function itself. |
301+
| `EXTRA_BUILD_ARGS` | Additional arguments that are passed in at build time to both `cargo lambda`. For example, [`--all-features`]. |

cdk-examples/README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ cd my-app
1717
npm i
1818
```
1919

20-
Next, ensure that you have [`cargo-zigbuild`](https://github.com/messense/cargo-zigbuild) installed. You will need this to cross-compile Rust code for deployment via `cdk`.
21-
If you don't have `cargo-zigbuild` installed, refer to the [Getting Started](https://github.com/rnag/rust.aws-cdk-lambda#getting-started) section in docs for more info on getting set up.
20+
Next, ensure that you have [`cargo-lambda`](https://crates.io/crates/cargo-lambda) installed. You will need this to cross-compile Rust code for deployment via `cdk`.
21+
If you don't have `cargo-lambda` installed, refer to the [Getting Started](https://github.com/rnag/rust.aws-cdk-lambda#getting-started) section in docs for more info on getting set up.
2222

2323
Now you can deploy the app with `cdk`:
2424

25-
> Note: on an initial run, it may take a _really_ long time on the compilation step with `cargo-zigbuild`. In my case, it sometimes took up to _12 minutes_! But don't worry, any subsequent deployments should be overall faster.
25+
> Note: on an initial run, it may take a _really_ long time on the compilation step with `cargo-lambda`. In my case, it sometimes took up to _12 minutes_! But don't worry, any subsequent deployments should be overall faster.
2626
2727
```shell
2828
npx cdk deploy

lib/build.ts

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { spawnSync } from 'child_process';
22
import * as fs from 'fs';
3-
import * as path from 'path';
43
import { Settings } from '.';
54

65
let _builtWorkspaces = false,
@@ -18,7 +17,7 @@ export interface BaseBuildProps {
1817
readonly package?: string;
1918

2019
/**
21-
* The target to use `cargo-zigbuild` to compile to.
20+
* The target to use `cargo lambda` to compile to.
2221
*
2322
* Normally you'll need to first add the target to your toolchain:
2423
* $ rustup target add <target>
@@ -45,7 +44,7 @@ export interface BaseBuildProps {
4544
readonly buildEnvironment?: NodeJS.ProcessEnv;
4645

4746
/**
48-
* Additional arguments that are passed in at build time to `cargo-zigbuild`.
47+
* Additional arguments that are passed in at build time to `cargo lambda`.
4948
*
5049
* ## Examples
5150
*
@@ -74,21 +73,14 @@ export interface BuildOptions extends BaseBuildProps {
7473
}
7574

7675
/**
77-
* Build with `cargo-zigbuild zigbuild`
76+
* Build with `cargo lambda`
7877
*/
7978
export function build(options: BuildOptions): void {
8079
try {
8180
let outputName: string;
8281
let shouldCompile: boolean;
8382
let extra_args: string[] | undefined;
8483

85-
let targetReleaseDir = path.join(
86-
options.entry,
87-
'target',
88-
options.target,
89-
'release'
90-
);
91-
9284
// Build binary
9385
if (options.bin) {
9486
outputName = options.bin!;
@@ -123,9 +115,9 @@ export function build(options: BuildOptions): void {
123115

124116
if (shouldCompile) {
125117
// Check if directory `./target/{{target}}/release` exists
126-
const releaseDirExists = fs.existsSync(targetReleaseDir);
118+
const releaseDirExists = fs.existsSync(options.outDir);
127119

128-
// Base arguments for `cargo-zigbuild`
120+
// Base arguments for `cargo lambda`
129121

130122
const buildArgs = ['--quiet', '--color', 'always'];
131123

@@ -155,45 +147,43 @@ export function build(options: BuildOptions): void {
155147
console.log(`🍺 Building Rust code...`);
156148
} else {
157149
// The `release` directory doesn't exist for the specified
158-
// target. This is most likely an initial run, so `cargo-zigbuild`
150+
// target. This is most likely an initial run, so `cargo lambda`
159151
// will take much longer than usual to cross-compile the code.
160152
//
161153
// Print out an informative message that the `build` step is
162154
// expected to take longer than usual.
163155
console.log(
164-
`🍺 Building Rust code with \`cargo-zigbuild\`. This may take a few minutes...`
156+
`🍺 Building Rust code with \`cargo lambda\`. This may take a few minutes...`
165157
);
166158
}
167159

168160
const args: string[] = [
169-
'zigbuild',
161+
'lambda',
162+
'build',
163+
'--lambda-dir',
164+
options.outDir,
170165
'--release',
171166
'--target',
172167
options.target,
173168
...buildArgs,
174169
...extra_args!,
175170
];
176171

177-
const zigBuild = spawnSync('cargo-zigbuild', args, {
172+
const cargo = spawnSync('cargo', args, {
178173
cwd: options.entry,
179174
env: buildEnv,
180175
});
181176

182-
if (zigBuild.status !== 0) {
183-
console.error(zigBuild.stderr.toString().trim());
184-
console.error(`💥 Run \`cargo zigbuild\` errored.`);
177+
if (cargo.status !== 0) {
178+
console.error(cargo.stderr.toString().trim());
179+
console.error(`💥 Run \`cargo lambda\` errored.`);
185180
process.exit(1);
186181
// Note: I don't want to raise an error here, as that will clutter the
187182
// output with the stack trace here. But maybe, there's a way to
188183
// suppress that?
189-
// throw new Error(zigBuild.stderr.toString().trim());
184+
// throw new Error(cargo.stderr.toString().trim());
190185
}
191186
}
192-
193-
let from = path.join(targetReleaseDir, outputName);
194-
let to = path.join(options.outDir, 'bootstrap');
195-
196-
fs.copyFileSync(from, to);
197187
} catch (err) {
198188
throw new Error(
199189
`Failed to build file at ${options.entry}: ${err}`

lib/function.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export interface RustFunctionProps
5050
}
5151

5252
/**
53-
* A Rust Lambda function built using `cargo-zigbuild`
53+
* A Rust Lambda function built using `cargo lambda`
5454
*/
5555
export class RustFunction extends lambda.Function {
5656
constructor(
@@ -77,25 +77,18 @@ export class RustFunction extends lambda.Function {
7777

7878
const handlerDir = path.join(
7979
buildDir,
80-
// We need to generate a *unique* hash in case there are multiple
81-
// executables, so use the `binName` here instead.
82-
crypto
83-
.createHash('sha256')
84-
.update(executable)
85-
.digest('hex')
80+
executable
8681
);
87-
createDirectory(buildDir);
88-
createDirectory(handlerDir);
8982

9083
let start = performance.now();
9184

92-
// Build with `cargo-zigbuild`
85+
// Build with `cargo-lambda`
9386
build({
9487
...props,
9588
entry,
9689
bin: binName,
9790
target: target,
98-
outDir: handlerDir,
91+
outDir: buildDir,
9992
});
10093

10194
logTime(start, `🎯 Cross-compile \`${executable}\``);

lib/settings.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export const Settings = {
7676

7777
/**
7878
* Key-value pairs that are passed in at compile time, i.e. to `cargo
79-
* build` or `cargo-zigbuild`.
79+
* build` or `cargo lambda`.
8080
*
8181
* Use environment variables to apply configuration changes, such
8282
* as test and production environment configurations, without changing your
@@ -87,7 +87,7 @@ export const Settings = {
8787
BUILD_ENVIRONMENT: undefined as NodeJS.ProcessEnv | undefined,
8888

8989
/**
90-
* Additional arguments that are passed in at build time to `cargo-zigbuild`.
90+
* Additional arguments that are passed in at build time to `cargo lambda`.
9191
*
9292
* ## Examples
9393
*

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@
4242
"aws-cdk-lib": "^2.0.0",
4343
"constructs": "^10.0.43"
4444
},
45+
"optionalDependencies": {
46+
"@ziglang/cli": "^0.0.8"
47+
},
4548
"homepage": "https://github.com/rnag/rust.aws-cdk-lambda",
4649
"engines": {
4750
"node": ">= 10.3.0"

0 commit comments

Comments
 (0)