Use anyhow more idiomatically (#31052)

https://github.com/zed-industries/zed/issues/30972 brought up another
case where our context is not enough to track the actual source of the
issue: we get a general top-level error without inner error.

The reason for this was `.ok_or_else(|| anyhow!("failed to read HEAD
SHA"))?; ` on the top level.

The PR finally reworks the way we use anyhow to reduce such issues (or
at least make it simpler to bubble them up later in a fix).
On top of that, uses a few more anyhow methods for better readability.

* `.ok_or_else(|| anyhow!("..."))`, `map_err` and other similar error
conversion/option reporting cases are replaced with `context` and
`with_context` calls
* in addition to that, various `anyhow!("failed to do ...")` are
stripped with `.context("Doing ...")` messages instead to remove the
parasitic `failed to` text
* `anyhow::ensure!` is used instead of `if ... { return Err(...); }`
calls
* `anyhow::bail!` is used instead of `return Err(anyhow!(...));`

Release Notes:

- N/A
This commit is contained in:
Kirill Bulatov 2025-05-21 02:06:07 +03:00 committed by GitHub
parent 1e51a7ac44
commit 16366cf9f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
294 changed files with 2037 additions and 2610 deletions

View file

@ -10,7 +10,7 @@ use crate::{
db::{User, UserId},
rpc,
};
use anyhow::anyhow;
use anyhow::Context as _;
use axum::{
Extension, Json, Router,
body::Body,
@ -220,7 +220,7 @@ async fn create_access_token(
.db
.get_user_by_id(user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let mut impersonated_user_id = None;
if let Some(impersonate) = params.impersonate {

View file

@ -1,4 +1,4 @@
use anyhow::{Context, anyhow, bail};
use anyhow::{Context as _, bail};
use axum::{
Extension, Json, Router,
extract::{self, Query},
@ -89,7 +89,7 @@ async fn get_billing_preferences(
.db
.get_user_by_github_user_id(params.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
let preferences = app.db.get_billing_preferences(user.id).await?;
@ -138,7 +138,7 @@ async fn update_billing_preferences(
.db
.get_user_by_github_user_id(body.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let billing_customer = app.db.get_billing_customer_by_user_id(user.id).await?;
@ -241,7 +241,7 @@ async fn list_billing_subscriptions(
.db
.get_user_by_github_user_id(params.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let subscriptions = app.db.get_billing_subscriptions(user.id).await?;
@ -307,7 +307,7 @@ async fn create_billing_subscription(
.db
.get_user_by_github_user_id(body.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let Some(stripe_billing) = app.stripe_billing.clone() else {
log::error!("failed to retrieve Stripe billing object");
@ -432,7 +432,7 @@ async fn manage_billing_subscription(
.db
.get_user_by_github_user_id(body.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let Some(stripe_client) = app.stripe_client.clone() else {
log::error!("failed to retrieve Stripe client");
@ -454,7 +454,7 @@ async fn manage_billing_subscription(
.db
.get_billing_customer_by_user_id(user.id)
.await?
.ok_or_else(|| anyhow!("billing customer not found"))?;
.context("billing customer not found")?;
let customer_id = CustomerId::from_str(&customer.stripe_customer_id)
.context("failed to parse customer ID")?;
@ -462,7 +462,7 @@ async fn manage_billing_subscription(
.db
.get_billing_subscription_by_id(body.subscription_id)
.await?
.ok_or_else(|| anyhow!("subscription not found"))?;
.context("subscription not found")?;
let subscription_id = SubscriptionId::from_str(&subscription.stripe_subscription_id)
.context("failed to parse subscription ID")?;
@ -559,7 +559,7 @@ async fn manage_billing_subscription(
None
}
})
.ok_or_else(|| anyhow!("No subscription item to update"))?;
.context("No subscription item to update")?;
Some(CreateBillingPortalSessionFlowData {
type_: CreateBillingPortalSessionFlowDataType::SubscriptionUpdateConfirm,
@ -653,7 +653,7 @@ async fn migrate_to_new_billing(
.db
.get_user_by_github_user_id(body.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let old_billing_subscriptions_by_user = app
.db
@ -732,13 +732,13 @@ async fn sync_billing_subscription(
.db
.get_user_by_github_user_id(body.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let billing_customer = app
.db
.get_billing_customer_by_user_id(user.id)
.await?
.ok_or_else(|| anyhow!("billing customer not found"))?;
.context("billing customer not found")?;
let stripe_customer_id = billing_customer
.stripe_customer_id
.parse::<stripe::CustomerId>()
@ -1031,13 +1031,13 @@ async fn sync_subscription(
let billing_customer =
find_or_create_billing_customer(app, stripe_client, subscription.customer)
.await?
.ok_or_else(|| anyhow!("billing customer not found"))?;
.context("billing customer not found")?;
if let Some(SubscriptionKind::ZedProTrial) = subscription_kind {
if subscription.status == SubscriptionStatus::Trialing {
let current_period_start =
DateTime::from_timestamp(subscription.current_period_start, 0)
.ok_or_else(|| anyhow!("No trial subscription period start"))?;
.context("No trial subscription period start")?;
app.db
.update_billing_customer(
@ -1243,7 +1243,7 @@ async fn get_monthly_spend(
.db
.get_user_by_github_user_id(params.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let Some(llm_db) = app.llm_db.clone() else {
return Err(Error::http(
@ -1311,7 +1311,7 @@ async fn get_current_usage(
.db
.get_user_by_github_user_id(params.github_user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let feature_flags = app.db.get_user_flags(user.id).await?;
let has_extended_trial = feature_flags

View file

@ -1,6 +1,5 @@
use std::sync::{Arc, OnceLock};
use anyhow::anyhow;
use axum::{
Extension, Json, Router,
extract::{self, Query},
@ -39,7 +38,7 @@ impl CheckIsContributorParams {
return Ok(ContributorSelector::GitHubLogin { github_login });
}
Err(anyhow!(
Err(anyhow::anyhow!(
"must be one of `github_user_id` or `github_login`."
))?
}

View file

@ -1,6 +1,6 @@
use crate::db::ExtensionVersionConstraints;
use crate::{AppState, Error, Result, db::NewExtensionVersion};
use anyhow::{Context as _, anyhow};
use anyhow::Context as _;
use aws_sdk_s3::presigning::PresigningConfig;
use axum::{
Extension, Json, Router,
@ -181,7 +181,7 @@ async fn download_latest_extension(
.db
.get_extension(&params.extension_id, constraints.as_ref())
.await?
.ok_or_else(|| anyhow!("unknown extension"))?;
.context("unknown extension")?;
download_extension(
Extension(app),
Path(DownloadExtensionParams {
@ -238,7 +238,7 @@ async fn download_extension(
))
.presigned(PresigningConfig::expires_in(EXTENSION_DOWNLOAD_URL_LIFETIME).unwrap())
.await
.map_err(|e| anyhow!("failed to create presigned extension download url {e}"))?;
.context("creating presigned extension download url")?;
Ok(Redirect::temporary(url.uri()))
}
@ -374,7 +374,7 @@ async fn fetch_extension_manifest(
blob_store_bucket: &String,
extension_id: &str,
version: &str,
) -> Result<NewExtensionVersion, anyhow::Error> {
) -> anyhow::Result<NewExtensionVersion> {
let object = blob_store_client
.get_object()
.bucket(blob_store_bucket)
@ -397,8 +397,8 @@ async fn fetch_extension_manifest(
String::from_utf8_lossy(&manifest_bytes)
)
})?;
let published_at = object.last_modified.ok_or_else(|| {
anyhow!("missing last modified timestamp for extension {extension_id} version {version}")
let published_at = object.last_modified.with_context(|| {
format!("missing last modified timestamp for extension {extension_id} version {version}")
})?;
let published_at = time::OffsetDateTime::from_unix_timestamp_nanos(published_at.as_nanos())?;
let published_at = PrimitiveDateTime::new(published_at.date(), published_at.time());

View file

@ -1,3 +1,4 @@
use anyhow::Context as _;
use collections::HashMap;
use semantic_version::SemanticVersion;
@ -13,18 +14,12 @@ pub struct IpsFile {
impl IpsFile {
pub fn parse(bytes: &[u8]) -> anyhow::Result<IpsFile> {
let mut split = bytes.splitn(2, |&b| b == b'\n');
let header_bytes = split
.next()
.ok_or_else(|| anyhow::anyhow!("No header found"))?;
let header: Header = serde_json::from_slice(header_bytes)
.map_err(|e| anyhow::anyhow!("Failed to parse header: {}", e))?;
let header_bytes = split.next().context("No header found")?;
let header: Header = serde_json::from_slice(header_bytes).context("parsing header")?;
let body_bytes = split
.next()
.ok_or_else(|| anyhow::anyhow!("No body found"))?;
let body_bytes = split.next().context("No body found")?;
let body: Body = serde_json::from_slice(body_bytes)
.map_err(|e| anyhow::anyhow!("Failed to parse body: {}", e))?;
let body: Body = serde_json::from_slice(body_bytes).context("parsing body")?;
Ok(IpsFile { header, body })
}

View file

@ -3,7 +3,7 @@ use crate::{
db::{self, AccessTokenId, Database, UserId},
rpc::Principal,
};
use anyhow::{Context as _, anyhow};
use anyhow::Context as _;
use axum::{
http::{self, Request, StatusCode},
middleware::Next,
@ -85,14 +85,14 @@ pub async fn validate_header<B>(mut req: Request<B>, next: Next<B>) -> impl Into
.db
.get_user_by_id(user_id)
.await?
.ok_or_else(|| anyhow!("user {} not found", user_id))?;
.with_context(|| format!("user {user_id} not found"))?;
if let Some(impersonator_id) = validate_result.impersonator_id {
let admin = state
.db
.get_user_by_id(impersonator_id)
.await?
.ok_or_else(|| anyhow!("user {} not found", impersonator_id))?;
.with_context(|| format!("user {impersonator_id} not found"))?;
req.extensions_mut()
.insert(Principal::Impersonated { user, admin });
} else {
@ -192,7 +192,7 @@ pub async fn verify_access_token(
let db_token = db.get_access_token(token.id).await?;
let token_user_id = db_token.impersonated_user_id.unwrap_or(db_token.user_id);
if token_user_id != user_id {
return Err(anyhow!("no such access token"))?;
return Err(anyhow::anyhow!("no such access token"))?;
}
let t0 = Instant::now();

View file

@ -5,7 +5,7 @@ mod tables;
pub mod tests;
use crate::{Error, Result, executor::Executor};
use anyhow::anyhow;
use anyhow::{Context as _, anyhow};
use collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use dashmap::DashMap;
use futures::StreamExt;
@ -320,11 +320,9 @@ impl Database {
let mut tx = Arc::new(Some(tx));
let result = f(TransactionHandle(tx.clone())).await;
let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
return Err(anyhow!(
"couldn't complete transaction because it's still in use"
))?;
};
let tx = Arc::get_mut(&mut tx)
.and_then(|tx| tx.take())
.context("couldn't complete transaction because it's still in use")?;
Ok((tx, result))
}
@ -344,11 +342,9 @@ impl Database {
let mut tx = Arc::new(Some(tx));
let result = f(TransactionHandle(tx.clone())).await;
let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
return Err(anyhow!(
"couldn't complete transaction because it's still in use"
))?;
};
let tx = Arc::get_mut(&mut tx)
.and_then(|tx| tx.take())
.context("couldn't complete transaction because it's still in use")?;
Ok((tx, result))
}
@ -853,9 +849,7 @@ fn db_status_to_proto(
)
}
_ => {
return Err(anyhow!(
"Unexpected combination of status fields: {entry:?}"
));
anyhow::bail!("Unexpected combination of status fields: {entry:?}");
}
};
Ok(proto::StatusEntry {

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use sea_orm::sea_query::Query;
impl Database {
@ -51,7 +52,7 @@ impl Database {
Ok(access_token::Entity::find_by_id(access_token_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such access token"))?)
.context("no such access token")?)
})
.await
}

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use super::*;
#[derive(Debug)]
@ -82,7 +84,7 @@ impl Database {
Ok(preferences
.into_iter()
.next()
.ok_or_else(|| anyhow!("billing preferences not found"))?)
.context("billing preferences not found")?)
})
.await
}

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use crate::db::billing_subscription::{
StripeCancellationReason, StripeSubscriptionStatus, SubscriptionKind,
};
@ -51,7 +53,7 @@ impl Database {
Ok(billing_subscription::Entity::find_by_id(id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to retrieve inserted billing subscription"))?)
.context("failed to retrieve inserted billing subscription")?)
})
.await
}

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use prost::Message;
use text::{EditOperation, UndoOperation};
@ -467,7 +468,7 @@ impl Database {
.filter(buffer::Column::ChannelId.eq(channel_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such buffer"))?;
.context("no such buffer")?;
let serialization_version = self
.get_buffer_operation_serialization_version(buffer.id, buffer.epoch, &tx)
@ -606,7 +607,7 @@ impl Database {
.into_values::<_, QueryOperationSerializationVersion>()
.one(tx)
.await?
.ok_or_else(|| anyhow!("missing buffer snapshot"))?)
.context("missing buffer snapshot")?)
}
pub async fn get_channel_buffer(
@ -621,7 +622,7 @@ impl Database {
.find_related(buffer::Entity)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such buffer"))?)
.context("no such buffer")?)
}
async fn get_buffer_state(
@ -643,7 +644,7 @@ impl Database {
)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such snapshot"))?;
.context("no such snapshot")?;
let version = snapshot.operation_serialization_version;
(snapshot.text, version)
@ -839,7 +840,7 @@ fn operation_from_storage(
_format_version: i32,
) -> Result<proto::operation::Variant, Error> {
let operation =
storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!("{}", error))?;
storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!("{error}"))?;
let version = version_from_storage(&operation.version);
Ok(if operation.is_undo {
proto::operation::Variant::Undo(proto::operation::Undo {

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::{
ErrorCode, ErrorCodeExt,
proto::{ChannelBufferVersion, VectorClockEntry, channel_member::Kind},
@ -647,11 +648,8 @@ impl Database {
.and(channel_member::Column::UserId.eq(for_user)),
)
.one(&*tx)
.await?;
let Some(membership) = membership else {
Err(anyhow!("no such member"))?
};
.await?
.context("no such member")?;
let mut update = membership.into_active_model();
update.role = ActiveValue::Set(role);

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use super::*;
impl Database {
@ -215,7 +217,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such contact"))?;
.context("no such contact")?;
contact::Entity::delete_by_id(contact.id).exec(&*tx).await?;

View file

@ -1,5 +1,6 @@
use std::str::FromStr;
use anyhow::Context;
use chrono::Utc;
use sea_orm::sea_query::IntoCondition;
use util::ResultExt;
@ -166,7 +167,7 @@ impl Database {
.filter(extension::Column::ExternalId.eq(extension_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such extension: {extension_id}"))?;
.with_context(|| format!("no such extension: {extension_id}"))?;
let extensions = [extension];
let mut versions = self
@ -274,7 +275,7 @@ impl Database {
.filter(extension::Column::ExternalId.eq(*external_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to insert extension"))?
.context("failed to insert extension")?
};
extension_version::Entity::insert_many(versions.iter().map(|version| {

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::Notification;
use sea_orm::{SelectColumns, TryInsertResult};
use time::OffsetDateTime;
@ -330,7 +331,7 @@ impl Database {
.filter(channel_message::Column::Nonce.eq(Uuid::from_u128(nonce)))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to insert message"))?
.context("failed to insert message")?
.id;
}
}

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::Notification;
use util::ResultExt;
@ -256,7 +257,7 @@ pub fn model_to_proto(this: &Database, row: notification::Model) -> Result<proto
let kind = this
.notification_kinds_by_id
.get(&row.kind)
.ok_or_else(|| anyhow!("Unknown notification kind"))?;
.context("Unknown notification kind")?;
Ok(proto::Notification {
id: row.id.to_proto(),
kind: kind.to_string(),
@ -276,5 +277,5 @@ fn notification_kind_from_proto(
.notification_kinds_by_name
.get(&proto.kind)
.copied()
.ok_or_else(|| anyhow!("invalid notification kind {:?}", proto.kind))?)
.with_context(|| format!("invalid notification kind {:?}", proto.kind))?)
}

View file

@ -49,7 +49,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("could not find participant"))?;
.context("could not find participant")?;
if participant.room_id != room_id {
return Err(anyhow!("shared project on unexpected room"))?;
}
@ -128,7 +128,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("project not found"))?;
.context("project not found")?;
let room = if let Some(room_id) = project.room_id {
Some(self.get_room(room_id, &tx).await?)
} else {
@ -160,7 +160,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
self.update_project_worktrees(project.id, worktrees, &tx)
.await?;
@ -242,7 +242,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project: {project_id}"))?;
.with_context(|| format!("no such project: {project_id}"))?;
// Update metadata.
worktree::Entity::update(worktree::ActiveModel {
@ -624,16 +624,13 @@ impl Database {
let project_id = ProjectId::from_proto(update.project_id);
let worktree_id = update.worktree_id as i64;
self.project_transaction(project_id, |tx| async move {
let summary = update
.summary
.as_ref()
.ok_or_else(|| anyhow!("invalid summary"))?;
let summary = update.summary.as_ref().context("invalid summary")?;
// Ensure the update comes from the host.
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -677,16 +674,13 @@ impl Database {
) -> Result<TransactionGuard<Vec<ConnectionId>>> {
let project_id = ProjectId::from_proto(update.project_id);
self.project_transaction(project_id, |tx| async move {
let server = update
.server
.as_ref()
.ok_or_else(|| anyhow!("invalid language server"))?;
let server = update.server.as_ref().context("invalid language server")?;
// Ensure the update comes from the host.
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -732,7 +726,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -778,7 +772,7 @@ impl Database {
Ok(project::Entity::find_by_id(id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?)
.context("no such project")?)
})
.await
}
@ -1074,7 +1068,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let collaborators = project
.find_related(project_collaborator::Entity)
.all(&*tx)
@ -1143,7 +1137,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to read project host"))?;
.context("failed to read project host")?;
Ok(())
})
@ -1162,7 +1156,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let role_from_room = if let Some(room_id) = project.room_id {
room_participant::Entity::find()
@ -1287,7 +1281,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let mut collaborators = project_collaborator::Entity::find()
.filter(project_collaborator::Column::ProjectId.eq(project_id))

View file

@ -161,7 +161,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("user is not in the room"))?;
.context("user is not in the room")?;
let called_user_role = match caller.role.unwrap_or(ChannelRole::Member) {
ChannelRole::Admin | ChannelRole::Member => ChannelRole::Member,
@ -193,7 +193,7 @@ impl Database {
let room = self.get_room(room_id, &tx).await?;
let incoming_call = Self::build_incoming_call(&room, called_user_id)
.ok_or_else(|| anyhow!("failed to build incoming call"))?;
.context("failed to build incoming call")?;
Ok((room, incoming_call))
})
.await
@ -279,7 +279,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no call to cancel"))?;
.context("no call to cancel")?;
room_participant::Entity::delete(participant.into_active_model())
.exec(&*tx)
@ -310,7 +310,7 @@ impl Database {
.into_values::<_, QueryChannelId>()
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such room"))?;
.context("no such room")?;
if channel_id.is_some() {
Err(anyhow!("tried to join channel call directly"))?
@ -462,7 +462,7 @@ impl Database {
}
let (channel, room) = self.get_channel_room(room_id, tx).await?;
let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
let channel = channel.context("no channel for room")?;
Ok(JoinRoom {
room,
channel: Some(channel),
@ -505,7 +505,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("project does not exist"))?;
.context("project does not exist")?;
if project.host_user_id != Some(user_id) {
return Err(anyhow!("no such project"))?;
}
@ -519,7 +519,7 @@ impl Database {
.position(|collaborator| {
collaborator.user_id == user_id && collaborator.is_host
})
.ok_or_else(|| anyhow!("host not found among collaborators"))?;
.context("host not found among collaborators")?;
let host = collaborators.swap_remove(host_ix);
let old_connection_id = host.connection();
@ -1051,11 +1051,7 @@ impl Database {
let tx = tx;
let location_kind;
let location_project_id;
match location
.variant
.as_ref()
.ok_or_else(|| anyhow!("invalid location"))?
{
match location.variant.as_ref().context("invalid location")? {
proto::participant_location::Variant::SharedProject(project) => {
location_kind = 0;
location_project_id = Some(ProjectId::from_proto(project.id));
@ -1119,7 +1115,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("only admins can set participant role"))?;
.context("only admins can set participant role")?;
if role.requires_cla() {
self.check_user_has_signed_cla(user_id, room_id, &tx)
@ -1156,7 +1152,7 @@ impl Database {
let channel = room::Entity::find_by_id(room_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("could not find room"))?
.context("could not find room")?
.find_related(channel::Entity)
.one(tx)
.await?;
@ -1297,7 +1293,7 @@ impl Database {
let db_room = room::Entity::find_by_id(room_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("could not find room"))?;
.context("could not find room")?;
let mut db_participants = db_room
.find_related(room_participant::Entity)

View file

@ -1,3 +1,4 @@
use anyhow::Context as _;
use chrono::NaiveDateTime;
use super::*;
@ -247,7 +248,7 @@ impl Database {
.into_values::<_, QueryAs>()
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("could not find user"))?;
.context("could not find user")?;
Ok(metrics_id.to_string())
})
.await

View file

@ -1,5 +1,5 @@
use crate::db::{ProjectId, Result, RoomId, ServerId, UserId};
use anyhow::anyhow;
use anyhow::Context as _;
use rpc::ConnectionId;
use sea_orm::entity::prelude::*;
@ -18,10 +18,10 @@ impl Model {
pub fn host_connection(&self) -> Result<ConnectionId> {
let host_connection_server_id = self
.host_connection_server_id
.ok_or_else(|| anyhow!("empty host_connection_server_id"))?;
.context("empty host_connection_server_id")?;
let host_connection_id = self
.host_connection_id
.ok_or_else(|| anyhow!("empty host_connection_id"))?;
.context("empty host_connection_id")?;
Ok(ConnectionId {
owner_id: host_connection_server_id.0 as u32,
id: host_connection_id as u32,

View file

@ -1,4 +1,4 @@
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use std::fs;
use std::path::Path;
@ -6,8 +6,8 @@ pub fn get_dotenv_vars(current_dir: impl AsRef<Path>) -> Result<Vec<(String, Str
let current_dir = current_dir.as_ref();
let mut vars = Vec::new();
let env_content = fs::read_to_string(current_dir.join(".env.toml"))
.map_err(|_| anyhow!("no .env.toml file found"))?;
let env_content =
fs::read_to_string(current_dir.join(".env.toml")).context("no .env.toml file found")?;
add_vars(env_content, &mut vars)?;

View file

@ -14,7 +14,7 @@ pub mod user_backfiller;
#[cfg(test)]
mod tests;
use anyhow::anyhow;
use anyhow::Context as _;
use aws_config::{BehaviorVersion, Region};
use axum::{
http::{HeaderMap, StatusCode},
@ -339,7 +339,7 @@ fn build_stripe_client(config: &Config) -> anyhow::Result<stripe::Client> {
let api_key = config
.stripe_api_key
.as_ref()
.ok_or_else(|| anyhow!("missing stripe_api_key"))?;
.context("missing stripe_api_key")?;
Ok(stripe::Client::new(api_key))
}
@ -348,11 +348,11 @@ async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::
config
.blob_store_access_key
.clone()
.ok_or_else(|| anyhow!("missing blob_store_access_key"))?,
.context("missing blob_store_access_key")?,
config
.blob_store_secret_key
.clone()
.ok_or_else(|| anyhow!("missing blob_store_secret_key"))?,
.context("missing blob_store_secret_key")?,
None,
None,
"env",
@ -363,13 +363,13 @@ async fn build_blob_store_client(config: &Config) -> anyhow::Result<aws_sdk_s3::
config
.blob_store_url
.as_ref()
.ok_or_else(|| anyhow!("missing blob_store_url"))?,
.context("missing blob_store_url")?,
)
.region(Region::new(
config
.blob_store_region
.clone()
.ok_or_else(|| anyhow!("missing blob_store_region"))?,
.context("missing blob_store_region")?,
))
.credentials_provider(keys)
.load()
@ -383,11 +383,11 @@ async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis
config
.kinesis_access_key
.clone()
.ok_or_else(|| anyhow!("missing kinesis_access_key"))?,
.context("missing kinesis_access_key")?,
config
.kinesis_secret_key
.clone()
.ok_or_else(|| anyhow!("missing kinesis_secret_key"))?,
.context("missing kinesis_secret_key")?,
None,
None,
"env",
@ -398,7 +398,7 @@ async fn build_kinesis_client(config: &Config) -> anyhow::Result<aws_sdk_kinesis
config
.kinesis_region
.clone()
.ok_or_else(|| anyhow!("missing kinesis_region"))?,
.context("missing kinesis_region")?,
))
.credentials_provider(keys)
.load()

View file

@ -19,7 +19,7 @@ use usage_measure::UsageMeasure;
use std::future::Future;
use std::sync::Arc;
use anyhow::anyhow;
use anyhow::Context;
pub use sea_orm::ConnectOptions;
use sea_orm::prelude::*;
use sea_orm::{
@ -93,7 +93,7 @@ impl LlmDatabase {
Ok(self
.models
.get(&(provider, name.to_string()))
.ok_or_else(|| anyhow!("unknown model {provider:?}:{name}"))?)
.with_context(|| format!("unknown model {provider:?}:{name}"))?)
}
pub fn model_by_id(&self, id: ModelId) -> Result<&model::Model> {
@ -101,7 +101,7 @@ impl LlmDatabase {
.models
.values()
.find(|model| model.id == id)
.ok_or_else(|| anyhow!("no model for ID {id:?}"))?)
.with_context(|| format!("no model for ID {id:?}"))?)
}
pub fn options(&self) -> &ConnectOptions {
@ -142,11 +142,9 @@ impl LlmDatabase {
let mut tx = Arc::new(Some(tx));
let result = f(TransactionHandle(tx.clone())).await;
let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
return Err(anyhow!(
"couldn't complete transaction because it's still in use"
))?;
};
let tx = Arc::get_mut(&mut tx)
.and_then(|tx| tx.take())
.context("couldn't complete transaction because it's still in use")?;
Ok((tx, result))
}

View file

@ -2,7 +2,7 @@ use crate::db::billing_subscription::SubscriptionKind;
use crate::db::{billing_subscription, user};
use crate::llm::AGENT_EXTENDED_TRIAL_FEATURE_FLAG;
use crate::{Config, db::billing_preference};
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use chrono::{NaiveDateTime, Utc};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};
@ -49,7 +49,7 @@ impl LlmTokenClaims {
let secret = config
.llm_api_secret
.as_ref()
.ok_or_else(|| anyhow!("no LLM API secret"))?;
.context("no LLM API secret")?;
let plan = if is_staff {
Plan::ZedPro
@ -63,7 +63,7 @@ impl LlmTokenClaims {
let subscription_period =
billing_subscription::Model::current_period(Some(subscription), is_staff)
.map(|(start, end)| (start.naive_utc(), end.naive_utc()))
.ok_or_else(|| anyhow!("A plan is required to use Zed's hosted models or edit predictions. Visit https://zed.dev/account to get started."))?;
.context("A plan is required to use Zed's hosted models or edit predictions. Visit https://zed.dev/account to get started.")?;
let now = Utc::now();
let claims = Self {
@ -112,7 +112,7 @@ impl LlmTokenClaims {
let secret = config
.llm_api_secret
.as_ref()
.ok_or_else(|| anyhow!("no LLM API secret"))?;
.context("no LLM API secret")?;
match jsonwebtoken::decode::<Self>(
token,

View file

@ -1,4 +1,4 @@
use anyhow::anyhow;
use anyhow::{Context as _, anyhow};
use axum::headers::HeaderMapExt;
use axum::{
Extension, Router,
@ -138,11 +138,11 @@ async fn main() -> Result<()> {
.config
.llm_database_url
.as_ref()
.ok_or_else(|| anyhow!("missing LLM_DATABASE_URL"))?;
.context("missing LLM_DATABASE_URL")?;
let max_connections = state
.config
.llm_database_max_connections
.ok_or_else(|| anyhow!("missing LLM_DATABASE_MAX_CONNECTIONS"))?;
.context("missing LLM_DATABASE_MAX_CONNECTIONS")?;
let mut db_options = db::ConnectOptions::new(database_url);
db_options.max_connections(max_connections);
@ -287,7 +287,7 @@ async fn setup_llm_database(config: &Config) -> Result<()> {
let database_url = config
.llm_database_url
.as_ref()
.ok_or_else(|| anyhow!("missing LLM_DATABASE_URL"))?;
.context("missing LLM_DATABASE_URL")?;
let db_options = db::ConnectOptions::new(database_url.clone());
let db = LlmDatabase::new(db_options, Executor::Production).await?;

View file

@ -30,12 +30,11 @@ pub async fn run_database_migrations(
for migration in migrations {
match applied_migrations.get(&migration.version) {
Some(applied_migration) => {
if migration.checksum != applied_migration.checksum {
Err(anyhow!(
"checksum mismatch for applied migration {}",
migration.description
))?;
}
anyhow::ensure!(
migration.checksum == applied_migration.checksum,
"checksum mismatch for applied migration {}",
migration.description
);
}
None => {
let elapsed = connection.apply(&migration).await?;

View file

@ -664,7 +664,7 @@ impl Server {
Err(error) => {
let proto_err = match &error {
Error::Internal(err) => err.to_proto(),
_ => ErrorCode::Internal.message(format!("{}", error)).to_proto(),
_ => ErrorCode::Internal.message(format!("{error}")).to_proto(),
};
peer.respond_with_error(receipt, proto_err)?;
Err(error)
@ -938,7 +938,7 @@ impl Server {
.db
.get_user_by_id(user_id)
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let update_user_plan = make_update_user_plan_message(
&self.app_state.db,
@ -1169,7 +1169,7 @@ pub async fn handle_metrics(Extension(server): Extension<Arc<Server>>) -> Result
let metric_families = prometheus::gather();
let encoded_metrics = encoder
.encode_to_string(&metric_families)
.map_err(|err| anyhow!("{}", err))?;
.map_err(|err| anyhow!("{err}"))?;
Ok(encoded_metrics)
}
@ -1685,7 +1685,7 @@ async fn decline_call(message: proto::DeclineCall, session: Session) -> Result<(
.await
.decline_call(Some(room_id), session.user_id())
.await?
.ok_or_else(|| anyhow!("failed to decline call"))?;
.context("declining call")?;
room_updated(&room, &session.peer);
}
@ -1715,9 +1715,7 @@ async fn update_participant_location(
session: Session,
) -> Result<()> {
let room_id = RoomId::from_proto(request.room_id);
let location = request
.location
.ok_or_else(|| anyhow!("invalid location"))?;
let location = request.location.context("invalid location")?;
let db = session.db().await;
let room = db
@ -2246,7 +2244,7 @@ async fn create_buffer_for_peer(
session.connection_id,
)
.await?;
let peer_id = request.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?;
let peer_id = request.peer_id.context("invalid peer id")?;
session
.peer
.forward_send(session.connection_id, peer_id.into(), request)?;
@ -2377,10 +2375,7 @@ async fn follow(
) -> Result<()> {
let room_id = RoomId::from_proto(request.room_id);
let project_id = request.project_id.map(ProjectId::from_proto);
let leader_id = request
.leader_id
.ok_or_else(|| anyhow!("invalid leader id"))?
.into();
let leader_id = request.leader_id.context("invalid leader id")?.into();
let follower_id = session.connection_id;
session
@ -2411,10 +2406,7 @@ async fn follow(
async fn unfollow(request: proto::Unfollow, session: Session) -> Result<()> {
let room_id = RoomId::from_proto(request.room_id);
let project_id = request.project_id.map(ProjectId::from_proto);
let leader_id = request
.leader_id
.ok_or_else(|| anyhow!("invalid leader id"))?
.into();
let leader_id = request.leader_id.context("invalid leader id")?.into();
let follower_id = session.connection_id;
session
@ -3358,9 +3350,7 @@ async fn join_channel_internal(
};
channel_updated(
&joined_room
.channel
.ok_or_else(|| anyhow!("channel not returned"))?,
&joined_room.channel.context("channel not returned")?,
&joined_room.room,
&session.peer,
&*session.connection_pool().await,
@ -3568,9 +3558,7 @@ async fn send_channel_message(
// TODO: adjust mentions if body is trimmed
let timestamp = OffsetDateTime::now_utc();
let nonce = request
.nonce
.ok_or_else(|| anyhow!("nonce can't be blank"))?;
let nonce = request.nonce.context("nonce can't be blank")?;
let channel_id = ChannelId::from_proto(request.channel_id);
let CreatedChannelMessage {
@ -3710,10 +3698,7 @@ async fn update_channel_message(
)
.await?;
let nonce = request
.nonce
.clone()
.ok_or_else(|| anyhow!("nonce can't be blank"))?;
let nonce = request.nonce.clone().context("nonce can't be blank")?;
let message = proto::ChannelMessage {
sender_id: session.user_id().to_proto(),
@ -3818,14 +3803,12 @@ async fn get_supermaven_api_key(
return Err(anyhow!("supermaven not enabled for this account"))?;
}
let email = session
.email()
.ok_or_else(|| anyhow!("user must have an email"))?;
let email = session.email().context("user must have an email")?;
let supermaven_admin_api = session
.supermaven_client
.as_ref()
.ok_or_else(|| anyhow!("supermaven not configured"))?;
.context("supermaven not configured")?;
let result = supermaven_admin_api
.try_get_or_create_user(CreateExternalUserRequest { id: user_id, email })
@ -3973,7 +3956,7 @@ async fn get_private_user_info(
let user = db
.get_user_by_id(session.user_id())
.await?
.ok_or_else(|| anyhow!("user not found"))?;
.context("user not found")?;
let flags = db.get_user_flags(session.user_id()).await?;
response.send(proto::GetPrivateUserInfoResponse {
@ -4019,19 +4002,23 @@ async fn get_llm_api_token(
let user = db
.get_user_by_id(user_id)
.await?
.ok_or_else(|| anyhow!("user {} not found", user_id))?;
.with_context(|| format!("user {user_id} not found"))?;
if user.accepted_tos_at.is_none() {
Err(anyhow!("terms of service not accepted"))?
}
let Some(stripe_client) = session.app_state.stripe_client.as_ref() else {
Err(anyhow!("failed to retrieve Stripe client"))?
};
let stripe_client = session
.app_state
.stripe_client
.as_ref()
.context("failed to retrieve Stripe client")?;
let Some(stripe_billing) = session.app_state.stripe_billing.as_ref() else {
Err(anyhow!("failed to retrieve Stripe billing object"))?
};
let stripe_billing = session
.app_state
.stripe_billing
.as_ref()
.context("failed to retrieve Stripe billing object")?;
let billing_customer =
if let Some(billing_customer) = db.get_billing_customer_by_user_id(user.id).await? {
@ -4047,7 +4034,7 @@ async fn get_llm_api_token(
stripe::Expandable::Id(customer_id),
)
.await?
.ok_or_else(|| anyhow!("billing customer not found"))?
.context("billing customer not found")?
};
let billing_subscription =

View file

@ -1,5 +1,5 @@
use crate::db::{ChannelId, ChannelRole, UserId};
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use collections::{BTreeMap, HashMap, HashSet};
use rpc::ConnectionId;
use semantic_version::SemanticVersion;
@ -77,7 +77,7 @@ impl ConnectionPool {
let connection = self
.connections
.get_mut(&connection_id)
.ok_or_else(|| anyhow!("no such connection"))?;
.context("no such connection")?;
let user_id = connection.user_id;

View file

@ -1,6 +1,6 @@
use super::{RandomizedTest, TestClient, TestError, TestServer, UserTestPlan};
use crate::{db::UserId, tests::run_randomized_test};
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use call::ActiveCall;
use collections::{BTreeMap, HashMap};
@ -782,8 +782,7 @@ impl RandomizedTest for ProjectCollaborationTest {
let save =
project.update(cx, |project, cx| project.save_buffer(buffer.clone(), cx));
let save = cx.spawn(|cx| async move {
save.await
.map_err(|err| anyhow!("save request failed: {:?}", err))?;
save.await.context("save request failed")?;
assert!(
buffer
.read_with(&cx, |buffer, _| { buffer.saved_version().to_owned() })

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Context as _, Result};
use chrono::{DateTime, Utc};
use util::ResultExt;
@ -144,12 +144,9 @@ impl UserBackfiller {
}
}
let response = match response.error_for_status() {
Ok(response) => response,
Err(err) => return Err(anyhow!("failed to fetch GitHub user: {err}")),
};
response
.error_for_status()
.context("fetching GitHub user")?
.json()
.await
.with_context(|| format!("failed to deserialize GitHub user from '{url}'"))