Skip to main content

Crate calmlens

Crate calmlens 

Source
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 async ServerClient, built on Tokio and reqwest.
  • rustls (default): TLS through rustls, verifying certificates with the operating system’s trust store. native-tls uses the platform TLS library instead.
  • blocking: blocking::ServerClient, the same API without async.
  • tracing: a tracing event, with the target calmlens, for every HTTP attempt: failed attempts at INFO, or at DEBUG like the rest when an on_attempt hook 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§

blockingblocking
The blocking client (the blocking feature): the async client’s API without async.
models
Typed request options and response models.
testingtesting
An offline, programmable client for tests (the testing feature).

Structs§

AssetsClientasync
Asset operations. Get it from ServerClient::assets.
AttemptEventasync
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.
CdnClientasync
CDN URLs, signed asset URLs, display info and downloads. Get it from ServerClient::cdn.
CdnResponseasync
A streaming CDN response. Drop it to close an unfinished download.
Error
Every failure the SDK returns: API errors, validation, transport failures and timeouts.
EventsClientasync
The events feed. Get it from ServerClient::events.
FoldersClientasync
Folder operations. Get it from ServerClient::folders.
HashListsClientasync
Hash list operations. Get it from ServerClient::hash_lists.
LensesClientasync
The project’s lenses: named image transforms the CDN applies at /@<identifier>. Get it from ServerClient::lenses. The CDN serves files made with each lens’s current definition; ServerClient::ensure_lenses creates or changes lenses by identifier, for applications that declare theirs in code.
MetadataFieldsClientasync
The project’s metadata fields, which share the project settings’ revision. Get it from ServerClient::metadata_fields.
PoliciesClientasync
Moderation policy operations. Get it from ServerClient::policies.
ProjectSettingsClientasync
The project’s settings. Get it from ServerClient::project_settings.
RequestOptionsasync
Options for the calls made through a ServerClient::with_options handle, such as client.with_options(RequestOptions::new().header("X-Trace", "1")).assets().retrieve(id).
ServedAssetInfoasync
Pixel dimensions of the representation served by the CDN.
ServerClientasync
The async CalmLens client.
ServerClientBuilderasync
Configures a ServerClient. Create it with ServerClient::builder.
ServerTiming
The time the API reports spending on a request, from its Server-Timing response header. Subtracting total from an attempt’s duration leaves the time spent outside CalmLens: the network, TLS, sending the request body and the caller’s own machine.
TextClientasync
Text moderation. Get it from ServerClient::text.
UnknownValue
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_str but not constructed, so code that needs a value this version doesn’t list compares the enum’s as_str() in a _ arm instead of matching Unknown; that comparison keeps working once a later version adds the variant.
UploadPresetsClientasync
The project’s upload presets: the rules for uploads from browsers and apps. Get it from ServerClient::upload_presets. UploadPresetsClient::ensure creates or replaces presets by key, for deploys that declare them in code; send each preset’s revision to refuse a change made since you read it.
UploadTokensClientasync
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§

ErrorCode
A CalmLens error code, such as asset/not-found or sdk/timeout.
ErrorKind
What kind of failure an Error is, for handling a class of failures rather than each ErrorCode. Kinds form a tree: parent names the broader kind, and Error::is answers whether an error is a kind or any kind beneath it, so error.is(ErrorKind::Api) holds for every non-2xx response.

Constants§

ASSET_BATCH_MAX_ASSETSasync
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::batch request takes.
DECISION_POLL_FIRST_INTERVALasync
The pause before AssetsClient::wait_for_decision’s next check when the API answered a check without waiting for the decision.
DECISION_POLL_INTERVAL_FACTORasync
How much longer each such pause between decision checks is than the one before.
DECISION_POLL_MAX_INTERVALasync
The longest pause between decision checks.
DEFAULT_BASE_URLasync
The production API base URL.
DEFAULT_CDN_BASE_URLasync
The production CDN base URL.
DEFAULT_DECISION_TIMEOUTasync
How long AssetsClient::wait_for_decision waits by default.
DEFAULT_MAX_RESPONSE_BYTESasync
The default size limit for API responses: larger ones fail with sdk/response-too-large. Change it with ServerClientBuilder::max_response_bytes.
DEFAULT_MAX_RETRIESasync
How many times a repeatable request is retried by default.
DEFAULT_PART_SIZE_BYTESasync
Content larger than this many bytes is uploaded in parts of this size by default: 8 MiB.
DEFAULT_SIGNED_URL_EXPIRES_INasync
A signed asset URL’s lifetime in seconds when the options give none: 15 minutes.
DEFAULT_TIMEOUTasync
The default timeout of each API call attempt.
DEFAULT_UPLOAD_TIMEOUTasync
The default timeout of each binary upload attempt: none.
DEFAULT_UPLOAD_TOKEN_SECONDSasync
An upload token’s lifetime in seconds when the options give none: 10 minutes.
ENSURE_LENSES_MAX_PER_REQUESTasync
The most lens definitions ServerClient::ensure_lenses sends in one request.
MAX_PART_SIZE_BYTESasync
The largest part_size_bytes: 64 MiB.
MAX_RETRIEVE_WAIT_SECONDSasync
The longest wait_timeout of AssetsClient::retrieve, in seconds: the API holds a response for its decision at most this long.
MAX_SIGNED_URL_EXPIRES_INasync
The longest signed asset URL lifetime the API accepts, in seconds: 24 hours.
MIN_PART_SIZE_BYTESasync
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_body keeps, in bytes.
RETRIEVE_WAIT_TIMEOUT_MARGINasync
How much longer than its wait_timeout a waiting retrieve’s attempt may take, for the API to answer once the wait is over.
RETRY_AFTER_MAXasync
The longest Retry-After delay the SDK waits for; a longer one returns the error (or, for cdn().serve, the response) to the caller instead.
RETRY_BASE_DELAYasync
The backoff before retry n (from 0) is min(RETRY_MAX_DELAY, RETRY_BASE_DELAY * 2^n), of which the client waits half plus a random share of the other half.
RETRY_MAX_DELAYasync
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§

EventFacts
An event with facts: an Event from the events feed or a WebhookEventPayload delivery, for get_event_fact and get_event_facts.
ResourceEvent
An event that may be about a resource: an Event from the events feed or a WebhookEventPayload delivery, for is_newer_event and EventsClient::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_event for 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) and WEBHOOK_SIGNATURE_HEADER. Use it to test a webhook handler with the current time, since handlers reject deliveries more than five minutes old. Fails with sdk/invalid-argument when delivery_id is not a valid header value.
create_webhook_signature_header
Returns the WEBHOOK_SIGNATURE_HEADER value for the raw body signed at timestamp. Arguments follow the same order as verify_webhook_signature.
get_event_fact
The value of one of an event’s facts, by key, such as flagged-categories on an asset.blocked event, or None when the event doesn’t carry it. A key the event repeats gives its first value. The fact’s url, when it has one, is on the fact in facts.
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, as get_event_fact reads it.
is_newer_event
Whether to apply event after last_sequence, the highest sequence you have applied for its resource (None when none). Deliveries can arrive out of order: an event about a resource is newer only with a higher resource.sequence, so a retried or repeated delivery of an earlier one returns false. Events about no resource have no sequence and are always new. Store the highest resource.sequence applied per resource.id and ignore events this returns false for.
parse_webhook_event
Parses a webhook delivery body without verifying it; prefer construct_webhook_event.
user_agent
The User-Agent the SDK sends: calmlens-rust/<version> (rustc/<compiler version>).
verify_webhook_headers
Verifies a delivery from its request headers: WEBHOOK_SIGNATURE_HEADER and WEBHOOK_TIMESTAMP_HEADER, whose names http::HeaderMap matches 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, now in Unix seconds and the tolerance in seconds, like verify_webhook_signature.
verify_webhook_signature
Verifies the exact raw body bytes against the WEBHOOK_SIGNATURE_HEADER and WEBHOOK_TIMESTAMP_HEADER values, rejecting timestamps more than tolerance seconds from now (Unix seconds; use WEBHOOK_SIGNATURE_TOLERANCE_SECONDS). Pass the request body as received, never a re-serialized JSON value; it need not be valid UTF-8.

Type Aliases§

ByteStreamasync
A stream of upload or download chunks.
Result
Result with the SDK’s Error.