Rust SDK
Use the Rust SDK to moderate content, manage assets and handle events from your server, through an async client or its blocking counterpart. It requires Rust 1.88 or later; a minor release may raise that to a version released at least six months earlier, and a patch release never does.
Install
cargo add calmlens
cargo add tokio --features macros,rt-multi-thread
cargo add futures-utilSee Versioning and support for what each version change means and where to find the changelog.
The default features are async (the async ServerClient) and rustls (TLS through rustls, verifying certificates with the operating system's trust store). Other features:
| Feature | Adds |
|---|---|
blocking | calmlens::blocking::ServerClient, the same API without async |
native-tls | TLS through the platform library instead of rustls |
tracing | A tracing event, with the target calmlens, for every HTTP attempt |
testing | calmlens::testing::MockServerClient, for [dev-dependencies] only |
With default-features = false, the crate contains only the models and the webhook helpers, without an HTTP client.
Moderate content
Create an API key and copy your project ID as described in Authentication, and keep them on your server. Create one client when your application starts and share it: clones are cheap and share connections, so store it in your application state rather than creating one per request. assets().create queues processing; assets().classify and text().classify wait for the decision. Documents, websites, audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.
use calmlens::{models::*, ServerClient};
#[tokio::main]
async fn main() -> calmlens::Result<()> {
// Reads CALMLENS_API_KEY, CALMLENS_PROJECT_ID and, when set, CALMLENS_BASE_URL.
let client = ServerClient::from_env()?;
let asset = client
.text()
.classify(ClassifyText::new("Great photo!").external_id("comment-42"))
.await?;
if asset.classification.moderation.decision == Some(AssetModerationDecision::Allowed) {
println!("Publish {}", asset.id);
}
Ok(())
}Publish only an allowed result; serve an age-restricted one only to viewers your app allows, by setting .viewer_claims(ViewerClaims::new().age_confirmed(true)) on a CdnRequest or SignAssetUrlOptions, which adds them to the URL; a signed URL or your API key alone doesn't serve it. See Age-restricted assets and Reading classification results.
classification.moderation.decision is None until there's a decision. The enums, such as AssetModerationDecision and Visibility, keep values this SDK version doesn't list as Unknown, and every response model keeps fields it doesn't know in extra, so new API values never fail decoding; a response that lacks a field the API always sends fails with sdk/invalid-response. Treat a decision you don't recognise as not allowed. To act on a value this version doesn't list, compare as_str() in a _ arm rather than matching Unknown, which stops matching once a later version lists the value.
Options types are #[non_exhaustive]: build them with new, which takes the required fields, and the chained setters, such as UpdateAsset::new(id).name("Holiday").clear_description(), where clear_* sends null. Path IDs also convert from strings: client.assets().retrieve("asset_e5Gm2Rk8XqT3wLp9VbN4".into()).
Waiting for a decision
assets().wait_for_decision retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, until its classification.status is completed or failed, and returns that asset. If there's no decision within the timeout (60 seconds by default), it fails with sdk/timeout, and the error's details() include assetId, the last classificationStatus and moderationDecision (null while there is none). Drop the future to stop waiting.
let queued = client
.assets()
.create(SubmitAsset::new("note.txt", Content::bytes(b"Hello".to_vec(), "text/plain")))
.await?;
let decided = client
.assets()
.wait_for_decision(WaitForDecision::new(queued.id).timeout(std::time::Duration::from_secs(30)))
.await?;Blocking applications
Enable the blocking feature for calmlens::blocking::ServerClient. It runs the async client on a private runtime, so you can create and drop it anywhere, including inside an async runtime. Its calls block the current thread, so don't call them from async code; use the async client there.
use calmlens::{blocking::ServerClient, models::*};
fn main() -> calmlens::Result<()> {
let client = ServerClient::from_env()?;
for asset in client.assets().iterate(ListAssets::new()) {
println!("{}", asset?.id);
}
Ok(())
}Uploads
Content::bytes, Content::text, Content::reader(reader, size, mime_type), Content::stream(stream, size, mime_type) and Content::file(path, mime_type) create upload content; Content::unsized_stream(stream, mime_type) sends a stream of unknown length with chunked transfer encoding. Readers, streams and files are sent as they are read, so the whole file never needs to be in memory. Content::file opens the file first, so it returns std::io::Result<Content>; calmlens::Error doesn't convert from std::io::Error, so map the error in a function that returns calmlens::Result:
let content = Content::file("photo.jpg", "image/jpeg")
.map_err(|error| calmlens::Error::new("sdk/invalid-argument", error.to_string()))?;Set Content.size_in_bytes to declare a payload's byte length explicitly. The SDK rejects a size that differs from the payload's measured length or the size supplied to a reader or stream, before sending the request.
Content larger than part_size_bytes (8 MiB by default) from Content::bytes, base64 or Content::file is uploaded in parts automatically: each part is retried on its own, and calling assets().create or assets().classify again with the same idempotency_key resumes an interrupted upload. To send the parts yourself, for example when you produce a file in chunks, send the first part with SubmitAsset::multipart(name, content.part(1, is_final)) and later parts with assets().upload_part. Set total_size_in_bytes on the first request when you know the file's size. Whether the upload was started with assets().create (queued) or assets().classify (wait for the decision) is fixed by the first part, so any process that knows the asset ID can send the remaining parts. See Multipart uploads.
Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.
Metadata is a list of {id, value} items, such as .metadata(vec![MetadataItem::new("campaign.id", "launch-2026")]). The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.
Upload presets
Pass upload_preset_id on SubmitAsset to apply an upload preset's folder, visibility, file types, size limit, moderation policy and processing options. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.upload_tokens().sign(SignUploadToken::new(...)). Signing happens locally with your API key and makes no request.
CDN methods
To upload a public image for delivery, retain its content and use an API key with Create assets (assets:create) and Share assets (assets:share). Keep the image unpublished until moderation allows it, then use its rendered CDN resource. For a private image, keep visibility private and sign its URL on your server with a key that has Share assets. See Authentication.
let upload = SubmitAsset::new("photo.jpg", Content::bytes(std::fs::read("photo.jpg")?, "image/jpeg"))
.visibility(Visibility::Public)
.processing_options(ProcessingOptions::new().retain_content(true));
let image = client.assets().classify(upload).await?;
if image.classification.moderation.decision == Some(AssetModerationDecision::Allowed) {
let src = client.cdn().get_asset_url(&CdnRequest::asset(&image.id).resource(CdnResource::Rendered))?;
}Fetch retained content directly from your backend with client.cdn().serve():
use calmlens::{models::*, ServerClient};
async fn example(client: &ServerClient) -> Result<(), Box<dyn std::error::Error>> {
let result = client
.cdn()
.serve(CdnRequest::new().asset_id("asset_e5Gm2Rk8XqT3wLp9VbN4").resource("original"))
.await?;
println!("{}", result.status());
Ok(())
}cdn().serve(CdnRequest) returns a streaming CdnResponse whatever its status, containing raw content bytes, not the asset report. Check status(), then read it with chunk(), into_stream(), bytes() or, for text assets (such as comments sent with text().classify), text(); the blocking response implements std::io::Read. Drop an unfinished response to close it. The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with cdn().sign_asset_url instead (see Signed asset URLs).
Upload with .processing_options(ProcessingOptions::new().retain_content(true)) on SubmitAsset to retain content. The CDN delivers by the current classification.moderation.decision, and still requires available content and authorised access. See Delivery while moderation runs.
Methods
Each method takes the options model shown, from calmlens::models. The Rust SDK reference details configuration, models and update fields, uploads, retries, CDN URLs, hash lists and errors.
| Method | Purpose |
|---|---|
text().classify(ClassifyText) | Classify text and wait for the decision. |
assets().create(SubmitAsset) | Upload content and queue processing. |
assets().classify(SubmitAsset) | Upload content and wait for the decision where supported. |
assets().upload_part(UploadPart) | Send the next part of a multipart upload. |
assets().retrieve(AssetId) | Fetch one asset. |
assets().retrieve_by_external_id(RetrieveByExternalId) | Fetch the asset with that external_id, such as the one an 409 asset/duplicate-external-id error names in details.assetId. |
assets().wait_for_decision(WaitForDecision) | Retrieve an asset until it is completed or failed; see Waiting for a decision. |
assets().list_timeline(ListTimeline) / assets().iterate_timeline(ListTimeline) | Page through an audio or video asset's findings timeline Preview, in time order. |
assets().list(ListAssets) / assets().iterate(ListAssets) | List one page of assets, or iterate over every matching asset. |
assets().search(SearchAssets) | Search assets by meaning and by name, ID, external_id, description and tags, best match first; see Asset search. |
assets().list_children(ListChildren) / assets().iterate_children(ListChildren) | List an asset's extracted children. |
assets().update(UpdateAsset) | Update asset fields. |
assets().move_asset(MoveAsset) | Move an asset to a folder, or to the project root. |
assets().retry(AssetId) | Retry an eligible processing failure. |
assets().decide(DecideAsset) | Record a reviewer's decision (an AssetModerationDecision: allowed, limited, age-restricted, blocked or purged) with a required note, using DecideAsset::new(asset_id, decision, note). An asset pending moderation can only be blocked or purged, and purging needs .confirm_purge(true); see POST /. |
assets().request_review(RequestAssetReview) | Send an asset to the human review queue, such as when a user reports it; see Send an asset for human review. |
assets().remove_content(AssetId) | Remove stored content and keep the asset record and report. |
assets().delete(AssetId) | Delete the asset record and its content. |
assets().batch(BatchAssets) | Delete up to 500 assets or remove their stored content in one queued request; see POST /. |
folders().list, iterate, retrieve, create, update, move_folder, delete | Manage folders, with ListFolders, FolderId, CreateFolder, UpdateFolder and MoveFolder. ListFolders::new() lists the first 50 folders at the project root, sorted by name. |
hash_lists().list, iterate, retrieve, create, update, delete | Manage hash lists that image uploads are compared with, with ListHashLists, HashListId, CreateHashList and UpdateHashList. |
hash_lists().list_entries, iterate_entries, add_entry, remove_entry | Manage the hashes in a hash list, with ListHashListEntries, AddHashListEntry and HashListEntryId. |
policies().list, iterate, retrieve, create, update, reset, upgrade, set_automatic_updates, delete, retrieve_assigned, assign | Manage the organisation's moderation policies and choose the one the project uses, with ListPolicies, PolicyId, CreatePolicy, UpdatePolicy, ResetPolicy, UpgradePolicy, SetPolicyAutomaticUpdates and AssignPolicy; see Policies. |
events().list(ListEvents) / events().pages(ListEvents) | Read one page of the project event feed, or follow its cursor page by page. |
lenses().list, iterate, create, retrieve, update, delete | Manage the project's lenses, with ListLenses, LensDefinition, LensId and UpdateLens; see Lenses. |
ensure_lens(LensDefinition) / ensure_lenses(EnsureLenses) | Create lenses by identifier, or change them to the definitions sent. |
cdn().get_asset_url(&CdnRequest) / cdn().serve(CdnRequest) | Build a public asset URL or a resource URL beneath it, or stream content. |
cdn().sign_asset_url(SignAssetUrlOptions) | Sign a private asset's URL for browsers and apps. |
cdn().get_asset_info(&str, GetAssetInfoOptions) | Read an asset URL's display info (/info). |
upload_tokens().sign(SignUploadToken) | Sign an upload token locally, without a request. |
Pagination
Every list returns a cursor page with items, next_cursor and has_more, 50 items unless page_size says otherwise (up to 100). Sort with sort, a comma-separated list of fields, each ascending unless prefixed with -, such as .sort("-createdAt,id"). Asset, hash list, policy and lens lists sort by up to two of createdAt and id; folders sort by one of name and createdAt. The timeline and the events feed have no sort. Each list method returns one page: pass its next_cursor as cursor while has_more is true. Each list also has an iterator that fetches the next page as you read: assets().iterate, assets().iterate_children, assets().iterate_timeline, folders().iterate, hash_lists().iterate, hash_lists().iterate_entries, policies().iterate and lenses().iterate yield items, and events().pages yields pages. The async client returns a Stream; the blocking client returns an Iterator.
use futures_util::TryStreamExt;
let mut assets = client.assets().iterate(ListAssets::new().page_size(100));
while let Some(asset) = assets.try_next().await? {
println!("{}", asset.id);
}events().pages(ListEvents::new().cursor(cursor)) follows each page's next_cursor until a page has has_more: false. An events page's next_cursor is always set: store the last one and continue from it on the next poll. Without cursor, the first page is empty and its next_cursor marks the current time. See Reading the feed.
Errors and retries
Every call returns calmlens::Error:
| Method | Returns |
|---|---|
kind() | An ErrorKind, the class of failure: Api for any non-2xx response, beneath it BadRequest, Authentication, PermissionDenied, NotFound, Conflict, PayloadTooLarge, UnprocessableEntity, RateLimit and Server; then Connection, Timeout, Cancelled, InvalidArgument (with Configuration beneath it), InvalidResponse and WebhookVerification. error.is(ErrorKind::Api) holds for the kind and every kind beneath it, and kind.parent() names the broader kind |
code() | An ErrorCode, such as ErrorCode::AssetNotFound. Compare with a string: error.code() == "asset/not-found" |
status() | The HTTP status (http::StatusCode) of an API error |
raw_body() | An error response's body as text, up to 16 KiB, such as a proxy's HTML page |
request_id() | The response's X-Request-Id, or the error body's requestId without one; include it when you contact support |
retry_after() | The Retry-After delay the failed response sent, if any |
details(), headers(), source() | The API's details, such as validation issues, the response headers and the underlying error |
is_not_found(), is_retryable(), is_timeout() | Common checks |
is_local() | true for errors the SDK raised without a response, such as invalid arguments, content it refuses before sending, timeouts and connection failures: the code is the one the API would use, and status() and request_id() are None |
Invalid client options return sdk/invalid-config, and invalid method arguments, such as an empty asset ID, sdk/invalid-argument. Upload content is checked before it's sent and uses the API's codes, such as 400 upload-payload/invalid, or 413 upload/too-large for content of known size over the upload limit.
| Failure | What the SDK does | What you do |
|---|---|---|
Network failure (sdk/transport-error) or timeout (sdk/timeout) | Retries GET requests, uploads and multipart parts up to twice, waiting from half a second, doubling per retry up to 8 seconds, with some randomness | Once retries run out, retry later: is_retryable() is true |
429, 500, 502, 503, 504 or 409 idempotency/request-in-progress | Retries the same requests, waiting for Retry-After (seconds or a date) when the API sends one | A Retry-After over a minute is returned to you instead: wait, then retry |
wait_for_decision runs out of time | Fails with sdk/timeout | Wait again, or rely on a webhook |
Failure of another write, such as assets().update | Not retried | Retry only when repeating the change is safe |
| Upload from a file, reader or stream | Sent once | Upload again from the start |
| Upload retried from another process | Each upload and part sends an Idempotency-Key, reused for its own retries | Set the same idempotency_key on SubmitAsset, ClassifyText or UploadPart |
| Redirect | Not followed; fails with sdk/http-error | Check the base URLs |
API response over max_response_bytes | Fails with sdk/response-too-large | Raise the limit |
Configure retries with ServerClient::builder(key, project).max_retries(n); 0 turns them off. See Retrying requests safely.
| Setting | Default | Limits |
|---|---|---|
timeout | 120 seconds | Each API call attempt, text uploads and the wait for a CDN response's headers |
upload_timeout | None | Binary uploads, so large files are not cut off |
read_timeout | 120 seconds | The wait for more response data, on every request including CDN streams |
connect_timeout | 10 seconds | Opening a connection |
max_response_bytes | 32 MiB | API response bodies |
part_size_bytes | 8 MiB | Content larger than this is uploaded in parts of this size, from 5 to 64 MiB |
client.with_options(RequestOptions::new()...) returns a handle that shares the client's connections and applies a timeout, a deadline for each whole call, retry limit, idempotency key, extra headers, query parameters and body properties to its calls; client.with_timeout(duration) and client.with_max_retries(n) are shorthands. Route requests through a proxy with ServerClientBuilder::proxy(url), and trust a private root certificate, such as a corporate proxy's, with add_root_certificate(pem). See Client configuration for app_info, the attempt hook and logging, and request for endpoints this SDK version has no method for.
Webhooks
Verify the raw request body before parsing it. construct_webhook_event(raw_body, &headers, secret) checks the signature and the timestamp (within WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, 300 seconds) and returns a models::WebhookEventPayload: the event in the same shape events().list returns, with id, project_id, event_type, severity, title, description, asset_id, asset_sequence, facts and created_at at the top level. description, asset_id and asset_sequence are None when the event has none. It reads the headers in any letter case and joins repeated ones. A missing, wrong or stale signature returns sdk/invalid-webhook-signature; a body that isn't a delivery, or whose fields don't have the types the API sends, returns sdk/invalid-webhook-payload.
With axum, take the body as Bytes, never a parsed Json extractor:
use axum::{body::Bytes, http::{HeaderMap, StatusCode}};
async fn calmlens_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
let secret = std::env::var("CALMLENS_WEBHOOK_SECRET").unwrap_or_default();
match calmlens::construct_webhook_event(&body, &headers, &secret) {
Ok(event) => {
// Queue work keyed by event.id, then respond quickly.
println!("{} {:?}", event.event_type, event.asset_id);
StatusCode::NO_CONTENT
}
Err(error) if error.code() == "sdk/invalid-webhook-signature" => StatusCode::UNAUTHORIZED,
Err(_) => StatusCode::BAD_REQUEST,
}
}With actix-web, take the body as web::Bytes and pass the header values to construct_webhook_event_at:
use actix_web::{web, HttpRequest, HttpResponse};
async fn calmlens_webhook(request: HttpRequest, body: web::Bytes) -> HttpResponse {
let header = |name: &str| request.headers().get(name).and_then(|v| v.to_str().ok()).unwrap_or("");
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let secret = std::env::var("CALMLENS_WEBHOOK_SECRET").unwrap_or_default();
match calmlens::construct_webhook_event_at(
&body,
header(calmlens::WEBHOOK_SIGNATURE_HEADER),
header(calmlens::WEBHOOK_TIMESTAMP_HEADER),
&secret,
now,
calmlens::WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
) {
Ok(_event) => HttpResponse::NoContent().finish(),
Err(error) if error.code() == "sdk/invalid-webhook-signature" => HttpResponse::Unauthorized().finish(),
Err(_) => HttpResponse::BadRequest().finish(),
}
}An event carries only its asset's ID. client.events().retrieve_asset(&event).await? retrieves the asset as it is now, or returns None for an event that isn't about an asset. The asset's event_sequence is the asset_sequence of its latest event when it was read, so an event with a higher asset_sequence happened after the state you retrieved. event.json() returns the body as received, including fields this SDK version doesn't model, and event.is_test() tells a test send from the portal apart from a real event. Deduplicate by event ID. See Webhooks, and Webhook helpers for the header constants, the separate verify and parse functions and signing test deliveries.
Deduplicating by event.id stops a redelivery being applied twice, but it doesn't put events in order: a retry can arrive after a later event about the same asset. Store the highest asset_sequence you've applied for each asset, and apply an event only when is_newer_asset_event(&event, last_sequence) is true, so a late asset.allowed never undoes a later asset.blocked. See Event order.
Test webhooks locally
Your tests and CI need no CLI: the testing helpers build and sign deliveries offline, so your handler's verification runs unchanged. To forward your project's real events to a handler on your machine, install the calmlens CLI, a standalone executable for macOS, Linux and Windows:
curl -fsSL https://calmlens.com/install.sh | shThen run calmlens login and calmlens listen --forward-to <url>. See Local development for Windows, Homebrew, release downloads and npm, sending portal test events through a tunnel, and creating test events with calmlens trigger.
Testing
Use calmlens::testing::MockServerClient, behind the testing feature, for offline tests. See Rust testing.