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.

Install

cargo add calmlens
cargo add tokio --features macros,rt-multi-thread
cargo add futures-util

See 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 with bundled root certificates). Other features:

FeatureAdds
blockingcalmlens::blocking::ServerClient, the same API without async
rustls-native-rootsTLS with the operating system's root certificates
native-tlsTLS through the platform library
testingcalmlens::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. 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<()> {
    let client = ServerClient::new(
        std::env::var("CALMLENS_API_KEY").expect("CALMLENS_API_KEY is set"),
        std::env::var("CALMLENS_PROJECT_ID").expect("CALMLENS_PROJECT_ID is set"),
    )?;
    let asset = client
        .text()
        .classify(ClassifyText {
            text: "Great photo!".into(),
            external_id: Some("comment-42".into()),
            ..Default::default()
        })
        .await?;
    if asset.classification.moderation.status == AssetModerationStatus::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: Some(ViewerClaims { age_confirmed: Some(true), ..Default::default() }) 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. See Reading classification results.

The status enums, such as AssetModerationStatus, and Visibility have an Unknown variant, and every response model keeps fields this SDK version doesn't know in extra, so new API values never fail decoding. Treat a status you don't recognise as not allowed.

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 and the last classificationStatus and moderationStatus. 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::new(
        std::env::var("CALMLENS_API_KEY").expect("CALMLENS_API_KEY is set"),
        std::env::var("CALMLENS_PROJECT_ID").expect("CALMLENS_PROJECT_ID is set"),
    )?;
    for asset in client.assets().iterate(ListAssets::default()) {
        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: Some(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 and size limit. 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

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 { asset_id: Some("asset_5Gm2Rk8XqT3wLp9VbN4c".into()), resource: Some("original".into()), ..Default::default() }).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: Some(ProcessingOptions { keep_content_after_processing: Some(true), ..Default::default() }) on SubmitAsset to retain content. The CDN delivers by the current classification.moderation.status, 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.

MethodPurpose
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().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/:assetId/decision.
assets().explain(ExplainAsset)Fetch the full policy evidence for a decision (which rules and findings produced it), or with rerun moderate the asset again under the current policy.
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 /projects/:projectId/assets/batch.
folders().list, iterate, retrieve, create, update, move_folder, deleteManage folders, with ListFolders, FolderId, CreateFolder, UpdateFolder and MoveFolder. ListFolders::default() lists the first 50 folders at the project root, sorted by name.
hash_lists().list, iterate, retrieve, create, update, deleteManage hash lists that image uploads are compared with, with ListHashLists, HashListId, CreateHashList and UpdateHashList.
hash_lists().list_entries, iterate_entries, add_entry, remove_entryManage 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, assignManage 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, deleteManage 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 Some("-createdAt,id".into()). 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 { page_size: Some(100), ..Default::default() });
while let Some(asset) = assets.try_next().await? {
    println!("{}", asset.id);
}

events().pages(ListEvents { cursor: Some(cursor), ..Default::default() }) 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:

MethodReturns
code()An ErrorCode, such as ErrorCode::AssetNotFound, or ErrorCode::Other for codes this SDK version doesn't know. Compare with a string: error.code() == "asset/not-found"
status()The HTTP status of an API error
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

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.

FailureWhat the SDK doesWhat 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 randomnessOnce retries run out, retry later: is_retryable() is true
429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or a date) when the API sends oneA Retry-After over a minute is returned to you instead: wait, then retry
wait_for_decision runs out of timeFails with sdk/timeoutWait again, or rely on a webhook
Failure of another write, such as assets().updateNot retriedRetry only when repeating the change is safe
Upload from a file, reader or streamSent onceUpload again from the start
Upload retried from another processEach upload and part sends an Idempotency-Key, reused for its own retriesSet the same idempotency_key on SubmitAsset, ClassifyText or UploadPart
RedirectNot followed; fails with sdk/http-errorCheck the base URLs
API response over max_response_bytesFails with sdk/response-too-largeRaise the limit

Configure retries with ServerClient::builder(key, project).max_retries(n); 0 turns them off. See Retrying requests safely.

SettingDefaultLimits
timeout120 secondsEach API call attempt, text uploads and the wait for a CDN response's headers
upload_timeoutNoneBinary uploads, so large files are not cut off
read_timeout120 secondsThe wait for more response data, on every request including CDN streams
connect_timeout10 secondsOpening a connection
max_response_bytes32 MiBAPI response bodies
part_size_bytes8 MiBContent larger than this is uploaded in parts of this size, from 5 to 64 MiB

client.with_timeout(duration) and client.with_max_retries(n) return a handle that shares the client's connections and applies that timeout (uploads and CDN downloads included) or retry limit to its calls. Pass your own reqwest::Client with ServerClientBuilder::http_client for a proxy or custom certificates. Its own connect and read timeouts then apply instead of connect_timeout and read_timeout, and it follows redirects unless you build it with .redirect(reqwest::redirect::Policy::none()).

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, facts and created_at at the top level. description, asset_id and asset 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(),
    }
}

Read the asset snapshot with accessors such as asset.moderation_status(). 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, and retrieve the asset for its current state rather than trusting the snapshot. See Webhooks, and Webhook helpers for the header constants, the separate verify and parse functions and signing test deliveries.

Command-line tool

See Local development to install the CLI, forward signed events and trigger test uploads.

Testing

Use calmlens::testing::MockServerClient, behind the testing feature, for offline tests. See Rust testing.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies