use crate::error::{invalid_argument, invalid_config, invalid_payload, ErrorCode};
use crate::models::*;
use crate::transport::{
decode, execute, read_file_range, stream_error, upload_body, uuid, CallOptions, Deadline,
Exchange, Prepared, RequestBody, Transport, DEFAULT_MAX_RESPONSE_BYTES,
};
use crate::{Error, ResourceEvent, Result};
use bytes::Bytes;
use futures_util::{stream::BoxStream, StreamExt, TryStreamExt};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use serde::Serialize;
use std::{
collections::{HashMap, VecDeque},
fmt,
sync::{Arc, Mutex},
time::Duration,
};
pub const DEFAULT_BASE_URL: &str = "https://api.calmlens.com/v1";
pub const DEFAULT_CDN_BASE_URL: &str = "https://cdn.calmlens.com/v1";
pub const ENSURE_LENSES_MAX_PER_REQUEST: usize = 100;
pub const MAX_SIGNED_URL_EXPIRES_IN: u64 = 24 * 60 * 60;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
pub const DEFAULT_UPLOAD_TIMEOUT: Option<Duration> = None;
pub const DEFAULT_MAX_RETRIES: u32 = 2;
pub const DEFAULT_SIGNED_URL_EXPIRES_IN: u64 = 15 * 60;
pub const DEFAULT_UPLOAD_TOKEN_SECONDS: u32 = 10 * 60;
pub const DEFAULT_PART_SIZE_BYTES: u64 = 8 * 1024 * 1024;
pub const MIN_PART_SIZE_BYTES: u64 = 5 * 1024 * 1024;
pub const MAX_PART_SIZE_BYTES: u64 = 64 * 1024 * 1024;
const MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH: usize = 240;
pub const DEFAULT_DECISION_TIMEOUT: Duration = Duration::from_secs(60);
pub const DECISION_POLL_FIRST_INTERVAL: Duration = Duration::from_millis(500);
pub const DECISION_POLL_INTERVAL_FACTOR: f64 = 1.5;
pub const DECISION_POLL_MAX_INTERVAL: Duration = Duration::from_secs(2);
pub const MAX_RETRIEVE_WAIT_SECONDS: u32 = 30;
pub const RETRIEVE_WAIT_TIMEOUT_MARGIN: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub struct ServerClientBuilder {
api_key: String,
project_id: String,
base_url: String,
cdn_base_url: String,
timeout: Duration,
upload_timeout: Option<Duration>,
connect_timeout: Duration,
read_timeout: Duration,
max_retries: u32,
max_response_bytes: usize,
part_size_bytes: u64,
proxy: Option<String>,
root_certificates: Vec<Vec<u8>>,
app_info: Option<AppInfo>,
on_attempt: Option<crate::observe::AttemptHook>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AppInfo {
name: String,
version: Option<String>,
url: Option<String>,
}
impl AppInfo {
fn suffix(&self) -> String {
let mut suffix = format!(" {}", self.name);
if let Some(version) = &self.version {
suffix.push('/');
suffix.push_str(version);
}
if let Some(url) = &self.url {
suffix.push_str(&format!(" ({url})"));
}
suffix
}
}
impl fmt::Debug for ServerClientBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ServerClientBuilder")
.field("api_key", &"[redacted]")
.field("project_id", &self.project_id)
.field("base_url", &self.base_url)
.field("cdn_base_url", &self.cdn_base_url)
.field("timeout", &self.timeout)
.field("upload_timeout", &self.upload_timeout)
.field("connect_timeout", &self.connect_timeout)
.field("read_timeout", &self.read_timeout)
.field("max_retries", &self.max_retries)
.field("max_response_bytes", &self.max_response_bytes)
.field("part_size_bytes", &self.part_size_bytes)
.field("proxy", &self.proxy.as_ref().map(|_| "[set]"))
.field("root_certificates", &self.root_certificates.len())
.field("app_info", &self.app_info)
.field("on_attempt", &self.on_attempt.is_some())
.finish()
}
}
impl ServerClientBuilder {
pub(crate) fn new(api_key: String, project_id: String) -> Self {
Self {
api_key,
project_id,
base_url: DEFAULT_BASE_URL.into(),
cdn_base_url: DEFAULT_CDN_BASE_URL.into(),
timeout: DEFAULT_TIMEOUT,
upload_timeout: DEFAULT_UPLOAD_TIMEOUT,
connect_timeout: Duration::from_secs(10),
read_timeout: Duration::from_secs(120),
max_retries: DEFAULT_MAX_RETRIES,
max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
part_size_bytes: DEFAULT_PART_SIZE_BYTES,
proxy: None,
root_certificates: Vec::new(),
app_info: None,
on_attempt: None,
}
}
pub fn from_env() -> Result<Self> {
let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty());
let (Some(api_key), Some(project_id)) =
(var("CALMLENS_API_KEY"), var("CALMLENS_PROJECT_ID"))
else {
return Err(invalid_config(
"Set CALMLENS_API_KEY and CALMLENS_PROJECT_ID, or pass the API key and project ID",
));
};
let mut builder = Self::new(api_key, project_id);
if let Some(base_url) = var("CALMLENS_BASE_URL") {
builder.base_url = base_url;
}
Ok(builder)
}
pub fn base_url(mut self, value: impl Into<String>) -> Self {
self.base_url = value.into();
self
}
pub fn cdn_base_url(mut self, value: impl Into<String>) -> Self {
self.cdn_base_url = value.into();
self
}
pub fn timeout(mut self, value: Duration) -> Self {
self.timeout = value;
self
}
pub fn upload_timeout(mut self, value: Duration) -> Self {
self.upload_timeout = Some(value);
self
}
pub fn max_response_bytes(mut self, value: usize) -> Self {
self.max_response_bytes = value;
self
}
pub fn part_size_bytes(mut self, value: u64) -> Self {
self.part_size_bytes = value;
self
}
pub fn connect_timeout(mut self, value: Duration) -> Self {
self.connect_timeout = value;
self
}
pub fn read_timeout(mut self, value: Duration) -> Self {
self.read_timeout = value;
self
}
pub fn max_retries(mut self, value: u32) -> Self {
self.max_retries = value;
self
}
pub fn proxy(mut self, url: impl Into<String>) -> Self {
self.proxy = Some(url.into());
self
}
pub fn add_root_certificate(mut self, pem: impl Into<Vec<u8>>) -> Self {
self.root_certificates.push(pem.into());
self
}
pub fn app_info(
mut self,
name: impl Into<String>,
version: Option<&str>,
url: Option<&str>,
) -> Self {
self.app_info = Some(AppInfo {
name: name.into(),
version: version.map(str::to_owned),
url: url.map(str::to_owned),
});
self
}
pub fn on_attempt(
mut self,
hook: impl Fn(&crate::AttemptEvent) + Send + Sync + 'static,
) -> Self {
self.on_attempt = Some(Arc::new(hook));
self
}
pub fn build(self) -> Result<ServerClient> {
let config = self.validate()?;
let mut http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(self.connect_timeout)
.read_timeout(self.read_timeout)
.no_proxy();
if let Some(url) = &self.proxy {
let proxy = reqwest::Proxy::all(url.as_str()).map_err(|cause| {
invalid_config("proxy must be an HTTP(S) or SOCKS proxy URL").with_source(cause)
})?;
http = http.proxy(proxy);
}
for pem in &self.root_certificates {
let certificates = reqwest::Certificate::from_pem_bundle(pem).map_err(|cause| {
invalid_config("add_root_certificate needs PEM certificates").with_source(cause)
})?;
if certificates.is_empty() {
return Err(invalid_config(
"add_root_certificate needs PEM certificates",
));
}
for certificate in certificates {
http = http.add_root_certificate(certificate);
}
}
let http = http.build().map_err(|cause| {
invalid_config(format!("Could not create the HTTP client: {cause}")).with_source(cause)
})?;
Ok(ServerClient::from_parts(config, Transport::Http(http)))
}
#[cfg(feature = "testing")]
pub(crate) fn base_urls(&self) -> [String; 2] {
[&self.base_url, &self.cdn_base_url].map(|url| url.trim_end_matches('/').to_owned())
}
#[cfg(feature = "testing")]
pub(crate) fn build_mock(
self,
mock: Arc<crate::testing::MockTransport>,
) -> Result<ServerClient> {
Ok(ServerClient::from_parts(
self.validate()?,
Transport::Mock(mock),
))
}
fn validate(&self) -> Result<Config> {
for (name, value) in [
("timeout", Some(self.timeout)),
("upload_timeout", self.upload_timeout),
("connect_timeout", Some(self.connect_timeout)),
("read_timeout", Some(self.read_timeout)),
] {
if value.is_some_and(|value| value.is_zero()) {
return Err(invalid_config(format!("{name} must be positive")));
}
}
if self.max_response_bytes == 0 {
return Err(invalid_config("max_response_bytes must be positive"));
}
if !(MIN_PART_SIZE_BYTES..=MAX_PART_SIZE_BYTES).contains(&self.part_size_bytes) {
return Err(invalid_config(format!(
"part_size_bytes must be from {MIN_PART_SIZE_BYTES} (5 MiB) to {MAX_PART_SIZE_BYTES} (64 MiB)"
)));
}
if self.api_key.is_empty() || self.project_id.is_empty() {
return Err(invalid_config("API key and project ID are required"));
}
id(&self.project_id).map_err(|_| invalid_config("Invalid project ID"))?;
if !self.api_key.bytes().all(|byte| matches!(byte, 0x21..=0x7e)) {
return Err(invalid_config(
"The API key must be printable ASCII without spaces",
));
}
let api_key = HeaderValue::from_str(&self.api_key)
.map_err(|_| invalid_config("The API key contains characters a header cannot"))?;
let mut api_key = api_key;
api_key.set_sensitive(true);
let mut urls = Vec::new();
for url in [&self.base_url, &self.cdn_base_url] {
let parsed = reqwest::Url::parse(url).ok().filter(|url| {
["http", "https"].contains(&url.scheme())
&& url.query().is_none()
&& url.fragment().is_none()
});
if parsed.is_none() {
return Err(invalid_config(format!(
"Base URLs must be absolute HTTP(S) URLs without a query: {url:?}"
)));
}
urls.push(url.trim_end_matches('/').to_owned());
}
let user_agent = format!(
"{}{}",
crate::user_agent(),
self.app_info
.as_ref()
.map(AppInfo::suffix)
.unwrap_or_default()
);
let user_agent = HeaderValue::from_str(&user_agent)
.map_err(|_| invalid_config("app_info must be printable ASCII"))?;
Ok(Config {
observer: crate::observe::Observer {
hook: self.on_attempt.clone(),
log: crate::observe::LogLevel::from_env(),
},
user_agent,
api_key,
project_id: self.project_id.clone(),
cdn_base_url: urls.pop().unwrap_or_default(),
base_url: urls.pop().unwrap_or_default(),
timeout: self.timeout,
upload_timeout: self.upload_timeout,
max_retries: self.max_retries,
max_response_bytes: self.max_response_bytes,
part_size_bytes: self.part_size_bytes,
})
}
}
struct Config {
observer: crate::observe::Observer,
user_agent: HeaderValue,
api_key: HeaderValue,
project_id: String,
base_url: String,
cdn_base_url: String,
timeout: Duration,
upload_timeout: Option<Duration>,
max_retries: u32,
max_response_bytes: usize,
part_size_bytes: u64,
}
struct Inner {
config: Config,
transport: Transport,
user_agent: HeaderValue,
lenses: Mutex<HashMap<String, Lens>>,
ensuring: tokio::sync::Mutex<()>,
interrupted_uploads: Mutex<VecDeque<String>>,
}
const INTERRUPTED_UPLOADS: usize = 1000;
struct InterruptedUpload<'a> {
uploads: &'a Mutex<VecDeque<String>>,
key: Option<String>,
}
impl InterruptedUpload<'_> {
fn completed(mut self) {
if let Some(key) = self.key.take() {
let mut uploads = self.uploads.lock().unwrap_or_else(|e| e.into_inner());
uploads.retain(|remembered| *remembered != key);
}
}
}
impl Drop for InterruptedUpload<'_> {
fn drop(&mut self) {
if let Some(key) = self.key.take() {
let mut uploads = self.uploads.lock().unwrap_or_else(|e| e.into_inner());
uploads.retain(|remembered| *remembered != key);
if uploads.len() >= INTERRUPTED_UPLOADS {
uploads.pop_front();
}
uploads.push_back(key);
}
}
}
#[derive(Clone)]
pub struct ServerClient {
inner: Arc<Inner>,
timeout: Option<Duration>,
max_retries: Option<u32>,
request_options: Option<Arc<RequestOptions>>,
deadline_at: Option<tokio::time::Instant>,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct RequestOptions {
pub timeout: Option<Duration>,
pub deadline: Option<Duration>,
pub max_retries: Option<u32>,
pub idempotency_key: Option<String>,
pub headers: Vec<(String, String)>,
pub extra_query: Vec<(String, String)>,
pub extra_body: serde_json::Map<String, serde_json::Value>,
}
impl RequestOptions {
pub fn new() -> Self {
Self::default()
}
pub fn timeout(mut self, value: Duration) -> Self {
self.timeout = Some(value);
self
}
pub fn max_retries(mut self, value: u32) -> Self {
self.max_retries = Some(value);
self
}
pub fn deadline(mut self, value: Duration) -> Self {
self.deadline = Some(value);
self
}
pub fn idempotency_key(mut self, value: impl Into<String>) -> Self {
self.idempotency_key = Some(value.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.extra_query.push((name.into(), value.into()));
self
}
pub fn body_field(
mut self,
name: impl Into<String>,
value: impl Into<serde_json::Value>,
) -> Self {
self.extra_body.insert(name.into(), value.into());
self
}
}
impl fmt::Debug for ServerClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let config = &self.inner.config;
f.debug_struct("ServerClient")
.field("api_key", &"[redacted]")
.field("project_id", &config.project_id)
.field("base_url", &config.base_url)
.field("cdn_base_url", &config.cdn_base_url)
.field("timeout", &self.timeout.unwrap_or(config.timeout))
.field(
"max_retries",
&self.max_retries.unwrap_or(config.max_retries),
)
.finish_non_exhaustive()
}
}
impl ServerClient {
pub fn new(api_key: impl Into<String>, project_id: impl Into<String>) -> Result<Self> {
Self::builder(api_key, project_id).build()
}
pub fn from_env() -> Result<Self> {
ServerClientBuilder::from_env()?.build()
}
pub fn builder(
api_key: impl Into<String>,
project_id: impl Into<String>,
) -> ServerClientBuilder {
ServerClientBuilder::new(api_key.into(), project_id.into())
}
fn from_parts(config: Config, transport: Transport) -> Self {
let user_agent = config.user_agent.clone();
Self {
inner: Arc::new(Inner {
config,
transport,
user_agent,
lenses: Mutex::new(HashMap::new()),
ensuring: tokio::sync::Mutex::new(()),
interrupted_uploads: Mutex::new(VecDeque::new()),
}),
timeout: None,
max_retries: None,
request_options: None,
deadline_at: None,
}
}
pub fn with_timeout(&self, timeout: Duration) -> Self {
Self {
timeout: Some(timeout),
..self.clone()
}
}
pub fn with_options(&self, options: RequestOptions) -> Self {
Self {
timeout: options.timeout.or(self.timeout),
max_retries: options.max_retries.or(self.max_retries),
request_options: Some(Arc::new(options)),
..self.clone()
}
}
pub async fn request(
&self,
method: Method,
path: &str,
body: Option<&serde_json::Value>,
) -> Result<serde_json::Value> {
if !path.starts_with('/') || path.starts_with("//") {
return Err(invalid_argument("path must start with a single /"));
}
let mut request = self.prepare(method, path, &[])?;
if let Some(body) = body {
request = request.json(body)?;
}
let (_, headers, body) = self.send(request).await?;
if body.is_empty() {
return Ok(serde_json::Value::Null);
}
let is_json = headers
.get(http::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.map(|essence| {
let essence = essence.trim().to_ascii_lowercase();
essence == "application/json" || essence.ends_with("+json")
})
.unwrap_or(false);
if is_json {
if let Ok(value) = serde_json::from_slice(&body) {
return Ok(value);
}
}
Ok(serde_json::Value::String(
String::from_utf8_lossy(&body).into_owned(),
))
}
pub fn with_max_retries(&self, max_retries: u32) -> Self {
Self {
max_retries: Some(max_retries),
..self.clone()
}
}
pub fn project_id(&self) -> &str {
&self.inner.config.project_id
}
pub fn assets(&self) -> AssetsClient<'_> {
AssetsClient(self)
}
pub fn folders(&self) -> FoldersClient<'_> {
FoldersClient(self)
}
pub fn hash_lists(&self) -> HashListsClient<'_> {
HashListsClient(self)
}
pub fn policies(&self) -> PoliciesClient<'_> {
PoliciesClient(self)
}
pub fn upload_presets(&self) -> UploadPresetsClient<'_> {
UploadPresetsClient(self)
}
pub fn project_settings(&self) -> ProjectSettingsClient<'_> {
ProjectSettingsClient(self)
}
pub fn metadata_fields(&self) -> MetadataFieldsClient<'_> {
MetadataFieldsClient(self)
}
pub fn lenses(&self) -> LensesClient<'_> {
LensesClient(self)
}
pub fn events(&self) -> EventsClient<'_> {
EventsClient(self)
}
pub fn cdn(&self) -> CdnClient<'_> {
CdnClient(self)
}
pub fn text(&self) -> TextClient<'_> {
TextClient(self)
}
pub fn upload_tokens(&self) -> UploadTokensClient<'_> {
UploadTokensClient(self)
}
pub async fn ensure_lens(&self, lens: LensDefinition) -> Result<Lens> {
let mut lenses = self
.ensure_lenses(EnsureLenses { lenses: vec![lens] })
.await?;
lenses
.pop()
.ok_or_else(|| Error::new(ErrorCode::InvalidResponse, "Unexpected lens response"))
}
pub async fn ensure_lenses(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
self.for_call()?.ensure_lenses_in_call(options).await
}
async fn ensure_lenses_in_call(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
if options.lenses.is_empty() {
return Err(invalid_argument("At least one lens is required"));
}
let _ensuring = self.inner.ensuring.lock().await;
let mut keys = Vec::with_capacity(options.lenses.len());
let mut missing: Vec<(String, &LensDefinition)> = Vec::new();
let mut resolved = HashMap::new();
{
let cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
for lens in &options.lenses {
id(&lens.identifier)?;
let key = serde_json::to_string(&LensDefinition {
active: Some(lens.active.unwrap_or(true)),
..lens.clone()
})
.map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
match cache.get(&key) {
Some(cached) => {
resolved.insert(key.clone(), cached.clone());
}
None if !missing.iter().any(|(k, _)| *k == key) => {
missing.push((key.clone(), lens))
}
None => {}
}
keys.push(key);
}
}
#[derive(Serialize)]
struct Body<'a> {
lenses: Vec<&'a LensDefinition>,
}
#[derive(serde::Deserialize)]
struct Response {
lenses: Vec<Lens>,
}
impl crate::models::Responded for Response {}
let base_key = self.call_idempotency_key();
let split = missing.len() > ENSURE_LENSES_MAX_PER_REQUEST;
if split
&& base_key
.as_ref()
.is_some_and(|key| key.chars().count() > MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH)
{
return Err(invalid_argument(format!(
"idempotency_key can be at most {MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH} characters for lenses sent in several requests"
)));
}
for (index, chunk) in missing.chunks(ENSURE_LENSES_MAX_PER_REQUEST).enumerate() {
let mut request = self.prepare_for(
"ensureLenses",
Method::PUT,
&self.project_path("lenses")?,
&[],
)?;
if let Some(key) = &base_key {
let key = match split {
true => format!("{key}:chunk-{}", index + 1),
false => key.clone(),
};
request = request.header("idempotency-key", &key)?;
}
let request = request.json(&Body {
lenses: chunk.iter().map(|(_, lens)| *lens).collect(),
})?;
let response: Response = self.call(request).await?;
if response.lenses.len() != chunk.len() {
return Err(Error::new(
ErrorCode::InvalidResponse,
format!(
"Expected {} lenses but CalmLens returned {}",
chunk.len(),
response.lenses.len()
),
));
}
let mut cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
for ((key, definition), lens) in chunk.iter().zip(response.lenses) {
if lens.identifier != definition.identifier {
return Err(Error::new(
ErrorCode::InvalidResponse,
format!("Expected lens {:?} at its position", definition.identifier),
));
}
cache.retain(|_, cached| cached.identifier != lens.identifier);
cache.insert(key.clone(), lens.clone());
resolved.insert(key.clone(), lens);
}
}
Ok(keys
.iter()
.filter_map(|key| resolved.get(key).cloned())
.collect())
}
fn options(&self) -> Result<CallOptions> {
let config = &self.inner.config;
Ok(CallOptions {
timeout: config.timeout,
upload_timeout: config.upload_timeout,
timeout_override: self.timeout,
max_retries: self.max_retries.unwrap_or(config.max_retries),
max_response_bytes: config.max_response_bytes,
deadline_at: match self.deadline_at {
Some(deadline_at) => Some(deadline_at),
None => self.start_deadline()?,
},
})
}
fn start_deadline(&self) -> Result<Option<tokio::time::Instant>> {
let Some(deadline) = self
.request_options
.as_ref()
.and_then(|options| options.deadline)
else {
return Ok(None);
};
if deadline.is_zero() {
return Err(invalid_argument("deadline must be positive"));
}
Ok(self.inner.transport.now().checked_add(deadline))
}
fn for_call(&self) -> Result<Self> {
let deadline_at = match self.deadline_at {
Some(deadline_at) => Some(deadline_at),
None => self.start_deadline()?,
};
Ok(Self {
deadline_at,
..self.clone()
})
}
fn project_path(&self, path: &str) -> Result<String> {
Ok(format!(
"/projects/{}/{path}",
id(&self.inner.config.project_id)?
))
}
fn prepare_for(
&self,
operation: &'static str,
method: Method,
path: &str,
query: &[(String, String)],
) -> Result<Prepared> {
let mut request = self.prepare(method, path, query)?;
request.operation = Some(operation);
Ok(request)
}
fn prepare_url_for(
&self,
operation: &'static str,
method: Method,
url: &str,
query: &[(String, String)],
) -> Result<Prepared> {
let mut request = self.prepare_url(method, url, query)?;
request.operation = Some(operation);
Ok(request)
}
fn call_idempotency_key(&self) -> Option<String> {
self.request_options
.as_ref()
.and_then(|options| options.idempotency_key.clone())
}
fn with_request_options(&self, mut request: Prepared) -> Result<Prepared> {
let Some(options) = &self.request_options else {
return Ok(request);
};
for (name, value) in &options.headers {
let name = http::HeaderName::from_bytes(name.as_bytes())
.map_err(|_| invalid_argument(format!("Invalid header name {name:?}")))?;
if [http::header::USER_AGENT, http::header::AUTHORIZATION].contains(&name)
|| name == "x-api-key"
|| name == "x-calmlens-client"
{
continue;
}
let value = HeaderValue::from_str(value)
.map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
request.headers.append(name, value);
}
if !options.extra_query.is_empty() {
request
.url
.query_pairs_mut()
.extend_pairs(&options.extra_query);
}
if let Some(key) = &options.idempotency_key {
let write = !matches!(request.method, Method::GET | Method::HEAD);
if write && !request.headers.contains_key("idempotency-key") {
request = request.header("idempotency-key", key)?;
}
}
if !options.extra_body.is_empty() {
request = request.merge_json(&options.extra_body)?;
}
Ok(request)
}
fn prepare(&self, method: Method, path: &str, query: &[(String, String)]) -> Result<Prepared> {
let url = format!("{}{path}", self.inner.config.base_url);
let mut request = self.prepare_url(method, &url, query)?;
request.headers.insert(
http::header::ACCEPT,
HeaderValue::from_static("application/json"),
);
Ok(request)
}
fn prepare_url(
&self,
method: Method,
url: &str,
query: &[(String, String)],
) -> Result<Prepared> {
let mut url = reqwest::Url::parse(url).map_err(|cause| {
invalid_argument(format!("Invalid URL: {cause}")).with_source(cause)
})?;
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(query);
}
let mut request = Prepared::new(method, url);
request
.headers
.insert("x-api-key", self.inner.config.api_key.clone());
request
.headers
.insert(http::header::USER_AGENT, self.inner.user_agent.clone());
request.headers.insert(
"x-calmlens-client",
HeaderValue::from_static(crate::CLIENT_HEADER),
);
Ok(request)
}
async fn send(&self, request: Prepared) -> Result<(u16, HeaderMap, Bytes)> {
self.send_keyed(request)
.await
.map(|(status, headers, body, _)| (status, headers, body))
}
async fn send_keyed(
&self,
request: Prepared,
) -> Result<(u16, HeaderMap, Bytes, Option<String>)> {
let options = self.options()?;
let request = self.with_request_options(request)?;
let key = request
.headers
.get("idempotency-key")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let exchange = execute(
&self.inner.transport,
request,
options,
true,
&self.inner.config.observer,
)
.await?;
let (status, headers) = (exchange.status, exchange.headers.clone());
let body = exchange.read(options.max_response_bytes).await?;
Ok((status, headers, body, key))
}
async fn call<T: serde::de::DeserializeOwned + crate::models::Responded>(
&self,
request: Prepared,
) -> Result<T> {
let (status, headers, body, key) = self.send_keyed(request).await?;
let mut value: T = decode(status, &headers, &body)?;
value.set_last_response(crate::transport::last_response(status, &headers, key));
Ok(value)
}
async fn call_empty(&self, request: Prepared) -> Result<()> {
self.send(request).await.map(|_| ())
}
async fn call_upload(&self, request: Prepared) -> Result<Asset> {
let (status, headers, body, key) = self.send_keyed(request).await?;
uploaded_asset(status, &headers, &body, key)
}
async fn call_replay_only(&self, request: Prepared) -> Result<Option<Asset>> {
let (status, headers, body, key) = self.send_keyed(request).await?;
if status == 204 {
return Ok(None);
}
uploaded_asset(status, &headers, &body, key).map(Some)
}
async fn submit(
&self,
options: SubmitAsset,
wait: bool,
operation: &'static str,
) -> Result<Asset> {
let external_id = options.external_id.clone();
self.submit_upload(options, wait, operation)
.await
.map_err(|error| match external_id {
Some(external_id) if !external_id.is_empty() => error.with_external_id(external_id),
_ => error,
})
}
async fn submit_upload(
&self,
options: SubmitAsset,
wait: bool,
operation: &'static str,
) -> Result<Asset> {
let sources = [
options.content.is_some(),
options.part.is_some(),
options.url.is_some(),
];
if sources.iter().filter(|present| **present).count() != 1 {
return Err(invalid_payload(
"Supply exactly one of content, part, or url; isFinal belongs in part",
));
}
let explicit_key = options
.idempotency_key
.clone()
.or_else(|| self.call_idempotency_key());
let explicit = explicit_key.is_some();
let idempotency_key = explicit_key.unwrap_or_else(uuid);
let fields = serde_json::to_value(UploadFields {
name: &options.name,
processing_options: options.processing_options.as_ref(),
visibility: options.visibility.as_ref(),
metadata: options.metadata.as_ref(),
tags: options.tags.as_ref(),
author_id: options.author_id.as_ref(),
context: options.context.as_ref(),
external_id: options.external_id.as_ref(),
external_url: options.external_url.as_ref(),
folder_id: match &options.folder_id {
Patch::Value(folder) => Some(folder),
_ => None,
},
upload_preset_id: options.upload_preset_id.as_ref(),
})
.map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
let serde_json::Value::Object(fields) = fields else {
unreachable!("upload fields serialize as an object")
};
let mut query = Query::default();
query.push("wait", wait);
if let Some(url) = &options.url {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct UrlBody<'a> {
name: &'a str,
url: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<&'a ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
visibility: Option<&'a Visibility>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<&'a Vec<MetadataItem>>,
#[serde(skip_serializing_if = "Option::is_none")]
tags: Option<&'a Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
author_id: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
context: Option<&'a ModerationContext>,
#[serde(skip_serializing_if = "Option::is_none")]
external_id: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
external_url: Option<&'a String>,
#[serde(skip_serializing_if = "Patch::is_missing")]
folder_id: &'a Patch<String>,
#[serde(skip_serializing_if = "Option::is_none")]
upload_preset_id: Option<&'a String>,
}
let request = self
.prepare_for(
operation,
Method::POST,
&self.project_path("assets")?,
&[("wait".into(), wait.to_string())],
)?
.header("idempotency-key", &idempotency_key)?
.json(&UrlBody {
name: &options.name,
url,
processing_options: options.processing_options.as_ref(),
visibility: options.visibility.as_ref(),
metadata: options.metadata.as_ref(),
tags: options.tags.as_ref(),
author_id: options.author_id.as_ref(),
context: options.context.as_ref(),
external_id: options.external_id.as_ref(),
external_url: options.external_url.as_ref(),
folder_id: &options.folder_id,
upload_preset_id: options.upload_preset_id.as_ref(),
})?;
return self.call_upload(request).await;
}
let multipart = options.part.is_some();
let mut content = match (options.content, options.part) {
(Some(content), _) | (None, Some(content)) => content,
(None, None) => return Err(invalid_payload("Content is required")),
};
if !multipart && content.mime_type.is_empty() && matches!(content.payload, Payload::Text(_))
{
content.mime_type = "text/plain".into();
}
if content.mime_type.trim().is_empty() {
return Err(missing_upload_mime_type());
}
let is_final = content.is_final.unwrap_or(false);
let deadline = upload_deadline(&content.payload);
let part_size = self.inner.config.part_size_bytes;
let mut text = None;
let (source, body, size) = match content.payload {
Payload::Text(value) => {
let size = value.len() as u64;
text = Some(value);
(None, RequestBody::Empty, Some(size))
}
Payload::File { path, size } if !multipart && size > part_size => {
(Some(PartSource::File(path)), RequestBody::Empty, Some(size))
}
payload => {
let splittable =
!multipart && matches!(payload, Payload::Bytes(_) | Payload::Base64(_));
match upload_body(payload, multipart, content.size_in_bytes)? {
(RequestBody::Bytes(bytes), size)
if splittable && bytes.len() as u64 > part_size =>
{
(Some(PartSource::Bytes(bytes)), RequestBody::Empty, size)
}
(body, size) => (None, body, size),
}
}
};
if let (Some(source), Some(total)) = (source, size) {
if idempotency_key.chars().count() > MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH {
return Err(invalid_argument(format!(
"idempotency_key can be at most {MAX_SPLIT_IDEMPOTENCY_KEY_LENGTH} characters for an upload sent in parts"
)));
}
return self
.submit_in_parts(
operation,
(query, &fields),
&content.mime_type,
(source, total),
(idempotency_key, explicit),
)
.await;
}
if let Some(plain_text) = text {
let mut body = fields;
let mut text = serde_json::Map::new();
text.insert("plainText".into(), plain_text.into());
text.insert("type".into(), content.mime_type.into());
if multipart {
if let Some(number) = content.part_number {
text.insert("partNumber".into(), number.into());
}
text.insert("isFinal".into(), is_final.into());
body.insert("part".into(), text.into());
if let Some(size) = content.size_in_bytes {
body.insert("sizeInBytes".into(), size.into());
}
if let Some(total) = options.total_size_in_bytes {
body.insert("totalSizeInBytes".into(), total.into());
}
} else {
body.insert("content".into(), text.into());
}
let mut request = self
.prepare_for(
operation,
Method::POST,
&self.project_path("assets")?,
&query.0,
)?
.header("idempotency-key", &idempotency_key)?
.json(&body)?;
request.deadline = deadline;
return self.call_upload(request).await;
}
query.push("contentType", &content.mime_type);
query.opt("sizeInBytes", size);
if multipart {
query.push("partNumber", content.part_number.unwrap_or(1));
query.push("isFinal", is_final);
query.opt("totalSizeInBytes", options.total_size_in_bytes);
}
let (form_type, body) = upload_form(&fields, &content.mime_type, body)?;
let mut request = self
.prepare_for(
operation,
Method::POST,
&self.project_path("assets")?,
&query.0,
)?
.header("content-type", &form_type)?
.header(
"x-calmlens-upload",
if multipart { "part" } else { "content" },
)?
.header("idempotency-key", &idempotency_key)?;
request.body = body;
request.deadline = deadline;
self.call_upload(request).await
}
async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
let path = format!("/assets/{}/part", id(&options.asset_id)?);
let part_number = options.part.part_number.unwrap_or(0);
let is_final = options.part.is_final.unwrap_or(false);
let deadline = upload_deadline(&options.part.payload);
let (body, size) = upload_body(options.part.payload, true, options.part.size_in_bytes)?;
let idempotency_key = options
.idempotency_key
.or_else(|| self.call_idempotency_key())
.unwrap_or_else(uuid);
self.send_part(
&path,
(part_number, is_final),
(body, size),
options.wait,
&idempotency_key,
deadline,
)
.await
}
async fn send_part(
&self,
path: &str,
(part_number, is_final): (u32, bool),
(body, size): (RequestBody, Option<u64>),
wait: Option<bool>,
idempotency_key: &str,
deadline: Deadline,
) -> Result<Asset> {
let mut query = Query::default();
query.push("partNumber", part_number);
query.push("isFinal", is_final);
query.opt("wait", wait);
query.opt("sizeInBytes", size);
let mut request = self
.prepare_for("assets.uploadPart", Method::POST, path, &query.0)?
.header("x-calmlens-upload", "part")?
.header("idempotency-key", idempotency_key)?;
request.body = body;
request.deadline = deadline;
self.call_upload(request).await
}
async fn submit_in_parts(
&self,
operation: &'static str,
(mut query, fields): (Query, &serde_json::Map<String, serde_json::Value>),
mime_type: &str,
(source, total): (PartSource, u64),
(key, explicit): (String, bool),
) -> Result<Asset> {
let part_size = self.inner.config.part_size_bytes;
let count = u32::try_from(total.div_ceil(part_size))
.map_err(|_| invalid_payload("The content has too many parts"))?;
let piece = |number: u32| {
let start = u64::from(number - 1) * part_size;
let end = (u64::from(number) * part_size).min(total);
source.read(start, (end - start) as usize)
};
query.push("contentType", mime_type);
query.push("sizeInBytes", part_size.min(total));
query.push("partNumber", 1);
query.push("isFinal", false);
query.push("totalSizeInBytes", total);
let first_part = |file: Bytes| -> Result<Prepared> {
let (form_type, body) = upload_form(fields, mime_type, RequestBody::Bytes(file))?;
let mut request = self
.prepare_for(
operation,
Method::POST,
&self.project_path("assets")?,
&query.0,
)?
.header("content-type", &form_type)?
.header("x-calmlens-upload", "part")?
.header("idempotency-key", &key)?;
request.body = body;
request.deadline = Deadline::Upload;
Ok(request)
};
let uploads = &self.inner.interrupted_uploads;
let resumes = explicit
&& uploads
.lock()
.unwrap_or_else(|e| e.into_inner())
.contains(&key);
let interrupted = explicit.then(|| InterruptedUpload {
uploads,
key: Some(key.clone()),
});
let uploaded = async {
let existing = if resumes {
let check = first_part(Bytes::new())?.header("idempotency-replay-only", "true")?;
self.call_replay_only(check).await?
} else {
None
};
let resumed = existing.is_some();
let asset = match existing {
Some(asset) => asset,
None => self.call_upload(first_part(piece(1).await?)?).await?,
};
if resumed && asset.upload.status == AssetUploadStatus::Completed {
return Ok(asset);
}
self.send_later_parts(asset, &key, count, &piece).await
}
.await;
if let (Ok(_), Some(interrupted)) = (&uploaded, interrupted) {
interrupted.completed();
}
uploaded
}
async fn send_later_parts<F, P>(
&self,
mut asset: Asset,
key: &str,
count: u32,
piece: &F,
) -> Result<Asset>
where
F: Fn(u32) -> P,
P: std::future::Future<Output = Result<Bytes>>,
{
let path = format!("/assets/{}/part", id(&asset.id)?);
let mut number = match asset.upload.parts_received {
Some(received) if (2..count).contains(&received) => received + 1,
_ => 2,
};
while number <= count {
let is_final = number == count;
let part = piece(number).await?;
let size = part.len() as u64;
let sent = self
.send_part(
&path,
(number, is_final),
(RequestBody::Bytes(part), Some(size)),
None,
&format!("{key}:part-{number}"),
Deadline::Upload,
)
.await;
match sent {
Ok(next) => {
asset = next;
number += 1;
}
Err(error) => {
let expected = error
.details()
.get("expectedPartNumber")
.and_then(serde_json::Value::as_u64);
if *error.code() == ErrorCode::UploadPartInvalidNumber {
if let Some(expected) = expected
.filter(|expected| *expected > u64::from(number))
.and_then(|expected| u32::try_from(expected).ok())
.filter(|expected| *expected <= count)
{
number = expected;
continue;
}
}
if is_final && *error.code() == ErrorCode::UploadNotOpen {
return AssetsClient(self)
.retrieve(RetrieveAsset::new(asset.id))
.await;
}
return Err(error.with_idempotency_key(key.to_owned()));
}
}
}
Ok(asset)
}
async fn list_page(&self, options: &ListAssets) -> Result<AssetPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_deref());
query.opt("pageSize", options.page_size);
query.opt("filter", options.filter.as_ref());
query.opt("sort", options.sort.as_ref());
self.call(self.prepare_for(
"assets.list",
Method::GET,
&self.project_path("assets")?,
&query.0,
)?)
.await
}
async fn children_page(&self, options: &ListChildren) -> Result<AssetPage> {
let path = format!("/assets/{}/children", id(&options.asset_id)?);
let mut query = Query::default();
query.opt("cursor", options.cursor.as_deref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
self.call(self.prepare_for("assets.listChildren", Method::GET, &path, &query.0)?)
.await
}
async fn timeline_page(&self, options: &ListTimeline) -> Result<AssetTimelinePage> {
let path = self.project_path(&format!("assets/{}/timeline", id(&options.asset_id)?))?;
let mut query = Query::default();
query.opt("cursor", options.cursor.as_deref());
query.opt("pageSize", options.page_size);
self.call(self.prepare_for("assets.listTimeline", Method::GET, &path, &query.0)?)
.await
}
async fn events_page(&self, options: &ListEvents) -> Result<EventsPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
if let Some(types) = options.types.as_deref().filter(|types| !types.is_empty()) {
let types: Vec<&str> = types.iter().map(EventType::as_str).collect();
query.push("types", types.join(","));
}
query.opt("assetId", options.asset_id.as_ref());
query.opt("since", options.since);
self.call(self.prepare_for(
"events.list",
Method::GET,
&self.project_path("events")?,
&query.0,
)?)
.await
}
}
fn uploaded_asset(
status: u16,
headers: &HeaderMap,
body: &[u8],
key: Option<String>,
) -> Result<Asset> {
let value: serde_json::Value = decode(status, headers, body)?;
if value["id"].as_str().is_none_or(|id| id.is_empty()) {
return Err(Error::new(
ErrorCode::InvalidResponse,
"Expected an uploaded asset response",
)
.with_http_status(status));
}
let mut asset: Asset = serde_json::from_value(value).map_err(|cause| {
Error::new(
ErrorCode::InvalidResponse,
format!("Invalid asset response: {cause}"),
)
.with_http_status(status)
.with_source(cause)
})?;
asset.set_last_response(crate::transport::last_response(status, headers, key));
Ok(asset)
}
enum PartSource {
Bytes(Bytes),
File(std::path::PathBuf),
}
impl PartSource {
async fn read(&self, offset: u64, length: usize) -> Result<Bytes> {
match self {
Self::Bytes(bytes) => Ok(bytes.slice(offset as usize..offset as usize + length)),
Self::File(path) => read_file_range(path.clone(), offset, length).await,
}
}
}
fn missing_upload_mime_type() -> Error {
let mut details = serde_json::Map::new();
details.insert("mimeType".into(), "".into());
details.insert("source".into(), "calmlens".into());
Error::new(
ErrorCode::UploadUnsupportedType,
"The upload has no type: set a MIME type such as image/png, application/pdf or \
text/plain",
)
.with_details(details)
}
fn upload_deadline(payload: &Payload) -> Deadline {
match payload {
Payload::Text(_) => Deadline::Api,
_ => Deadline::Upload,
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct UploadFields<'a> {
name: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<&'a ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
visibility: Option<&'a Visibility>,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<&'a Vec<MetadataItem>>,
#[serde(skip_serializing_if = "Option::is_none")]
tags: Option<&'a Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
author_id: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
context: Option<&'a ModerationContext>,
#[serde(skip_serializing_if = "Option::is_none")]
external_id: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
external_url: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
folder_id: Option<&'a String>,
#[serde(skip_serializing_if = "Option::is_none")]
upload_preset_id: Option<&'a String>,
}
fn upload_form(
fields: &serde_json::Map<String, serde_json::Value>,
mime_type: &str,
file: RequestBody,
) -> Result<(String, RequestBody)> {
let boundary = format!("calmlens-{}", uuid());
let options = serde_json::to_string(fields)
.map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
let mime_type: String = mime_type
.chars()
.filter(|c| *c != '\r' && *c != '\n')
.collect();
let head = Bytes::from(format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"options\"\r\nContent-Type: application/json\r\n\r\n{options}\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"file\"\r\nContent-Type: {mime_type}\r\n\r\n"
));
let tail = Bytes::from(format!("\r\n--{boundary}--\r\n"));
let envelope = (head.len() + tail.len()) as u64;
let body = match file {
RequestBody::Empty => RequestBody::Bytes([head, tail].concat().into()),
RequestBody::Bytes(bytes) => RequestBody::Bytes([head, bytes, tail].concat().into()),
RequestBody::Stream(stream, size) => {
let stream = stream.map(|stream| -> crate::ByteStream {
Box::pin(
futures_util::stream::once(async move { Ok(head) })
.chain(stream)
.chain(futures_util::stream::once(async move { Ok(tail) })),
)
});
RequestBody::Stream(stream, size.map(|size| size + envelope))
}
};
Ok((format!("multipart/form-data; boundary={boundary}"), body))
}
#[derive(Default)]
struct Query(Vec<(String, String)>);
impl Query {
fn push(&mut self, key: &str, value: impl fmt::Display) {
self.0.push((key.into(), value.to_string()));
}
fn opt(&mut self, key: &str, value: Option<impl fmt::Display>) {
if let Some(value) = value {
self.push(key, value);
}
}
}
fn percent_encode(value: &str, keep: &[u8]) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || keep.contains(&byte) {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
pub const ASSET_BATCH_MAX_ASSETS: usize = 500;
pub(crate) fn id(value: &str) -> Result<String> {
if value.is_empty() {
return Err(invalid_argument("Identifier is required"));
}
if value == "." || value == ".." {
return Err(invalid_argument("Identifier cannot be \".\" or \"..\""));
}
Ok(percent_encode(value, b"-_.!~*'()"))
}
fn encode_selector(value: &str) -> String {
percent_encode(value, b"-_.!~*'();/:@&=+$,")
}
#[derive(Debug, Clone, Copy)]
pub struct AssetsClient<'a>(&'a ServerClient);
impl AssetsClient<'_> {
pub async fn create(&self, options: SubmitAsset) -> Result<Asset> {
self.0
.for_call()?
.submit(options, false, "assets.create")
.await
}
pub async fn classify(&self, options: SubmitAsset) -> Result<Asset> {
self.0
.for_call()?
.submit(options, true, "assets.classify")
.await
}
pub async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
self.0.upload_part(options).await
}
pub async fn search(&self, options: SearchAssets) -> Result<AssetSearchResponse> {
let mut query = Query::default();
query.push("query", &options.query);
query.opt("mode", options.mode.as_ref());
query.opt("pageSize", options.page_size);
self.0
.call(self.0.prepare_for(
"assets.search",
Method::GET,
&self.0.project_path("assets/search")?,
&query.0,
)?)
.await
}
pub async fn list(&self, options: ListAssets) -> Result<AssetPage> {
self.0.list_page(&options).await
}
pub fn iterate(&self, options: ListAssets) -> BoxStream<'static, Result<Asset>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.list_page(&options).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListAssets {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn list_children(&self, options: ListChildren) -> Result<AssetPage> {
self.0.children_page(&options).await
}
pub async fn list_timeline(&self, options: ListTimeline) -> Result<AssetTimelinePage> {
self.0.timeline_page(&options).await
}
pub fn iterate_timeline(
&self,
options: ListTimeline,
) -> BoxStream<'static, Result<MediaClassificationSegment>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.timeline_page(&options).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListTimeline {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub fn iterate_children(&self, options: ListChildren) -> BoxStream<'static, Result<Asset>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.children_page(&options).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListChildren {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn retrieve(&self, options: RetrieveAsset) -> Result<Asset> {
let path = format!("/assets/{}", id(&options.asset_id)?);
let mut query = Query::default();
query.opt("waitFor", options.wait_for.as_ref());
query.opt("waitTimeout", options.wait_timeout);
let mut client = self.0.clone();
if options.wait_for.is_some() {
let wait = Duration::from_secs(
options
.wait_timeout
.unwrap_or(MAX_RETRIEVE_WAIT_SECONDS)
.into(),
);
let needed = wait + RETRIEVE_WAIT_TIMEOUT_MARGIN;
if client.timeout.unwrap_or(client.inner.config.timeout) < needed {
client.timeout = Some(needed);
}
}
client
.call(client.prepare_for("assets.retrieve", Method::GET, &path, &query.0)?)
.await
}
pub async fn retrieve_by_external_id(&self, options: RetrieveByExternalId) -> Result<Asset> {
let path = self.0.project_path(&format!(
"assets/by-external-id/{}",
id(&options.external_id)?
))?;
self.0
.call(
self.0
.prepare_for("assets.retrieveByExternalId", Method::GET, &path, &[])?,
)
.await
}
pub async fn wait_for_decision(&self, options: WaitForDecision) -> Result<Asset> {
let timeout = options.timeout.unwrap_or(DEFAULT_DECISION_TIMEOUT);
let options_asset_id = options.asset_id;
let client = self.0.for_call()?;
let assets = AssetsClient(&client);
let transport = &client.inner.transport;
let deadline = transport.now().checked_add(timeout);
let mut delay = DECISION_POLL_FIRST_INTERVAL;
let mut details = serde_json::Map::new();
details.insert("assetId".into(), options_asset_id.clone().into());
details.insert("classificationStatus".into(), serde_json::Value::Null);
details.insert("moderationDecision".into(), serde_json::Value::Null);
let remaining =
|| deadline.map(|deadline| deadline.saturating_duration_since(transport.now()));
loop {
let left = remaining();
if !timeout.is_zero() && left == Some(Duration::ZERO) {
break;
}
let call_left = client
.deadline_at
.map(|deadline_at| deadline_at.saturating_duration_since(transport.now()));
let mut retrieve = RetrieveAsset::new(options_asset_id.clone());
let wait = [left, call_left]
.into_iter()
.flatten()
.min()
.unwrap_or(Duration::from_secs(MAX_RETRIEVE_WAIT_SECONDS.into()));
let seconds = wait.as_secs().min(MAX_RETRIEVE_WAIT_SECONDS.into()) as u32;
if !timeout.is_zero() && seconds >= 1 {
retrieve = retrieve
.wait_for(AssetWaitFor::Decision)
.wait_timeout(seconds);
}
let started = transport.now();
let request = assets.retrieve(retrieve.clone());
let result = match left {
Some(left) if !timeout.is_zero() => {
match tokio::time::timeout(left, request).await {
Ok(result) => result,
Err(_) => break,
}
}
_ => request.await,
};
let left = remaining();
if !timeout.is_zero() && left == Some(Duration::ZERO) {
break;
}
let asset = result?;
if asset.is_decided() {
return Ok(asset);
}
details.insert(
"classificationStatus".into(),
asset.classification.status.as_str().into(),
);
details.insert(
"moderationDecision".into(),
serde_json::json!(asset.classification.moderation.decision),
);
if left == Some(Duration::ZERO) {
break;
}
let waited = retrieve.wait_timeout.is_some_and(|seconds| {
transport.now() - started >= Duration::from_secs(seconds.into())
});
let pause = if waited {
Duration::ZERO
} else {
left.map_or(delay, |left| left.min(delay))
};
if client
.deadline_at
.is_some_and(|deadline_at| transport.now() + pause >= deadline_at)
{
break;
}
if !pause.is_zero() {
transport.sleep(pause).await;
delay = delay
.mul_f64(DECISION_POLL_INTERVAL_FACTOR)
.min(DECISION_POLL_MAX_INTERVAL);
}
}
Err(Error::new(
ErrorCode::Timeout,
format!("No moderation decision within {timeout:?}"),
)
.with_details(details))
}
pub async fn update(&self, options: UpdateAsset) -> Result<Asset> {
let path = format!("/assets/{}", id(&options.asset_id)?);
let request = self
.0
.prepare_for("assets.update", Method::PATCH, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn retry(&self, options: AssetId) -> Result<Asset> {
let path = format!("/assets/{}/retry", id(&options.asset_id)?);
self.0
.call(
self.0
.prepare_for("assets.retry", Method::POST, &path, &[])?,
)
.await
}
pub async fn decide(&self, options: DecideAsset) -> Result<Asset> {
let path = format!("/assets/{}/decision", id(&options.asset_id)?);
let request = self
.0
.prepare_for("assets.decide", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn request_review(&self, options: RequestAssetReview) -> Result<AssetReviewRequest> {
let path = format!("/assets/{}/review-requests", id(&options.asset_id)?);
let request = self
.0
.prepare_for("assets.requestReview", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn remove_content(&self, options: AssetId) -> Result<Asset> {
let path = format!("/assets/{}/content", id(&options.asset_id)?);
self.0
.call(
self.0
.prepare_for("assets.removeContent", Method::DELETE, &path, &[])?,
)
.await
}
pub async fn delete(&self, options: AssetId) -> Result<()> {
let path = format!("/assets/{}", id(&options.asset_id)?);
self.0
.call_empty(
self.0
.prepare_for("assets.delete", Method::DELETE, &path, &[])?,
)
.await
}
pub async fn batch(&self, options: BatchAssets) -> Result<BatchAssetsResponse> {
let path = self.0.project_path("assets/batch")?;
let request = self
.0
.prepare_for("assets.batch", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn move_asset(&self, options: MoveAsset) -> Result<Asset> {
let path = format!("/assets/{}/move", id(&options.asset_id)?);
let request = self
.0
.prepare_for("assets.move", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
}
fn next_cursor<T>(items: &[T], has_more: bool, next_cursor: &Option<String>) -> Option<String> {
let more = has_more && !items.is_empty();
next_cursor.clone().filter(|_| more)
}
fn repeated_cursor(cursor: &str) -> Error {
let mut details = serde_json::Map::new();
details.insert("cursor".into(), cursor.into());
Error::new(
ErrorCode::InvalidResponse,
"The API returned a cursor it had already returned, with more pages to follow",
)
.with_details(details)
}
fn pages<O, P, C, F, Fut>(first: O, cursor: C, fetch: F) -> BoxStream<'static, Result<P>>
where
O: Send + 'static,
P: Send + 'static,
C: Fn(&O) -> Option<String> + Send + Sync + 'static,
F: Fn(O) -> Fut + Send + 'static,
Fut: std::future::Future<Output = Result<(P, Option<O>)>> + Send + 'static,
{
let mut sent = std::collections::HashSet::new();
if let Some(first) = cursor(&first) {
sent.insert(first);
}
let cursor = Arc::new(cursor);
futures_util::stream::try_unfold((Some(first), sent), move |(next, mut sent)| {
let page = next.map(&fetch);
let cursor = cursor.clone();
let checked = page.map(|page| async move {
let (page, next) = page.await?;
if let Some(next_cursor) = next.as_ref().and_then(|next| cursor(next)) {
if !sent.insert(next_cursor.clone()) {
return Err(repeated_cursor(&next_cursor));
}
}
Ok((page, (next, sent)))
});
async move {
match checked {
None => Ok(None),
Some(checked) => checked.await.map(Some),
}
}
})
.boxed()
}
fn paginate<O, C, F, Fut, T>(first: O, cursor: C, fetch: F) -> BoxStream<'static, Result<T>>
where
O: Send + 'static,
T: Send + 'static,
C: Fn(&O) -> Option<String> + Send + Sync + 'static,
F: Fn(O) -> Fut + Send + 'static,
Fut: std::future::Future<Output = Result<(Vec<T>, Option<O>)>> + Send + 'static,
{
pages(first, cursor, fetch)
.map_ok(|items| futures_util::stream::iter(items.into_iter().map(Ok)))
.try_flatten()
.boxed()
}
#[derive(Debug, Clone, Copy)]
pub struct FoldersClient<'a>(&'a ServerClient);
impl FoldersClient<'_> {
pub async fn list(&self, options: ListFolders) -> Result<FolderPage> {
let mut query = Query::default();
query.opt("parentId", options.parent_id.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
query.opt("cursor", options.cursor.as_ref());
query.opt("search", options.search.as_ref());
let request = self.0.prepare_for(
"folders.list",
Method::GET,
&self.0.project_path("folders")?,
&query.0,
)?;
self.0.call(request).await
}
pub fn iterate(&self, options: ListFolders) -> BoxStream<'static, Result<Folder>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.folders().list(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListFolders {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn create(&self, options: CreateFolder) -> Result<Folder> {
let request = self
.0
.prepare_for(
"folders.create",
Method::POST,
&self.0.project_path("folders")?,
&[],
)?
.json(&options)?;
self.0.call(request).await
}
pub async fn retrieve(&self, options: FolderId) -> Result<Folder> {
let path = format!("/folders/{}", id(&options.folder_id)?);
self.0
.call(
self.0
.prepare_for("folders.retrieve", Method::GET, &path, &[])?,
)
.await
}
pub async fn update(&self, options: UpdateFolder) -> Result<Folder> {
let path = format!("/folders/{}", id(&options.folder_id)?);
let request = self
.0
.prepare_for("folders.update", Method::PATCH, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn move_folder(&self, options: MoveFolder) -> Result<Folder> {
let path = format!("/folders/{}/move", id(&options.folder_id)?);
let request = self
.0
.prepare_for("folders.move", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn delete(&self, options: FolderId) -> Result<()> {
let path = format!("/folders/{}", id(&options.folder_id)?);
self.0
.call_empty(
self.0
.prepare_for("folders.delete", Method::DELETE, &path, &[])?,
)
.await
}
}
#[derive(Debug, Clone, Copy)]
pub struct HashListsClient<'a>(&'a ServerClient);
impl HashListsClient<'_> {
pub async fn list(&self, options: ListHashLists) -> Result<HashListPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
let request = self.0.prepare_for(
"hashLists.list",
Method::GET,
&self.0.project_path("hash-lists")?,
&query.0,
)?;
self.0.call(request).await
}
pub fn iterate(&self, options: ListHashLists) -> BoxStream<'static, Result<HashList>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.hash_lists().list(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListHashLists {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn retrieve(&self, options: HashListId) -> Result<HashList> {
let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
self.0
.call(
self.0
.prepare_for("hashLists.retrieve", Method::GET, &path, &[])?,
)
.await
}
pub async fn create(&self, options: CreateHashList) -> Result<HashList> {
let request = self
.0
.prepare_for(
"hashLists.create",
Method::POST,
&self.0.project_path("hash-lists")?,
&[],
)?
.json(&options)?;
self.0.call(request).await
}
pub async fn update(&self, options: UpdateHashList) -> Result<HashList> {
let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
let request = self
.0
.prepare_for("hashLists.update", Method::PATCH, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn delete(&self, options: HashListId) -> Result<()> {
let path = format!("/hash-lists/{}", id(&options.hash_list_id)?);
self.0
.call_empty(
self.0
.prepare_for("hashLists.delete", Method::DELETE, &path, &[])?,
)
.await
}
pub async fn list_entries(&self, options: ListHashListEntries) -> Result<HashListEntryPage> {
let path = format!("/hash-lists/{}/entries", id(&options.hash_list_id)?);
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
self.0
.call(
self.0
.prepare_for("hashLists.listEntries", Method::GET, &path, &query.0)?,
)
.await
}
pub fn iterate_entries(
&self,
options: ListHashListEntries,
) -> BoxStream<'static, Result<HashListEntry>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.hash_lists().list_entries(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListHashListEntries {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn add_entry(&self, options: AddHashListEntry) -> Result<HashListEntry> {
let path = format!("/hash-lists/{}/entries", id(&options.hash_list_id)?);
let request = self
.0
.prepare_for("hashLists.addEntry", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn remove_entry(&self, options: HashListEntryId) -> Result<()> {
let path = format!("/hash-list-entries/{}", id(&options.entry_id)?);
self.0
.call_empty(
self.0
.prepare_for("hashLists.removeEntry", Method::DELETE, &path, &[])?,
)
.await
}
}
#[derive(Debug, Clone, Copy)]
pub struct PoliciesClient<'a>(&'a ServerClient);
impl PoliciesClient<'_> {
fn path(policy_id: &str, suffix: &str) -> Result<String> {
Ok(format!("/policies/{}{suffix}", id(policy_id)?))
}
pub async fn list(&self, options: ListPolicies) -> Result<PolicyPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
self.0
.call(
self.0
.prepare_for("policies.list", Method::GET, "/policies", &query.0)?,
)
.await
}
pub fn iterate(&self, options: ListPolicies) -> BoxStream<'static, Result<Policy>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.policies().list(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListPolicies {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn retrieve(&self, options: PolicyId) -> Result<Policy> {
let path = Self::path(&options.policy_id, "")?;
self.0
.call(
self.0
.prepare_for("policies.retrieve", Method::GET, &path, &[])?,
)
.await
}
pub async fn create(&self, options: CreatePolicy) -> Result<Policy> {
let request = self
.0
.prepare_for("policies.create", Method::POST, "/policies", &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn update(&self, options: UpdatePolicy) -> Result<Policy> {
let path = Self::path(&options.policy_id, "")?;
let request = self
.0
.prepare_for("policies.update", Method::PATCH, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn reset(&self, options: ResetPolicy) -> Result<Policy> {
let path = Self::path(&options.policy_id, "/reset")?;
let request = self
.0
.prepare_for("policies.reset", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn upgrade(&self, options: UpgradePolicy) -> Result<Policy> {
let path = Self::path(&options.policy_id, "/upgrade")?;
let request = self
.0
.prepare_for("policies.upgrade", Method::POST, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn set_automatic_updates(
&self,
options: SetPolicyAutomaticUpdates,
) -> Result<Policy> {
let path = Self::path(&options.policy_id, "/automatic-updates")?;
let request = self
.0
.prepare_for("policies.setAutomaticUpdates", Method::PUT, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn delete(&self, options: PolicyId) -> Result<()> {
let path = Self::path(&options.policy_id, "")?;
self.0
.call_empty(
self.0
.prepare_for("policies.delete", Method::DELETE, &path, &[])?,
)
.await
}
pub async fn retrieve_assigned(&self) -> Result<Policy> {
let path = self.0.project_path("policy")?;
self.0
.call(
self.0
.prepare_for("policies.retrieveAssigned", Method::GET, &path, &[])?,
)
.await
}
pub async fn assign(&self, options: AssignPolicy) -> Result<Policy> {
let path = self.0.project_path("policy")?;
let request = self
.0
.prepare_for("policies.assign", Method::PUT, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
}
#[derive(Debug, Clone, Copy)]
pub struct UploadPresetsClient<'a>(&'a ServerClient);
impl UploadPresetsClient<'_> {
pub async fn list(&self, options: ListUploadPresets) -> Result<UploadPresetPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
let path = self.0.project_path("upload-presets")?;
self.0
.call(
self.0
.prepare_for("uploadPresets.list", Method::GET, &path, &query.0)?,
)
.await
}
pub fn iterate(&self, options: ListUploadPresets) -> BoxStream<'static, Result<UploadPreset>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.upload_presets().list(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListUploadPresets {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn ensure(
&self,
options: EnsureUploadPresets,
) -> Result<EnsureUploadPresetsResponse> {
let path = self.0.project_path("upload-presets")?;
let request = self
.0
.prepare_for("uploadPresets.ensure", Method::PUT, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn delete(&self, options: UploadPresetId) -> Result<()> {
let path = format!("/upload-presets/{}", id(&options.upload_preset_id)?);
self.0
.call_empty(
self.0
.prepare_for("uploadPresets.delete", Method::DELETE, &path, &[])?,
)
.await
}
}
#[derive(Debug, Clone, Copy)]
pub struct ProjectSettingsClient<'a>(&'a ServerClient);
impl ProjectSettingsClient<'_> {
pub async fn get(&self) -> Result<ProjectSettingsResource> {
let path = self.0.project_path("settings")?;
self.0
.call(
self.0
.prepare_for("projectSettings.get", Method::GET, &path, &[])?,
)
.await
}
pub async fn update(&self, options: UpdateProjectSettings) -> Result<ProjectSettingsResource> {
let path = self.0.project_path("settings")?;
let request = self
.0
.prepare_for("projectSettings.update", Method::PUT, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn patch(&self, options: PatchProjectSettings) -> Result<ProjectSettingsResource> {
let path = self.0.project_path("settings")?;
let request = self
.0
.prepare_for("projectSettings.patch", Method::PATCH, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
}
#[derive(Debug, Clone, Copy)]
pub struct MetadataFieldsClient<'a>(&'a ServerClient);
impl MetadataFieldsClient<'_> {
pub async fn list(&self) -> Result<MetadataFieldsResource> {
let path = self.0.project_path("metadata-fields")?;
self.0
.call(
self.0
.prepare_for("metadataFields.list", Method::GET, &path, &[])?,
)
.await
}
pub async fn ensure(&self, options: EnsureMetadataFields) -> Result<MetadataFieldsResource> {
let path = self.0.project_path("metadata-fields")?;
let request = self
.0
.prepare_for("metadataFields.ensure", Method::PUT, &path, &[])?
.json(&options)?;
self.0.call(request).await
}
pub async fn delete(&self, options: DeleteMetadataField) -> Result<()> {
let path = self
.0
.project_path(&format!("metadata-fields/{}", id(&options.field_id)?))?;
let mut query = Query::default();
query.opt("revision", options.revision);
self.0
.call_empty(self.0.prepare_for(
"metadataFields.delete",
Method::DELETE,
&path,
&query.0,
)?)
.await
}
}
#[derive(Debug, Clone, Copy)]
pub struct LensesClient<'a>(&'a ServerClient);
impl LensesClient<'_> {
fn path(lens_id: &str) -> Result<String> {
Ok(format!("/lenses/{}", id(lens_id)?))
}
fn forget(&self, changed: impl Fn(&Lens) -> bool) {
let mut cache = self
.0
.inner
.lenses
.lock()
.unwrap_or_else(|e| e.into_inner());
cache.retain(|_, cached| !changed(cached));
}
pub async fn list(&self, options: ListLenses) -> Result<LensPage> {
let mut query = Query::default();
query.opt("cursor", options.cursor.as_ref());
query.opt("pageSize", options.page_size);
query.opt("sort", options.sort.as_ref());
let request = self.0.prepare_for(
"lenses.list",
Method::GET,
&self.0.project_path("lenses")?,
&query.0,
)?;
self.0.call(request).await
}
pub fn iterate(&self, options: ListLenses) -> BoxStream<'static, Result<Lens>> {
let client = self.0.clone();
paginate(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.lenses().list(options.clone()).await?;
let next =
next_cursor(&page.items, page.has_more, &page.next_cursor).map(|cursor| {
ListLenses {
cursor: Some(cursor),
..options
}
});
Ok((page.items, next))
}
},
)
}
pub async fn create(&self, options: LensDefinition) -> Result<Lens> {
id(&options.identifier)?;
let request = self
.0
.prepare_for(
"lenses.create",
Method::POST,
&self.0.project_path("lenses")?,
&[],
)?
.json(&options)?;
let lens: Lens = self.0.call(request).await?;
self.forget(|cached| cached.identifier == lens.identifier);
Ok(lens)
}
pub async fn retrieve(&self, options: LensId) -> Result<Lens> {
let path = Self::path(&options.lens_id)?;
self.0
.call(
self.0
.prepare_for("lenses.retrieve", Method::GET, &path, &[])?,
)
.await
}
pub async fn update(&self, options: UpdateLens) -> Result<Lens> {
let path = Self::path(&options.lens_id)?;
let request = self
.0
.prepare_for("lenses.update", Method::PATCH, &path, &[])?
.json(&options)?;
let lens: Lens = self.0.call(request).await?;
self.forget(|cached| !cached.id.is_empty() && cached.id == lens.id);
Ok(lens)
}
pub async fn delete(&self, options: LensId) -> Result<()> {
let path = Self::path(&options.lens_id)?;
self.0
.call_empty(
self.0
.prepare_for("lenses.delete", Method::DELETE, &path, &[])?,
)
.await?;
self.forget(|cached| cached.id == options.lens_id);
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct EventsClient<'a>(&'a ServerClient);
impl EventsClient<'_> {
pub async fn list(&self, options: ListEvents) -> Result<EventsPage> {
self.0.events_page(&options).await
}
pub fn iterate(&self, options: ListEvents) -> BoxStream<'static, Result<Event>> {
self.pages(options)
.map_ok(|page| futures_util::stream::iter(page.items.into_iter().map(Ok)))
.try_flatten()
.boxed()
}
pub fn pages(&self, options: ListEvents) -> BoxStream<'static, Result<EventsPage>> {
let client = self.0.clone();
pages(
options,
|options| options.cursor.clone(),
move |options| {
let client = client.clone();
async move {
let page = client.events_page(&options).await?;
let next = page.has_more.then(|| ListEvents {
cursor: Some(page.next_cursor.clone()),
since: None,
..options
});
Ok((page, next))
}
},
)
}
pub async fn retrieve_asset(&self, event: &impl ResourceEvent) -> Result<Option<Asset>> {
match event.event_resource() {
Some(resource) if resource.kind == EventResourceKind::Asset => self
.0
.assets()
.retrieve(RetrieveAsset::new(resource.id.clone()))
.await
.map(Some),
_ => Ok(None),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct UploadTokensClient<'a>(&'a ServerClient);
impl UploadTokensClient<'_> {
pub fn sign(&self, options: SignUploadToken) -> Result<SignedUploadToken> {
let api_key = String::from_utf8_lossy(self.0.inner.config.api_key.as_bytes()).into_owned();
let now = self.0.inner.transport.epoch_millis();
sign_upload_token(&api_key, options, now, &uuid())
}
}
pub(crate) fn sign_asset_url(
api_key: &str,
client_project_id: &str,
cdn_base_url: &str,
options: SignAssetUrlOptions,
now: u64,
) -> Result<SignedAssetUrl> {
use crate::asset_grant::{sign, GrantAsset, GrantClaims};
let expires_in = options.expires_in.unwrap_or(DEFAULT_SIGNED_URL_EXPIRES_IN);
if expires_in < 1 {
return Err(invalid_argument(
"expires_in must be a whole number of seconds, at least 1",
));
}
asset_segment(options.asset_id.as_deref(), options.external_id.as_deref())?;
let asset = match (options.asset_id, options.external_id) {
(Some(asset_id), _) => GrantAsset::Id(asset_id),
(_, external_id) => GrantAsset::ExternalId(external_id.unwrap_or_default()),
};
let location = AssetLocation {
resource: options.resource.as_ref(),
lens: options.lens.as_deref(),
transform: options.transform.as_ref(),
viewer_claims: options.viewer_claims.as_ref(),
};
let project_id = options.project_id.as_deref().unwrap_or(client_project_id);
let project = id(project_id)?;
let expires_at = now
.saturating_add(expires_in.saturating_mul(1000))
.div_ceil(1000)
.saturating_mul(1000);
let token = sign(
&GrantClaims {
project_id: project_id.to_owned(),
asset,
original: location.resource() == CdnResource::Original.as_str(),
expires_at,
},
api_key,
);
Ok(SignedAssetUrl {
url: location.append(&format!("{cdn_base_url}/assets/{project}/{token}"))?,
expires_at,
})
}
pub(crate) fn sign_upload_token(
api_key: &str,
options: SignUploadToken,
now: u64,
nonce: &str,
) -> Result<SignedUploadToken> {
use base64::Engine;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
id(&options.upload_preset_id).map_err(|_| invalid_argument("Upload preset ID is required"))?;
let ttl = options.expires_in.unwrap_or(DEFAULT_UPLOAD_TOKEN_SECONDS);
if ttl < 1 {
return Err(invalid_argument(
"expires_in must be a whole number of seconds, at least 1",
));
}
if options.external_id.as_deref() == Some("") {
return Err(invalid_argument("externalId must be a non-empty string"));
}
let prefix_length = if api_key.starts_with("clsk_") { 13 } else { 8 };
let prefix: String = api_key.chars().take(prefix_length).collect();
let expires_at = now + u64::from(ttl) * 1000;
#[derive(Serialize)]
struct Claims<'a> {
v: u8,
u: &'a str,
k: &'a str,
e: u64,
n: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
x: Option<&'a str>,
}
let claims = Claims {
v: 1,
u: &options.upload_preset_id,
k: &prefix,
e: expires_at,
n: nonce,
x: options.external_id.as_deref(),
};
let body = base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(serde_json::to_vec(&claims).map_err(|e| invalid_argument(e.to_string()))?);
let secret: String = Sha256::digest(api_key.as_bytes())
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
.map_err(|e| invalid_argument(e.to_string()))?;
mac.update(format!("calmlens-upload-token:v1:{body}").as_bytes());
let signature: String = mac
.finalize()
.into_bytes()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
Ok(SignedUploadToken {
token: format!("clut_{body}.{signature}"),
expires_at,
})
}
#[derive(Debug, Clone, Copy)]
pub struct TextClient<'a>(&'a ServerClient);
impl TextClient<'_> {
pub async fn classify(&self, options: ClassifyText) -> Result<Asset> {
let name = options
.name
.or_else(|| options.external_id.clone().filter(|id| !id.is_empty()))
.unwrap_or_else(|| "text".into());
let options = SubmitAsset {
name,
content: Some(Content::text(options.text)),
visibility: options.visibility,
processing_options: options.processing_options,
metadata: options.metadata,
tags: options.tags,
author_id: options.author_id,
context: options.context,
external_id: options.external_id,
external_url: options.external_url,
folder_id: options.folder_id,
upload_preset_id: options.upload_preset_id,
idempotency_key: options.idempotency_key,
..SubmitAsset::blank()
};
self.0
.for_call()?
.submit(options, true, "text.classify")
.await
}
}
fn asset_url_of(url: &str) -> String {
let path = url
.split('?')
.next()
.unwrap_or_default()
.trim_end_matches('/');
let parts: Vec<&str> = path.split('/').collect();
match parts.iter().rposition(|part| *part == "assets") {
Some(assets) if assets >= 3 && parts.len() > assets + 3 => parts[..assets + 3].join("/"),
_ => path.to_owned(),
}
}
const CDN_RESOURCE_PATHS: [(&str, &str); 7] = [
("original", "original"),
("rendered", "rendered"),
("preview", "preview"),
("placeholder", "placeholder"),
("hls", "hls/index.m3u8"),
("embed", "embed"),
("info", "info"),
];
const EXTERNAL_ID_SEGMENT_PREFIX: &str = "ext:";
fn asset_segment(asset_id: Option<&str>, external_id: Option<&str>) -> Result<String> {
match (asset_id, external_id) {
(Some(asset_id), None) => id(asset_id),
(None, Some("")) => Err(invalid_argument("External ID is required")),
(None, Some(external_id)) => Ok(format!(
"{EXTERNAL_ID_SEGMENT_PREFIX}{}",
percent_encode(external_id, b"-_.!~*'()")
)),
_ => Err(invalid_argument("Pass either asset_id or external_id")),
}
}
fn viewer_claims_query(claims: Option<&ViewerClaims>) -> Result<String> {
let Some(claims) = claims else {
return Ok(String::new());
};
let mut sent = Vec::new();
if let Some(region) = &claims.region {
let region = serde_json::to_string(region)
.map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
sent.push(format!("\"region\":{region}"));
}
if claims.age_confirmed == Some(true) {
sent.push("\"ageConfirmed\":true".to_owned());
}
if sent.is_empty() {
return Ok(String::new());
}
let json = format!("{{{}}}", sent.join(","));
Ok(format!("?viewerClaims={}", percent_encode(&json, b"-._~")))
}
struct AssetLocation<'a> {
resource: Option<&'a CdnResource>,
lens: Option<&'a str>,
transform: Option<&'a CdnTransform>,
viewer_claims: Option<&'a ViewerClaims>,
}
impl AssetLocation<'_> {
fn resource(&self) -> &str {
self.resource.map_or("rendered", CdnResource::as_str)
}
fn resource_path(&self) -> Result<String> {
let resource = self.resource();
match CDN_RESOURCE_PATHS
.iter()
.find(|(name, _)| *name == resource)
{
Some((_, path)) => Ok((*path).to_owned()),
None if resource.is_empty() => Err(invalid_argument("Resource is required")),
None => {
id(resource).map_err(|_| invalid_argument("Resource cannot be \".\" or \"..\""))
}
}
}
fn append(&self, asset_url: &str) -> Result<String> {
let path = self.resource_path()?;
let mut url = format!("{asset_url}/{path}");
let mut selector = Vec::new();
if let Some(lens) = self.lens {
selector.push(format!("@{}", id(lens)?));
}
if let Some(value) = self.transform.filter(|value| !value.is_empty()) {
selector.push(match value {
CdnTransform::Selector(_) => encode_selector(&value.selector()?),
CdnTransform::Options(_) => value.selector()?,
});
}
if !selector.is_empty() {
url.push('/');
url.push_str(&selector.join(","));
}
url.push_str(&viewer_claims_query(self.viewer_claims)?);
Ok(url)
}
}
#[derive(Debug, Clone, Copy)]
pub struct CdnClient<'a>(&'a ServerClient);
impl CdnClient<'_> {
fn project_segment(&self, project_id: Option<&str>) -> Result<String> {
id(project_id.unwrap_or(&self.0.inner.config.project_id))
}
pub fn get_asset_url(&self, options: &CdnRequest) -> Result<String> {
let project = self.project_segment(options.project_id.as_deref())?;
let asset = asset_segment(options.asset_id.as_deref(), options.external_id.as_deref())?;
let location = AssetLocation {
resource: options.resource.as_ref(),
lens: options.lens.as_deref(),
transform: options.transform.as_ref(),
viewer_claims: options.viewer_claims.as_ref(),
};
location.append(&format!(
"{}/assets/{project}/{asset}",
self.0.inner.config.cdn_base_url
))
}
pub fn sign_asset_url(&self, options: SignAssetUrlOptions) -> Result<SignedAssetUrl> {
let now = self.0.inner.transport.epoch_millis();
let api_key = String::from_utf8_lossy(self.0.inner.config.api_key.as_bytes()).into_owned();
sign_asset_url(
&api_key,
&self.0.inner.config.project_id,
&self.0.inner.config.cdn_base_url,
options,
now,
)
}
pub async fn get_asset_info(
&self,
url: &str,
options: GetAssetInfoOptions,
) -> Result<AssetInfo> {
let parsed = reqwest::Url::parse(url)
.ok()
.filter(|parsed| parsed.has_host())
.ok_or_else(|| invalid_argument("url must be an absolute asset URL"))?;
let without_fragment = url.split('#').next().unwrap_or_default();
let base = without_fragment.split('?').next().unwrap_or_default();
let claims = match options.viewer_claims {
Some(claims) => Some(claims),
None => match parsed.query_pairs().find(|(key, _)| key == "viewerClaims") {
Some((_, raw)) => {
Some(serde_json::from_str::<ViewerClaims>(&raw).map_err(|cause| {
invalid_argument("The asset URL's viewerClaims are not valid JSON")
.with_source(cause)
})?)
}
None => None,
},
};
let info_url = format!(
"{}/info{}",
asset_url_of(base),
viewer_claims_query(claims.as_ref())?
);
let mut request =
self.0
.prepare_url_for("cdn.getAssetInfo", Method::GET, &info_url, &[])?;
request.headers.remove("x-api-key");
request.headers.insert(
http::header::ACCEPT,
HeaderValue::from_static("application/json"),
);
let options = self.0.options()?;
let exchange = execute(
&self.0.inner.transport,
request,
options,
true,
&self.0.inner.config.observer,
)
.await?;
let (status, headers) = (exchange.status, exchange.headers.clone());
let body = exchange.read(options.max_response_bytes).await?;
let mut info: AssetInfo = decode(status, &headers, &body)?;
info.set_last_response(crate::transport::last_response(status, &headers, None));
if info.id.is_empty() || info.project_id.is_empty() || !info.availability.is_known() {
return Err(
Error::new(ErrorCode::InvalidResponse, "The CDN returned no asset info")
.with_http_status(status),
);
}
Ok(info)
}
pub async fn serve(&self, options: CdnRequest) -> Result<CdnResponse> {
let url = self.get_asset_url(&options)?;
let init = options.init.unwrap_or_default();
let method = Method::from_bytes(init.method.as_deref().unwrap_or("GET").as_bytes())
.map_err(|_| invalid_argument("Invalid HTTP method"))?;
let mut request = self.0.prepare_url_for("cdn.serve", method, &url, &[])?;
for (name, value) in &init.headers {
if name.eq_ignore_ascii_case("x-api-key") {
continue;
}
let name = http::HeaderName::from_bytes(name.as_bytes())
.map_err(|_| invalid_argument(format!("Invalid header name {name:?}")))?;
let value = HeaderValue::from_str(value)
.map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
request.headers.insert(name, value);
}
self.fetch(request).await
}
#[cfg(feature = "testing")]
pub(crate) async fn fetch_unauthenticated(&self, url: &str) -> Result<CdnResponse> {
let mut request =
self.0
.prepare_url_for("cdn.fetchUnauthenticated", Method::GET, url, &[])?;
request.headers.remove("x-api-key");
self.fetch(request).await
}
async fn fetch(&self, mut request: Prepared) -> Result<CdnResponse> {
request.deadline = Deadline::Headers;
let exchange: Exchange = execute(
&self.0.inner.transport,
request,
self.0.options()?,
false,
&self.0.inner.config.observer,
)
.await?;
Ok(CdnResponse {
status: StatusCode::from_u16(exchange.status)
.map_err(|_| Error::new(ErrorCode::InvalidResponse, "Invalid status"))?,
headers: exchange.headers.clone(),
body: exchange.stream(),
})
}
}
pub struct CdnResponse {
status: StatusCode,
headers: HeaderMap,
body: crate::ByteStream,
}
impl fmt::Debug for CdnResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CdnResponse")
.field("status", &self.status)
.field("headers", &self.headers)
.finish_non_exhaustive()
}
}
impl CdnResponse {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn get_asset_info(&self) -> Option<crate::ServedAssetInfo> {
crate::ServedAssetInfo::from_headers(&self.headers)
}
pub async fn chunk(&mut self) -> Result<Option<Bytes>> {
match self.body.next().await {
None => Ok(None),
Some(chunk) => chunk.map(Some).map_err(stream_error),
}
}
pub async fn bytes(mut self) -> Result<Bytes> {
let mut body = Vec::new();
while let Some(chunk) = self.chunk().await? {
body.extend_from_slice(&chunk);
}
Ok(body.into())
}
pub async fn text(self) -> Result<String> {
String::from_utf8(self.bytes().await?.to_vec()).map_err(|cause| {
Error::new(ErrorCode::InvalidResponse, "Invalid UTF-8 response").with_source(cause)
})
}
pub fn into_stream(self) -> BoxStream<'static, Result<Bytes>> {
self.body.map_err(stream_error).boxed()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn interrupt(uploads: &Mutex<VecDeque<String>>, key: &str) {
drop(InterruptedUpload {
uploads,
key: Some(key.to_owned()),
});
}
#[test]
fn interrupted_uploads_keep_the_most_recent_keys() {
let uploads = Mutex::new(VecDeque::new());
for index in 0..=INTERRUPTED_UPLOADS {
interrupt(&uploads, &format!("key-{index}"));
}
interrupt(&uploads, "key-1");
let remembered = uploads.lock().unwrap();
assert_eq!(remembered.len(), INTERRUPTED_UPLOADS);
assert!(!remembered.contains(&"key-0".to_owned()));
assert_eq!(remembered.front().map(String::as_str), Some("key-2"));
assert_eq!(remembered.back().map(String::as_str), Some("key-1"));
}
}