Rust Functions
Build high-performance serverless functions with Rust for maximum speed and efficiency.
Overview
Rust Edge Functions are ideal for:
- High-performance computing
- Low-latency requirements
- Memory-intensive operations
- CPU-bound tasks
- Cryptographic operations
When to Use Rust vs Python
| Use Case | Recommended |
|---|---|
| AI/ML tasks | Python |
| Rapid prototyping | Python |
| Data transformation | Python |
| High-throughput processing | Rust |
| Cryptography | Rust |
| Image/video processing | Rust |
| Low memory footprint | Rust |
Start with Python for faster development, then optimize with Rust if needed.
Creating a Function
Navigate to Edge Functions
Go to the Edge Functions section in your dashboard.
Create New Function
Click "New Function" and select Rust as the language.
Write Your Code
Write your function logic in the code editor.
Deploy
Click "Deploy" to compile and deploy your function.
Function Structure
// functions/hello.rs
use serde::{Deserialize, Serialize};
use dypai::{Request, Response};
#[derive(Deserialize)]
struct RequestBody {
name: Option<String>,
}
#[derive(Serialize)]
struct ResponseBody {
message: String,
status: String,
}
pub async fn handler(request: Request) -> Response {
let body: RequestBody = request.json().await.unwrap_or(RequestBody { name: None });
let name = body.name.unwrap_or_else(|| "World".to_string());
Response::json(&ResponseBody {
message: format!("Hello, {}!", name),
status: "success".to_string(),
})
}Request Object
use dypai::{Request, Response};
use std::collections::HashMap;
pub async fn handler(request: Request) -> Response {
// HTTP method
let method = request.method();
// Headers
let auth = request.header("authorization");
let content_type = request.header("content-type");
// Query parameters
let query: HashMap<String, String> = request.query();
let page = query.get("page").unwrap_or(&"1".to_string());
// URL parameters
let user_id = request.param("id");
// Request body (JSON)
let body: serde_json::Value = request.json().await.unwrap();
// Raw body
let raw = request.body().await;
Response::json(&serde_json::json!({
"method": method.to_string()
}))
}Response Formats
use dypai::Response;
// JSON response
pub async fn handler(request: Request) -> Response {
Response::json(&serde_json::json!({
"message": "Success"
}))
}
// Response with status code
pub async fn handler(request: Request) -> Response {
Response::json(&serde_json::json!({
"error": "Not found"
})).status(404)
}
// Response with headers
pub async fn handler(request: Request) -> Response {
Response::json(&serde_json::json!({
"data": "value"
}))
.status(201)
.header("X-Custom-Header", "value")
}
// Plain text response
pub async fn handler(request: Request) -> Response {
Response::text("Hello, World!")
}
// Binary response
pub async fn handler(request: Request) -> Response {
let bytes = vec![0u8; 100];
Response::bytes(bytes)
.header("Content-Type", "application/octet-stream")
}Database Access
use dypai::db;
#[derive(Serialize, Deserialize)]
struct User {
id: uuid::Uuid,
email: String,
name: String,
}
pub async fn handler(request: Request) -> Response {
// Query data
let users: Vec<User> = db::query(
"SELECT * FROM users WHERE active = $1",
&[&true]
).await.unwrap();
// Insert data
let result = db::query_one(
"INSERT INTO users (email, name) VALUES ($1, $2) RETURNING id",
&[&"user@example.com", &"John Doe"]
).await.unwrap();
// Update data
db::execute(
"UPDATE users SET last_login = NOW() WHERE id = $1",
&[&user_id]
).await.unwrap();
Response::json(&users)
}Making HTTP Requests
use reqwest::Client;
pub async fn handler(request: Request) -> Response {
let client = Client::new();
// GET request
let response = client
.get("https://api.example.com/data")
.header("Authorization", "Bearer token")
.send()
.await
.unwrap();
let data: serde_json::Value = response.json().await.unwrap();
// POST request
let _response = client
.post("https://api.example.com/webhook")
.json(&serde_json::json!({
"event": "user_created",
"user_id": 123
}))
.send()
.await
.unwrap();
Response::json(&data)
}Error Handling
use dypai::{Request, Response, Error};
pub async fn handler(request: Request) -> Result<Response, Error> {
let body: RequestBody = request.json().await
.map_err(|_| Error::bad_request("Invalid JSON body"))?;
let user_id = body.user_id
.ok_or_else(|| Error::bad_request("user_id is required"))?;
let user = db::query_one(
"SELECT * FROM users WHERE id = $1",
&[&user_id]
)
.await
.map_err(|_| Error::not_found("User not found"))?;
Ok(Response::json(&user))
}Example: High-Performance Data Processing
use rayon::prelude::*;
use dypai::{Request, Response};
#[derive(Deserialize)]
struct DataPoint {
value: f64,
category: String,
}
#[derive(Serialize)]
struct ProcessedResult {
category: String,
sum: f64,
average: f64,
count: usize,
}
pub async fn handler(request: Request) -> Response {
let data: Vec<DataPoint> = request.json().await.unwrap();
// Parallel processing with Rayon
let results: Vec<ProcessedResult> = data
.par_iter()
.fold(
|| std::collections::HashMap::new(),
|mut acc, point| {
acc.entry(point.category.clone())
.or_insert_with(Vec::new)
.push(point.value);
acc
}
)
.reduce(
|| std::collections::HashMap::new(),
|mut a, b| {
for (k, v) in b {
a.entry(k).or_insert_with(Vec::new).extend(v);
}
a
}
)
.into_iter()
.map(|(category, values)| {
let sum: f64 = values.iter().sum();
let count = values.len();
ProcessedResult {
category,
sum,
average: sum / count as f64,
count,
}
})
.collect();
Response::json(&results)
}Example: Cryptographic Operations
use sha2::{Sha256, Digest};
use hmac::{Hmac, Mac};
use dypai::{Request, Response};
type HmacSha256 = Hmac<Sha256>;
pub async fn handler(request: Request) -> Response {
// Verify webhook signature
let signature = request.header("x-webhook-signature").unwrap();
let body = request.body().await;
let secret = std::env::var("WEBHOOK_SECRET").unwrap();
let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
mac.update(&body);
let expected = hex::encode(mac.finalize().into_bytes());
if signature != expected {
return Response::json(&serde_json::json!({
"error": "Invalid signature"
})).status(401);
}
// Process verified request
Response::json(&serde_json::json!({
"verified": true
}))
}Available Crates
| Crate | Use Case |
|---|---|
serde | Serialization |
reqwest | HTTP client |
tokio | Async runtime |
rayon | Parallel processing |
sha2 | SHA hashing |
hmac | HMAC authentication |
uuid | UUID generation |
chrono | Date/time handling |
image | Image processing |
Request additional crates through the dashboard settings.