Ruby SDK reference

Look up the Ruby SDK's settings and how it behaves. Install it, and find the method list and main workflows, on the Ruby SDK page.

Client settings

CalmLens::ServerClient.new takes api_key: and project_id:, plus these optional settings:

SettingDefaultMeaning
base_url:https://api.calmlens.com/v1The API base URL.
cdn_base_url:https://cdn.calmlens.com/v1The CDN base URL.
timeout:120 secondsEach socket read or write, not a whole transfer.
open_timeout:10 secondsOpening a connection.
upload_timeout:NoneEach attempt of a binary upload as a whole.
max_retries:2Retries of requests that are safe to repeat; see Retries and timeouts.
retry_base_delay:0.5 secondsThe first retry's wait when the API gives no Retry-After.
max_response_bytes:32 MiBThe largest response body the client reads.
part_size_bytes:8 MiBContent larger than this is uploaded in parts of this size; see Upload content. From 5 MiB (5242880) to 64 MiB (67108864).

A URL with credentials, a query or a fragment, or one that isn't HTTP(S), raises CalmLens::ConfigurationError (sdk/invalid-config). CalmLens::VERSION holds the gem version.

Options and field names

Every option name may be snake_case or camelCase, at any depth, so options added to the API later work without an SDK update: processing_options: {keep_content_after_processing: true} is sent as processingOptions.keepContentAfterProcessing. Keys inside metadata are yours and are sent unchanged. Responses are Hashes with the API's camelCase String keys.

Request options

Every method also accepts request_options:, which applies to that call only:

KeyMeaning
idempotency_keyThe Idempotency-Key to send. Uploads get a generated one when you omit it; passing one on another write makes that write retryable.
timeoutSeconds allowed for each socket read or write.
open_timeoutSeconds allowed to open a connection.
upload_timeoutSeconds allowed for each attempt of a binary upload.
max_retriesRetries for this call.
max_response_bytesThe largest response body this call reads.

Types

sig/ holds RBS signatures for every public method, with record types for each option Hash and response in sig/types.rbs: CalmLens::asset (with asset_classification, asset_moderation and asset_content), classification_report (categories, qualifiers, labels, media segments and features results), processing_options_input, folder, lens, event, events_page, asset_page, asset_search_response, signed_url and others. Steep and other RBS tools check your calls and the response keys you read:

asset = client.assets.classify(name: 'photo.jpg', content: {data: File.binread('photo.jpg'), type: 'image/jpeg'},
                               processing_options: {features: {ocr: {enabled: true}}})
asset['classification']['moderation']['status']       # CalmLens::asset_moderation_status
asset.dig('content', 'extractedText')                 # CalmLens::extracted_text?

The signatures describe snake_case Symbol option keys; camelCase and String keys work at runtime but are not typed. Results whose fields depend on status (category, qualifier and feature results) are typed as one record with those fields optional: check status, then read score or reason. metadata values and API error details are any JSON (CalmLens::json_value).

Conversation context

assets.create, assets.classify and text.classify take author_id: and context:, the earlier posts in the conversation, oldest first; see Threaded moderation.

client.text.classify(text: 'Same to you', author_id: 'user-9',
                     context: {items: [{text: 'Nice photo!', author_id: 'user-1'}, {text: 'Thanks', author_id: 'user-9'}]})

The SDK sends only the posts CalmLens uses: the most recent 5 (CalmLens::ModerationContext::USED_ITEMS) that fit in 2,000 characters (CalmLens::ModerationContext::USED_CHARACTERS, counted as Unicode code points). The newest post is always sent. CalmLens::ModerationContext.select_items(items) returns the posts that would be sent. The asset returns authorId and the context used; context is nil once the content is removed.

Upload content

Content is one of:

FormUse
{type:, plain_text:}Text.
{type:, base64:}Base64-encoded bytes.
{type:, data:}A binary String or an IO.

An IO is streamed and never read into memory. A File, Tempfile or StringIO, or any IO given with size_in_bytes:, is sent with a Content-Length; a stream of unknown length, such as a pipe or socket, is sent with chunked transfer encoding. A stream that ends early or holds more bytes than declared fails with 400 upload-payload/invalid.

assets.create and assets.classify send content: larger than part_size_bytes: (8 MiB by default) as a multipart upload for you when the client knows its size and can read it again: a binary String, base64, or a File, Tempfile, StringIO or other IO that can seek. Text, and pipes and sockets, go in one request. Parts are part_size_bytes: long, except the last. Each part is retried on its own, and part n from the second onwards carries the key <idempotency_key>:part-<n>, so a key you pass in request_options: can be at most 240 characters for content sent in parts. Parts the API already received are skipped, and the call returns the asset from the final part. If a call fails partway, call it again with the same idempotency_key to resume: the API replays the parts it has and the client sends the rest. Content in parts can be as large as its type allows: images up to 20 MiB, audio and video up to 50 MiB and other files up to 5,000 MiB.

File.open('report.pdf', 'rb') do |file|
  client.assets.create(name: 'report.pdf', content: {data: file, type: 'application/pdf'},
                       request_options: {idempotency_key: "upload-#{upload_id}"})
end

To send the parts yourself, such as a file you produce in chunks, start with part: on assets.create or assets.classify and continue with assets.upload_part. Whether the final part waits for the decision is chosen at the start and saved with the upload; pass wait: to upload_part only to override it. See Multipart uploads.

Reviewer decisions

assets.decide replaces the policy's decision with yours: classification.moderation.status becomes the decision, the decision and note join manualReviews, and the matching asset.<status> event is sent with the API key as its actor. Purging needs confirm_purge: true and the assets:delete permission, and permanently deletes the stored content. A reviewer decision does not change classification.completedAt.

client.assets.decide(asset_id: asset_id, decision: 'blocked', note: 'Spam reported by three members')
client.assets.decide(asset_id: asset_id, decision: 'purged', note: 'Illegal content', confirm_purge: true)

CDN URLs

cdn.get_asset_url builds a URL without a request and cdn.serve fetches one with your API key. Both name the asset with asset_id: or external_id:, and take project_id: (the client's by default) and a resource:. Without a resource, get_asset_url returns the asset URL, which every resource is a path beneath, and serve fetches rendered.

ResourceLens or transform
rendered, previewAccepted
original, placeholder, hls, embed, infoRejected with sdk/invalid-argument
None (the asset URL)Rejected with sdk/invalid-argument

cdn.get_asset_url, cdn.serve and cdn.sign_asset_url accept a lens:, a transform:, or both; the transform's options replace the lens's options of the same name. A transform is an options string or an options Hash, serialized with sorted option keys, so equal transforms share a URL:

client.cdn.get_asset_url(asset_id: asset_id, resource: 'rendered', transform: 'format=png,width=1024')
client.cdn.get_asset_url(asset_id: asset_id, resource: 'rendered', transform: {width: 1024, format: 'png'})
# => ".../rendered/format=png,width=1024" in both cases

A transform is one path segment of options, such as fit=cover,format=webp,width=640, and a lens comes first in the same segment (/rendered/@thumbnail,width=320). Nested options are dotted (border.color) and hex colours drop the #. See Lenses and transforms.

viewer_claims:, such as {age_confirmed: true}, is added unsigned as a JSON viewerClaims query parameter after any lens or transform, leaving out the defaults. Set age_confirmed only where your app has already decided the viewer may see age-restricted content; see Viewer region for the region claim and proxies.

Serving responses

cdn.serve returns a CalmLens::Response with status, headers (lowercase names), success?, request_id, content_type and content_length. With a block it yields the response with a streaming body, read with each_chunk; without one it returns the response with the body read. Read the body once, with each_chunk or body. Error statuses are returned, not raised.

Signed asset URLs

cdn.sign_asset_url(asset_id:, ...) signs a private asset's URL on your server and returns {'url', 'expiresAt'} (Unix milliseconds). expires_in: is 1 to 86,400 seconds (default 900), and original: true lets the URL serve the original; without it, /original returns 403 signed-url/original-not-granted.

signed = client.cdn.sign_asset_url(asset_id: asset_id, expires_in: 900)
thumbnail = "#{signed['url']}/rendered/@thumbnail"

Every resource is a path beneath the signed URL, as beneath a public one. The grant binds the project, the asset, original access and the expiry; resource:, lens:, transform: and viewer_claims: are appended unsigned, exactly as get_asset_url appends them, so you can change them without signing again. See Signed asset URLs.

cdn.get_asset_info(url) reads an asset URL's display info, public or signed, without the API key: the asset's type, size, rendered file, preview, stream and availability for the URL's viewer claims (or viewer_claims:). A refusal raises the CDN's code, such as 403 signed-url/expired.

Upload tokens

client.upload_tokens.sign signs a single-use token for an upload preset locally with your API key, without a request:

signed = client.upload_tokens.sign(
  upload_preset_id: 'preset_4Lk8Qw2Xm9Rt5Vb3Nc7P',
  external_id: 'post-42',     # optional: the uploaded asset gets this ID
  expires_in: 600             # optional: seconds, 1 to 3600, 600 by default
)
# signed['token'], signed['expiresAt'] (milliseconds since the Unix epoch)

Folders

folders.list returns a cursor page with items, the visible ancestors of the listed folders, nextCursor and hasMore, and folders.each iterates over every folder it lists. Set parent_id: to open a branch (omit it for the project root), search: to list only children whose name contains it, and sort: to name (the default) or createdAt, descending when prefixed with -. Only empty folders can be deleted. List one folder's assets with assets.list(filter: 'folderId==fldr_…'), or the project root's with folderId==null. See Pagination and filtering.

Hash lists

Add a 64-character PDQ hash, or an image asset whose hash CalmLens computed. Adding a hash already in the list returns its existing entry, and an asset without a perceptual hash fails with 409 hash-list/asset-not-hashed. See Hash lists.

list = client.hash_lists.create(name: 'Removed images', action: 'block')
entry = client.hash_lists.add_entry(hash_list_id: list['id'], asset_id: asset_id, label: 'Report 1042')
page = client.hash_lists.list_entries(hash_list_id: list['id'], page_size: 50) # items, nextCursor, hasMore
hashes = client.hash_lists.each_entry(hash_list_id: list['id']).map { |item| item['hash'] }
client.hash_lists.update(hash_list_id: list['id'], action: 'flag', description: nil)
client.hash_lists.remove_entry(entry_id: entry['id'])
client.hash_lists.delete(hash_list_id: list['id']) # deletes its entries too

Policies

Policies belong to the API key's organisation and are read and changed by ID. policies.list returns a page of the organisation's policies, oldest first unless sort: says otherwise, policies.each iterates over all of them, and policies.retrieve_assigned returns the policy the project moderates with. A policy's settings define every category with its action, allowances and restrictions. Its preset is nil or names the preset it started from, with mode live (the organisation's own preset policy, following the latest release), pinned (the organisation's own preset policy, held at version) or copy (a policy made from a preset). Every change sends the policy's current revision; a policy changed since is refused with 409 policy/revision-conflict. See Manage policies in code.

current = client.policies.retrieve_assigned
kids = client.policies.create(preset_id: 'children-platform', name: 'Kids section')
kids = client.policies.update(policy_id: kids['id'], revision: kids['revision'], description: 'Stricter rules')
kids = client.policies.reset(policy_id: kids['id'], revision: kids['revision'], preset_version: kids['preset']['version'])
client.policies.assign(policy_id: kids['id'])

policies.reset restores the settings of the release a pinned or copy policy is pinned to (send preset.version), and policies.upgrade moves an unchanged one to the latest release (send preset.latestVersion). policies.set_automatic_updates(policy_id:, enabled:, revision:, preset_version:) switches the organisation's own preset policy between live and pinned, and policies.delete returns nil.

Lenses

A lens is a named image transform the CDN applies at /@<identifier>, and the CDN serves files made with its current definition. ensure_lenses and ensure_lens create lenses, or change them to the definitions you send, by identifier; definitions this client already saved are not sent again. To manage lenses one by one, lenses.list returns a page of the project's lenses (newest first unless sort: says otherwise), lenses.each iterates over them, lenses.create creates one whose identifier is new to the project (otherwise 409 lens/identifier-taken), and lenses.retrieve, lenses.update and lenses.delete take its lens_id:. See Lenses and transforms.

card = client.lenses.create(identifier: 'card', name: 'Card', type: 'image', active: true, transform: {width: 600})
client.lenses.update(lens_id: card['id'], transform: {width: 1200})
client.lenses.delete(lens_id: card['id'])

Events

Each event has id, projectId, type, severity, title, description, assetId, asset (the asset as it was when the event was created), facts and createdAt; description, assetId and asset are nil when the event has none. facts is an array of {'key', 'value', 'url'?} entries registered for its type; see Event facts. CalmLens.get_event_fact(event, 'flagged-categories') returns one fact's value, or nil when the event doesn't carry it, and CalmLens.get_event_facts(event) returns every value by key; a key the event repeats keeps its first value. Both read an events.list item, a delivery body or a parsed CalmLens::WebhookEvent. An unknown cursor raises 400 cursor/invalid.

Webhooks

CalmLens.parse_webhook_event(payload:, secret:, ...) takes either signature: and timestamp: or the request's headers:. headers: accepts a Hash with names in any case (an Array of repeated values is joined with ,), Net::HTTPHeader or a Rack env. The header names are CalmLens::WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER and WEBHOOK_DELIVERY_HEADER.

A delivery signed more than CalmLens::WEBHOOK_SIGNATURE_TOLERANCE_SECONDS (300) from your clock fails; change the window with tolerance_seconds: on parse_webhook_event, verify_webhook_signature or verify_webhook_request.

The returned CalmLens::WebhookEvent has id, project_id, type, severity, title, description, asset_id, asset_sequence, asset, facts, created_at and test?. Deliveries can arrive out of order, so store the highest assetSequence you have applied for each asset. CalmLens.newer_asset_event?(event, last_sequence) (or event.newer_than?(last_sequence)) is false for an event whose asset_sequence isn't higher than last_sequence, and true for a newer one, an event that isn't about an asset, or a nil last_sequence. to_payload returns the whole body as received, including fields CalmLens adds later. A Sinatra or Rack handler that acknowledges first and works in the background:

post '/webhooks/calmlens' do
  request.body.rewind
  event = CalmLens.parse_webhook_event(payload: request.body.read, headers: request.env,
                                       secret: ENV.fetch('CALMLENS_WEBHOOK_SECRET'))
  enqueue(event.id, event.to_payload) # skip an event ID you have already queued
  204
rescue CalmLens::WebhookVerificationError
  400
end

To build signed deliveries for tests, see Webhook handlers.

Errors

Every error is a CalmLens::Error with code, message, details, status, request_id, headers, retry_after and cause. Include request_id when you contact support. not_found? is true for a missing resource; retryable? is true for sdk/transport-error, sdk/timeout, 409 idempotency/request-in-progress, 429, 500, 502, 503 and 504, whichever class carries them. Compare codes with the constants in CalmLens::ErrorCodes (the API's codes, with their HTTP statuses in CalmLens::ErrorCodes::STATUSES) and CalmLens::SdkErrorCodes.

ClassWhen
CalmLens::APIError and its subclasses BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, ServerErrorThe API answered with an error status, or with a redirect (sdk/http-error with the 3xx status), which is never followed.
CalmLens::ConnectionError (sdk/transport-error), CalmLens::TimeoutError (sdk/timeout)No complete response arrived, or assets.wait_for_decision had no decision in time.
CalmLens::InvalidResponseError (sdk/invalid-response, sdk/response-too-large)A successful response could not be read or was not what the API returns, such as an upload answered without an asset, or a response was larger than max_response_bytes:.
CalmLens::InvalidArgumentError (sdk/invalid-argument, or an upload/* code for payload checks the API also makes)An argument was rejected before sending.
CalmLens::ConfigurationError (sdk/invalid-config)ServerClient.new received an invalid setting, such as a malformed base_url:.
CalmLens::WebhookVerificationError (sdk/invalid-webhook-signature, sdk/invalid-webhook-payload)A webhook delivery failed verification.

Retries and timeouts

GET and HEAD requests, and requests that carry an Idempotency-Key, are retried up to max_retries: times. Uploads always carry a key, reused on every retry, so CalmLens runs them once and replays the saved response; other writes carry one only when you pass request_options: {idempotency_key: '...'}. Connection failures, timeouts, 429, 500, 502, 503, 504 and 409 idempotency/request-in-progress are retried with exponential backoff from retry_base_delay:, doubling up to 8 seconds, with half of each wait fixed and half random. A Retry-After in seconds or as an HTTP date replaces the backoff (0 retries at once); one over 60 seconds is raised to you instead of waited out. Redirects are never retried or followed. A streamed upload is retried only when its IO can rewind. cdn.serve retries like a read and returns the last response.

timeout: limits each socket read or write, so large downloads are not cut off. Binary uploads (file content and multipart parts) have no deadline unless you set upload_timeout:, which then limits each attempt as a whole; text content follows timeout:. A response body over max_response_bytes: fails with sdk/response-too-large, before it is read when its Content-Length says so. See Retrying requests safely.

Connections

Reuse one client. It keeps up to 8 idle keep-alive connections per host, is safe to share between threads, and never follows redirects, so your API key never reaches another host. After fork (Puma, Unicorn, Resque) the child opens its own connections instead of sharing the parent's. Call close when finished. Requests identify themselves as calmlens-ruby/<version> (ruby/<version>), and inspect never shows the API key.

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