use crate::error::{invalid_config, ErrorCode};
use crate::models::*;
use crate::{Error, Result};
use bytes::Bytes;
use futures_util::{Stream, StreamExt};
use http::{HeaderMap, StatusCode};
use std::{fmt, future::Future, pin::Pin, sync::Arc, time::Duration};
struct Runtime(Option<tokio::runtime::Runtime>);
impl Runtime {
fn block_on<F: Future>(&self, future: F) -> F::Output {
self.0
.as_ref()
.expect("runtime is present until drop")
.block_on(future)
}
}
impl Drop for Runtime {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[derive(Clone, Debug)]
pub struct ServerClientBuilder(crate::ServerClientBuilder);
impl ServerClientBuilder {
pub fn from_env() -> Result<Self> {
crate::ServerClientBuilder::from_env().map(Self)
}
pub fn base_url(self, value: impl Into<String>) -> Self {
Self(self.0.base_url(value))
}
pub fn cdn_base_url(self, value: impl Into<String>) -> Self {
Self(self.0.cdn_base_url(value))
}
pub fn timeout(self, value: Duration) -> Self {
Self(self.0.timeout(value))
}
pub fn upload_timeout(self, value: Duration) -> Self {
Self(self.0.upload_timeout(value))
}
pub fn max_response_bytes(self, value: usize) -> Self {
Self(self.0.max_response_bytes(value))
}
pub fn connect_timeout(self, value: Duration) -> Self {
Self(self.0.connect_timeout(value))
}
pub fn read_timeout(self, value: Duration) -> Self {
Self(self.0.read_timeout(value))
}
pub fn max_retries(self, value: u32) -> Self {
Self(self.0.max_retries(value))
}
pub fn proxy(self, url: impl Into<String>) -> Self {
Self(self.0.proxy(url))
}
pub fn add_root_certificate(self, pem: impl Into<Vec<u8>>) -> Self {
Self(self.0.add_root_certificate(pem))
}
pub fn app_info(
self,
name: impl Into<String>,
version: Option<&str>,
url: Option<&str>,
) -> Self {
Self(self.0.app_info(name, version, url))
}
pub fn build(self) -> Result<ServerClient> {
ServerClient::from_async(self.0.build()?)
}
}
#[derive(Clone)]
pub struct ServerClient {
client: crate::ServerClient,
runtime: Arc<Runtime>,
}
impl fmt::Debug for ServerClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("blocking::ServerClient")
.field(&self.client)
.finish()
}
}
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(crate::ServerClient::builder(api_key, project_id))
}
pub fn from_async(client: crate::ServerClient) -> Result<Self> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("calmlens-blocking")
.enable_all()
.build()
.map_err(|cause| {
invalid_config(format!("Could not start the client runtime: {cause}"))
.with_source(cause)
})?;
Ok(Self {
client,
runtime: Arc::new(Runtime(Some(runtime))),
})
}
pub fn as_async(&self) -> &crate::ServerClient {
&self.client
}
pub fn with_timeout(&self, timeout: Duration) -> Self {
Self {
client: self.client.with_timeout(timeout),
runtime: self.runtime.clone(),
}
}
pub fn with_max_retries(&self, max_retries: u32) -> Self {
Self {
client: self.client.with_max_retries(max_retries),
runtime: self.runtime.clone(),
}
}
fn wait<T>(&self, future: impl Future<Output = T>) -> T {
self.runtime.block_on(future)
}
fn iter<T>(&self, stream: impl Stream<Item = T> + Send + 'static) -> Iter<T> {
Iter {
stream: Box::pin(stream),
runtime: self.runtime.clone(),
}
}
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 fn ensure_lens(&self, lens: LensDefinition) -> Result<Lens> {
self.wait(self.client.ensure_lens(lens))
}
pub fn ensure_lenses(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
self.wait(self.client.ensure_lenses(options))
}
}
pub struct Iter<T> {
stream: Pin<Box<dyn Stream<Item = T> + Send>>,
runtime: Arc<Runtime>,
}
impl<T> fmt::Debug for Iter<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Iter").finish_non_exhaustive()
}
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.runtime.block_on(self.stream.next())
}
}
macro_rules! blocking_methods {
($handle:ident => $async_handle:ident { $( $(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty; )* }) => {
impl $handle<'_> {
$(
$(#[$doc])*
pub fn $name(&self, $($arg: $ty),*) -> $ret {
self.0.wait(self.0.client.$async_handle().$name($($arg),*))
}
)*
}
};
}
#[derive(Debug, Clone, Copy)]
pub struct AssetsClient<'a>(&'a ServerClient);
blocking_methods!(AssetsClient => assets {
fn create(options: SubmitAsset) -> Result<Asset>;
fn classify(options: SubmitAsset) -> Result<Asset>;
fn upload_part(options: UploadPart) -> Result<Asset>;
fn search(options: SearchAssets) -> Result<AssetSearchResponse>;
fn list(options: ListAssets) -> Result<AssetPage>;
fn list_children(options: ListChildren) -> Result<AssetPage>;
fn list_timeline(options: ListTimeline) -> Result<AssetTimelinePage>;
fn retrieve(options: AssetId) -> Result<Asset>;
fn wait_for_decision(options: WaitForDecision) -> Result<Asset>;
fn update(options: UpdateAsset) -> Result<Asset>;
fn retry(options: AssetId) -> Result<Asset>;
fn decide(options: DecideAsset) -> Result<Asset>;
fn remove_content(options: AssetId) -> Result<Asset>;
fn delete(options: AssetId) -> Result<()>;
fn batch(options: BatchAssets) -> Result<BatchAssetsResponse>;
fn move_asset(options: MoveAsset) -> Result<Asset>;
});
impl AssetsClient<'_> {
pub fn iterate(&self, options: ListAssets) -> Iter<Result<Asset>> {
self.0.iter(self.0.client.assets().iterate(options))
}
pub fn iterate_children(&self, options: ListChildren) -> Iter<Result<Asset>> {
self.0
.iter(self.0.client.assets().iterate_children(options))
}
pub fn iterate_timeline(
&self,
options: ListTimeline,
) -> Iter<Result<MediaClassificationSegment>> {
self.0
.iter(self.0.client.assets().iterate_timeline(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct FoldersClient<'a>(&'a ServerClient);
blocking_methods!(FoldersClient => folders {
fn list(options: ListFolders) -> Result<FolderPage>;
fn create(options: CreateFolder) -> Result<Folder>;
fn retrieve(options: FolderId) -> Result<Folder>;
fn update(options: UpdateFolder) -> Result<Folder>;
fn move_folder(options: MoveFolder) -> Result<Folder>;
fn delete(options: FolderId) -> Result<()>;
});
impl FoldersClient<'_> {
pub fn iterate(&self, options: ListFolders) -> Iter<Result<Folder>> {
self.0.iter(self.0.client.folders().iterate(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct HashListsClient<'a>(&'a ServerClient);
blocking_methods!(HashListsClient => hash_lists {
fn list(options: ListHashLists) -> Result<HashListPage>;
fn retrieve(options: HashListId) -> Result<HashList>;
fn create(options: CreateHashList) -> Result<HashList>;
fn update(options: UpdateHashList) -> Result<HashList>;
fn delete(options: HashListId) -> Result<()>;
fn list_entries(options: ListHashListEntries) -> Result<HashListEntryPage>;
fn add_entry(options: AddHashListEntry) -> Result<HashListEntry>;
fn remove_entry(options: HashListEntryId) -> Result<()>;
});
impl HashListsClient<'_> {
pub fn iterate(&self, options: ListHashLists) -> Iter<Result<HashList>> {
self.0.iter(self.0.client.hash_lists().iterate(options))
}
pub fn iterate_entries(&self, options: ListHashListEntries) -> Iter<Result<HashListEntry>> {
self.0
.iter(self.0.client.hash_lists().iterate_entries(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct PoliciesClient<'a>(&'a ServerClient);
blocking_methods!(PoliciesClient => policies {
fn list(options: ListPolicies) -> Result<PolicyPage>;
fn retrieve(options: PolicyId) -> Result<Policy>;
fn create(options: CreatePolicy) -> Result<Policy>;
fn update(options: UpdatePolicy) -> Result<Policy>;
fn reset(options: ResetPolicy) -> Result<Policy>;
fn upgrade(options: UpgradePolicy) -> Result<Policy>;
fn set_automatic_updates(options: SetPolicyAutomaticUpdates) -> Result<Policy>;
fn delete(options: PolicyId) -> Result<()>;
fn retrieve_assigned() -> Result<Policy>;
fn assign(options: AssignPolicy) -> Result<Policy>;
});
impl PoliciesClient<'_> {
pub fn iterate(&self, options: ListPolicies) -> Iter<Result<Policy>> {
self.0.iter(self.0.client.policies().iterate(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct UploadPresetsClient<'a>(&'a ServerClient);
blocking_methods!(UploadPresetsClient => upload_presets {
fn list(options: ListUploadPresets) -> Result<UploadPresetPage>;
fn ensure(options: EnsureUploadPresets) -> Result<EnsureUploadPresetsResponse>;
fn delete(options: UploadPresetId) -> Result<()>;
});
impl UploadPresetsClient<'_> {
pub fn iterate(&self, options: ListUploadPresets) -> Iter<Result<UploadPreset>> {
self.0.iter(self.0.client.upload_presets().iterate(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct ProjectSettingsClient<'a>(&'a ServerClient);
blocking_methods!(ProjectSettingsClient => project_settings {
fn get() -> Result<ProjectSettingsResource>;
fn update(options: UpdateProjectSettings) -> Result<ProjectSettingsResource>;
});
#[derive(Debug, Clone, Copy)]
pub struct MetadataFieldsClient<'a>(&'a ServerClient);
blocking_methods!(MetadataFieldsClient => metadata_fields {
fn list() -> Result<MetadataFieldsResource>;
fn ensure(options: EnsureMetadataFields) -> Result<MetadataFieldsResource>;
fn delete(options: DeleteMetadataField) -> Result<()>;
});
#[derive(Debug, Clone, Copy)]
pub struct LensesClient<'a>(&'a ServerClient);
blocking_methods!(LensesClient => lenses {
fn list(options: ListLenses) -> Result<LensPage>;
fn create(options: LensDefinition) -> Result<Lens>;
fn retrieve(options: LensId) -> Result<Lens>;
fn update(options: UpdateLens) -> Result<Lens>;
fn delete(options: LensId) -> Result<()>;
});
impl LensesClient<'_> {
pub fn iterate(&self, options: ListLenses) -> Iter<Result<Lens>> {
self.0.iter(self.0.client.lenses().iterate(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct EventsClient<'a>(&'a ServerClient);
blocking_methods!(EventsClient => events {
fn list(options: ListEvents) -> Result<EventsPage>;
});
impl EventsClient<'_> {
pub fn iterate(&self, options: ListEvents) -> Iter<Result<Event>> {
self.0.iter(self.0.client.events().iterate(options))
}
pub fn pages(&self, options: ListEvents) -> Iter<Result<EventsPage>> {
self.0.iter(self.0.client.events().pages(options))
}
}
#[derive(Debug, Clone, Copy)]
pub struct TextClient<'a>(&'a ServerClient);
blocking_methods!(TextClient => text {
fn classify(options: ClassifyText) -> Result<Asset>;
});
#[derive(Debug, Clone, Copy)]
pub struct UploadTokensClient<'a>(&'a ServerClient);
impl UploadTokensClient<'_> {
pub fn sign(&self, options: SignUploadToken) -> Result<SignedUploadToken> {
self.0.client.upload_tokens().sign(options)
}
}
#[derive(Debug, Clone, Copy)]
pub struct CdnClient<'a>(&'a ServerClient);
impl CdnClient<'_> {
pub fn get_asset_url(&self, options: &CdnRequest) -> Result<String> {
self.0.client.cdn().get_asset_url(options)
}
pub fn sign_asset_url(&self, options: SignAssetUrlOptions) -> Result<SignedAssetUrl> {
self.0.wait(self.0.client.cdn().sign_asset_url(options))
}
pub fn get_asset_info(&self, url: &str, options: GetAssetInfoOptions) -> Result<AssetInfo> {
self.0
.wait(self.0.client.cdn().get_asset_info(url, options))
}
pub fn serve(&self, options: CdnRequest) -> Result<CdnResponse> {
let response = self.0.wait(self.0.client.cdn().serve(options))?;
Ok(CdnResponse {
response,
runtime: self.0.runtime.clone(),
pending: Bytes::new(),
})
}
}
pub struct CdnResponse {
response: crate::CdnResponse,
runtime: Arc<Runtime>,
pending: Bytes,
}
impl fmt::Debug for CdnResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.response.fmt(f)
}
}
impl CdnResponse {
pub fn status(&self) -> StatusCode {
self.response.status()
}
pub fn headers(&self) -> &HeaderMap {
self.response.headers()
}
pub fn get_asset_info(&self) -> Option<crate::ServedAssetInfo> {
self.response.get_asset_info()
}
pub fn chunk(&mut self) -> Result<Option<Bytes>> {
if !self.pending.is_empty() {
return Ok(Some(std::mem::take(&mut self.pending)));
}
self.runtime.block_on(self.response.chunk())
}
pub fn bytes(mut self) -> Result<Bytes> {
let mut body = Vec::new();
while let Some(chunk) = self.chunk()? {
body.extend_from_slice(&chunk);
}
Ok(body.into())
}
pub fn text(self) -> Result<String> {
String::from_utf8(self.bytes()?.to_vec()).map_err(|cause| {
Error::new(ErrorCode::InvalidResponse, "Invalid UTF-8 response").with_source(cause)
})
}
}
impl std::io::Read for CdnResponse {
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
if self.pending.is_empty() {
match self.runtime.block_on(self.response.chunk()) {
Ok(Some(chunk)) => self.pending = chunk,
Ok(None) => return Ok(0),
Err(error) => {
let kind = if error.is_timeout() {
std::io::ErrorKind::TimedOut
} else {
std::io::ErrorKind::Other
};
return Err(std::io::Error::new(kind, error));
}
}
}
let count = buffer.len().min(self.pending.len());
buffer[..count].copy_from_slice(&self.pending.split_to(count));
Ok(count)
}
}