Expand description
The CalmLens Rust SDK: moderation, storage and CDN delivery.
use calmlens::{models::*, ServerClient};
let client = ServerClient::new("your-api-key", "proj_8fK2mQx7Lp4NvB3tRz9Y")?;
let asset = client.assets().classify(SubmitAsset::text("Hello world")).await?;
if asset.classification.moderation.decision == Some(AssetModerationDecision::Allowed) {
println!("{}", asset.id);
}§Features
async(default): the asyncServerClient, built on Tokio and reqwest.rustls(default): TLS through rustls, verifying certificates with the operating system’s trust store.native-tlsuses the platform TLS library instead.blocking:blocking::ServerClient, the same API withoutasync.tracing: atracingevent, with the targetcalmlens, for every HTTP attempt: failed attempts atINFO, or atDEBUGlike the rest when anon_attempthook reports them.testing:testing::MockServerClient, an offline client for tests. Enable it in[dev-dependencies]only.
With default-features = false the crate offers the models and the webhook helpers
(construct_webhook_event) without an HTTP stack.
Every SDK call returns Error, whose kind is an ErrorKind and whose
code is an ErrorCode.
Options types are #[non_exhaustive]: build them with new (which takes the required
fields) and the chained setters, so a minor release can add an option.
The minimum supported Rust version is 1.88. A minor release may raise it to a version released at least six months earlier; a patch release never does.
Modules§
- blocking
blocking - The blocking client (the
blockingfeature): the async client’s API withoutasync. - models
- Typed request options and response models.
- testing
testing - An offline, programmable client for tests (the
testingfeature).
Structs§
- Assets
Client async - Asset operations. Get it from
ServerClient::assets. - Attempt
Event async - One HTTP attempt the client made, as passed to
ServerClientBuilder::on_attempt. It never holds the API key, upload tokens, signed URL grants or bodies. - Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- CdnClient
async - CDN URLs, signed asset URLs, display info and downloads. Get it from
ServerClient::cdn. - CdnResponse
async - A streaming CDN response. Drop it to close an unfinished download.
- Error
- Every failure the SDK returns: API errors, validation, transport failures and timeouts.
- Events
Client async - The events feed. Get it from
ServerClient::events. - Folders
Client async - Folder operations. Get it from
ServerClient::folders. - Hash
Lists Client async - Hash list operations. Get it from
ServerClient::hash_lists. - Lenses
Client async - The project’s lenses: named image transforms the CDN applies at
/@<identifier>. Get it fromServerClient::lenses. The CDN serves files made with each lens’s current definition;ServerClient::ensure_lensescreates or changes lenses by identifier, for applications that declare theirs in code. - Metadata
Fields Client async - The project’s metadata fields, which share the project settings’
revision. Get it fromServerClient::metadata_fields. - Policies
Client async - Moderation policy operations. Get it from
ServerClient::policies. - Project
Settings Client async - The project’s settings. Get it from
ServerClient::project_settings. - Request
Options async - Options for the calls made through a
ServerClient::with_optionshandle, such asclient.with_options(RequestOptions::new().header("X-Trace", "1")).assets().retrieve(id). - Served
Asset Info async - Pixel dimensions of the representation served by the CDN.
- Server
Client async - The async CalmLens client.
- Server
Client Builder async - Configures a
ServerClient. Create it withServerClient::builder. - Server
Timing - The time the API reports spending on a request, from its
Server-Timingresponse header. Subtractingtotalfrom an attempt’s duration leaves the time spent outside CalmLens: the network, TLS, sending the request body and the caller’s own machine. - Text
Client async - Text moderation. Get it from
ServerClient::text. - Unknown
Value - A wire value an enum of this SDK version does not list, such as an event type the API added
later. It can be read with
as_strbut not constructed, so code that needs a value this version doesn’t list compares the enum’sas_str()in a_arm instead of matchingUnknown; that comparison keeps working once a later version adds the variant. - Upload
Presets Client async - The project’s upload presets: the rules for uploads from browsers and apps. Get it from
ServerClient::upload_presets.UploadPresetsClient::ensurecreates or replaces presets by key, for deploys that declare them in code; send each preset’srevisionto refuse a change made since you read it. - Upload
Tokens Client async - Signs upload tokens, which let a browser upload through an upload preset. Get it from
ServerClient::upload_tokens. Signing happens locally with the API key; no request is made.
Enums§
- Error
Code - A CalmLens error code, such as
asset/not-foundorsdk/timeout. - Error
Kind - What kind of failure an
Erroris, for handling a class of failures rather than eachErrorCode. Kinds form a tree:parentnames the broader kind, andError::isanswers whether an error is a kind or any kind beneath it, soerror.is(ErrorKind::Api)holds for every non-2xx response.
Constants§
- ASSET_
BATCH_ MAX_ ASSETS async - Encodes an identifier as one path segment. “.” and “..” are rejected because URL
resolution treats them as relative segments, which would reach another route.
The most assets one
AssetsClient::batchrequest takes. - DECISION_
POLL_ FIRST_ INTERVAL async - The pause before
AssetsClient::wait_for_decision’s next check when the API answered a check without waiting for the decision. - DECISION_
POLL_ INTERVAL_ FACTOR async - How much longer each such pause between decision checks is than the one before.
- DECISION_
POLL_ MAX_ INTERVAL async - The longest pause between decision checks.
- DEFAULT_
BASE_ URL async - The production API base URL.
- DEFAULT_
CDN_ BASE_ URL async - The production CDN base URL.
- DEFAULT_
DECISION_ TIMEOUT async - How long
AssetsClient::wait_for_decisionwaits by default. - DEFAULT_
MAX_ RESPONSE_ BYTES async - The default size limit for API responses: larger ones fail with
sdk/response-too-large. Change it withServerClientBuilder::max_response_bytes. - DEFAULT_
MAX_ RETRIES async - How many times a repeatable request is retried by default.
- DEFAULT_
PART_ SIZE_ BYTES async - Content larger than this many bytes is uploaded in parts of this size by default: 8 MiB.
- DEFAULT_
SIGNED_ URL_ EXPIRES_ IN async - A signed asset URL’s lifetime in seconds when the options give none: 15 minutes.
- DEFAULT_
TIMEOUT async - The default timeout of each API call attempt.
- DEFAULT_
UPLOAD_ TIMEOUT async - The default timeout of each binary upload attempt: none.
- DEFAULT_
UPLOAD_ TOKEN_ SECONDS async - An upload token’s lifetime in seconds when the options give none: 10 minutes.
- ENSURE_
LENSES_ MAX_ PER_ REQUEST async - The most lens definitions
ServerClient::ensure_lensessends in one request. - MAX_
PART_ SIZE_ BYTES async - The largest
part_size_bytes: 64 MiB. - MAX_
RETRIEVE_ WAIT_ SECONDS async - The longest
wait_timeoutofAssetsClient::retrieve, in seconds: the API holds a response for its decision at most this long. - MAX_
SIGNED_ URL_ EXPIRES_ IN async - The longest signed asset URL lifetime the API accepts, in seconds: 24 hours.
- MIN_
PART_ SIZE_ BYTES async - The smallest
part_size_bytes: every part but the last is at least 5 MiB. - RAW_
BODY_ MAX_ BYTES - The largest error response body
Error::raw_bodykeeps, in bytes. - RETRIEVE_
WAIT_ TIMEOUT_ MARGIN async - How much longer than its
wait_timeouta waiting retrieve’s attempt may take, for the API to answer once the wait is over. - RETRY_
AFTER_ MAX async - The longest
Retry-Afterdelay the SDK waits for; a longer one returns the error (or, forcdn().serve, the response) to the caller instead. - RETRY_
BASE_ DELAY async - The backoff before retry
n(from 0) ismin(RETRY_MAX_DELAY, RETRY_BASE_DELAY * 2^n), of which the client waits half plus a random share of the other half. - RETRY_
MAX_ DELAY async - The longest backoff between attempts.
- VERSION
- This SDK’s version, from its Cargo manifest.
- WEBHOOK_
DELIVERY_ HEADER - Header carrying the delivery ID; use it to deduplicate retried deliveries.
- WEBHOOK_
SIGNATURE_ HEADER - Header carrying
v1=<hex HMAC-SHA256>signatures of"<timestamp>.<raw body>". - WEBHOOK_
SIGNATURE_ TOLERANCE_ SECONDS - Deliveries whose timestamp is further than this from the receiver’s clock are rejected.
- WEBHOOK_
TIMESTAMP_ HEADER - Header carrying the Unix timestamp (seconds) that was signed.
Traits§
- Event
Facts - An event with facts: an
Eventfrom the events feed or aWebhookEventPayloaddelivery, forget_event_factandget_event_facts. - Resource
Event - An event that may be about a resource: an
Eventfrom the events feed or aWebhookEventPayloaddelivery, foris_newer_eventandEventsClient::retrieve_asset.
Functions§
- construct_
webhook_ event - Verifies a delivery’s signature and freshness from its headers, then parses it.
- construct_
webhook_ event_ at construct_webhook_eventfor frameworks with their own header types (such as actix-web), and for tests: takes the header values (repeated headers joined with,), the current Unix time and the tolerance in seconds.- create_
webhook_ headers - The headers of one signed delivery of the raw
body, as CalmLens sends them:content-type,WEBHOOK_DELIVERY_HEADER,WEBHOOK_TIMESTAMP_HEADER(timestamp, Unix seconds) andWEBHOOK_SIGNATURE_HEADER. Use it to test a webhook handler with the current time, since handlers reject deliveries more than five minutes old. Fails withsdk/invalid-argumentwhendelivery_idis not a valid header value. - create_
webhook_ signature_ header - Returns the
WEBHOOK_SIGNATURE_HEADERvalue for the rawbodysigned attimestamp. Arguments follow the same order asverify_webhook_signature. - get_
event_ fact - The value of one of an event’s facts, by key, such as
flagged-categorieson anasset.blockedevent, orNonewhen the event doesn’t carry it. A key the event repeats gives its first value. The fact’surl, when it has one, is on the fact infacts. - get_
event_ facts - An event’s facts as values by key, such as
{"flagged-categories": ["hate"]}. A key the event repeats keeps its first value, asget_event_factreads it. - is_
newer_ event - Whether to apply
eventafterlast_sequence, the highestsequenceyou have applied for its resource (Nonewhen none). Deliveries can arrive out of order: an event about a resource is newer only with a higherresource.sequence, so a retried or repeated delivery of an earlier one returnsfalse. Events about no resource have no sequence and are always new. Store the highestresource.sequenceapplied perresource.idand ignore events this returnsfalsefor. - parse_
webhook_ event - Parses a webhook delivery body without verifying it; prefer
construct_webhook_event. - user_
agent - The
User-Agentthe SDK sends:calmlens-rust/<version> (rustc/<compiler version>). - verify_
webhook_ headers - Verifies a delivery from its request headers:
WEBHOOK_SIGNATURE_HEADERandWEBHOOK_TIMESTAMP_HEADER, whose nameshttp::HeaderMapmatches in any case. Repeated headers are joined with,, so a signature list split across headers verifies (and a repeated timestamp does not). Takes the raw body,nowin Unix seconds and the tolerance in seconds, likeverify_webhook_signature. - verify_
webhook_ signature - Verifies the exact raw
bodybytes against theWEBHOOK_SIGNATURE_HEADERandWEBHOOK_TIMESTAMP_HEADERvalues, rejecting timestamps more thantoleranceseconds fromnow(Unix seconds; useWEBHOOK_SIGNATURE_TOLERANCE_SECONDS). Pass the request body as received, never a re-serialized JSON value; it need not be valid UTF-8.
Type Aliases§
- Byte
Stream async - A stream of upload or download chunks.
- Result
Resultwith the SDK’sError.