Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Move Space error classification to Rust

Manav Rathi591e4f503e1f
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 23d0ed8dce..9f5d4c3f3e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2788,9 +2788,11 @@ dependencies = [
"ente-core",
"ente-space",
"ente-wasm-log",
+ "js-sys",
"log",
"serde",
"serde-wasm-bindgen",
+ "thiserror 2.0.18",
"tokio",
"wasm-bindgen",
"wasm-bindgen-futures",
diff --git a/rust/bindings/wasm/space/Cargo.toml b/rust/bindings/wasm/space/Cargo.toml
index 41d33fe308..a6fd63b2e2 100644
--- a/rust/bindings/wasm/space/Cargo.toml
+++ b/rust/bindings/wasm/space/Cargo.toml
@@ -9,9 +9,11 @@ crate-type = ["cdylib"]
ente-core.workspace = true
ente-space.workspace = true
ente-wasm-log.workspace = true
+js-sys.workspace = true
log.workspace = true
serde.workspace = true
serde-wasm-bindgen.workspace = true
+thiserror.workspace = true
wasm-bindgen.workspace = true
wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rs
index 16fe65eeb2..e88dc4e6b4 100644
--- a/rust/bindings/wasm/space/src/space.rs
+++ b/rust/bindings/wasm/space/src/space.rs
@@ -1,6 +1,6 @@
use std::collections::BTreeMap;
-use ente_core::{b64, http};
+use ente_core::b64;
use ente_space::{
AccountSpaceCtx, CreatedSpace, DecryptedMessage, DecryptedPost, DecryptedSpaceProfile,
MessageConversationActivity, MessageResponse, OpenAccountSpaceCtxInput, OpenSpaceLinkCtxInput,
@@ -11,79 +11,46 @@ use serde::{Deserialize, Serialize};
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
-#[wasm_bindgen]
-pub struct WasmSpaceError {
- code: String,
- message: String,
- status: Option<u16>,
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Space(#[from] ente_space::Error),
+ #[error(transparent)]
+ Serde(#[from] swb::Error),
}
-#[wasm_bindgen]
-impl WasmSpaceError {
- #[wasm_bindgen(getter)]
- pub fn code(&self) -> String {
- self.code.clone()
- }
-
- #[wasm_bindgen(getter)]
- pub fn message(&self) -> String {
- self.message.clone()
- }
-
- #[wasm_bindgen(getter)]
- pub fn status(&self) -> Option<u16> {
- self.status
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ match self {
+ Self::Space(error) if error.is_content_error() => Some("content_unavailable"),
+ Self::Space(ente_space::Error::SpaceLimitReached) => Some("space_limit_reached"),
+ Self::Space(ente_space::Error::SpaceSlugAlreadyExists) => {
+ Some("space_slug_already_exists")
+ }
+ Self::Space(ente_space::Error::InvalidSpaceSlug) => Some("invalid_space_slug"),
+ Self::Space(ente_space::Error::PostLimitReached) => Some("post_limit_reached"),
+ Self::Space(ente_space::Error::SessionUnauthorized) => Some("session_unauthorized"),
+ Self::Space(ente_space::Error::PermissionDenied) => Some("permission_denied"),
+ _ => None,
+ }
}
- // Preserve the structured error when web logging stringifies this value.
- #[wasm_bindgen(js_name = toString)]
- pub fn js_to_string(&self) -> String {
- format!("{}: {}", self.code, self.message)
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
}
fn is_content_error(&self) -> bool {
- matches!(
- self.code.as_str(),
- "crypto" | "base64_decode" | "invalid_input" | "missing_friend_sealed_space_key"
- )
+ matches!(self, Self::Space(error) if error.is_content_error())
}
}
-impl From<ente_space::SpaceError> for WasmSpaceError {
- fn from(e: ente_space::SpaceError) -> Self {
- let (code, status) = match &e {
- ente_space::SpaceError::Http(http::Error::Http { status, .. }) => {
- ("http", Some(*status))
- }
- ente_space::SpaceError::Http(http::Error::Api { status, code, .. }) => {
- (code.as_str(), Some(*status))
- }
- ente_space::SpaceError::Http(http::Error::Network(_)) => ("network", None),
- ente_space::SpaceError::Http(http::Error::Parse(_)) => ("parse", None),
- ente_space::SpaceError::Crypto(_) => ("crypto", None),
- ente_space::SpaceError::Base64Decode(_) => ("base64_decode", None),
- ente_space::SpaceError::InvalidInput(_) => ("invalid_input", None),
- ente_space::SpaceError::MissingSecretKey => ("missing_secret_key", None),
- ente_space::SpaceError::MissingFriendSealedSpaceKey => {
- ("missing_friend_sealed_space_key", None)
- }
- ente_space::SpaceError::EntityKeyConflict => ("entity_key_conflict", None),
- };
- Self {
- code: code.to_owned(),
- message: e.to_string(),
- status,
- }
- }
-}
-
-impl From<swb::Error> for WasmSpaceError {
- fn from(e: swb::Error) -> Self {
- Self {
- code: "serde".to_owned(),
- message: e.to_string(),
- status: None,
+impl From<Error> for JsValue {
+ fn from(error: Error) -> Self {
+ let js_error = js_sys::Error::new(&error.message());
+ if let Some(name) = error.name() {
+ js_error.set_name(name);
}
+ js_error.into()
}
}
@@ -285,9 +252,9 @@ struct SentFriendRequestJs {
created_at: String,
}
-fn decode_b64_field(value: &str) -> Result<Vec<u8>, WasmSpaceError> {
+fn decode_b64_field(value: &str) -> Result<Vec<u8>, Error> {
b64::decode(value)
- .map_err(ente_space::SpaceError::from)
+ .map_err(ente_space::Error::from)
.map_err(Into::into)
}
@@ -295,7 +262,7 @@ fn decode_b64_field(value: &str) -> Result<Vec<u8>, WasmSpaceError> {
pub fn encrypt_space_root_entity_key(
space_root_key_b64: &str,
master_key_b64: &str,
-) -> Result<String, WasmSpaceError> {
+) -> Result<String, Error> {
ente_space::encrypt_space_root_entity_key(space_root_key_b64, master_key_b64)
.map_err(Into::into)
}
@@ -304,20 +271,17 @@ pub fn encrypt_space_root_entity_key(
pub fn decrypt_space_root_entity_key(
encrypted_key_b64: &str,
master_key_b64: &str,
-) -> Result<String, WasmSpaceError> {
+) -> Result<String, Error> {
ente_space::decrypt_space_root_entity_key(encrypted_key_b64, master_key_b64).map_err(Into::into)
}
-fn utf8_field(bytes: Vec<u8>, field: &str) -> Result<String, WasmSpaceError> {
+fn utf8_field(bytes: Vec<u8>, field: &str) -> Result<String, Error> {
String::from_utf8(bytes).map_err(|err| {
- ente_space::SpaceError::InvalidInput(format!("invalid {field} utf8: {err}")).into()
+ ente_space::Error::InvalidInput(format!("invalid {field} utf8: {err}")).into()
})
}
-fn optional_utf8_field(
- bytes: Option<Vec<u8>>,
- field: &str,
-) -> Result<Option<String>, WasmSpaceError> {
+fn optional_utf8_field(bytes: Option<Vec<u8>>, field: &str) -> Result<Option<String>, Error> {
bytes.map(|value| utf8_field(value, field)).transpose()
}
@@ -328,7 +292,7 @@ fn created_space_to_js(value: CreatedSpace) -> CreatedSpaceJs {
}
}
-fn profile_to_js(value: DecryptedSpaceProfile) -> Result<SpaceProfileJs, WasmSpaceError> {
+fn profile_to_js(value: DecryptedSpaceProfile) -> Result<SpaceProfileJs, Error> {
let profile = String::from_utf8(value.profile).unwrap_or_else(|error| {
log::warn!(
"Space profile {} has invalid UTF-8: {error}",
@@ -349,10 +313,7 @@ fn profile_to_js(value: DecryptedSpaceProfile) -> Result<SpaceProfileJs, WasmSpa
})
}
-fn actor_to_js(
- actor: SpaceActorResponse,
- profile: Option<Vec<u8>>,
-) -> Result<ActorJs, WasmSpaceError> {
+fn actor_to_js(actor: SpaceActorResponse, profile: Option<Vec<u8>>) -> Result<ActorJs, Error> {
Ok(ActorJs {
space_id: actor.space_id,
space_slug: actor.space_slug,
@@ -366,7 +327,7 @@ fn actor_to_js(
async fn account_actor_to_js(
ctx: &AccountSpaceCtx,
actor: SpaceActorResponse,
-) -> Result<ActorJs, WasmSpaceError> {
+) -> Result<ActorJs, Error> {
let fallback = actor.clone();
let converted = match ctx.decrypt_actor_profile(&actor).await {
Ok(profile) => actor_to_js(actor, profile),
@@ -376,10 +337,9 @@ async fn account_actor_to_js(
Ok(actor) => Ok(actor),
Err(error) if error.is_content_error() => {
log::warn!(
- "Space profile {} fell back to public fields: {}: {}",
+ "Space profile {} fell back to public fields: {}",
fallback.space_id,
- error.code,
- error.message
+ error.message()
);
public_actor_to_js(fallback)
}
@@ -387,14 +347,14 @@ async fn account_actor_to_js(
}
}
-fn public_actor_to_js(actor: SpaceActorResponse) -> Result<ActorJs, WasmSpaceError> {
+fn public_actor_to_js(actor: SpaceActorResponse) -> Result<ActorJs, Error> {
actor_to_js(actor, None)
}
fn post_object_to_js(
post_key: Option<&[u8]>,
object: ente_space::PostObjectPayload,
-) -> Result<PostObjectJs, WasmSpaceError> {
+) -> Result<PostObjectJs, Error> {
let metadata = match post_key {
Some(post_key) => ente_space::client::decrypt_post_object_metadata(post_key, &object)?,
None => None,
@@ -415,7 +375,7 @@ fn post_object_to_js(
fn post_objects_to_js(
post_key: Option<&[u8]>,
objects: Vec<ente_space::PostObjectPayload>,
-) -> Result<Vec<PostObjectJs>, WasmSpaceError> {
+) -> Result<Vec<PostObjectJs>, Error> {
objects
.into_iter()
.map(|object| post_object_to_js(post_key, object))
@@ -426,7 +386,7 @@ async fn account_post_to_js(
ctx: &AccountSpaceCtx,
post: PostResponse,
decrypted: DecryptedPost,
-) -> Result<PostJs, WasmSpaceError> {
+) -> Result<PostJs, Error> {
let author = account_actor_to_js(ctx, post.author).await?;
Ok(PostJs {
post_id: post.post_id,
@@ -443,7 +403,7 @@ async fn account_post_to_js(
})
}
-fn unavailable_post_to_js(post: PostResponse) -> Result<PostJs, WasmSpaceError> {
+fn unavailable_post_to_js(post: PostResponse) -> Result<PostJs, Error> {
Ok(PostJs {
post_id: post.post_id,
space_id: post.space_id,
@@ -462,7 +422,7 @@ fn unavailable_post_to_js(post: PostResponse) -> Result<PostJs, WasmSpaceError>
async fn account_post_page_to_js(
ctx: &AccountSpaceCtx,
page: ente_space::PostPage,
-) -> Result<PostPageJs, WasmSpaceError> {
+) -> Result<PostPageJs, Error> {
let mut items = Vec::with_capacity(page.items.len());
for post in page.items {
let fallback = post.clone();
@@ -474,10 +434,9 @@ async fn account_post_page_to_js(
Ok(post) => items.push(post),
Err(error) if error.is_content_error() => {
log::warn!(
- "Space post {} is unavailable: {}: {}",
+ "Space post {} is unavailable: {}",
fallback.post_id,
- error.code,
- error.message
+ error.message()
);
items.push(unavailable_post_to_js(fallback)?);
}
@@ -490,7 +449,7 @@ async fn account_post_page_to_js(
})
}
-fn link_post_to_js(post: PostResponse, decrypted: DecryptedPost) -> Result<PostJs, WasmSpaceError> {
+fn link_post_to_js(post: PostResponse, decrypted: DecryptedPost) -> Result<PostJs, Error> {
Ok(PostJs {
post_id: post.post_id,
space_id: post.space_id,
@@ -509,7 +468,7 @@ fn link_post_to_js(post: PostResponse, decrypted: DecryptedPost) -> Result<PostJ
async fn account_message_to_js(
message: MessageResponse,
decrypted: DecryptedMessage,
-) -> Result<MessageJs, WasmSpaceError> {
+) -> Result<MessageJs, Error> {
Ok(message_to_js(message, decrypted.payload.text))
}
@@ -553,7 +512,7 @@ async fn account_message_response_to_js(
ctx: &AccountSpaceCtx,
viewer_space_id: &str,
message: MessageResponse,
-) -> Result<MessageJs, WasmSpaceError> {
+) -> Result<MessageJs, Error> {
if message.is_deleted {
return Ok(message_to_js(message, String::new()));
}
@@ -570,16 +529,15 @@ async fn resilient_account_message_response_to_js(
ctx: &AccountSpaceCtx,
viewer_space_id: &str,
message: MessageResponse,
-) -> Result<MessageJs, WasmSpaceError> {
+) -> Result<MessageJs, Error> {
let fallback = message.clone();
match account_message_response_to_js(ctx, viewer_space_id, message).await {
Ok(message) => Ok(message),
Err(error) if error.is_content_error() => {
log::warn!(
- "Space message {} is unavailable: {}: {}",
+ "Space message {} is unavailable: {}",
fallback.message_id,
- error.code,
- error.message
+ error.message()
);
Ok(unavailable_message_to_js(fallback))
}
@@ -591,7 +549,7 @@ async fn message_conversation_activity_text(
ctx: &AccountSpaceCtx,
viewer_space_id: &str,
activity: &MessageConversationActivity,
-) -> Result<Option<String>, WasmSpaceError> {
+) -> Result<Option<String>, Error> {
if activity.message_cipher.trim().is_empty()
|| activity.encrypted_message_key.trim().is_empty()
|| activity.message_id.is_none()
@@ -627,7 +585,7 @@ async fn message_conversation_activity_to_js(
ctx: &AccountSpaceCtx,
viewer_space_id: &str,
activity: MessageConversationActivity,
-) -> Result<MessageConversationActivityJs, WasmSpaceError> {
+) -> Result<MessageConversationActivityJs, Error> {
let text = message_conversation_activity_text(ctx, viewer_space_id, &activity).await?;
Ok(MessageConversationActivityJs {
id: activity.id,
@@ -662,16 +620,15 @@ async fn resilient_message_conversation_activity_to_js(
ctx: &AccountSpaceCtx,
viewer_space_id: &str,
activity: MessageConversationActivity,
-) -> Result<MessageConversationActivityJs, WasmSpaceError> {
+) -> Result<MessageConversationActivityJs, Error> {
let fallback = activity.clone();
match message_conversation_activity_to_js(ctx, viewer_space_id, activity).await {
Ok(activity) => Ok(activity),
Err(error) if error.is_content_error() => {
log::warn!(
- "Space conversation activity {} is unavailable: {}: {}",
+ "Space conversation activity {} is unavailable: {}",
fallback.id,
- error.code,
- error.message
+ error.message()
);
Ok(unavailable_message_conversation_activity_to_js(fallback))
}
@@ -680,9 +637,7 @@ async fn resilient_message_conversation_activity_to_js(
}
#[wasm_bindgen(js_name = spaceOpenAccountCtx)]
-pub async fn space_open_account_ctx(
- input: JsValue,
-) -> Result<SpaceAccountCtxHandle, WasmSpaceError> {
+pub async fn space_open_account_ctx(input: JsValue) -> Result<SpaceAccountCtxHandle, Error> {
let input: OpenAccountSpaceCtxJsInput = swb::from_value(input)?;
let space_root_key = decode_b64_field(&input.space_root_key_b64)?;
let ctx = AccountSpaceCtx::open(OpenAccountSpaceCtxInput {
@@ -698,7 +653,7 @@ pub async fn space_open_account_ctx(
}
#[wasm_bindgen(js_name = spaceOpenLinkCtx)]
-pub async fn space_open_link_ctx(input: JsValue) -> Result<SpaceLinkCtxHandle, WasmSpaceError> {
+pub async fn space_open_link_ctx(input: JsValue) -> Result<SpaceLinkCtxHandle, Error> {
let input: OpenSpaceLinkCtxJsInput = swb::from_value(input)?;
let inner = SpaceLinkCtx::open(OpenSpaceLinkCtxInput {
base_url: input.base_url,
@@ -720,14 +675,14 @@ pub struct SpaceLinkCtxHandle {
#[wasm_bindgen]
impl SpaceLinkCtxHandle {
#[wasm_bindgen(js_name = getProfile)]
- pub fn get_profile(&self) -> Result<JsValue, WasmSpaceError> {
+ pub fn get_profile(&self) -> Result<JsValue, Error> {
let mut profile = profile_to_js(self.inner.profile().clone())?;
profile.posts = Some(self.inner.posts());
swb::to_value(&profile).map_err(Into::into)
}
#[wasm_bindgen(js_name = listPosts)]
- pub async fn list_posts(&self) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_posts(&self) -> Result<JsValue, Error> {
let page = self.inner.list_posts().await?;
let mut items = Vec::with_capacity(page.items.len());
for post in page.items {
@@ -740,10 +695,9 @@ impl SpaceLinkCtxHandle {
Ok(post) => items.push(post),
Err(error) if error.is_content_error() => {
log::warn!(
- "Space post {} is unavailable: {}: {}",
+ "Space post {} is unavailable: {}",
fallback.post_id,
- error.code,
- error.message
+ error.message()
);
items.push(unavailable_post_to_js(fallback)?);
}
@@ -763,7 +717,7 @@ impl SpaceLinkCtxHandle {
endpoint: String,
p256dh: String,
auth: String,
- ) -> Result<String, WasmSpaceError> {
+ ) -> Result<String, Error> {
self.inner
.subscribe_web_push(endpoint, p256dh, auth)
.await
@@ -771,7 +725,7 @@ impl SpaceLinkCtxHandle {
}
#[wasm_bindgen(js_name = unsubscribeWebPush)]
- pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<(), WasmSpaceError> {
+ pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<(), Error> {
self.inner
.unsubscribe_web_push(endpoint)
.await
@@ -784,7 +738,7 @@ impl SpaceLinkCtxHandle {
encrypted_post_key: String,
key_version: i32,
object_key: String,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_post_asset(&encrypted_post_key, key_version, &object_key)
.await
@@ -796,7 +750,7 @@ impl SpaceLinkCtxHandle {
&self,
object_id: String,
key_version: i32,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_profile_asset("avatar", &object_id, key_version)
.await
@@ -808,7 +762,7 @@ impl SpaceLinkCtxHandle {
&self,
object_id: String,
key_version: i32,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_profile_asset("cover", &object_id, key_version)
.await
@@ -824,10 +778,7 @@ pub struct SpaceAccountCtxHandle {
#[wasm_bindgen]
impl SpaceAccountCtxHandle {
#[wasm_bindgen(js_name = getOrCreateSpaceLink)]
- pub async fn get_or_create_space_link(
- &self,
- space_id: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ pub async fn get_or_create_space_link(&self, space_id: String) -> Result<JsValue, Error> {
let value = self.inner.get_or_create_space_link(&space_id).await?;
swb::to_value(&CreatedSpaceLinkJs {
space_id: value.space_id,
@@ -838,7 +789,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = rotateSpaceLink)]
- pub async fn rotate_space_link(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn rotate_space_link(&self, space_id: String) -> Result<JsValue, Error> {
let value = self.inner.rotate_space_link(&space_id).await?;
swb::to_value(&CreatedSpaceLinkJs {
space_id: value.space_id,
@@ -854,7 +805,7 @@ impl SpaceAccountCtxHandle {
space_slug: String,
profile: String,
referred_by_space_id: Option<String>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(&created_space_to_js(
self.inner
.create_space_with_referrer(
@@ -868,7 +819,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listOwnedSpaces)]
- pub async fn list_owned_spaces(&self) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_owned_spaces(&self) -> Result<JsValue, Error> {
swb::to_value(&self.inner.list_owned_spaces().await?).map_err(Into::into)
}
@@ -877,7 +828,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
viewer_space_id: Option<String>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(&profile_to_js(
self.inner
.get_space_profile_for_display(&space_id, viewer_space_id.as_deref(), None)
@@ -891,7 +842,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
profile: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -907,13 +858,13 @@ impl SpaceAccountCtxHandle {
space_id: String,
profile: String,
avatar_bytes: Vec<u8>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let space_key = self
.inner
.resolve_owned_space_key(&space_id)
.await?
.ok_or_else(|| {
- ente_space::SpaceError::InvalidInput(format!(
+ ente_space::Error::InvalidInput(format!(
"space {space_id} is not owned by the account"
))
})?;
@@ -936,13 +887,13 @@ impl SpaceAccountCtxHandle {
space_id: String,
profile: String,
cover_bytes: Vec<u8>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let space_key = self
.inner
.resolve_owned_space_key(&space_id)
.await?
.ok_or_else(|| {
- ente_space::SpaceError::InvalidInput(format!(
+ ente_space::Error::InvalidInput(format!(
"space {space_id} is not owned by the account"
))
})?;
@@ -971,16 +922,13 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
space_slug: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(&self.inner.update_space_slug(&space_id, &space_slug).await?)
.map_err(Into::into)
}
#[wasm_bindgen(js_name = lookupSpaceBySlug)]
- pub async fn lookup_space_by_slug(
- &self,
- space_slug: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ pub async fn lookup_space_by_slug(&self, space_slug: String) -> Result<JsValue, Error> {
swb::to_value(&self.inner.lookup_space_by_slug(&space_slug).await?).map_err(Into::into)
}
@@ -989,7 +937,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
target_space_id: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -1004,7 +952,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
space_username: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -1020,7 +968,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
cursor: Option<String>,
limit: Option<i32>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let page = self.inner.list_feed(&space_id, cursor, limit).await?;
swb::to_value(
&account_post_page_to_js(
@@ -1051,7 +999,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = unreadStatus)]
- pub async fn unread_status(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn unread_status(&self, space_id: String) -> Result<JsValue, Error> {
swb::to_value(&self.inner.unread_status(&space_id).await?).map_err(Into::into)
}
@@ -1060,7 +1008,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
friend_space_id: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -1077,7 +1025,7 @@ impl SpaceAccountCtxHandle {
viewer_space_id: Option<String>,
cursor: Option<String>,
limit: Option<i32>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&account_post_page_to_js(
&self.inner,
@@ -1096,7 +1044,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
post_id: i64,
viewer_space_id: Option<String>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let post = self
.inner
.get_post(&space_id, post_id, viewer_space_id.as_deref())
@@ -1115,7 +1063,7 @@ impl SpaceAccountCtxHandle {
photo_bytes: Vec<u8>,
caption: Option<String>,
photo_options: JsValue,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let photo_options: PostPhotoAssetOptionsJsInput = swb::from_value(photo_options)?;
let post_key = self.inner.generate_post_key();
let object = self
@@ -1159,7 +1107,7 @@ impl SpaceAccountCtxHandle {
post_id: i64,
viewer_space_id: Option<String>,
object_key: String,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_post_asset(&space_id, post_id, viewer_space_id.as_deref(), &object_key)
.await
@@ -1174,7 +1122,7 @@ impl SpaceAccountCtxHandle {
key_version: i32,
viewer_space_id: Option<String>,
object_key: String,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_post_asset_with_key(
&space_id,
@@ -1194,7 +1142,7 @@ impl SpaceAccountCtxHandle {
viewer_space_id: Option<String>,
object_id: String,
key_version: i32,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_profile_asset(
&space_id,
@@ -1214,7 +1162,7 @@ impl SpaceAccountCtxHandle {
viewer_space_id: Option<String>,
object_id: String,
key_version: i32,
- ) -> Result<Vec<u8>, WasmSpaceError> {
+ ) -> Result<Vec<u8>, Error> {
self.inner
.download_profile_asset(
&space_id,
@@ -1233,7 +1181,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
post_id: i64,
like: bool,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(&self.inner.like_post(&space_id, post_id, like).await?).map_err(Into::into)
}
@@ -1243,7 +1191,7 @@ impl SpaceAccountCtxHandle {
sender_space_id: String,
space_id: String,
text: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let message = self
.inner
.send_message(&sender_space_id, &space_id, &text)
@@ -1262,7 +1210,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
message_id: String,
text: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let message = self
.inner
.reply_to_message(&sender_space_id, &space_id, &message_id, &text)
@@ -1281,7 +1229,7 @@ impl SpaceAccountCtxHandle {
post_space_id: String,
post_id: i64,
text: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let message = self
.inner
.reply_to_post(&sender_space_id, &post_space_id, post_id, &text)
@@ -1299,7 +1247,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
message_id: String,
like: bool,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -1310,11 +1258,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = deleteMessage)]
- pub async fn delete_message(
- &self,
- space_id: String,
- message_id: String,
- ) -> Result<(), WasmSpaceError> {
+ pub async fn delete_message(&self, space_id: String, message_id: String) -> Result<(), Error> {
self.inner
.delete_message(&space_id, &message_id)
.await
@@ -1322,7 +1266,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listConversations)]
- pub async fn list_conversations(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_conversations(&self, space_id: String) -> Result<JsValue, Error> {
let response = self.inner.list_conversations(&space_id).await?;
let mut friends = Vec::with_capacity(response.friends.len());
for friend in response.friends {
@@ -1380,7 +1324,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
cursor: Option<String>,
limit: Option<i32>,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
let page = self
.inner
.list_message_thread(&viewer_space_id, &space_id, cursor, limit)
@@ -1405,7 +1349,7 @@ impl SpaceAccountCtxHandle {
space_id: String,
post_id: i64,
caption: Option<String>,
- ) -> Result<(), WasmSpaceError> {
+ ) -> Result<(), Error> {
let post = self
.inner
.get_post(&space_id, post_id, Some(&space_id))
@@ -1426,7 +1370,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = deletePost)]
- pub async fn delete_post(&self, space_id: String, post_id: i64) -> Result<(), WasmSpaceError> {
+ pub async fn delete_post(&self, space_id: String, post_id: i64) -> Result<(), Error> {
self.inner
.delete_post(&space_id, post_id)
.await
@@ -1434,7 +1378,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listSpaceFriends)]
- pub async fn list_space_friends(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_space_friends(&self, space_id: String) -> Result<JsValue, Error> {
let friends = self.inner.list_space_friends(&space_id).await?;
let mut items = Vec::with_capacity(friends.len());
for friend in friends {
@@ -1448,7 +1392,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listFriendRequests)]
- pub async fn list_friend_requests(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_friend_requests(&self, space_id: String) -> Result<JsValue, Error> {
let requests = self.inner.list_friend_requests(&space_id).await?;
let mut items = Vec::with_capacity(requests.len());
for request in requests {
@@ -1462,10 +1406,7 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listSentFriendRequests)]
- pub async fn list_sent_friend_requests(
- &self,
- space_id: String,
- ) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_sent_friend_requests(&self, space_id: String) -> Result<JsValue, Error> {
let requests = self.inner.list_sent_friend_requests(&space_id).await?;
let mut items = Vec::with_capacity(requests.len());
for request in requests {
@@ -1483,7 +1424,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
request_id: i64,
- ) -> Result<JsValue, WasmSpaceError> {
+ ) -> Result<JsValue, Error> {
swb::to_value(
&self
.inner
@@ -1498,7 +1439,7 @@ impl SpaceAccountCtxHandle {
&self,
space_id: String,
request_id: i64,
- ) -> Result<(), WasmSpaceError> {
+ ) -> Result<(), Error> {
self.inner
.delete_friend_request(&space_id, request_id)
.await
@@ -1510,7 +1451,7 @@ impl SpaceAccountCtxHandle {
&self,
actor_space_id: String,
space_id: String,
- ) -> Result<(), WasmSpaceError> {
+ ) -> Result<(), Error> {
self.inner
.unfriend_by_space(&actor_space_id, &space_id)
.await
@@ -1518,12 +1459,12 @@ impl SpaceAccountCtxHandle {
}
#[wasm_bindgen(js_name = listFriendShares)]
- pub async fn list_friend_shares(&self, space_id: String) -> Result<JsValue, WasmSpaceError> {
+ pub async fn list_friend_shares(&self, space_id: String) -> Result<JsValue, Error> {
swb::to_value(&self.inner.list_friend_shares(&space_id).await?).map_err(Into::into)
}
#[wasm_bindgen(js_name = refreshFriendShares)]
- pub async fn refresh_friend_shares(&self, space_id: String) -> Result<usize, WasmSpaceError> {
+ pub async fn refresh_friend_shares(&self, space_id: String) -> Result<usize, Error> {
self.inner
.refresh_friend_shares(&space_id)
.await
@@ -1617,7 +1558,7 @@ mod tests {
let converted = match account_post_page_to_js(&ctx, page).await {
Ok(converted) => converted,
- Err(error) => panic!("{}", error.js_to_string()),
+ Err(error) => panic!("{error}"),
};
assert_eq!(converted.items.len(), 3);
@@ -1666,21 +1607,21 @@ mod tests {
message("message-1", &encrypted_message_key, &valid_cipher),
)
.await
- .unwrap_or_else(|error| panic!("{}", error.js_to_string()));
+ .unwrap_or_else(|error| panic!("{error}"));
let corrupt = resilient_account_message_response_to_js(
&ctx,
"space-1",
message("message-2", &encrypted_message_key, &corrupt_cipher),
)
.await
- .unwrap_or_else(|error| panic!("{}", error.js_to_string()));
+ .unwrap_or_else(|error| panic!("{error}"));
let last = resilient_account_message_response_to_js(
&ctx,
"space-1",
message("message-3", &encrypted_message_key, &valid_cipher),
)
.await
- .unwrap_or_else(|error| panic!("{}", error.js_to_string()));
+ .unwrap_or_else(|error| panic!("{error}"));
assert!(!first.is_unavailable);
assert!(corrupt.is_unavailable);
@@ -1703,14 +1644,14 @@ mod tests {
};
let activity = resilient_message_conversation_activity_to_js(&ctx, "space-1", activity)
.await
- .unwrap_or_else(|error| panic!("{}", error.js_to_string()));
+ .unwrap_or_else(|error| panic!("{error}"));
assert!(activity.is_unavailable);
}
#[test]
fn http_errors_are_not_content_errors() {
- let error = WasmSpaceError::from(ente_space::SpaceError::Http(http::Error::Http {
+ let error = Error::from(ente_space::Error::Http(ente_core::http::Error::Http {
status: 500,
path: "/space".into(),
}));
@@ -1730,7 +1671,7 @@ mod tests {
cover: None,
updated_at: None,
})
- .unwrap_or_else(|error| panic!("{}", error.js_to_string()));
+ .unwrap_or_else(|error| panic!("{error}"));
assert!(profile.profile.is_empty());
assert_eq!(profile.space_slug, "alice");
diff --git a/rust/crates/space/src/client/assets.rs b/rust/crates/space/src/client/assets.rs
index 86201319ed..efc27f9be4 100644
--- a/rust/crates/space/src/client/assets.rs
+++ b/rust/crates/space/src/client/assets.rs
@@ -1,10 +1,10 @@
use super::{
AccountSpaceCtx, PostPhotoAssetOptions, UPLOAD_PURPOSE_AVATAR, UPLOAD_PURPOSE_COVER,
encrypt_post_object_metadata, ensure_space_upload_size, ensure_supported_photo_bytes,
- ensure_supported_photo_media_type, profile_object_id_from_key,
+ ensure_supported_photo_media_type, map_account_error, profile_object_id_from_key,
};
use crate::crypto::{content_md5_base64, encrypt_asset_payload};
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::PostObjectMetadata;
use crate::transport::{
AssetDownloadResponse, PostObjectPayload, PresignUploadRequest, PresignUploadResponse,
@@ -58,7 +58,8 @@ impl AccountSpaceCtx {
.json(&request)
.send()
.await?
- .error_for_status()?
+ .error_for_status()
+ .map_err(map_account_error)?
.json()
.await?)
}
@@ -82,7 +83,8 @@ impl AccountSpaceCtx {
.json(&request)
.send()
.await?
- .error_for_status()?
+ .error_for_status()
+ .map_err(map_account_error)?
.json()
.await?)
}
@@ -187,9 +189,7 @@ impl AccountSpaceCtx {
.await?
}
_ => {
- return Err(SpaceError::InvalidInput(
- "invalid profile asset purpose".into(),
- ));
+ return Err(Error::InvalidInput("invalid profile asset purpose".into()));
}
};
self.upload_bytes(&presign, &encrypted).await?;
@@ -237,7 +237,7 @@ impl AccountSpaceCtx {
.resolve_space_key_for_version_for_viewer(space_id, viewer_space_id, Some(key_version))
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!(
+ Error::InvalidInput(format!(
"no space key available for {space_id} version {key_version}"
))
})?;
diff --git a/rust/crates/space/src/client/entity_keys.rs b/rust/crates/space/src/client/entity_keys.rs
index d54b86d235..aa06d0eca6 100644
--- a/rust/crates/space/src/client/entity_keys.rs
+++ b/rust/crates/space/src/client/entity_keys.rs
@@ -1,5 +1,5 @@
use super::AccountSpaceCtx;
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::transport::{CreateEntityKeyRequest, EntityKeyPayload, EntityKeyResponse};
use ente_core::b64;
@@ -38,7 +38,7 @@ impl AccountSpaceCtx {
.send()
.await?;
if response.status() == 409 {
- return Err(SpaceError::EntityKeyConflict);
+ return Err(Error::EntityKeyConflict);
}
response.error_for_status()?;
Ok(())
@@ -73,7 +73,7 @@ impl AccountSpaceCtx {
fn split_entity_key_payload(payload: &EntityKeyPayload) -> Result<(String, String)> {
let combined = b64::decode(&payload.encrypted_key)?;
if combined.len() <= SPACE_ENTITY_KEY_HEADER_BYTES {
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"entity key payload is missing header".into(),
));
}
diff --git a/rust/crates/space/src/client/friends.rs b/rust/crates/space/src/client/friends.rs
index 76695bed21..f7df056215 100644
--- a/rust/crates/space/src/client/friends.rs
+++ b/rust/crates/space/src/client/friends.rs
@@ -1,6 +1,6 @@
use super::AccountSpaceCtx;
use crate::crypto::seal_with_public_key;
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::transport::{
AddFriendPayload, ConfirmFriendRequestPayload, FriendRelationshipResponse,
FriendStatusResponse, FriendTargetPayload, RefreshFriendSharesRequest, ShareUpdatePayload,
@@ -16,14 +16,10 @@ impl AccountSpaceCtx {
target_public_key: &[u8],
) -> Result<FriendStatusResponse> {
if target_space_id.trim().is_empty() {
- return Err(SpaceError::InvalidInput(
- "target space id is required".into(),
- ));
+ return Err(Error::InvalidInput("target space id is required".into()));
}
if target_public_key.is_empty() {
- return Err(SpaceError::InvalidInput(
- "target public key is required".into(),
- ));
+ return Err(Error::InvalidInput("target public key is required".into()));
}
let (requester_space, requester_space_key) =
self.profile_space_access(requester_space_id).await?;
@@ -97,18 +93,16 @@ impl AccountSpaceCtx {
request_id: i64,
) -> Result<FriendStatusResponse> {
if request_id <= 0 {
- return Err(SpaceError::InvalidInput(
- "friend request id is required".into(),
- ));
+ return Err(Error::InvalidInput("friend request id is required".into()));
}
let request = self
.list_friend_requests(space_id)
.await?
.into_iter()
.find(|value| value.request_id == request_id)
- .ok_or_else(|| SpaceError::InvalidInput("friend request is not available".into()))?;
+ .ok_or_else(|| Error::InvalidInput("friend request is not available".into()))?;
if request.requester.public_key.trim().is_empty() {
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"requester public key is required".into(),
));
}
@@ -138,9 +132,7 @@ impl AccountSpaceCtx {
pub async fn delete_friend_request(&self, space_id: &str, request_id: i64) -> Result<()> {
if request_id <= 0 {
- return Err(SpaceError::InvalidInput(
- "friend request id is required".into(),
- ));
+ return Err(Error::InvalidInput("friend request id is required".into()));
}
let path = format!("/spaces/{space_id}/friends/requests/{request_id}");
self.api().delete(&path).send().await?.error_for_status()?;
@@ -214,7 +206,7 @@ impl AccountSpaceCtx {
.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let friends = self.list_space_friends(space_id).await?;
let mut updates = Vec::new();
diff --git a/rust/crates/space/src/client/keys.rs b/rust/crates/space/src/client/keys.rs
index 88fa223aad..839562a03e 100644
--- a/rust/crates/space/src/client/keys.rs
+++ b/rust/crates/space/src/client/keys.rs
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use super::{AccountSpaceCtx, build_space_key_history_map};
use crate::crypto::{encrypt_secretbox_payload, generate_key};
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::CreatedSpace;
use crate::transport::{RotateSpaceKeyRequest, SpaceKeyResponse, SpaceKeyVersionResponse};
use ente_core::b64;
@@ -45,7 +45,7 @@ impl AccountSpaceCtx {
let access = self
.resolve_space_access(space_id)
.await?
- .ok_or_else(|| SpaceError::InvalidInput(format!("no access to space {space_id}")))?;
+ .ok_or_else(|| Error::InvalidInput(format!("no access to space {space_id}")))?;
let versions = self.list_space_key_versions(space_id, None).await?;
build_space_key_history_map(access.key_version, &access.space_key, &versions)
}
@@ -62,7 +62,7 @@ impl AccountSpaceCtx {
}
None => self.resolve_space_access(space_id).await?,
}
- .ok_or_else(|| SpaceError::InvalidInput(format!("no access to space {space_id}")))?;
+ .ok_or_else(|| Error::InvalidInput(format!("no access to space {space_id}")))?;
let versions = self
.list_space_key_versions(space_id, viewer_space_id)
.await?;
@@ -78,7 +78,7 @@ impl AccountSpaceCtx {
.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let current_profile = if profile.is_none() {
Some(
@@ -93,7 +93,7 @@ impl AccountSpaceCtx {
None => current_profile
.as_ref()
.map(|value| value.profile.clone())
- .ok_or_else(|| SpaceError::InvalidInput("missing current profile".into()))?,
+ .ok_or_else(|| Error::InvalidInput("missing current profile".into()))?,
};
let next_space_key = generate_key();
let space_root_key = self.get_or_create_space_root_key().await?;
diff --git a/rust/crates/space/src/client/links.rs b/rust/crates/space/src/client/links.rs
index 8adf7f67d3..c1c5e70d5e 100644
--- a/rust/crates/space/src/client/links.rs
+++ b/rust/crates/space/src/client/links.rs
@@ -12,7 +12,7 @@ use super::{
};
use crate::{
crypto::{decrypt_asset_payload, decrypt_secretbox_payload, encrypt_secretbox_payload},
- error::{Result, SpaceError},
+ error::{Error, Result},
models::{CreatedSpaceLink, DecryptedPost, DecryptedSpaceProfile, OpenSpaceLinkCtxInput},
transport::{
AssetDownloadResponse, PostPage, PostResponse, SpaceKeyVersionResponse,
@@ -81,7 +81,7 @@ impl AccountSpaceCtx {
});
}
if status.link_id <= 0 {
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"active space link is missing its ID".into(),
));
}
@@ -118,7 +118,7 @@ impl AccountSpaceCtx {
.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let access_key = generate_access_key();
let salt = Salt::generate();
@@ -178,9 +178,8 @@ impl AccountSpaceCtx {
fn decrypt_link_access_key(&self, status: &SpaceLinkStatusResponse) -> Result<String> {
let encrypted = b64::decode(&status.encrypted_access_key)?;
let plaintext = decrypt_secretbox_payload(self.space_root_key(), &encrypted)?;
- let access_key = String::from_utf8(plaintext).map_err(|error| {
- SpaceError::InvalidInput(format!("invalid link access key: {error}"))
- })?;
+ let access_key = String::from_utf8(plaintext)
+ .map_err(|error| Error::InvalidInput(format!("invalid link access key: {error}")))?;
validate_access_key(&access_key)?;
Ok(access_key)
}
@@ -191,9 +190,7 @@ impl SpaceLinkCtx {
validate_access_key(&input.access_key)?;
let space_slug = input.space_slug.trim().to_lowercase();
if space_slug.is_empty() {
- return Err(SpaceError::InvalidInput(
- "space username is required".into(),
- ));
+ return Err(Error::InvalidInput("space username is required".into()));
}
let api = build_api(
&input.base_url,
@@ -254,7 +251,7 @@ impl SpaceLinkCtx {
*cache_lock(&self.key_history, "space link key history")? = snapshot.key_history;
}
if !self.has_keys_for_posts(&page)? {
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"space link changed while posts were being loaded".into(),
));
}
@@ -380,7 +377,7 @@ impl SpaceLinkCtx {
cache_lock(&self.key_history, "space link key history")?
.get(&key_version)
.cloned()
- .ok_or_else(|| SpaceError::InvalidInput(format!("missing space key for {subject}")))
+ .ok_or_else(|| Error::InvalidInput(format!("missing space key for {subject}")))
}
}
@@ -392,7 +389,7 @@ async fn fetch_link_snapshot(
) -> Result<SpaceLinkSnapshot> {
for _ in 0..2 {
let fetch_profile = async {
- Ok::<SpaceLinkProfileResponse, SpaceError>(
+ Ok::<SpaceLinkProfileResponse, Error>(
api.get(&format!("{prefix}/profile"))
.header(AUTH_HEADER, auth_key)
.send()
@@ -403,7 +400,7 @@ async fn fetch_link_snapshot(
)
};
let fetch_versions = async {
- Ok::<Vec<SpaceKeyVersionResponse>, SpaceError>(
+ Ok::<Vec<SpaceKeyVersionResponse>, Error>(
api.get(&format!("{prefix}/versions"))
.header(AUTH_HEADER, auth_key)
.send()
@@ -440,7 +437,7 @@ async fn fetch_link_snapshot(
key_history,
});
}
- Err(SpaceError::InvalidInput(
+ Err(Error::InvalidInput(
"space link changed while it was being opened".into(),
))
}
@@ -451,7 +448,7 @@ fn validate_access_key(access_key: &str) -> Result<()> {
{
Ok(())
} else {
- Err(SpaceError::InvalidInput(
+ Err(Error::InvalidInput(
"space link access key must be 12 alphanumeric characters".into(),
))
}
@@ -486,7 +483,7 @@ fn derive_link_keys(
if mem_limit != argon::Params::INTERACTIVE.mem_limit
|| ops_limit != argon::Params::INTERACTIVE.ops_limit
{
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"unsupported space link KDF parameters".into(),
));
}
diff --git a/rust/crates/space/src/client/media.rs b/rust/crates/space/src/client/media.rs
index fc2f00e177..138930a941 100644
--- a/rust/crates/space/src/client/media.rs
+++ b/rust/crates/space/src/client/media.rs
@@ -1,5 +1,5 @@
use super::ONLY_PHOTOS_UPLOAD_MESSAGE;
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
pub(crate) fn ensure_supported_photo_media_type(
media_type: Option<&str>,
@@ -19,7 +19,7 @@ pub(crate) fn ensure_supported_photo_media_type(
}));
}
- Err(SpaceError::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()))
+ Err(Error::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()))
}
pub(crate) fn ensure_supported_photo_bytes(bytes: &[u8]) -> Result<&'static str> {
@@ -27,7 +27,7 @@ pub(crate) fn ensure_supported_photo_bytes(bytes: &[u8]) -> Result<&'static str>
return Ok(media_type);
}
- Err(SpaceError::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()))
+ Err(Error::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()))
}
pub(crate) fn supported_photo_media_type_for_bytes(bytes: &[u8]) -> Option<&'static str> {
diff --git a/rust/crates/space/src/client/messages.rs b/rust/crates/space/src/client/messages.rs
index f711a12421..7424fdc10f 100644
--- a/rust/crates/space/src/client/messages.rs
+++ b/rust/crates/space/src/client/messages.rs
@@ -5,7 +5,7 @@ use crate::crypto::{
decrypt_secretbox_payload, encrypt_secretbox_payload, generate_key, open_with_keypair,
seal_with_public_key,
};
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::{DecryptedMessage, MessagePayload};
use crate::transport::{
ConversationsResponse, CreateMessageRequest, LikeMessageResponse, MessagePage, MessageResponse,
@@ -90,7 +90,7 @@ impl AccountSpaceCtx {
) -> Result<MessageResponse> {
let reply_message_id = message_id.trim();
if reply_message_id.is_empty() {
- return Err(SpaceError::InvalidInput("message id is required".into()));
+ return Err(Error::InvalidInput("message id is required".into()));
}
let friend = self
.friend_actor_for_space(sender_space_id, space_id)
@@ -135,12 +135,10 @@ impl AccountSpaceCtx {
.await?
.is_some()
{
- return Err(SpaceError::InvalidInput(
- "cannot reply to your own post".into(),
- ));
+ return Err(Error::InvalidInput("cannot reply to your own post".into()));
}
if post.author.public_key.trim().is_empty() {
- return Err(SpaceError::InvalidInput(
+ return Err(Error::InvalidInput(
"post author public key is missing".into(),
));
}
@@ -170,7 +168,7 @@ impl AccountSpaceCtx {
message: &MessageResponse,
) -> Result<DecryptedMessage> {
if message.is_deleted {
- return Err(SpaceError::InvalidInput("message is deleted".into()));
+ return Err(Error::InvalidInput("message is deleted".into()));
}
let identity = self.space_identity_for(space_id).await?;
let sealed_key = b64::decode(&message.encrypted_message_key)?;
@@ -179,7 +177,7 @@ impl AccountSpaceCtx {
let packed_message = b64::decode(&message.message_cipher)?;
let plaintext = decrypt_secretbox_payload(&message_key, &packed_message)?;
let payload: MessagePayload = serde_json::from_slice(&plaintext)
- .map_err(|err| SpaceError::InvalidInput(format!("invalid message payload: {err}")))?;
+ .map_err(|err| Error::InvalidInput(format!("invalid message payload: {err}")))?;
Ok(DecryptedMessage {
message_key,
payload,
@@ -194,7 +192,7 @@ impl AccountSpaceCtx {
) -> Result<LikeMessageResponse> {
let message_id = message_id.trim();
if message_id.is_empty() {
- return Err(SpaceError::InvalidInput("message id is required".into()));
+ return Err(Error::InvalidInput("message id is required".into()));
}
let path = format!("/spaces/{space_id}/messages/{message_id}/like");
if like {
@@ -222,7 +220,7 @@ impl AccountSpaceCtx {
pub async fn delete_message(&self, space_id: &str, message_id: &str) -> Result<()> {
let message_id = message_id.trim();
if message_id.is_empty() {
- return Err(SpaceError::InvalidInput("message id is required".into()));
+ return Err(Error::InvalidInput("message id is required".into()));
}
let path = format!("/spaces/{space_id}/messages/{message_id}");
self.api().delete(&path).send().await?.error_for_status()?;
@@ -239,7 +237,7 @@ impl AccountSpaceCtx {
.into_iter()
.map(|value| value.friend)
.find(|friend| friend.space_id == space_id)
- .ok_or_else(|| SpaceError::InvalidInput(format!("space {space_id} is not a friend")))
+ .ok_or_else(|| Error::InvalidInput(format!("space {space_id} is not a friend")))
}
async fn message_request_for_payload(
@@ -253,7 +251,7 @@ impl AccountSpaceCtx {
let recipient_public_key = b64::decode(recipient_public_key)?;
let message_key = generate_key();
let plaintext = serde_json::to_vec(payload)
- .map_err(|err| SpaceError::InvalidInput(format!("invalid message payload: {err}")))?;
+ .map_err(|err| Error::InvalidInput(format!("invalid message payload: {err}")))?;
validate_message_payload(payload, plaintext.len())?;
let sender_key = seal_with_public_key(&message_key, &identity.public_key)?;
let recipient_key = seal_with_public_key(&message_key, &recipient_public_key)?;
diff --git a/rust/crates/space/src/client/mod.rs b/rust/crates/space/src/client/mod.rs
index 1d8fb668a1..4da545f011 100644
--- a/rust/crates/space/src/client/mod.rs
+++ b/rust/crates/space/src/client/mod.rs
@@ -26,7 +26,7 @@ use crate::crypto::{
ASSET_PAYLOAD_OVERHEAD_BYTES, SECRETBOX_PAYLOAD_OVERHEAD_BYTES, decrypt_secretbox_payload,
encrypt_secretbox_payload, generate_key, generate_keypair, open_with_keypair,
};
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::{
CreatedSpace, DecryptedFriendShare, DecryptedSpaceProfile, FeedItem, MessagePayload,
OpenAccountSpaceCtxInput, PostObjectMetadata,
@@ -38,7 +38,7 @@ use crate::transport::{
use ente_core::{
b64,
crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
+ http::{self, Api, ApiConfig, Auth, Http},
};
const UPLOAD_PURPOSE_AVATAR: &str = "avatar";
const UPLOAD_PURPOSE_COVER: &str = "cover";
@@ -74,7 +74,7 @@ fn profile_object_id_from_key(object_key: &str) -> Result<String> {
.next()
.filter(|value| !value.trim().is_empty() && !value.contains('/'))
.map(ToOwned::to_owned)
- .ok_or_else(|| SpaceError::InvalidInput("invalid profile asset object key".into()))
+ .ok_or_else(|| Error::InvalidInput("invalid profile asset object key".into()))
}
#[derive(Clone)]
@@ -159,7 +159,8 @@ impl AccountSpaceCtx {
.get("/account/space")
.send()
.await?
- .error_for_status()?
+ .error_for_status()
+ .map_err(map_session_error)?
.json()
.await?;
*cache_lock(&self.owned_spaces_cache, "owned spaces")? = Some(spaces.clone());
@@ -180,7 +181,7 @@ impl AccountSpaceCtx {
pub(crate) fn decrypt_space_identity(&self, space: &SpaceKeyResponse) -> Result<SpaceIdentity> {
if space.public_key.trim().is_empty() || space.encrypted_secret_key.trim().is_empty() {
- return Err(SpaceError::MissingSecretKey);
+ return Err(Error::MissingSecretKey);
}
let public_key = b64::decode(&space.public_key)?;
let encrypted_secret_key = b64::decode(&space.encrypted_secret_key)?;
@@ -194,7 +195,7 @@ impl AccountSpaceCtx {
pub(crate) async fn space_identity_for(&self, space_id: &str) -> Result<SpaceIdentity> {
let space_id = space_id.trim();
if space_id.is_empty() {
- return Err(SpaceError::InvalidInput("space id is required".into()));
+ return Err(Error::InvalidInput("space id is required".into()));
}
if let Some(value) = cache_lock(&self.space_identity_cache, "space identity")?
.get(space_id)
@@ -208,7 +209,7 @@ impl AccountSpaceCtx {
.into_iter()
.find(|value| value.space_id == space_id)
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let identity = self.decrypt_space_identity(&space)?;
cache_lock(&self.space_identity_cache, "space identity")?
@@ -224,7 +225,7 @@ impl AccountSpaceCtx {
let identity = self.space_identity_for(space_id).await?;
let ciphertext = b64::decode(&share.friend_sealed_space_key)?;
if ciphertext.is_empty() {
- return Err(SpaceError::MissingFriendSealedSpaceKey);
+ return Err(Error::MissingFriendSealedSpaceKey);
}
let space_key = open_with_keypair(&ciphertext, &identity.public_key, &identity.secret_key)?;
Ok(DecryptedFriendShare {
@@ -243,10 +244,10 @@ impl AccountSpaceCtx {
let space_root_key = self
.get_space_root_key()
.await?
- .ok_or_else(|| SpaceError::InvalidInput("space root key is missing".into()))?;
+ .ok_or_else(|| Error::InvalidInput("space root key is missing".into()))?;
let space_id = space_id.trim();
if space_id.is_empty() {
- return Err(SpaceError::InvalidInput("space id is required".into()));
+ return Err(Error::InvalidInput("space id is required".into()));
}
let space = self
.list_owned_spaces()
@@ -254,7 +255,7 @@ impl AccountSpaceCtx {
.into_iter()
.find(|value| value.space_id == space_id)
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let packed = b64::decode(&space.root_wrapped_space_key)?;
let space_key = decrypt_secretbox_payload(&space_root_key, &packed)?;
@@ -334,7 +335,8 @@ impl AccountSpaceCtx {
.send()
.await?
.error_for_code()
- .await?
+ .await
+ .map_err(map_create_space_error)?
.json::<SpaceKeyResponse>()
.await?;
self.cache_created_owned_space(SpaceKeyResponse {
@@ -391,7 +393,8 @@ impl AccountSpaceCtx {
.send()
.await?
.error_for_code()
- .await?
+ .await
+ .map_err(map_space_slug_error)?
.json()
.await?;
self.clear_owned_space_cache()?;
@@ -553,7 +556,7 @@ impl AccountSpaceCtx {
self.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})
}
@@ -572,7 +575,7 @@ impl AccountSpaceCtx {
) -> Result<Vec<DecryptedFriendShare>> {
let space_id = space_id.trim();
if space_id.is_empty() {
- return Err(SpaceError::InvalidInput("space id is required".into()));
+ return Err(Error::InvalidInput("space id is required".into()));
}
if let Some(value) = cache_lock(&self.friend_shares_cache, "friend shares")?
.get(space_id)
@@ -647,7 +650,7 @@ impl AccountSpaceCtx {
fn ensure_space_upload_size(purpose: &str, encrypted_size: usize, max_bytes: usize) -> Result<()> {
if encrypted_size == 0 || encrypted_size > max_bytes {
- return Err(SpaceError::InvalidInput(format!(
+ return Err(Error::InvalidInput(format!(
"{purpose} upload size must be between 1 and {max_bytes} bytes"
)));
}
@@ -656,7 +659,7 @@ fn ensure_space_upload_size(purpose: &str, encrypted_size: usize, max_bytes: usi
fn encrypt_post_object_metadata(post_key: &[u8], metadata: &PostObjectMetadata) -> Result<String> {
let plaintext = serde_json::to_vec(metadata)
- .map_err(|err| SpaceError::InvalidInput(format!("invalid post object metadata: {err}")))?;
+ .map_err(|err| Error::InvalidInput(format!("invalid post object metadata: {err}")))?;
Ok(b64::encode(&encrypt_secretbox_payload(
post_key, &plaintext,
)?))
@@ -672,15 +675,15 @@ pub fn decrypt_post_object_metadata(
let plaintext = decrypt_secretbox_payload(post_key, &b64::decode(cipher)?)?;
serde_json::from_slice(&plaintext)
.map(Some)
- .map_err(|err| SpaceError::InvalidInput(format!("invalid post object metadata: {err}")))
+ .map_err(|err| Error::InvalidInput(format!("invalid post object metadata: {err}")))
}
fn ensure_post_objects_are_photos(objects: &[PostObjectPayload], post_key: &[u8]) -> Result<()> {
for object in objects {
let metadata = decrypt_post_object_metadata(post_key, object)?
- .ok_or_else(|| SpaceError::InvalidInput("post object metadata is required".into()))?;
+ .ok_or_else(|| Error::InvalidInput("post object metadata is required".into()))?;
if ensure_supported_photo_media_type(metadata.media_type.as_deref())?.is_none() {
- return Err(SpaceError::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()));
+ return Err(Error::InvalidInput(ONLY_PHOTOS_UPLOAD_MESSAGE.into()));
}
}
Ok(())
@@ -688,17 +691,17 @@ fn ensure_post_objects_are_photos(objects: &[PostObjectPayload], post_key: &[u8]
fn validate_message_payload(payload: &MessagePayload, plaintext_len: usize) -> Result<()> {
if payload.text.chars().count() > MAX_SPACE_MESSAGE_TEXT_CHARS {
- return Err(SpaceError::InvalidInput(format!(
+ return Err(Error::InvalidInput(format!(
"message text must be {MAX_SPACE_MESSAGE_TEXT_CHARS} characters or fewer"
)));
}
if payload.text.len() > MAX_SPACE_MESSAGE_TEXT_BYTES {
- return Err(SpaceError::InvalidInput(format!(
+ return Err(Error::InvalidInput(format!(
"message text must be {MAX_SPACE_MESSAGE_TEXT_BYTES} bytes or fewer"
)));
}
if plaintext_len > MAX_SPACE_MESSAGE_PAYLOAD_BYTES {
- return Err(SpaceError::InvalidInput(format!(
+ return Err(Error::InvalidInput(format!(
"message payload must be {MAX_SPACE_MESSAGE_PAYLOAD_BYTES} bytes or fewer"
)));
}
@@ -743,7 +746,36 @@ pub(super) fn build_api(
fn cache_lock<'a, T>(cache: &'a Mutex<T>, name: &str) -> Result<MutexGuard<'a, T>> {
cache
.lock()
- .map_err(|_| SpaceError::InvalidInput(format!("{name} cache poisoned")))
+ .map_err(|_| Error::InvalidInput(format!("{name} cache poisoned")))
+}
+
+fn map_account_error(error: http::Error) -> Error {
+ match error.status_code() {
+ Some(403) => Error::PermissionDenied,
+ _ => map_session_error(error),
+ }
+}
+
+fn map_session_error(error: http::Error) -> Error {
+ match error.status_code() {
+ Some(401) => Error::SessionUnauthorized,
+ _ => error.into(),
+ }
+}
+
+fn map_create_space_error(error: http::Error) -> Error {
+ match &error {
+ http::Error::Api { code, .. } if code == "CONFLICT" => Error::SpaceLimitReached,
+ _ => map_space_slug_error(error),
+ }
+}
+
+fn map_space_slug_error(error: http::Error) -> Error {
+ match &error {
+ http::Error::Api { code, .. } if code == "ALREADY_EXISTS" => Error::SpaceSlugAlreadyExists,
+ http::Error::Api { code, .. } if code == "BAD_REQUEST" => Error::InvalidSpaceSlug,
+ _ => map_account_error(error),
+ }
}
pub(super) fn decrypt_space_profile(
diff --git a/rust/crates/space/src/client/posts.rs b/rust/crates/space/src/client/posts.rs
index e36b4acfd3..230ad9fe81 100644
--- a/rust/crates/space/src/client/posts.rs
+++ b/rust/crates/space/src/client/posts.rs
@@ -3,13 +3,13 @@ use super::{
post_response_from_feed_item,
};
use crate::crypto::{decrypt_secretbox_payload, encrypt_secretbox_payload, generate_key};
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::{DecryptedPost, FeedItem, FeedPage, HydratedKeys, PostObjectMetadata};
use crate::transport::{
CreatePostRequest, CreatePostResponse, LikePostResponse, PostObjectPayload, PostPage,
PostResponse, SpaceActorResponse, SpaceUnreadStatusResponse, UpdatePostCaptionRequest,
};
-use ente_core::b64;
+use ente_core::{b64, http};
impl AccountSpaceCtx {
pub fn generate_post_key(&self) -> Vec<u8> {
@@ -29,7 +29,7 @@ impl AccountSpaceCtx {
.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let caption_cipher = match caption_plaintext {
Some(value) => Some(b64::encode(&encrypt_secretbox_payload(
@@ -54,7 +54,12 @@ impl AccountSpaceCtx {
.json(&request)
.send()
.await?
- .error_for_status()?
+ .error_for_code()
+ .await
+ .map_err(|error| match &error {
+ http::Error::Api { code, .. } if code == "CONFLICT" => Error::PostLimitReached,
+ _ => error.into(),
+ })?
.json::<CreatePostResponse>()
.await?;
Ok((response.post_id, post_key_bytes))
@@ -141,12 +146,10 @@ impl AccountSpaceCtx {
let space_id = space_id.into();
let friend_space_id = friend_space_id.into();
if space_id.trim().is_empty() {
- return Err(SpaceError::InvalidInput("space id is required".into()));
+ return Err(Error::InvalidInput("space id is required".into()));
}
if friend_space_id.trim().is_empty() {
- return Err(SpaceError::InvalidInput(
- "friend space id is required".into(),
- ));
+ return Err(Error::InvalidInput("friend space id is required".into()));
}
let path = format!("/spaces/{space_id}/friends/{friend_space_id}/read");
Ok(self
@@ -266,7 +269,7 @@ impl AccountSpaceCtx {
let space_key = self
.resolve_space_key_for_version_for_viewer(space_id, viewer_space_id, Some(key_version))
.await?
- .ok_or_else(|| SpaceError::InvalidInput("missing space key for post".into()))?;
+ .ok_or_else(|| Error::InvalidInput("missing space key for post".into()))?;
let packed = b64::decode(encrypted_post_key)?;
decrypt_secretbox_payload(&space_key, &packed)
}
@@ -315,10 +318,7 @@ impl AccountSpaceCtx {
)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!(
- "no space key available for post {}",
- post.post_id
- ))
+ Error::InvalidInput(format!("no space key available for post {}", post.post_id))
})?;
self.decrypt_post(&space_key, post)
}
diff --git a/rust/crates/space/src/client/profiles.rs b/rust/crates/space/src/client/profiles.rs
index 9ae3938ad3..42b0761fb0 100644
--- a/rust/crates/space/src/client/profiles.rs
+++ b/rust/crates/space/src/client/profiles.rs
@@ -1,6 +1,9 @@
-use super::{AccountSpaceCtx, decrypt_space_profile, space_profile_without_payload};
+use super::{
+ AccountSpaceCtx, decrypt_space_profile, map_account_error, map_session_error,
+ space_profile_without_payload,
+};
use crate::crypto::encrypt_secretbox_payload;
-use crate::error::{Result, SpaceError};
+use crate::error::{Error, Result};
use crate::models::DecryptedSpaceProfile;
use crate::transport::{
ProfileAvatarPayload, ProfileCoverPayload, SpaceProfileResponse, UpdateSpaceProfileRequest,
@@ -29,7 +32,8 @@ impl AccountSpaceCtx {
.query(&query)
.send()
.await?
- .error_for_status()?
+ .error_for_status()
+ .map_err(map_session_error)?
.json()
.await?)
}
@@ -51,7 +55,7 @@ impl AccountSpaceCtx {
)
.await?;
let space_key = space_key.ok_or_else(|| {
- SpaceError::InvalidInput(format!(
+ Error::InvalidInput(format!(
"no key available for space {space_id} version {}",
profile.version
))
@@ -76,7 +80,7 @@ impl AccountSpaceCtx {
)
.await?;
let space_key = space_key.ok_or_else(|| {
- SpaceError::InvalidInput(format!(
+ Error::InvalidInput(format!(
"no key available for space {space_id} version {}",
profile.version
))
@@ -115,7 +119,7 @@ impl AccountSpaceCtx {
.resolve_owned_space_access(space_id)
.await?
.ok_or_else(|| {
- SpaceError::InvalidInput(format!("space {space_id} is not owned by the account"))
+ Error::InvalidInput(format!("space {space_id} is not owned by the account"))
})?;
let request = UpdateSpaceProfileRequest {
key_version: space_key.key_version,
@@ -135,7 +139,8 @@ impl AccountSpaceCtx {
.json(&request)
.send()
.await?
- .error_for_status()?
+ .error_for_status()
+ .map_err(map_account_error)?
.json()
.await?;
self.update_cached_owned_space_profile(space_id, request.encrypted_profile)?;
diff --git a/rust/crates/space/src/client/tests.rs b/rust/crates/space/src/client/tests.rs
index 35a0447b7f..27a699a419 100644
--- a/rust/crates/space/src/client/tests.rs
+++ b/rust/crates/space/src/client/tests.rs
@@ -637,7 +637,7 @@ async fn create_space_with_key_sends_encrypted_space_and_profile_payloads() {
}
#[tokio::test]
-async fn create_space_preserves_api_error_code() {
+async fn create_space_maps_owner_limit_error() {
let mut server = Server::new_async().await;
let ctx = test_account_ctx(&server.url());
let create_space = server
@@ -655,19 +655,12 @@ async fn create_space_preserves_api_error_code() {
Err(error) => error,
};
- assert!(matches!(
- error,
- SpaceError::Http(ente_core::http::Error::Api {
- status: 409,
- ref code,
- ..
- }) if code == "CONFLICT"
- ));
+ assert!(matches!(error, Error::SpaceLimitReached));
create_space.assert_async().await;
}
#[tokio::test]
-async fn update_space_slug_preserves_api_error_code() {
+async fn update_space_slug_maps_duplicate_error() {
let mut server = Server::new_async().await;
let ctx = test_account_ctx(&server.url());
let update_slug = server
@@ -682,14 +675,7 @@ async fn update_space_slug_preserves_api_error_code() {
.await
.expect_err("slug update should fail");
- assert!(matches!(
- error,
- SpaceError::Http(ente_core::http::Error::Api {
- status: 409,
- ref code,
- ..
- }) if code == "ALREADY_EXISTS"
- ));
+ assert!(matches!(error, Error::SpaceSlugAlreadyExists));
update_slug.assert_async().await;
}
@@ -942,6 +928,41 @@ async fn create_post_includes_space_key_version() {
create.assert_async().await;
}
+#[tokio::test]
+async fn create_post_maps_limit_error() {
+ let mut server = Server::new_async().await;
+ let space_root_key = generate_key();
+ let space_key = generate_key();
+ let ctx = test_account_ctx_with_space_root_key(&server.url(), space_root_key.clone());
+ let spaces = server
+ .mock("GET", "/account/space")
+ .with_status(200)
+ .with_body(owned_space_response(
+ &space_root_key,
+ &space_key,
+ "space_owner_main",
+ "owner-main",
+ 3,
+ ))
+ .create_async()
+ .await;
+ let create = server
+ .mock("POST", "/spaces/space_owner_main/posts")
+ .with_status(409)
+ .with_body(json!({ "code": "CONFLICT" }).to_string())
+ .create_async()
+ .await;
+
+ let error = ctx
+ .create_post("space_owner_main", &[], None, None)
+ .await
+ .expect_err("post creation should fail");
+
+ assert!(matches!(error, Error::PostLimitReached));
+ spaces.assert_async().await;
+ create.assert_async().await;
+}
+
#[tokio::test]
async fn create_post_rejects_video_object_media_type() {
let server = Server::new_async().await;
@@ -1172,7 +1193,7 @@ async fn get_space_profile_decrypted_returns_decryption_error() {
.await
.expect_err("profile decryption should fail");
- assert!(matches!(error, SpaceError::Crypto(_)));
+ assert!(matches!(error, Error::Crypto(_)));
profile.assert_async().await;
spaces.assert_async().await;
}
diff --git a/rust/crates/space/src/error.rs b/rust/crates/space/src/error.rs
index db92d993f9..8b19ff39f9 100644
--- a/rust/crates/space/src/error.rs
+++ b/rust/crates/space/src/error.rs
@@ -2,7 +2,7 @@ use ente_core::{b64, crypto, http};
use thiserror::Error;
#[derive(Debug, Error)]
-pub enum SpaceError {
+pub enum Error {
#[error(transparent)]
Http(#[from] http::Error),
@@ -23,9 +23,27 @@ pub enum SpaceError {
#[error("entity key conflict")]
EntityKeyConflict,
+
+ #[error("space limit reached")]
+ SpaceLimitReached,
+
+ #[error("space slug already exists")]
+ SpaceSlugAlreadyExists,
+
+ #[error("invalid space slug")]
+ InvalidSpaceSlug,
+
+ #[error("space post limit reached")]
+ PostLimitReached,
+
+ #[error("space session is unauthorized")]
+ SessionUnauthorized,
+
+ #[error("permission denied")]
+ PermissionDenied,
}
-impl SpaceError {
+impl Error {
pub fn is_content_error(&self) -> bool {
matches!(
self,
@@ -37,4 +55,4 @@ impl SpaceError {
}
}
-pub type Result<T> = std::result::Result<T, SpaceError>;
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/rust/crates/space/src/lib.rs b/rust/crates/space/src/lib.rs
index f2a897bf52..dd4479235b 100644
--- a/rust/crates/space/src/lib.rs
+++ b/rust/crates/space/src/lib.rs
@@ -12,7 +12,7 @@ pub use client::{
MAX_SPACE_POST_UPLOAD_BYTES, PostPhotoAssetOptions, SpaceLinkCtx,
};
pub use crypto::{decrypt_space_root_entity_key, encrypt_space_root_entity_key};
-pub use error::{Result, SpaceError};
+pub use error::{Error, Result};
pub use models::{
CreatedSpace, CreatedSpaceLink, DecryptedFriendShare, DecryptedMessage, DecryptedPost,
DecryptedSpaceProfile, FeedItem, FeedPage, HydratedKeys, MessagePayload,
diff --git a/rust/crates/space/tests/support/space.rs b/rust/crates/space/tests/support/space.rs
index c6910a0f81..9ff5fed369 100644
--- a/rust/crates/space/tests/support/space.rs
+++ b/rust/crates/space/tests/support/space.rs
@@ -1,7 +1,7 @@
use ente_core::b64;
use ente_core::crypto::{Key, Nonce, secretbox};
use ente_core::http;
-use ente_space::{AccountSpaceCtx, OpenAccountSpaceCtxInput, SpaceError};
+use ente_space::{AccountSpaceCtx, Error, OpenAccountSpaceCtxInput};
use serde::Deserialize;
use super::{CLIENT_PACKAGE, USER_AGENT, auth::TestAccount};
@@ -90,17 +90,17 @@ pub fn profile_payload(display_name: &str, bio: &str) -> Vec<u8> {
format!(r#"{{"displayName":"{display_name}","bio":"{bio}"}}"#).into_bytes()
}
-pub fn assert_http_status<T>(result: Result<T, SpaceError>, expected_status: u16) {
+pub fn assert_http_status<T>(result: Result<T, Error>, expected_status: u16) {
match result {
- Err(SpaceError::Http(http::Error::Http { status, .. })) if status == expected_status => {}
+ Err(Error::Http(http::Error::Http { status, .. })) if status == expected_status => {}
Err(error) => panic!("expected HTTP {expected_status}, got {error:?}"),
Ok(_) => panic!("expected HTTP {expected_status}, got success"),
}
}
-pub fn assert_invalid_input_contains<T>(result: Result<T, SpaceError>, expected: &str) {
+pub fn assert_invalid_input_contains<T>(result: Result<T, Error>, expected: &str) {
match result {
- Err(SpaceError::InvalidInput(message)) if message.contains(expected) => {}
+ Err(Error::InvalidInput(message)) if message.contains(expected) => {}
Err(error) => panic!("expected invalid input containing {expected:?}, got {error:?}"),
Ok(_) => panic!("expected invalid input containing {expected:?}, got success"),
}
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index c063be24d7..dd4e582f68 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -366,16 +366,8 @@ interface SpaceConversationsContext {
listConversations: (spaceId: string) => Promise<SpaceConversationsResponse>;
}
-export const isSpaceContentError = (error: unknown) => {
- if (!error || typeof error != "object" || !("code" in error)) return false;
- const code = error.code;
- return (
- code == "crypto" ||
- code == "base64_decode" ||
- code == "invalid_input" ||
- code == "missing_friend_sealed_space_key"
- );
-};
+export const isSpaceContentError = (error: unknown) =>
+ error instanceof Error && error.name == "content_unavailable";
const timestampMsFromSpaceDate = (value: string) => {
const parsed = Date.parse(value);
@@ -1341,12 +1333,8 @@ export const createCurrentPhotoPost = async ({
}
};
-export const isSpacePostLimitReachedError = (error: unknown) => {
- if (!error || typeof error != "object" || !("status" in error)) {
- return false;
- }
- return (error as { status?: unknown }).status == 409;
-};
+export const isSpacePostLimitReachedError = (error: unknown) =>
+ error instanceof Error && error.name == "post_limit_reached";
const normalizedImageDimension = (dimension: number | undefined) =>
typeof dimension == "number" && Number.isFinite(dimension) && dimension > 0
diff --git a/web/apps/space/src/services/spaceProfile.ts b/web/apps/space/src/services/spaceProfile.ts
index ec68697b05..b8552710b3 100644
--- a/web/apps/space/src/services/spaceProfile.ts
+++ b/web/apps/space/src/services/spaceProfile.ts
@@ -93,24 +93,8 @@ const spaceProfilePayloadFor = (profile: SetupProfileInput) =>
username: normalizeSpaceUsername(profile.username),
});
-const spaceHTTPStatus = (error: unknown) => {
- if (!error || typeof error != "object" || !("status" in error)) {
- return undefined;
- }
- const { status } = error as { status?: unknown };
- return typeof status == "number" ? status : undefined;
-};
-
-const spaceHTTPCode = (error: unknown) => {
- if (!error || typeof error != "object" || !("code" in error)) {
- return undefined;
- }
- const { code } = error as { code?: unknown };
- return typeof code == "string" ? code : undefined;
-};
-
export const isSpaceSessionUnauthorized = (error: unknown) =>
- spaceHTTPStatus(error) == 401;
+ error instanceof Error && error.name == "session_unauthorized";
const defaultOwnedSpace = (spaces: OwnedSpace[]) => spaces[0];
@@ -622,44 +606,28 @@ export const saveSpaceProfile = async (
currentSpaceProfile = undefined;
pendingCurrentSpaceProfile = undefined;
return savedProfile;
- } catch (error) {
- if (spaceHTTPCode(error) == "ALREADY_EXISTS") {
- throw new Error("This username is already taken.", {
- cause: error,
- });
- }
- if (spaceHTTPCode(error) == "CONFLICT") {
- throw new Error(
- "A Space already exists for this account. Please refresh and try again.",
- { cause: error },
- );
- }
- throw error;
} finally {
releaseCurrentSpaceContext(ctx);
}
};
export const spaceProfileErrorMessage = (error: unknown) => {
- const code = spaceHTTPCode(error);
- if (code == "ALREADY_EXISTS") return "This username is already taken.";
- if (code == "CONFLICT") {
- return "A Space already exists for this account. Please refresh and try again.";
+ if (!(error instanceof Error)) {
+ return "Couldn't save your profile. Please try again.";
}
- const status = spaceHTTPStatus(error);
- if (status == 409) {
- return "This profile conflicts with the current account state. Please refresh and try again.";
+ if (error.name == "space_slug_already_exists")
+ return "This username is already taken.";
+ if (error.name == "space_limit_reached") {
+ return "A Space already exists for this account. Please refresh and try again.";
}
- if (status == 400) {
- const message = error instanceof Error ? error.message : "";
- if (message.toLowerCase().includes("reserved")) {
- return "This username is reserved.";
- }
+ if (error.name == "invalid_space_slug") {
return "That username is not available. Please choose another.";
}
- if (status == 401) return "Your session expired. Please sign in again.";
- if (status == 403) return "You do not have access to update this profile.";
- return error instanceof Error
- ? error.message
- : "Couldn't save your profile. Please try again.";
+ if (error.name == "session_unauthorized") {
+ return "Your session expired. Please sign in again.";
+ }
+ if (error.name == "permission_denied") {
+ return "You do not have access to update this profile.";
+ }
+ return error.message;
};