Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(observability): log expected refusals and closed agent sessions below ERROR (#8421)
teob1fa6bb55a7f
diff --git a/crates/access_requests/src/domain/service.rs b/crates/access_requests/src/domain/service.rsindex 1be7dbdc9c..4b385b9a93 100644--- a/crates/access_requests/src/domain/service.rs+++ b/crates/access_requests/src/domain/service.rs@@ -9,6 +9,7 @@ use models_permissions::{sharing::{SharingFacts, SharingTeamRole},};use std::sync::Arc;+use tracing::Level;use uuid::Uuid;#[cfg(test)]@@ -173,7 +174,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Read current request state; non-reviewers never receive other people's requests.- #[tracing::instrument(name = "access_requests.state", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.state", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn state(&self,user: MacroUserIdStr<'static>,@@ -215,7 +216,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Submit or change one pending access request. Identical pending replays are harmless.- #[tracing::instrument(name = "access_requests.submit", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.submit", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn submit(&self,user: MacroUserIdStr<'static>,@@ -280,7 +281,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Cancel only the caller's current revision.- #[tracing::instrument(name = "access_requests.cancel", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.cancel", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn cancel(&self,user: MacroUserIdStr<'static>,@@ -304,7 +305,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Resolve a pending revision and atomically grant access or begin the denial cooldown.- #[tracing::instrument(name = "access_requests.resolve", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.resolve", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn resolve(&self,user: MacroUserIdStr<'static>,@@ -347,7 +348,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Direct grants are visible to reviewers and their recipient only.- #[tracing::instrument(name = "access_requests.direct_access", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.direct_access", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn direct_access(&self,user: MacroUserIdStr<'static>,@@ -364,7 +365,7 @@ impl<R: RequestRepository, A: EntityAccessService, C: Clock> AccessRequestServic}/// Explicit owner management can reduce a direct grant, preserving other access paths.- #[tracing::instrument(name = "access_requests.set_direct_access", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err)]+ #[tracing::instrument(name = "access_requests.set_direct_access", skip_all, fields(entity_id = %entity.entity_id, entity_type = ?entity.entity_type), err(level = Level::DEBUG))]pub async fn set_direct_access(&self,user: MacroUserIdStr<'static>,diff --git a/crates/access_requests/src/inbound/axum_router.rs b/crates/access_requests/src/inbound/axum_router.rsindex 7f564c229b..a08b138d1e 100644--- a/crates/access_requests/src/inbound/axum_router.rs+++ b/crates/access_requests/src/inbound/axum_router.rs@@ -18,6 +18,7 @@ use macro_authorization::{use macro_user_id::user_id::MacroUserIdStr;use serde::Deserialize;use std::sync::Arc;+use tracing::Level;use uuid::Uuid;/// Shared service and authentication wiring.@@ -140,7 +141,7 @@ impl IntoResponse for RequestError {#[utoipa::path(get, tag = "access-requests", operation_id = "access_requests_state",path = "/entities/{entity_type}/{entity_id}/access-requests", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path), Page),responses((status = 200, body = AccessRequestState), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn state_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -165,7 +166,7 @@ where#[utoipa::path(put, tag = "access-requests", operation_id = "access_requests_submit",path = "/entities/{entity_type}/{entity_id}/access-requests/mine", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path)), request_body = RequestAccess,responses((status = 200, body = AccessRequest), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn submit_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -191,7 +192,7 @@ where#[utoipa::path(delete, tag = "access-requests", operation_id = "access_requests_cancel",path = "/entities/{entity_type}/{entity_id}/access-requests/mine", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path), Revision),responses((status = 200, body = () ), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn cancel_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -220,7 +221,7 @@ where#[utoipa::path(post, tag = "access-requests", operation_id = "access_requests_resolve",path = "/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path), ("request_id" = Uuid, Path)), request_body = ResolveRequest,responses((status = 200, body = AccessRequest), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn resolve_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -251,7 +252,7 @@ where#[utoipa::path(get, tag = "access-requests", operation_id = "access_requests_direct",path = "/entities/{entity_type}/{entity_id}/direct-access", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path)),responses((status = 200, body = Vec<DirectAccess>), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn direct_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -275,7 +276,7 @@ where#[utoipa::path(put, tag = "access-requests", operation_id = "access_requests_set_direct",path = "/entities/{entity_type}/{entity_id}/direct-access/{user_id}", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path), ("user_id" = String, Path)), request_body = SetDirectAccess,responses((status = 200, body = ()), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn set_direct_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,@@ -306,7 +307,7 @@ where#[utoipa::path(delete, tag = "access-requests", operation_id = "access_requests_remove_direct",path = "/entities/{entity_type}/{entity_id}/direct-access/{user_id}", params(("entity_type" = ShareEntityType, Path), ("entity_id" = Uuid, Path), ("user_id" = String, Path)),responses((status = 200, body = ()), (status = 400), (status = 403), (status = 404), (status = 409), (status = 429), (status = 500)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn remove_direct_handler<R, A, C, Auth>(State(state): State<AccessRequestsRouterState<R, A, C, Auth>>,user: MacroAuthorizationExtractor<Auth, UserOnly>,diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rsindex 47ca00d73a..8a9d8a2861 100644--- a/crates/agent_egress/src/domain/service.rs+++ b/crates/agent_egress/src/domain/service.rs@@ -131,7 +131,7 @@ whereForward: Forwarder + 'static,Approvals: OwnerApprovals,{- #[tracing::instrument(skip_all, err, fields(+ #[tracing::instrument(skip_all, fields(destination = ?target,method = %request.method(),session = tracing::field::Empty,@@ -139,6 +139,27 @@ whereupstream_status = tracing::field::Empty,))]async fn proxy(+ &self,+ token: &SessionToken,+ target: EgressTarget,+ request: ProxyRequest,+ ) -> Result<ProxyResponse, EgressError> {+ self.authorize_and_forward(token, target, request)+ .await+ .inspect_err(log_proxy_error)+ }+}++impl<Sessions, Credentials, Tokens, Forward, Approvals>+ EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>+where+ Sessions: SessionAuthority + 'static,+ Credentials: McpCredentials,+ Tokens: GithubTokens,+ Forward: Forwarder + 'static,+ Approvals: OwnerApprovals,+{+ async fn authorize_and_forward(&self,token: &SessionToken,target: EgressTarget,@@ -447,6 +468,19 @@ where}}+/// Logs a failed proxy call in the current span.+///+/// Unlike `#[instrument(err)]`, whose level is fixed, this keeps a closed+/// session at INFO: ending a session revokes its egress, and the session's MCP+/// clients still make a last reconnect or `DELETE` after it closes. Every other+/// refusal or failure stays at ERROR.+fn log_proxy_error(error: &EgressError) {+ match error {+ EgressError::SessionClosed => tracing::info!(error = %error),+ _ => tracing::error!(error = %error),+ }+}+/// What became of a request to a server the owner has no live grant for.enum Unconnected {/// The proxy answered it itself; nothing goes upstream.diff --git a/crates/agent_egress/src/inbound/axum_router.rs b/crates/agent_egress/src/inbound/axum_router.rsindex 3011445c49..88d7553310 100644--- a/crates/agent_egress/src/inbound/axum_router.rs+++ b/crates/agent_egress/src/inbound/axum_router.rs@@ -16,6 +16,7 @@ use axum_extra::headers::{Authorization, HeaderMapExt};use http::{HeaderMap, StatusCode};use http_body_util::BodyExt;use std::sync::Arc;+use tracing::Level;use crate::domain::error::EgressError;use crate::domain::model::{@@ -81,7 +82,7 @@ async fn health() -> &'static str {// `skip_all` on every handler is load-bearing: the request's headers carry the// sandbox's session token, and an instrument attribute that Debug-formatted// `request` would put it in the trace.-#[tracing::instrument(skip_all, err, fields(%slug))]+#[tracing::instrument(skip_all, err(level = Level::INFO), fields(%slug))]async fn mcp_handler<Service>(State(state): State<EgressRouterState<Service>>,Path(slug): Path<String>,@@ -101,7 +102,7 @@ where/// One of the owner's custom servers, on its own route: a key is not a slug,/// and keeping the two apart means neither can be mistaken for the other.-#[tracing::instrument(skip_all, err, fields(%key))]+#[tracing::instrument(skip_all, err(level = Level::INFO), fields(%key))]async fn custom_mcp_handler<Service>(State(state): State<EgressRouterState<Service>>,Path(key): Path<String>,@@ -116,7 +117,7 @@ wheremcp_proxy(state, McpDestination::Custom(key), request).await}-#[tracing::instrument(skip_all, err)]+#[tracing::instrument(skip_all, err(level = Level::INFO))]async fn preview_mcp_handler<Service: EgressService>(State(state): State<EgressRouterState<Service>>,request: Request,@@ -127,7 +128,7 @@ async fn preview_mcp_handler<Service: EgressService>(/// Macro's own MCP server, on its own route rather than under `/mcp/{slug}`:/// with no name shared between the built-in server and the owner's connected/// apps, no connected app can collide with it.-#[tracing::instrument(skip_all, err)]+#[tracing::instrument(skip_all, err(level = Level::INFO))]async fn macro_mcp_handler<Service>(State(state): State<EgressRouterState<Service>>,request: Request,@@ -166,7 +167,7 @@ where}/// One git smart-HTTP request through the proxy.-#[tracing::instrument(skip_all, err, fields(%path))]+#[tracing::instrument(skip_all, err(level = Level::INFO), fields(%path))]async fn git_proxy<Service>(state: EgressRouterState<Service>,path: String,diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rsindex f095676077..b89ae0e490 100644--- a/crates/agent_egress/src/outbound/session_authority.rs+++ b/crates/agent_egress/src/outbound/session_authority.rs@@ -18,6 +18,7 @@use agent_session::domain::ports::AgentSessionRepo;use agent_session::domain::{credentials::authenticate_session, error::AgentSessionError};use model_owner::Owner;+use tracing::Level;use crate::domain::error::EgressError;use crate::domain::model::{McpServerListing, McpServerSlug, RepoSlug, SessionGrant, SessionToken};@@ -43,7 +44,7 @@ impl<Sessions> SessionAuthority for StoredTokenSessionAuthority<Sessions>whereSessions: AgentSessionRepo,{- #[tracing::instrument(skip_all, err)]+ #[tracing::instrument(skip_all, err(level = Level::DEBUG))]async fn authorize(&self, token: &SessionToken) -> Result<SessionGrant, EgressError> {let session = authenticate_session(&self.sessions, &token.hash()).awaitdiff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rsindex 14193eebb4..b5fefb6027 100644--- a/crates/crm/src/domain/service.rs+++ b/crates/crm/src/domain/service.rs@@ -1038,16 +1038,21 @@ where.await}- #[tracing::instrument(skip(self, access), err)]+ /// Logs by cause rather than with `err`: callers look up whatever address+ /// they were given, so one that is not an email is theirs to fix, while a+ /// repository failure stays at ERROR.+ #[tracing::instrument(skip(self, access))]async fn get_contact_by_email(&self,access: &CrmTeamReceipt<MemberTeamRole>,email: &str,) -> Result<Option<CrmContact>, CrmError> {- let email = normalize_contact_email(email)?;+ let email =+ normalize_contact_email(email).inspect_err(|error| tracing::info!(error = %error))?;self.companies_repository.get_contact_by_email_for_team(&access.team_id(), &email, access.include_hidden()).await+ .inspect_err(|error| tracing::error!(error = %error))}#[tracing::instrument(skip(self, access), err)]diff --git a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs b/crates/crm/src/inbound/axum_router/get_contact_by_email.rsindex 973d22aecf..1a0124f246 100644--- a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs+++ b/crates/crm/src/inbound/axum_router/get_contact_by_email.rs@@ -6,6 +6,7 @@ use entity_access::{use macro_authorization::MacroAuthorizationService;use model_error_response::ErrorResponse;use serde::{Deserialize, Serialize};+use tracing::Level;use utoipa::{IntoParams, ToSchema};use crate::domain::{auth::CrmTeamReceipt, model::CrmError, service::CrmService};@@ -46,7 +47,7 @@ pub struct GetContactByEmailResponse {(status = 500, body = ErrorResponse),),)]-#[tracing::instrument(skip_all, err, fields(email = %params.email))]+#[tracing::instrument(skip_all, err(level = Level::DEBUG), fields(email = %params.email))]pub async fn handler<C: CrmService,St,@@ -57,7 +58,8 @@ pub async fn handler<State(state): State<CrmRouterState<C, St, Eas, Auth>>,Query(params): Query<GetContactByEmailParams>,) -> Result<Json<GetContactByEmailResponse>, CrmError> {- let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;+ let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)+ .inspect_err(|error| tracing::error!(error = ?error, "invalid crm team receipt"))?;let contact = state.service.get_contact_by_email(&receipt, ¶ms.email)diff --git a/crates/databases/src/domain/service.rs b/crates/databases/src/domain/service.rsindex 6a593dd92c..677f74ef57 100644--- a/crates/databases/src/domain/service.rs+++ b/crates/databases/src/domain/service.rs@@ -28,6 +28,7 @@ use macro_event_broker::MacroEventBroker;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;use models_properties::shared::DataType;+use tracing::Level;use uuid::Uuid;use crate::domain::catalog::{self, TableEntry, takes_options};@@ -703,7 +704,7 @@ where.collect())}- #[tracing::instrument(skip(self, receipt), err)]+ #[tracing::instrument(skip(self, receipt), err(level = Level::INFO))]async fn get_database(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,@@ -867,7 +868,7 @@ whereself.store_query(viewer, database_id, definition).await}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self), err(level = Level::DEBUG))]async fn get_query(&self, viewer: Viewer, id: QueryId) -> Result<SavedQuery, SavedQueryError> {self.readable_query(&viewer, id).await}diff --git a/crates/databases/src/inbound/axum_router.rs b/crates/databases/src/inbound/axum_router.rsindex 9392f536a4..8fcabcf169 100644--- a/crates/databases/src/inbound/axum_router.rs+++ b/crates/databases/src/inbound/axum_router.rs@@ -26,6 +26,7 @@ use crate::domain::transfer::DatabaseTransferService;use casts::{column_casts_handler, column_conversion_handler};use models_databases::{DatabaseId, TableId};use std::sync::Arc;+use tracing::Level;use axum::{Json, Router,@@ -298,7 +299,7 @@ where(status = 500, body = ErrorResponse),))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn get_database_handler<Service, EntityAccess, Authorization>(access: DatabaseAccessLevelExtractor<ViewAccessLevel, EntityAccess, Authorization>,State(state): State<DatabasesRouterState<Service, EntityAccess, Authorization>>,diff --git a/crates/databases/src/inbound/axum_router/saved_queries.rs b/crates/databases/src/inbound/axum_router/saved_queries.rsindex 5ed768c06e..9ad4a2a9ad 100644--- a/crates/databases/src/inbound/axum_router/saved_queries.rs+++ b/crates/databases/src/inbound/axum_router/saved_queries.rs@@ -68,7 +68,7 @@ where(status = 500, body = ErrorResponse),))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn get_query_handler<Service, EntityAccess, Authorization>(State(state): State<DatabasesRouterState<Service, EntityAccess, Authorization>>,user: MacroAuthorizationExtractor<Authorization, UserOrInternal>,diff --git a/crates/forms/src/domain/service.rs b/crates/forms/src/domain/service.rsindex 2652ce866c..c8c61d459f 100644--- a/crates/forms/src/domain/service.rs+++ b/crates/forms/src/domain/service.rs@@ -27,6 +27,7 @@ use entity_access::domain::models::{};use macro_event_broker::MacroEventBroker;use macro_user_id::user_id::MacroUserIdStr;+use tracing::Level;use crate::domain::events::{self, FormMacroEvent, FormTopicEvent};use crate::domain::models::{@@ -359,7 +360,7 @@ whereself.submit(&receipt, submission).await}- #[tracing::instrument(skip(self, receipt), err)]+ #[tracing::instrument(skip(self, receipt), err(level = Level::DEBUG))]async fn my_response(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/crates/forms/src/inbound/axum_router/responses.rs b/crates/forms/src/inbound/axum_router/responses.rsindex bc0207c117..7fdd2f1ca0 100644--- a/crates/forms/src/inbound/axum_router/responses.rs+++ b/crates/forms/src/inbound/axum_router/responses.rs@@ -8,6 +8,7 @@ use macro_authorization::MacroAuthorizationService;use models_forms::{FormErrorResponse, FormTally, MyResponse, ResponseSummary, Submission, SubmissionOutcome,};+use tracing::Level;use super::access::FormReceipt;use super::{FormsApiError, FormsRouterState};@@ -44,7 +45,7 @@ whereparams(("id" = Uuid, Path, description = "Form id")),responses((status = 200, body = MyResponse), (status = 401, body = FormErrorResponse), (status = 403, body = FormErrorResponse),(status = 404, body = FormErrorResponse), (status = 500, body = FormErrorResponse)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err(level = Level::INFO), skip_all)]pub async fn get_my_form_response_handler<Service, EntityAccess, Authorization>(access: FormReceipt<ViewAccessLevel, EntityAccess, Authorization>,State(state): State<FormsRouterState<Service, EntityAccess, Authorization>>,diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rsindex 5c43f2224a..061381e164 100644--- a/crates/messages/src/domain/service.rs+++ b/crates/messages/src/domain/service.rs@@ -87,41 +87,49 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {}/// Read the same bounded message timeline for either parent.- #[tracing::instrument(err, skip(self, access))]+ #[tracing::instrument(skip(self, access))]pub async fn timeline(&self,access: EntityAccessReceipt<MessageView>,query: MessageTimelineQuery,) -> Result<MessagePage, MessageError> {- let (parent, query) = self.timeline_selection(&access, query).await?;- self.repo.timeline(&parent, query).await+ async {+ let (parent, query) = self.timeline_selection(&access, query).await?;+ self.repo.timeline(&parent, query).await+ }+ .await+ .inspect_err(log_read_error)}/// Read a parent's messages and its timeline activity as one ordered page./// Parents without a timeline activity source return their messages only.- #[tracing::instrument(err, skip(self, access))]+ #[tracing::instrument(skip(self, access))]pub async fn timeline_entries(&self,access: EntityAccessReceipt<MessageView>,query: MessageTimelineQuery,) -> Result<MessageTimelinePage, MessageError> {- let (parent, query) = self.timeline_selection(&access, query).await?;- let Some(source) = timeline_activity(&parent) else {- return self.repo.timeline(&parent, query).await.map(Into::into);- };- // These filters select a subset of roots, and activity has no matching- // filter, so the merged window would be wrong. Including deleted threads- // only adds tombstones on the same keyset, so it combines with activity.- if !query.ids.is_empty()- || query.anchored.is_some()- || query.activity_after.is_some()- || query.activity_before.is_some()- {- return Err(MessageError::Invalid(- "activity timelines cannot be combined with message filters",- ));+ async {+ let (parent, query) = self.timeline_selection(&access, query).await?;+ let Some(source) = timeline_activity(&parent) else {+ return self.repo.timeline(&parent, query).await.map(Into::into);+ };+ // These filters select a subset of roots, and activity has no matching+ // filter, so the merged window would be wrong. Including deleted threads+ // only adds tombstones on the same keyset, so it combines with activity.+ if !query.ids.is_empty()+ || query.anchored.is_some()+ || query.activity_after.is_some()+ || query.activity_before.is_some()+ {+ return Err(MessageError::Invalid(+ "activity timelines cannot be combined with message filters",+ ));+ }+ self.activity_timeline(&parent, source, query).await}- self.activity_timeline(&parent, source, query).await+ .await+ .inspect_err(log_read_error)}/// Validate a selection and resolve the parent it reads.@@ -157,34 +165,42 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {}/// Read a message and its canonical root for navigation.- #[tracing::instrument(err, skip(self, access))]+ #[tracing::instrument(skip(self, access))]pub async fn get(&self,access: EntityAccessReceipt<MessageView>,id: Uuid,) -> Result<Message, MessageError> {- let parent = parent_from_receipt(&access)?;- self.ensure_parent(&parent).await?;- self.active_message(&parent, id, true).await+ async {+ let parent = parent_from_receipt(&access)?;+ self.ensure_parent(&parent).await?;+ self.active_message(&parent, id, true).await+ }+ .await+ .inspect_err(log_read_error)}/// Open a specific discussion, including roots outside the current timeline page.- #[tracing::instrument(err, skip(self, access))]+ #[tracing::instrument(skip(self, access))]pub async fn get_thread(&self,access: EntityAccessReceipt<MessageView>,root_id: Uuid,) -> Result<MessageThread, MessageError> {- let parent = parent_from_receipt(&access)?;- self.ensure_parent(&parent).await?;- let state = self.active_thread(&parent, root_id).await?;- let root = self.active_message(&parent, root_id, true).await?;- let replies = self.repo.replies(&parent, root_id).await?;- Ok(MessageThread {- state,- root,- replies,- })+ async {+ let parent = parent_from_receipt(&access)?;+ self.ensure_parent(&parent).await?;+ let state = self.active_thread(&parent, root_id).await?;+ let root = self.active_message(&parent, root_id, true).await?;+ let replies = self.repo.replies(&parent, root_id).await?;+ Ok(MessageThread {+ state,+ root,+ replies,+ })+ }+ .await+ .inspect_err(log_read_error)}/// Load authorized history preceding a live prompt in this conversation.@@ -913,6 +929,21 @@ fn can_moderate(permission: &EntityPermission) -> bool {permission.satisfies::<OwnerAccessLevel>() || permission.satisfies::<AdminParticipantRole>()}+/// Logs a failed read in the current span.+///+/// Unlike `#[instrument(err)]`, whose level is fixed, this keeps refusals at+/// INFO: clients and agents read messages, threads, and parents that were+/// deleted under them. Repository failures stay at ERROR.+fn log_read_error(error: &MessageError) {+ match error {+ MessageError::Repository(_) => tracing::error!(error = %error),+ MessageError::NotFound+ | MessageError::Forbidden+ | MessageError::Invalid(_)+ | MessageError::Conflict => tracing::info!(error = %error),+ }+}+fn parent_from_receipt<P: RequiredPermission>(access: &EntityAccessReceipt<P>,) -> Result<MessageParent, MessageError> {diff --git a/crates/teams/src/domain/customer_repo.rs b/crates/teams/src/domain/customer_repo.rsindex 6cf858bf91..b1b3e71619 100644--- a/crates/teams/src/domain/customer_repo.rs+++ b/crates/teams/src/domain/customer_repo.rs@@ -54,11 +54,11 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<(), CustomerError>> + Send;/// The customer's active subscription, or their trialing one when none is- /// active. Errors with `SubscriptionNotActive` when they have neither.+ /// active. `None` when they have neither.fn get_subscription_id_for_customer(&self,customer_id: &stripe::CustomerId,- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;+ ) -> impl Future<Output = Result<Option<stripe::SubscriptionId>, CustomerError>> + Send;/// Add `amount` seats on `plan` to a subscription.fn increment_seat_count(diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex 2e519b1704..c8eee8c557 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -762,10 +762,7 @@ pub struct CreateSubscriptionArgs {/// Errors for customer repository#[derive(Debug, thiserror::Error)]pub enum CustomerError {- #[error("No stripe customer id")]- /// The customer does not have a stripe customer id- NoStripeCustomerId,- /// The customer has no active or trialing subscription+ /// The subscription is neither active nor trialing#[error("Subscription is not active")]SubscriptionNotActive,/// Invalid promotion codediff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex 4f09ac2e5a..ccf3cb5a4a 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -381,10 +381,7 @@ wherereturn Err(JoinTeamError::TeamError(TeamError::TeamNotPaying).into());}- if let Err(e) = self- .backfill_legacy_team_subscription_or_free(&team_id)- .await- {+ if let Err(e) = self.backfill_legacy_team_subscription(&team_id).await {self.rollback_add_user_to_team(&team_id,user_id,@@ -1184,11 +1181,15 @@ where}/// Backfills legacy teams that were created without a team subscription id.- #[tracing::instrument(skip(self), err)]+ /// A team whose owner has no Stripe customer, or no active or trialing+ /// subscription, is a free team rather than an error, and its size does+ /// not require an upgrade. Returns whether the team now pays through the+ /// owner's subscription.+ #[tracing::instrument(skip(self), fields(outcome = tracing::field::Empty), err)]async fn backfill_legacy_team_subscription(&self,team_id: &uuid::Uuid,- ) -> Result<(), GetTeamSubscriptionError> {+ ) -> Result<bool, GetTeamSubscriptionError> {let team_owner = self.team_repository.get_team_by_id(team_id)@@ -1197,19 +1198,25 @@ where.team.owner_id;- let customer_id = self+ let Some(customer_id) = self.team_repository.get_stripe_customer_id(&team_owner).await.map_err(GetTeamSubscriptionError::Team)?- .ok_or(CustomerError::NoStripeCustomerId)- .map_err(GetTeamSubscriptionError::Customer)?;+ else {+ tracing::Span::current().record("outcome", "no_customer");+ return Ok(false);+ };- let subscription_id = self+ let Some(subscription_id) = self.customer_repository.get_subscription_id_for_customer(&customer_id).await- .map_err(GetTeamSubscriptionError::Customer)?;+ .map_err(GetTeamSubscriptionError::Customer)?+ else {+ tracing::Span::current().record("outcome", "no_subscription");+ return Ok(false);+ };self.customer_repository.convert_subscription_to_team(&subscription_id, team_id, &team_owner)@@ -1226,25 +1233,8 @@ where.await.map_err(GetTeamSubscriptionError::Team)?;- Ok(())- }-- /// Runs [`Self::backfill_legacy_team_subscription`], treating "the owner- /// simply has no active subscription" as a benign outcome: the team is a- /// free team rather than an error. Team size does not require an upgrade.- /// Every other failure still propagates. Returns whether the team now- /// pays through the owner's subscription.- async fn backfill_legacy_team_subscription_or_free(- &self,- team_id: &uuid::Uuid,- ) -> Result<bool, GetTeamSubscriptionError> {- match self.backfill_legacy_team_subscription(team_id).await {- Ok(()) => Ok(true),- Err(GetTeamSubscriptionError::Customer(- CustomerError::NoStripeCustomerId | CustomerError::SubscriptionNotActive,- )) => Ok(false),- Err(e) => Err(e),- }+ tracing::Span::current().record("outcome", "linked");+ Ok(true)}/// Best-effort rollback of a direct team add (from@@ -1470,17 +1460,10 @@ wherereturn Ok(None);};- match self- .customer_repository+ self.customer_repository.get_subscription_id_for_customer(&customer_id).await- {- Ok(subscription_id) => Ok(Some(subscription_id)),- Err(CustomerError::NoStripeCustomerId | CustomerError::SubscriptionNotActive) => {- Ok(None)- }- Err(e) => Err(TeamError::StorageLayerError(e.into())),- }+ .map_err(|e| TeamError::StorageLayerError(e.into()))}#[tracing::instrument(skip(self), fields(invitee_plan = tracing::field::Empty), err)]@@ -1520,7 +1503,7 @@ where}(false, None) => {let linked = self- .backfill_legacy_team_subscription_or_free(&team_id)+ .backfill_legacy_team_subscription(&team_id).await.map_err(GetTeamSubscriptionError::into_invite_users_to_team_error)?;if linked {@@ -1877,7 +1860,7 @@ where}if let Err(e) = self- .backfill_legacy_team_subscription_or_free(&accepted_invite.member.team_id)+ .backfill_legacy_team_subscription(&accepted_invite.member.team_id).await{self.team_repositorydiff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex 7ca0dd998c..1cf0a082f7 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -975,6 +975,7 @@ struct MockCustomerRepository {fail_increment: bool,fail_decrement: bool,no_active_subscription: bool,+ fail_subscription_lookup: bool,journal: Journal,}@@ -1002,6 +1003,7 @@ impl Default for MockCustomerRepository {fail_increment: false,fail_decrement: false,no_active_subscription: false,+ fail_subscription_lookup: false,journal: Journal::default(),}}@@ -1124,16 +1126,18 @@ impl CustomerRepository for MockCustomerRepository {fn get_subscription_id_for_customer(&self,_: &stripe::CustomerId,- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {+ ) -> impl Future<Output = Result<Option<stripe::SubscriptionId>, CustomerError>> + Send {*self.subscription_lookup_calls.lock().unwrap() += 1;let no_active_subscription = self.no_active_subscription;+ let fail_subscription_lookup = self.fail_subscription_lookup;let subscription_id = self.subscription_id.clone();async move {- if no_active_subscription {- Err(CustomerError::SubscriptionNotActive)- } else {- Ok(subscription_id)+ if fail_subscription_lookup {+ return Err(CustomerError::StorageLayerError(anyhow::anyhow!(+ "stripe subscription lookup failed"+ )));}+ Ok((!no_active_subscription).then_some(subscription_id))}}@@ -3183,6 +3187,30 @@ async fn test_is_user_premium_without_active_subscription() {assert!(service.is_user_premium(&user_id).await.unwrap().is_none());}+#[tokio::test]+async fn test_is_user_premium_surfaces_a_stripe_failure() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut team_repo =+ MockTeamRepository::new(Vec::new(), "Test Team", Arc::new(Mutex::new(Vec::new())));+ team_repo.stripe_customer_id = Some("cus_test".parse().unwrap());+ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository {+ fail_subscription_lookup: true,+ ..Default::default()+ },+ RecordingChannelService::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let err = service.is_user_premium(&user_id).await.err().unwrap();++ assert!(matches!(err, TeamError::StorageLayerError(_)));+}+#[tokio::test]async fn invite_users_to_team_enterprise_bypasses_billing_and_preserves_side_effects() {let team_id = uuid::Uuid::from_u128(6000);@@ -4818,6 +4846,71 @@ async fn test_invite_users_to_team_backfills_legacy_team_subscription() {assert_eq!(*payment_update_calls.lock().unwrap(), vec![(team_id, true)]);}+#[tokio::test]+async fn invite_users_to_team_fails_when_the_owners_subscription_lookup_fails() {+ let team_id = uuid::Uuid::from_u128(43);+ let invite_id = uuid::Uuid::from_u128(430);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Legacy Team",+ mark_sent_calls,+ )+ .with_team(Team::new(+ team_id,+ "Legacy Team".to_string(),+ "legacy-team".to_string(),+ owner_id.clone().into_owned(),+ false,+ false,+ ));+ team_repo.team_payment_status = false;+ team_repo.team_subscription_id = None;+ team_repo.stripe_customer_id = Some("cus_backfill_invite".parse().unwrap());+ let invitation_persistence_calls = team_repo.invite_users_to_team_calls.clone();+ let payment_update_calls = team_repo.payment_update_calls.clone();++ let customer_repo = MockCustomerRepository {+ fail_subscription_lookup: true,+ ..Default::default()+ };+ let convert_calls = customer_repo.convert_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ RecordingChannelService::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let invites = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &owner_id);++ let err = service+ .invite_users_to_team(receipt, invites)+ .await+ .err()+ .unwrap();++ assert!(matches!(+ err,+ InviteUsersToTeamError::CustomerError(CustomerError::StorageLayerError(_))+ ));+ assert_eq!(*invitation_persistence_calls.lock().unwrap(), 0);+ assert!(convert_calls.lock().unwrap().is_empty());+ assert!(payment_update_calls.lock().unwrap().is_empty());+}+#[tokio::test]async fn join_team_enterprise_bypasses_billing_and_preserves_membership_side_effects() {let team_id = uuid::Uuid::from_u128(45);@@ -5227,6 +5320,106 @@ async fn test_join_team_owner_without_subscription_joins_as_free_team() {assert!(roles_service.upsert_calls.lock().unwrap().is_empty());}+#[tokio::test]+async fn test_join_team_owner_without_stripe_customer_joins_as_free_team() {+ let team_id = uuid::Uuid::from_u128(49);+ let invite_id = uuid::Uuid::from_u128(490);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Legacy Team", mark_sent_calls)+ .with_team(Team::new(+ team_id,+ "Legacy Team".to_string(),+ "legacy-team".to_string(),+ owner_id.into_owned(),+ false,+ false,+ ));+ team_repo.team_payment_status = false;+ team_repo.team_subscription_id = None;+ team_repo.stripe_customer_id = None;+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();+ let payment_update_calls = team_repo.payment_update_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let subscription_lookup_calls = customer_repo.subscription_lookup_calls.clone();+ let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ RecordingChannelService::default(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let member = service.join_team(&invite_id, &user_id).await.unwrap();++ assert_eq!(member.team_id, team_id);+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 0);+ assert_eq!(*subscription_lookup_calls.lock().unwrap(), 0);+ assert!(payment_update_calls.lock().unwrap().is_empty());+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn test_join_team_rolls_back_accept_when_the_subscription_lookup_fails() {+ let team_id = uuid::Uuid::from_u128(50);+ let invite_id = uuid::Uuid::from_u128(500);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Legacy Team", mark_sent_calls)+ .with_team(Team::new(+ team_id,+ "Legacy Team".to_string(),+ "legacy-team".to_string(),+ owner_id.into_owned(),+ false,+ false,+ ));+ team_repo.team_payment_status = false;+ team_repo.team_subscription_id = None;+ team_repo.stripe_customer_id = Some("cus_backfill_join".parse().unwrap());+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();++ let customer_repo = MockCustomerRepository {+ fail_subscription_lookup: true,+ ..Default::default()+ };+ let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ RecordingChannelService::default(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let err = service.join_team(&invite_id, &user_id).await.err().unwrap();++ assert!(matches!(+ err,+ JoinTeamError::CustomerError(CustomerError::StorageLayerError(_))+ ));+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+}+#[tokio::test]async fn test_join_team_increments_customer_seat_count() {let team_id = uuid::Uuid::from_u128(1);@@ -7762,6 +7955,113 @@ async fn try_join_team_by_domain_free_team_adds_sixth_member_without_billing_or_);}+/// A domain auto-join into a legacy team (no team subscription, not marked+/// paying) whose owner has a Stripe customer, so joining backfills.+fn legacy_team_domain_join(+ team_id: uuid::Uuid,+ user_id: &MacroUserIdStr<'_>,+) -> MockTeamRepository {+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let member = TeamMember {+ team_id,+ user_id: user_id.clone().into_owned(),+ role: TeamRole::Member,+ plan: SeatPlan::Premium,+ };+ let mut team_repo =+ MockTeamRepository::new(Vec::new(), "Legacy Team", Arc::new(Mutex::new(Vec::new())))+ .with_team(Team::new(+ team_id,+ "Legacy Team".to_string(),+ "legacy-team".to_string(),+ owner_id.into_owned(),+ false,+ false,+ ));+ team_repo.team_id_for_domain = Some(team_id);+ team_repo.team_payment_status = false;+ team_repo.team_subscription_id = None;+ team_repo.stripe_customer_id = Some("cus_backfill_domain".parse().unwrap());+ team_repo.add_user_to_team_result = Some(member.clone());+ team_repo.removed_member = Some(member);+ team_repo+}++#[tokio::test]+async fn try_join_team_by_domain_legacy_team_without_owner_subscription_joins_free() {+ let team_id = uuid::Uuid::from_u128(7050);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_repo = legacy_team_domain_join(team_id, &user_id);+ let remove_user_calls = team_repo.remove_user_calls.clone();++ let customer_repo = MockCustomerRepository {+ no_active_subscription: true,+ ..Default::default()+ };+ let subscription_lookup_calls = customer_repo.subscription_lookup_calls.clone();+ let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ RecordingChannelService::default(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let result = service.try_join_team_by_domain(&user_id).await.unwrap();++ assert_eq!(result.unwrap().team_id, team_id);+ assert_eq!(*subscription_lookup_calls.lock().unwrap(), 1);+ assert_eq!(*remove_user_calls.lock().unwrap(), 0);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn try_join_team_by_domain_rolls_back_when_the_subscription_lookup_fails() {+ let team_id = uuid::Uuid::from_u128(7060);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_repo = legacy_team_domain_join(team_id, &user_id);+ let remove_user_calls = team_repo.remove_user_calls.clone();++ let customer_repo = MockCustomerRepository {+ fail_subscription_lookup: true,+ ..Default::default()+ };+ let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ RecordingChannelService::default(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let err = service+ .try_join_team_by_domain(&user_id)+ .await+ .err()+ .unwrap();++ assert!(matches!(+ err,+ JoinTeamDirectlyError::JoinTeamError(JoinTeamError::CustomerError(+ CustomerError::StorageLayerError(_)+ ))+ ));+ assert_eq!(*remove_user_calls.lock().unwrap(), 1);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+}+#[tokio::test]async fn invite_join_does_not_create_teammate_dms_inline() {let team_id = uuid::Uuid::from_u128(7100);diff --git a/crates/teams/src/outbound/customer_repo.rs b/crates/teams/src/outbound/customer_repo.rsindex 63e55cb806..95b4ea7a3a 100644--- a/crates/teams/src/outbound/customer_repo.rs+++ b/crates/teams/src/outbound/customer_repo.rs@@ -767,7 +767,7 @@ impl CustomerRepository for CustomerRepositoryImpl {async fn get_subscription_id_for_customer(&self,customer_id: &stripe::CustomerId,- ) -> Result<stripe::SubscriptionId, CustomerError> {+ ) -> Result<Option<stripe::SubscriptionId>, CustomerError> {// Stripe's `active` filter excludes `trialing`, so list every// uncanceled subscription and choose here. A trial grants Pro like// an active subscription, and a team created during the trial must@@ -780,7 +780,7 @@ impl CustomerRepository for CustomerRepositoryImpl {.await.map_err(|e| CustomerError::StorageLayerError(e.into()))?;- paying_subscription(subscriptions.data).ok_or(CustomerError::SubscriptionNotActive)+ Ok(paying_subscription(subscriptions.data))}}diff --git a/crates/teams/src/outbound/customer_repo/test.rs b/crates/teams/src/outbound/customer_repo/test.rsindex 987062e1ce..264efdbf5e 100644--- a/crates/teams/src/outbound/customer_repo/test.rs+++ b/crates/teams/src/outbound/customer_repo/test.rs@@ -877,7 +877,7 @@ async fn cancelling_a_guard_holder_releases_the_subscription_for_another_instancasync fn subscription_for_customer(pool: sqlx::PgPool,statuses: &[(&str, stripe::SubscriptionStatus)],-) -> Result<stripe::SubscriptionId, CustomerError> {+) -> Result<Option<stripe::SubscriptionId>, CustomerError> {let server = MockServer::start().await;let list = stripe::List {data: statuses@@ -923,7 +923,7 @@ async fn a_trialing_subscription_is_linked_when_none_is_active(pool: sqlx::PgPoo).await.unwrap();- assert_eq!(found.as_str(), "sub_trial");+ assert_eq!(found.as_ref().map(|id| id.as_str()), Some("sub_trial"));}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -937,7 +937,7 @@ async fn an_active_subscription_wins_over_a_trial(pool: sqlx::PgPool) {).await.unwrap();- assert_eq!(found.as_str(), "sub_active");+ assert_eq!(found.as_ref().map(|id| id.as_str()), Some("sub_active"));}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -950,5 +950,23 @@ async fn unpaid_or_incomplete_subscriptions_are_not_linked(pool: sqlx::PgPool) {],).await;- assert!(matches!(found, Err(CustomerError::SubscriptionNotActive)));+ assert!(matches!(found, Ok(None)));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_failed_subscription_listing_is_an_error_not_a_free_customer(pool: sqlx::PgPool) {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/v1/subscriptions"))+ .respond_with(ResponseTemplate::new(500).set_body_json(json!({+ "error": { "type": "api_error", "message": "stripe is down" }+ })))+ .mount(&server)+ .await;++ let found = repo(&server, pool)+ .get_subscription_id_for_customer(&"cus_test".parse().unwrap())+ .await;++ assert!(matches!(found, Err(CustomerError::StorageLayerError(_))));}diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rsindex 1431649e6a..033a431169 100644--- a/services/authentication_service/src/api/link/gmail.rs+++ b/services/authentication_service/src/api/link/gmail.rs@@ -11,6 +11,7 @@ use macro_middleware::tracking::ClientIp;use model::response::ErrorResponse;use roles_and_permissions::domain::model::PermissionId;use serde_utils::urlencode::UrlEncoded;+use tracing::Level;use url::Url;use crate::{@@ -93,6 +94,7 @@ impl IntoResponse for InitGmailLinkError {InitGmailLinkError::TooManyInProgressLinks => StatusCode::TOO_MANY_REQUESTS,InitGmailLinkError::PaymentRequired => StatusCode::PAYMENT_REQUIRED,InitGmailLinkError::InternalError(_) | InitGmailLinkError::IdentityProviderNotFound => {+ tracing::error!(error = ?self, "gmail link initiation failed");StatusCode::INTERNAL_SERVER_ERROR}};@@ -136,7 +138,7 @@ pub(crate) struct InitGmailLinkQueryParams {(status = 500, body=ErrorResponse),))]-#[tracing::instrument(skip(ctx, ip_context, db_permissions), fields(client_ip=%ip_context, user_id=%db_permissions.authorization.authorization.user.user_context.user_id, fusion_user_id=%db_permissions.authorization.authorization.user.user_context.fusion_user_id), err)]+#[tracing::instrument(skip(ctx, ip_context, db_permissions), fields(client_ip=%ip_context, user_id=%db_permissions.authorization.authorization.user.user_context.user_id, fusion_user_id=%db_permissions.authorization.authorization.user.user_context.fusion_user_id), err(level = Level::INFO))]pub async fn init_gmail_link_handler(State(ctx): State<ApiContext>,query: Query<InitGmailLinkQueryParams>,diff --git a/services/authentication_service/src/api/mobile_welcome_email.rs b/services/authentication_service/src/api/mobile_welcome_email.rsindex 4994fa97a3..3586daaef0 100644--- a/services/authentication_service/src/api/mobile_welcome_email.rs+++ b/services/authentication_service/src/api/mobile_welcome_email.rs@@ -8,6 +8,7 @@ use axum::{use model::response::ErrorResponse;use thiserror::Error;use tower::ServiceBuilder;+use tracing::Level;use utoipa::ToSchema;use crate::api::{context::ApiContext, middleware, utils::default_redirect_url};@@ -35,7 +36,10 @@ impl IntoResponse for SendMobileWelcomeEmailError {SendMobileWelcomeEmailError::InvalidEmail| SendMobileWelcomeEmailError::EmailBlocked| SendMobileWelcomeEmailError::PersonalEmail => StatusCode::BAD_REQUEST,- SendMobileWelcomeEmailError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ SendMobileWelcomeEmailError::InternalError(error) => {+ tracing::error!(error = ?error, "mobile welcome email failed");+ StatusCode::INTERNAL_SERVER_ERROR+ }};(@@ -86,7 +90,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {(status = 500, body = ErrorResponse),))]-#[tracing::instrument(skip(ctx), fields(email=%req.email), err)]+#[tracing::instrument(skip(ctx), fields(email=%req.email), err(level = Level::INFO))]pub async fn handler(State(ctx): State<ApiContext>,extract::Json(req): extract::Json<SendMobileWelcomeEmailRequest>,diff --git a/services/document_storage_service/src/api/documents/get_document_processing_result.rs b/services/document_storage_service/src/api/documents/get_document_processing_result.rsindex f838ebaad5..e5ffeea09c 100644--- a/services/document_storage_service/src/api/documents/get_document_processing_result.rs+++ b/services/document_storage_service/src/api/documents/get_document_processing_result.rs@@ -49,22 +49,19 @@ pub async fn handler(.await{Ok(content) => content,+ Err(sqlx::Error::RowNotFound) => {+ tracing::info!("document has no processing result");+ return GenericResponse::builder()+ .message("processing result not found")+ .is_error(true)+ .send(StatusCode::NOT_FOUND);+ }Err(err) => {tracing::error!(error=?err, "unable to get processing result");- match err {- sqlx::Error::RowNotFound => {- return GenericResponse::builder()- .message("processing result not found")- .is_error(true)- .send(StatusCode::NOT_FOUND);- }- _ => {- return GenericResponse::builder()- .message("unable to get processing result")- .is_error(true)- .send(StatusCode::INTERNAL_SERVER_ERROR);- }- }+ return GenericResponse::builder()+ .message("unable to get processing result")+ .is_error(true)+ .send(StatusCode::INTERNAL_SERVER_ERROR);}};