

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Membangun fungsi Rust Lambda dengan Kargo Lambda in AWS SAM
<a name="building-rust"></a>

Gunakan Com AWS Serverless Application Model mand Line Interface (AWS SAMCLI) dengan AWS Lambda fungsi Rust Anda.

**Topics**
+ [Prasyarat](#building-rust-prerequisites)
+ [Melakukan konfigurasi AWS SAM untuk digunakan dengan fungsi Rust Lambda](#building-rust-configure)
+ [Contoh](#building-rust-examples)
+ [Mengoptimalkan build Rust di GitHub Tindakan](#building-rust-optimize-ci)

## Prasyarat
<a name="building-rust-prerequisites"></a>

**Rustbahasa**  
Untuk menginstalRust, lihat [ Menginstal Rust](https://www.rust-lang.org/tools/install) di situs web * Rust bahasa*.

**Cargo Lambda**  
Mem AWS SAMCLI butuhkan instalasi [Cargo Lambda](https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html), subperintah untukCargo. Untuk petunjuk instalasi, lihat [ Instal * Cargo Lambda asi*](https://www.cargo-lambda.info/guide/installation.html) dalam dokumentasi.

**Docker**  
Membangun dan menguji fungsi Rust Lambda membutuhkanDocker. Untuk instruksi instalasi, lihat [Menginstal Docker](install-docker.md).

## Melakukan konfigurasi AWS SAM untuk digunakan dengan fungsi Rust Lambda
<a name="building-rust-configure"></a>

### Langkah 1: Konfigurasikan AWS SAM templat
<a name="building-rust-configure-template"></a>

Konfigurasikan AWS SAM template Anda dengan yang berikut:
+ **Biner ** - Opsional. Tentukan kapan Cargo paket tunggal mendefinisikan lebih dari satu biner, untuk mengidentifikasi biner mana yang akan dibangun untuk fungsi ini. Anda tidak memerlukan properti ini ketika setiap fungsi adalah Cargo paketnya sendiri, seperti di ruang Cargo kerja.
+ **BuildMethod** – `rust-cargolambda`.
+ **CodeUri**— jalur ke `Cargo.toml` file Anda.
+ **Pen ** angan -`bootstrap`.
+ **Waktu pelaksan ** aan -`provided.al2023`.

Untuk mempelajari selengkapnya tentang runtime khusus, lihat AWS Lambda Runtime [ kustom ](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html) di Panduan Peng *AWS Lambda embang. *

Berikut adalah contoh AWS SAM template yang dikonfigurasi:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties: function_a
    Properties:
      CodeUri: ./rust_app
      Handler: bootstrap
      Runtime: provided.al2023
...
```

### Langkah 2: Gunakan AWS SAM CLI dengan fungsi Rust Lambda Anda
<a name="building-rust-configure-cli"></a>

Gunakan AWS SAMCLI perintah apa pun dengan AWS SAM template Anda. Untuk informasi selengkapnya, lihat [AWS SAM CLI](using-sam-cli.md).

## Contoh
<a name="building-rust-examples"></a>

### Contoh Hello World
<a name="building-rust-examples-hello"></a>

**Dalam contoh ini, kita membangun contoh aplikasi Hello World menggunakan Rust sebagai runtime kita. **

Pertama, kami menginisialisasi aplikasi tanpa server baru menggunakan. `sam init` Selama aliran interaktif, kami memilih aplikasi ** Hello World ** dan memilih ** runtime ** Rust.

```
$ sam init
...
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: {{1}}

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        ...
Template: {{1}}

Use the most popular runtime and package type? (Python and zip) [y/N]: {{ENTER}}

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - go (provided.al2)
        ...
        18 - python3.11
        19 - python3.10
        20 - ruby4.0
        21 - ruby3.3
        22 - ruby3.2
        23 - rust (provided.al2)
        24 - rust (provided.al2023)
Runtime: {{24}}

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is cargo.
We will proceed copying the template using cargo.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: {{ENTER}}

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: {{ENTER}}

Project name [sam-app]: {{hello-rust}}

    -----------------------
    Generating application:
    -----------------------
    Name: hello-rust
    Runtime: rust (provided.al2023)
    Architectures: x86_64
    Dependency Manager: cargo
    Application Template: hello-world
    Output Directory: .
    Configuration file: hello-rust/samconfig.toml
    
    Next steps can be found in the README file at hello-rust/README.md
        

Commands you can use next
=========================
[*] Create pipeline: cd hello-rust && sam pipeline init --bootstrap
[*] Validate SAM template: cd hello-rust && sam validate
[*] Test Function in the Cloud: cd hello-rust && sam sync --stack-name {stack-name} --watch
```

Berikut ini adalah struktur aplikasi Hello World kami:

```
hello-rust
├── README.md
├── events
│   └── event.json
├── rust_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── samconfig.toml
└── template.yaml
```

Dalam AWS SAM template kami, Rust fungsi kami didefinisikan sebagai berikut:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Metadata:
      BuildMethod: rust-cargolambda 
    Properties:
      CodeUri: ./rust_app
      Handler: bootstrap
      Runtime: provided.al2023
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
```

Selanjutnya, kami menjalankan `sam build` untuk membangun aplikasi kami dan mempersiapkan penerapan. Membuat AWS SAMCLI `.aws-sam` direktori dan mengatur artefak build kami di sana. Fungsi kami dibangun menggunakan Cargo Lambda dan disimpan sebagai biner yang dapat dieksekusi di`.aws-sam/build/HelloWorldFunction/bootstrap`.

**catatan**  
Jika Anda berencana menjalankan **sam local invoke** perintah di macOS, Anda perlu membangun fungsi yang berbeda sebelum memanggil. Untuk melakukan ini, gunakan perintah berikut:  
**SAM\_BUILD\_MODE=debug sam build**
Perintah ini hanya diperlukan jika pengujian lokal akan dilakukan. Ini tidak disarankan saat membangun untuk penerapan.

```
hello-rust$ sam build
Starting Build use cache
Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-rust/rust_app runtime: provided.al2023 metadata: {'BuildMethod': 'rust-cargolambda'} architecture: x86_64 functions: HelloWorldFunction
Running RustCargoLambdaBuilder:CargoLambdaBuild
Running RustCargoLambdaBuilder:RustCopyAndRename

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

Selanjutnya, kami menerapkan aplikasi kami menggunakan`sam deploy --guided`.

```
hello-rust$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [hello-rust]: {{ENTER}}
        AWS Region [us-west-2]: {{ENTER}}
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: {{ENTER}}
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: {{ENTER}}
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: {{ENTER}}
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: {{y}}
        Save arguments to configuration file [Y/n]: {{ENTER}}
        SAM configuration file [samconfig.toml]: {{ENTER}}
        SAM configuration environment [default]: {{ENTER}}

        Looking for resources needed for deployment:

        ...

        Uploading to hello-rust/56ba6585d80577dd82a7eaaee5945c0b  817973 / 817973  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : hello-rust
        Region                       : us-west-2
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to hello-rust/a4fc54cb6ab75dd0129e4cdb564b5e89.template  1239 / 1239  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------
Operation                  LogicalResourceId          ResourceType               Replacement              
---------------------------------------------------------------------------------------------------------
+ Add                      HelloWorldFunctionHelloW   AWS::Lambda::Permission    N/A                      
                           orldPermissionProd                                                             
...                    
---------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1681427201/f0ef1563-5ab6-4b07-9361-864ca3de6ad6


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: {{y}}

2023-04-13 13:07:17 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
---------------------------------------------------------------------------------------------------------
ResourceStatus             ResourceType               LogicalResourceId          ResourceStatusReason     
---------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     -                        
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     Resource creation        
...
---------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------
Outputs                                                                                                 
---------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                           
Description         Implicit IAM Role created for Hello World function                                  
Value               arn:aws:iam::012345678910:role/hello-rust-HelloWorldFunctionRole-10II2P13AUDUY      

Key                 HelloWorldApi                                                                       
Description         API Gateway endpoint URL for Prod stage for Hello World function                    
Value               https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/                  

Key                 HelloWorldFunction                                                                  
Description         Hello World Lambda Function ARN                                                     
Value               arn:aws:lambda:us-west-2:012345678910:function:hello-rust-HelloWorldFunction-       
yk4HzGzYeZBj                                                                                            
---------------------------------------------------------------------------------------------------------


Successfully created/updated stack - hello-rust in us-west-2
```

Untuk menguji, kita dapat memanggil fungsi Lambda kita menggunakan titik akhir API.

```
$ curl https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/
Hello World!%
```

Untuk menguji fungsi kami secara lokal, pertama-tama kami memastikan `Architectures` properti fungsi kami cocok dengan mesin lokal kami.

```
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Metadata:
      BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda
    Properties:
      CodeUri: ./rust_app   # Points to dir of Cargo.toml
      Handler: bootstrap    # Do not change, as this is the default executable name produced by Cargo Lambda
      Runtime: provided.al2023
      Architectures:
        - arm64
...
```

Karena kami memodifikasi arsitektur kami dari `x86_64` ke `arm64` dalam contoh ini, kami menjalankan `sam build` untuk memperbarui artefak build kami. Kami kemudian berlari `sam local invoke` untuk memanggil fungsi kami secara lokal.

```
hello-rust$ sam local invoke
Invoking bootstrap (provided.al2023)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-provided.al2023
Building image.....................................................................................................................................
Using local image: public.ecr.aws/lambda/provided:al2023-rapid-arm64.

Mounting /Users/.../hello-rust/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Version: $LATEST
{"statusCode":200,"body":"Hello World!"}END RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6
REPORT RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6  Init Duration: 0.68 ms  Duration: 130.63 ms     Billed Duration: 131 ms     Memory Size: 128 MB     Max Memory Used: 128 MB
```

### Proyek fungsi Lambda tunggal
<a name="building-rust-examples-single"></a>

**Berikut adalah contoh aplikasi tanpa server yang berisi satu fungsi Rust Lambda. **

Struktur direktori proyek:

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── template.yaml
```

AWS SAM Templat:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2023
...
```

### Beberapa proyek fungsi Lambda
<a name="building-rust-examples-multiple"></a>

**Berikut adalah contoh aplikasi tanpa server yang berisi beberapa fungsi Rust Lambda, diatur sebagai Cargo ruang kerja. **

Kami merekomendasikan Cargo ruang kerja untuk aplikasi dengan beberapa fungsi Rust Lambda. Setiap fungsi adalah paketnya sendiri, sehingga fungsi dapat mendeklarasikan dependensi independen sambil berbagi kode umum melalui paket perpustakaan. Setiap paket menghasilkan satu biner yang dinamai setelah paket, jadi Anda tidak perlu mengatur properti `Binary` build.

Struktur direktori proyek:

```
.
├── Cargo.lock
├── Cargo.toml
├── function_a
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── function_b
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── template.yaml
```

`Cargo.toml`File ruang kerja, di root proyek:

```
[workspace]
resolver = "2"
members = [
    "function_a",
    "function_b",
]

[workspace.dependencies]
lambda_runtime = "0.13"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt"] }
```

`Cargo.toml`file untuk setiap fungsi, seperti`function_a/Cargo.toml`:

```
[package]
name = "function_a"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_runtime = { workspace = true }
serde = { workspace = true }
tokio = { workspace = true }
```

AWS SAM templat. Setiap `CodeUri` fungsi menunjuk ke direktori paket fungsi itu:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./function_a
      Handler: bootstrap
      Runtime: provided.al2023
  FunctionB:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./function_b
      Handler: bootstrap
      Runtime: provided.al2023
```

**catatan**  
Mem AWS SAMCLI bangun setiap fungsi di ruang kerja ke `target` direktori bersama ruang kerja, jadi meng Cargo kompilasi dependensi bersama sekali, bukan sekali untuk setiap fungsi. Perilaku ini memerlukan AWS SAMCLI versi 1.165.0 atau yang lebih baru. Pada versi sebelumnya, setiap fungsi dibangun di direktorinya sendiri `target` dan pohon ketergantungan penuh dikompilasi ulang untuk setiap fungsi, yang membuat build lebih lambat saat Anda menambahkan fungsi.

Berikan setiap paket fungsi nama biner yang unik. Nama paket unik dalam ruang kerja, jadi nama biner default sudah unik. Jika Anda mengganti nama biner dengan `[[bin]]` bagian, jangan berikan dua paket nama biner yang sama. Mereka mengkompilasi ke jalur yang sama di `target` direktori bersama dan saling mengganti. AWS SAMCLICatatan peringatan ketika mendeteksi ini.

Atau, satu paket dapat mendefinisikan beberapa binari. Dalam hal ini, gunakan properti `Binary` build untuk memilih biner untuk setiap fungsi:

```
Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_a
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2023
```

## Mengoptimalkan build Rust di GitHub Tindakan
<a name="building-rust-optimize-ci"></a>

Build Rust intensif komputasi, dan pelari integrasi berkelanjutan dimulai tanpa artefak yang dikompilasi. Aplikasi dengan beberapa fungsi yang berbagi dependensi besar, seperti AWSSDK, dapat menghabiskan sebagian besar waktu pembuatannya untuk mengkompilasi dependensi yang sama. Praktik berikut mengurangi waktu pembuatanGitHub Actions.

**Gunakan AWS SAMCLI versi 1.165.0 atau yang lebih baru untuk ruang kerja**  
Versi 1.165.0 dan yang lebih baru membangun setiap anggota ruang Cargo kerja ke `target` direktori bersama ruang kerja, sehingga dependensi bersama dikompilasi sekali per build, bukan sekali untuk setiap fungsi. Tentukan versi minimum saat Anda menginstal AWS SAMCLI sehingga build tidak diam-diam kembali ke perilaku yang lebih lambat.

**Cache Cargo registri dan `target` direktori**  
Cache Cargo registri (`~/.cargo/registry`dan`~/.cargo/git/db`) dan `target` direktori ruang kerja di antara proses, sehingga dependensi yang tidak berubah dipulihkan alih-alih dikompilasi ulang. Gunakan cache terpisah untuk setiap target kompilasi. Pekerjaan yang mengkompilasi artefak rilis untuk `arm64` menghasilkan artefak yang berbeda dari pekerjaan yang dikompilasi secara asli`x86_64`, sehingga cache bersama tidak pernah cocok.

**Sertakan pengaturan build di kunci cache**  
Cargotermasuk pengaturan seperti `opt-level` dan `codegen-units` dalam sidik jari yang digunakan untuk memutuskan apakah artefak yang dikompilasi dapat digunakan kembali. Jika Anda mengubah `[profile.release]` bagian `Cargo.toml` file ruang kerja Anda tanpa mengubah kunci cache, cache dipulihkan tetapi setiap peti tetap dikompilasi ulang. Sertakan hash `Cargo.toml` file ruang kerja dalam kunci cache sehingga mengubah pengaturan profil memulai cache baru.

**Komit `Cargo.lock` file Anda**  
Fungsi Lambda dapat dieksekusi, jadi komit file Anda`Cargo.lock`. Ini memberi Anda build yang dapat direproduksi dan kunci cache stabil yang hanya berubah ketika dependensi Anda berubah.

**Setel profil rilis untuk waktu pembuatan dan start dingin**  
Kode fungsi Anda dikompilasi ulang pada setiap proses, karena lebih sering berubah daripada dependensi Anda. Profil rilis default mengoptimalkan throughput runtime, yang tidak dibutuhkan banyak fungsi Lambda. Mengoptimalkan ukuran menghasilkan binari yang lebih kecil, yang juga membantu waktu mulai dingin, dan meningkatkan jumlah unit pembuatan kode meningkatkan paralelisme selama kompilasi. Biarkan pengoptimalan waktu tautan (`lto`) dinonaktifkan, karena membuat kompilasi lebih lambat. Tambahkan yang berikut ini ke `Cargo.toml` file ruang kerja Anda:  

```
[profile.release]
opt-level = "s"
codegen-units = 256
lto = false
strip = true
```
Ukur efeknya pada aplikasi Anda sendiri. Pengaturan ini memperdagangkan sejumlah kecil kinerja runtime untuk waktu pembuatan dan ukuran biner.

**Hindari proses alur kerja duplikat**  
Alur kerja yang berjalan pada keduanya `push` dan `pull_request` acara berjalan dua kali untuk komit yang sama. GitHub Actionscache dicakup oleh cabang dan permintaan tarik, sehingga keduanya menjalankan menulis ke cakupan cache yang berbeda dan tidak menggunakan kembali cache yang lain. Gunakan grup konkurensi yang dikunci pada komit kepala, sehingga hanya satu kali proses yang membangun setiap komit.

Alur kerja berikut membangun Cargo ruang kerja fungsi Rust Lambda untuk`arm64`, dan menerapkan praktik sebelumnya:

```
name: Build

on:
  push:
    branches: [main]
  pull_request:

# Collapse the push and pull_request runs for the same commit into a single run.
concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.head.sha || github.sha }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: aarch64-unknown-linux-gnu

      # Cache the Cargo registry and the workspace target directory. The key covers
      # the compilation target, Cargo.lock, and the workspace Cargo.toml, so that
      # changing a dependency or a release profile setting starts a new cache
      # instead of restoring one whose artifacts Cargo discards.
      - uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry/index
            ~/.cargo/registry/cache
            ~/.cargo/git/db
            target
          key: cargo-arm64-${{ hashFiles('Cargo.lock', 'Cargo.toml') }}
          restore-keys: |
            cargo-arm64-

      - name: Install build tools
        run: pip install cargo-lambda 'aws-sam-cli>=1.165.0'

      - name: Build
        run: sam build
```

En `restore-keys` tri memungkinkan proses dimulai dari cache terbaru ketika kunci tidak cocok persis, sehingga perubahan ketergantungan menggunakan kembali peti yang tidak berubah alih-alih mengkompilasi semuanya lagi.