Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Seanaye/fix/bot parsing errors (#4179)

Sean Aye123cb1327383
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 209f2f2edb..4f8cfae0eb 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1174,6 +1174,7 @@
"macro_project_utils",
"macro_service_urls",
"macro_sha_count_client",
+ "macro_tower_layers",
"macro_user_id",
"macro_uuid",
"mention_utils",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 186c563755..a37f576549 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3621,6 +3621,7 @@ dependencies = [
"macro_project_utils",
"macro_service_urls",
"macro_sha_count_client",
+ "macro_tower_layers",
"macro_user_id",
"macro_uuid",
"mockall",
diff --git a/rust/cloud-storage/channels/src/inbound/list_router.rs b/rust/cloud-storage/channels/src/inbound/list_router.rs
index 32736f1b57..a7923cb878 100644
--- a/rust/cloud-storage/channels/src/inbound/list_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/list_router.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use axum::{Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::get};
use frecency::domain::models::AggregateFrecency;
-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use macro_user_id::user_id::MacroUserIdStr;
use model_user::axum_extractor::MacroUserExtractor;
use serde::Serialize;
use thiserror::Error;
@@ -97,10 +97,11 @@ async fn get_channels_handler<S: ChannelListService>(
.await
.map_err(|_| ChannelListRouterErr::Internal)?;
- res.into_iter()
- .map(ApiChannelWithLatest::try_from)
- .collect::<Result<Vec<_>, _>>()
- .map(Json)
+ Ok(Json(
+ res.into_iter()
+ .map(ApiChannelWithLatest::new_from_domain)
+ .collect(),
+ ))
}
#[tracing::instrument(skip(service))]
@@ -124,7 +125,9 @@ pub async fn get_activity_handler<S: ChannelListService>(
.await
.map_err(|_| ChannelListRouterErr::Internal)?;
- Ok(Json(res.into_iter().map(ApiActivity::from).collect()))
+ Ok(Json(
+ res.into_iter().map(ApiActivity::new_from_domain).collect(),
+ ))
}
/// Participant role in API responses.
@@ -139,8 +142,8 @@ pub enum ParticipantRole {
Member,
}
-impl From<DomainParticipantRole> for ParticipantRole {
- fn from(value: DomainParticipantRole) -> Self {
+impl ParticipantRole {
+ fn new_from_domain(value: DomainParticipantRole) -> Self {
match value {
DomainParticipantRole::Owner => Self::Owner,
DomainParticipantRole::Admin => Self::Admin,
@@ -155,8 +158,7 @@ pub struct ChannelParticipant {
/// id of the channel
pub channel_id: Uuid,
/// id of the user
- #[schema(value_type = String)]
- pub user_id: MacroUserIdStr<'static>,
+ pub user_id: String,
/// type of the participant
pub role: ParticipantRole,
/// timestamp of when the user joined the channel
@@ -165,19 +167,15 @@ pub struct ChannelParticipant {
pub left_at: Option<chrono::DateTime<chrono::Utc>>,
}
-impl TryFrom<crate::domain::models::ChannelParticipant> for ChannelParticipant {
- type Error = ChannelListRouterErr;
-
- fn try_from(value: crate::domain::models::ChannelParticipant) -> Result<Self, Self::Error> {
- Ok(Self {
+impl ChannelParticipant {
+ fn new_from_domain(value: crate::domain::models::ChannelParticipant) -> Self {
+ Self {
channel_id: value.channel_id,
- user_id: MacroUserIdStr::parse_from_str(&value.user_id)
- .map_err(|_| ChannelListRouterErr::Internal)?
- .into_owned(),
- role: value.role.into(),
+ user_id: value.user_id,
+ role: ParticipantRole::new_from_domain(value.role),
joined_at: value.joined_at,
left_at: value.left_at,
- })
+ }
}
}
@@ -208,25 +206,23 @@ pub struct ApiChannelWithLatest {
pub frecency_score: Option<f64>,
}
-impl TryFrom<ChannelWithLatest> for ApiChannelWithLatest {
- type Error = ChannelListRouterErr;
-
- fn try_from(value: ChannelWithLatest) -> Result<Self, Self::Error> {
- Ok(Self {
+impl ApiChannelWithLatest {
+ fn new_from_domain(value: ChannelWithLatest) -> Self {
+ Self {
channel: ChannelWithParticipants {
- channel: value.channel.channel.into(),
+ channel: Channel::new_from_domain(value.channel.channel),
participants: value
.channel
.participants
.into_iter()
- .map(ChannelParticipant::try_from)
- .collect::<Result<Vec<_>, _>>()?,
+ .map(ChannelParticipant::new_from_domain)
+ .collect(),
},
- latest_message: value.latest_message.into(),
+ latest_message: LatestMessage::new_from_domain(value.latest_message),
viewed_at: value.viewed_at,
interacted_at: value.interacted_at,
frecency_score: map_frecency(value.frecency_score),
- })
+ }
}
}
@@ -257,12 +253,12 @@ pub struct Channel {
pub owner_id: MacroUserIdStr<'static>,
}
-impl From<ChannelListItem> for Channel {
- fn from(value: ChannelListItem) -> Self {
+impl Channel {
+ fn new_from_domain(value: ChannelListItem) -> Self {
Self {
id: value.id,
name: value.name,
- channel_type: value.channel_type.into(),
+ channel_type: ChannelType::new_from_domain(value.channel_type),
org_id: value.org_id.and_then(|org_id| u32::try_from(org_id).ok()),
team_id: value.team_id,
created_at: value.created_at,
@@ -281,11 +277,13 @@ pub struct LatestMessage {
pub latest_non_thread_message: Option<ChannelMessage>,
}
-impl From<crate::domain::models::LatestMessage> for LatestMessage {
- fn from(value: crate::domain::models::LatestMessage) -> Self {
+impl LatestMessage {
+ fn new_from_domain(value: crate::domain::models::LatestMessage) -> Self {
Self {
- latest_message: value.latest_message.map(ChannelMessage::from),
- latest_non_thread_message: value.latest_non_thread_message.map(ChannelMessage::from),
+ latest_message: value.latest_message.map(ChannelMessage::new_from_recent),
+ latest_non_thread_message: value
+ .latest_non_thread_message
+ .map(ChannelMessage::new_from_recent),
}
}
}
@@ -304,8 +302,8 @@ pub enum ChannelType {
Team,
}
-impl From<DomainChannelType> for ChannelType {
- fn from(value: DomainChannelType) -> Self {
+impl ChannelType {
+ fn new_from_domain(value: DomainChannelType) -> Self {
match value {
DomainChannelType::Public => Self::Public,
DomainChannelType::Private => Self::Private,
@@ -336,8 +334,8 @@ pub struct ChannelMessage {
pub mentions: Vec<String>,
}
-impl From<RecentChannelMessage> for ChannelMessage {
- fn from(value: RecentChannelMessage) -> Self {
+impl ChannelMessage {
+ fn new_from_recent(value: RecentChannelMessage) -> Self {
Self {
message_id: value.message_id,
thread_id: value.thread_id,
@@ -371,8 +369,8 @@ pub struct ApiActivity {
pub interacted_at: Option<chrono::DateTime<chrono::Utc>>,
}
-impl From<Activity> for ApiActivity {
- fn from(value: Activity) -> Self {
+impl ApiActivity {
+ fn new_from_domain(value: Activity) -> Self {
Self {
id: value.id,
user_id: value.user_id,
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index baf408c418..4546a16607 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -92,6 +92,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
] }
macro_project_utils = { path = "../macro_project_utils" }
macro_sha_count_client = { path = "../macro_sha_count_client" }
+macro_tower_layers = { path = "../macro_tower_layers" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
mockall = { workspace = true }
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 89e51a430c..f8eea09b20 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -8,12 +8,13 @@ use axum::middleware::Next;
use context::InternalFlag;
use github::inbound::github_sync_router::GithubSyncRouterState;
use macro_axum_utils::compose_layers;
+use macro_tower_layers::MacroRequestIdAndTracingLayer;
use model::version::{ServiceNameState, VersionedApiServiceName, validate_api_version};
use properties_service::PropertiesHandlerState;
use search_service::SearchHandlerState;
+use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
-use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
@@ -60,7 +61,7 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {
.merge(health::router())
.layer(
ServiceBuilder::new()
- .layer(TraceLayer::new_for_http())
+ .layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())
.layer(axum::middleware::from_fn_with_state(
ServiceNameState {
service_name: VersionedApiServiceName::DocumentStorageService,
diff --git a/rust/cloud-storage/macro_tower_layers/src/lib.rs b/rust/cloud-storage/macro_tower_layers/src/lib.rs
index e2e017691f..199910ef21 100644
--- a/rust/cloud-storage/macro_tower_layers/src/lib.rs
+++ b/rust/cloud-storage/macro_tower_layers/src/lib.rs
@@ -22,7 +22,7 @@ use tower_http::{
ServiceBuilderExt,
classify::{ServerErrorsAsFailures, SharedClassifier},
request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
- trace::{DefaultMakeSpan, DefaultOnRequest, OnResponse, TraceLayer},
+ trace::{DefaultMakeSpan, DefaultOnRequest, OnFailure, OnResponse, TraceLayer},
};
use tracing::{Level, Span};
@@ -55,67 +55,18 @@ impl CustomOnResponse {
}
}
-/// dynamic tracing event macro
-/// copied from [`tower_http`] source (its not public)
-macro_rules! event_dynamic_lvl {
- ( $(target: $target:expr,)? $(parent: $parent:expr,)? $lvl:expr, $($tt:tt)* ) => {
- match $lvl {
- tracing::Level::ERROR => {
- tracing::event!(
- $(target: $target,)?
- $(parent: $parent,)?
- tracing::Level::ERROR,
- $($tt)*
- );
- }
- tracing::Level::WARN => {
- tracing::event!(
- $(target: $target,)?
- $(parent: $parent,)?
- tracing::Level::WARN,
- $($tt)*
- );
- }
- tracing::Level::INFO => {
- tracing::event!(
- $(target: $target,)?
- $(parent: $parent,)?
- tracing::Level::INFO,
- $($tt)*
- );
- }
- tracing::Level::DEBUG => {
- tracing::event!(
- $(target: $target,)?
- $(parent: $parent,)?
- tracing::Level::DEBUG,
- $($tt)*
- );
- }
- tracing::Level::TRACE => {
- tracing::event!(
- $(target: $target,)?
- $(parent: $parent,)?
- tracing::Level::TRACE,
- $($tt)*
- );
- }
- }
- };
+struct Latency {
+ duration: Duration,
}
-impl<B> OnResponse<B> for CustomOnResponse {
- fn on_response(self, response: &Response<B>, latency: Duration, _span: &Span) {
- struct Latency {
- duration: Duration,
- }
-
- impl std::fmt::Display for Latency {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{} ms", self.duration.as_millis())
- }
- }
+impl std::fmt::Display for Latency {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{} ms", self.duration.as_millis())
+ }
+}
+impl<B> OnResponse<B> for CustomOnResponse {
+ fn on_response(self, response: &Response<B>, latency: Duration, span: &Span) {
let level = match latency.cmp(&self.warning_threshold) {
cmp::Ordering::Less => Level::INFO,
cmp::Ordering::Equal | cmp::Ordering::Greater => Level::WARN,
@@ -124,12 +75,62 @@ impl<B> OnResponse<B> for CustomOnResponse {
let latency = Latency { duration: latency };
let response_headers = tracing::field::debug(response.headers());
- event_dynamic_lvl!(
- level,
+ match level {
+ Level::ERROR => tracing::error!(
+ parent: span,
+ %latency,
+ status = response.status().as_u16(),
+ response_headers,
+ "finished processing request"
+ ),
+ Level::WARN => tracing::warn!(
+ parent: span,
+ %latency,
+ status = response.status().as_u16(),
+ response_headers,
+ "finished processing request"
+ ),
+ Level::INFO => tracing::info!(
+ parent: span,
+ %latency,
+ status = response.status().as_u16(),
+ response_headers,
+ "finished processing request"
+ ),
+ Level::DEBUG => tracing::debug!(
+ parent: span,
+ %latency,
+ status = response.status().as_u16(),
+ response_headers,
+ "finished processing request"
+ ),
+ Level::TRACE => tracing::trace!(
+ parent: span,
+ %latency,
+ status = response.status().as_u16(),
+ response_headers,
+ "finished processing request"
+ ),
+ }
+ }
+}
+
+/// Emits failed-request logs with the request span as the parent so logs include route context.
+#[derive(Clone)]
+pub struct CustomOnFailure;
+
+impl<FailureClass> OnFailure<FailureClass> for CustomOnFailure
+where
+ FailureClass: std::fmt::Display,
+{
+ fn on_failure(&mut self, failure_classification: FailureClass, latency: Duration, span: &Span) {
+ let latency = Latency { duration: latency };
+
+ tracing::error!(
+ parent: span,
+ classification = %failure_classification,
%latency,
- status = response.status().as_u16(),
- response_headers,
- "finished processing request"
+ "response failed"
);
}
}
@@ -143,6 +144,9 @@ type ServiceBuilderAlias = ServiceBuilder<
DefaultMakeSpan,
DefaultOnRequest,
CustomOnResponse,
+ tower_http::trace::DefaultOnBodyChunk,
+ tower_http::trace::DefaultOnEos,
+ CustomOnFailure,
>,
Stack<SetRequestIdLayer<RequestIdBuilder>, Identity>,
>,
@@ -195,7 +199,8 @@ impl MacroRequestIdAndTracingLayer {
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true))
- .on_response(CustomOnResponse::new_with_threshold(warning_threshold)),
+ .on_response(CustomOnResponse::new_with_threshold(warning_threshold))
+ .on_failure(CustomOnFailure),
)
.propagate_x_request_id();
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index b97456ae56..9f061d5dfd 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -285,7 +285,6 @@ where
impl<'a> MacroUserId<ArcCowStr<'a>> {
/// attempt to create a borrowed version of self from an input string
- #[tracing::instrument(err, level = "warn")]
pub fn parse_from_str(input: &'a str) -> Result<Self, ParseErr> {
let (_, out) = macro_user_id(input).finish().map_err(|e| e.cloned())?;
Ok(out)