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/chore/user id invariants (#693)

Sean Ayee2b8be836428
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b3daec0b23..2754373242 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -531,6 +531,7 @@ dependencies = [
"model",
"model-entity",
"model_notifications",
+ "model_user",
"models_team",
"native_app_service",
"non_empty",
@@ -1782,6 +1783,7 @@ dependencies = [
"chrono",
"futures",
"macro_db_migrator",
+ "macro_user_id",
"macro_uuid",
"model",
"serde",
@@ -2667,6 +2669,7 @@ dependencies = [
"model",
"model-entity",
"model_notifications",
+ "model_user",
"models_bulk_upload",
"models_opensearch",
"models_pagination",
@@ -5049,6 +5052,7 @@ dependencies = [
"anyhow",
"comms_service_client",
"macro_db_client",
+ "macro_user_id",
"model",
"model-entity",
"model_notifications",
@@ -5394,6 +5398,7 @@ dependencies = [
"base64 0.22.1",
"chrono",
"document_sub_type",
+ "macro_user_id",
"model-error-response",
"model_file_type",
"model_user",
@@ -7545,6 +7550,7 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_user_id",
"macro_uuid",
"mention_utils",
"model",
diff --git a/rust/cloud-storage/ai_tools/src/read.rs b/rust/cloud-storage/ai_tools/src/read.rs
index da43ffd722..c2089475a3 100644
--- a/rust/cloud-storage/ai_tools/src/read.rs
+++ b/rust/cloud-storage/ai_tools/src/read.rs
@@ -250,7 +250,7 @@ impl Read {
content: content_str,
metadata: DocumentMetadata {
document_name: metadata.document_name,
- owner: metadata.owner,
+ owner: metadata.owner.to_string(),
file_type: metadata.file_type,
project_id: metadata.project_id,
deleted: metadata.deleted_at.is_some(),
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index db3cece739..740221f879 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -76,6 +76,7 @@ mockall = { workspace = true }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
+model_user = { path = "../model_user", features = ["axum"] }
models_team = { path = "../models_team" }
native_app_service = { path = "../native_app_service" }
non_empty = { path = "../non_empty" }
diff --git a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
index e8b3aa2743..8b6e82e695 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
@@ -4,8 +4,11 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_user_id::{cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{
+ cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
+};
use model_entity::EntityType;
+use model_user::axum_extractor::MacroUserExtractor;
use teams::domain::{
model::{InviteUsersToTeamError, TeamInvite},
team_repo::TeamService,
@@ -20,7 +23,7 @@ use crate::api::{
team::TeamPathParam,
};
-use model::{response::ErrorResponse, tracking::IPContext, user::UserContext};
+use model::{response::ErrorResponse, tracking::IPContext};
use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};
@@ -35,8 +38,6 @@ pub struct InviteToTeamRequest {
pub enum InviteToTeamError {
#[error("unable to invite users to team")]
InviteUsersToTeamError(#[from] InviteUsersToTeamError),
- #[error("unable to parse user id")]
- InvalidMacroUserId,
#[error("unable to parse email")]
InvalidEmails,
#[error("no valid emails provided")]
@@ -46,12 +47,6 @@ pub enum InviteToTeamError {
impl IntoResponse for InviteToTeamError {
fn into_response(self) -> Response {
match self {
- InviteToTeamError::InvalidMacroUserId => (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "invalid user id",
- }),
- ),
InviteToTeamError::InvalidEmails => (
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
@@ -101,22 +96,18 @@ impl IntoResponse for InviteToTeamError {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context, req), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context, req), fields(client_ip=%ip_context.client_ip, user_id=%user_context.macro_user_id, fusion_user_id=%user_context.user_context.fusion_user_id))]
pub async fn handler(
access: TeamAccessRoleExtractor<OwnerRole>,
stripe_customer: StripeCustomerExtractor,
State(ctx): State<ApiContext>,
ip_context: Extension<IPContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(TeamPathParam { team_id }): Path<TeamPathParam>,
extract::Json(req): extract::Json<InviteToTeamRequest>,
) -> Result<StatusCode, InviteToTeamError> {
tracing::info!("invite_to_team");
- let user_id: MacroUserId<Lowercase> = MacroUserId::parse_from_str(&user_context.user_id)
- .map_err(|_| InviteToTeamError::InvalidMacroUserId)?
- .lowercase();
-
let emails: Vec<Result<Email<Lowercase>, _>> = req
.emails
.iter()
@@ -134,7 +125,7 @@ pub async fn handler(
let team_invites = ctx
.teams_service
- .invite_users_to_team(&team_id, &user_id, emails)
+ .invite_users_to_team(&team_id, &user_context.macro_user_id, emails)
.await
.map_err(InviteToTeamError::InviteUsersToTeamError)?;
@@ -156,14 +147,14 @@ pub async fn handler(
let db = ctx.db.clone();
let macro_notify_client = ctx.macro_notify_client.clone();
let team_invites = team_invites.clone();
- let invited_by = user_context.user_id.clone();
+ let invited_by = user_context.macro_user_id;
async move {
let _ = notify_team_invite(
&db,
&macro_notify_client,
&team_id,
team_invites,
- &invited_by,
+ invited_by,
)
.await
.inspect_err(|e| tracing::error!(error=?e, "unable to send notification"));
@@ -178,12 +169,12 @@ pub(in crate::api::team) async fn notify_team_invite(
macro_notify_client: &macro_notify::MacroNotify,
team_id: &uuid::Uuid,
team_invites: Vec<TeamInvite<'_>>,
- invited_by: &str,
+ invited_by: MacroUserIdStr<'static>,
) -> anyhow::Result<()> {
let team_name = macro_db_client::team::get::get_team_name(db, team_id).await?;
let notification_metadata = InviteToTeamMetadata {
- invited_by: invited_by.to_string(),
+ invited_by: invited_by.clone(),
team_name: team_name.clone(),
team_id: team_id.to_string(),
role: None,
@@ -194,7 +185,7 @@ pub(in crate::api::team) async fn notify_team_invite(
notification_entity: EntityType::Team
.with_entity_string(team_invite.team_invite_id.to_string()),
notification_event: NotificationEvent::InviteToTeam(notification_metadata.clone()),
- sender_id: Some(invited_by.to_string()),
+ sender_id: Some(invited_by.clone()),
recipient_ids: Some(vec![format!("macro|{}", team_invite.email.as_ref())]),
};
diff --git a/rust/cloud-storage/authentication_service/src/api/team/join_team.rs b/rust/cloud-storage/authentication_service/src/api/team/join_team.rs
index a28802c279..4a61287183 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/join_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/join_team.rs
@@ -4,7 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use model_user::axum_extractor::MacroUserExtractor;
use teams::domain::{model::JoinTeamError, team_repo::TeamService};
use crate::api::context::ApiContext;
@@ -12,7 +12,6 @@ use crate::api::context::ApiContext;
use model::{
response::{EmptyResponse, ErrorResponse},
tracking::IPContext,
- user::UserContext,
};
#[derive(serde::Deserialize)]
@@ -24,8 +23,6 @@ pub struct TeamInvitePathParam {
pub enum JoinTeamHandlerError {
#[error("unable to join team")]
JoinTeamError(#[from] JoinTeamError),
- #[error("unable to parse user id")]
- InvalidMacroUserId,
}
impl IntoResponse for JoinTeamHandlerError {
@@ -38,13 +35,6 @@ impl IntoResponse for JoinTeamHandlerError {
}),
)
.into_response(),
- JoinTeamHandlerError::InvalidMacroUserId => (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: &self.to_string(),
- }),
- )
- .into_response(),
}
}
}
@@ -64,21 +54,17 @@ impl IntoResponse for JoinTeamHandlerError {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context, ip_context), err, fields(user_id=%user_context.user_id, client_ip=%ip_context.client_ip))]
+#[tracing::instrument(skip(ctx, user_context, ip_context), err, fields(user_id=%user_context.macro_user_id, client_ip=%ip_context.client_ip))]
pub async fn handler(
State(ctx): State<ApiContext>,
ip_context: Extension<IPContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<Json<EmptyResponse>, JoinTeamHandlerError> {
tracing::info!("join_team");
- let user_id: MacroUserId<Lowercase> = MacroUserId::parse_from_str(&user_context.user_id)
- .map_err(|_| JoinTeamHandlerError::InvalidMacroUserId)?
- .lowercase();
-
ctx.teams_service
- .join_team(&team_invite_id, &user_id)
+ .join_team(&team_invite_id, &user_context.macro_user_id)
.await?;
Ok(Json(EmptyResponse::default()))
diff --git a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
index 74a10e9215..3ae6a5da96 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
@@ -4,6 +4,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};
@@ -15,7 +16,7 @@ use crate::api::{
use model::{
response::{EmptyResponse, ErrorResponse},
tracking::IPContext,
- user::UserContext,
+ user::axum_extractor::MacroUserExtractor,
};
#[derive(serde::Deserialize)]
@@ -41,12 +42,12 @@ pub struct Param {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.macro_user_id, fusion_user_id=%user_context.user_context.fusion_user_id))]
pub async fn handler(
access: TeamAccessRoleExtractor<AdminRole>,
State(ctx): State<ApiContext>,
ip_context: Extension<IPContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(Param {
team_id,
team_invite_id,
@@ -102,7 +103,7 @@ pub async fn handler(
let db = ctx.db.clone();
let macro_notify_client = ctx.macro_notify_client.clone();
let normalized_email = team_invite.email;
- let invited_by = user_context.user_id.clone();
+ let invited_by = user_context.macro_user_id;
let team_invite_id = team_invite.id;
async move {
let _ = notify_team_invite(
@@ -110,7 +111,7 @@ pub async fn handler(
&macro_notify_client,
&team_id,
&team_invite_id,
- &invited_by,
+ invited_by,
&normalized_email,
)
.await
@@ -126,13 +127,13 @@ async fn notify_team_invite(
macro_notify_client: &macro_notify::MacroNotify,
team_id: &uuid::Uuid,
team_invite_id: &uuid::Uuid,
- invited_by: &str,
+ invited_by: MacroUserIdStr<'static>,
normalized_email: &str,
) -> anyhow::Result<()> {
let team_name = macro_db_client::team::get::get_team_name(db, team_id).await?;
let notification_metadata = InviteToTeamMetadata {
- invited_by: invited_by.to_string(),
+ invited_by: invited_by.clone(),
team_name: team_name.clone(),
team_id: team_id.to_string(),
role: None,
@@ -141,7 +142,7 @@ async fn notify_team_invite(
let notification_queue_message = NotificationQueueMessage {
notification_entity: EntityType::Team.with_entity_string(team_invite_id.to_string()),
notification_event: NotificationEvent::InviteToTeam(notification_metadata),
- sender_id: Some(invited_by.to_string()),
+ sender_id: Some(invited_by),
recipient_ids: Some(vec![format!("macro|{normalized_email}")]),
};
diff --git a/rust/cloud-storage/authentication_service/src/api/team/reject_invitation.rs b/rust/cloud-storage/authentication_service/src/api/team/reject_invitation.rs
index 863085170d..0cf88f7d25 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/reject_invitation.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/reject_invitation.rs
@@ -1,19 +1,16 @@
+use crate::api::context::ApiContext;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_user_id::user_id::MacroUserId;
-use teams::domain::{model::RemoveTeamInviteError, team_repo::TeamService};
-
-use crate::api::context::ApiContext;
-
use model::{
response::{EmptyResponse, ErrorResponse},
tracking::IPContext,
- user::UserContext,
};
+use model_user::axum_extractor::MacroUserExtractor;
+use teams::domain::{model::RemoveTeamInviteError, team_repo::TeamService};
#[derive(serde::Deserialize)]
pub struct TeamInvitePathParam {
@@ -24,8 +21,6 @@ pub struct TeamInvitePathParam {
pub enum RejectInvitationError {
#[error("unable to reject invitation")]
RemoveTeamInviteError(#[from] RemoveTeamInviteError),
- #[error("unable to parse user id")]
- InvalidMacroUserId,
}
impl IntoResponse for RejectInvitationError {
@@ -53,12 +48,6 @@ impl IntoResponse for RejectInvitationError {
}),
),
},
- RejectInvitationError::InvalidMacroUserId => (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "invalid user id",
- }),
- ),
}
.into_response()
}
@@ -79,21 +68,17 @@ impl IntoResponse for RejectInvitationError {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.macro_user_id, fusion_user_id=%user_context.user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
ip_context: Extension<IPContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(TeamInvitePathParam { team_invite_id }): Path<TeamInvitePathParam>,
) -> Result<(StatusCode, Json<EmptyResponse>), RejectInvitationError> {
tracing::info!("reject_invitation");
- let macro_user_id = MacroUserId::parse_from_str(&user_context.user_id)
- .map_err(|_| RejectInvitationError::InvalidMacroUserId)?
- .lowercase();
-
ctx.teams_service
- .reject_invitation(&macro_user_id, &team_invite_id)
+ .reject_invitation(&user_context.macro_user_id, &team_invite_id)
.await?;
Ok((StatusCode::OK, Json(EmptyResponse::default())))
diff --git a/rust/cloud-storage/authentication_service/src/api/team/remove_user_from_team.rs b/rust/cloud-storage/authentication_service/src/api/team/remove_user_from_team.rs
index a9181fd2b5..2913106321 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/remove_user_from_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/remove_user_from_team.rs
@@ -1,22 +1,19 @@
+use crate::api::{
+ context::ApiContext,
+ middleware::team_access::{OwnerRole, TeamAccessRoleExtractor},
+};
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
};
-use macro_user_id::user_id::MacroUserId;
-use teams::domain::{model::RemoveUserFromTeamError, team_repo::TeamService};
-
-use crate::api::{
- context::ApiContext,
- middleware::team_access::{OwnerRole, TeamAccessRoleExtractor},
-};
-
use model::{
response::{EmptyResponse, ErrorResponse},
tracking::IPContext,
- user::UserContext,
};
+use model_user::axum_extractor::MacroUserExtractor;
+use teams::domain::{model::RemoveUserFromTeamError, team_repo::TeamService};
#[derive(serde::Deserialize)]
pub struct Param {
@@ -28,8 +25,6 @@ pub struct Param {
pub enum RemoveFromTeamError {
#[error("unable to remove user from team")]
RemoveUserFromTeamError(#[from] RemoveUserFromTeamError),
- #[error("unable to parse user id")]
- InvalidMacroUserId,
}
impl IntoResponse for RemoveFromTeamError {
@@ -75,12 +70,6 @@ impl IntoResponse for RemoveFromTeamError {
}),
),
},
- RemoveFromTeamError::InvalidMacroUserId => (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "invalid user id",
- }),
- ),
}
.into_response()
}
@@ -103,12 +92,12 @@ impl IntoResponse for RemoveFromTeamError {
(status = 500, body=ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.macro_user_id, fusion_user_id=%user_context.user_context.fusion_user_id))]
pub async fn handler(
access: TeamAccessRoleExtractor<OwnerRole>,
State(ctx): State<ApiContext>,
ip_context: Extension<IPContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(Param {
team_id,
remove_user_id,
@@ -116,12 +105,8 @@ pub async fn handler(
) -> Result<(StatusCode, Json<EmptyResponse>), RemoveFromTeamError> {
tracing::info!("remove_user_from_team");
- let remove_user_id = MacroUserId::parse_from_str(&remove_user_id)
- .map_err(|_| RemoveFromTeamError::InvalidMacroUserId)?
- .lowercase();
-
ctx.teams_service
- .remove_user_from_team(&team_id, &remove_user_id)
+ .remove_user_from_team(&team_id, &user_context.macro_user_id)
.await?;
Ok((StatusCode::OK, Json(EmptyResponse::default())))
diff --git a/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs b/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs
index 83ac86499e..98fe788c3e 100644
--- a/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs
+++ b/rust/cloud-storage/authentication_service/src/api/user/post_get_names_with_email.rs
@@ -36,18 +36,13 @@ pub async fn handler(
user_context: Extension<UserContext>,
extract::Json(req): extract::Json<GetNamesWithEmailRequestBody>,
) -> Result<Json<UserNames>, (StatusCode, String)> {
- let user_profile_ids: NonEmpty<Vec<MacroUserId<Lowercase>>> = NonEmpty::new(
- req.user_ids
- .into_iter()
- .map(|id| id.0.lowercase())
- .collect(),
- )
- .map_err(|_| {
- (
- StatusCode::BAD_REQUEST,
- "user_ids cannot be empty".to_string(),
- )
- })?;
+ let user_profile_ids: NonEmpty<Vec<MacroUserId<Lowercase>>> =
+ NonEmpty::new(req.user_ids.into_iter().map(|id| id.0).collect()).map_err(|_| {
+ (
+ StatusCode::BAD_REQUEST,
+ "user_ids cannot be empty".to_string(),
+ )
+ })?;
let user_names = get_user_names_with_email(&ctx.db, &user_context.user_id, user_profile_ids)
.await
diff --git a/rust/cloud-storage/comms_db_client/Cargo.toml b/rust/cloud-storage/comms_db_client/Cargo.toml
index b6b0a85995..d06797fba8 100644
--- a/rust/cloud-storage/comms_db_client/Cargo.toml
+++ b/rust/cloud-storage/comms_db_client/Cargo.toml
@@ -9,6 +9,7 @@ anyhow = { workspace = true }
cached = { workspace = true }
chrono = { workspace = true }
futures = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
serde = { workspace = true }
@@ -20,4 +21,4 @@ utoipa = { workspace = true, features = ["axum_extras", "chrono", "uuid"] }
uuid = { workspace = true }
[dev-dependencies]
-macro_db_migrator = { path = "../macro_db_migrator" }
\ No newline at end of file
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/comms_db_client/fixtures/messages_with_context.sql b/rust/cloud-storage/comms_db_client/fixtures/messages_with_context.sql
index 2f4f15d633..63d9649985 100644
--- a/rust/cloud-storage/comms_db_client/fixtures/messages_with_context.sql
+++ b/rust/cloud-storage/comms_db_client/fixtures/messages_with_context.sql
@@ -2,28 +2,28 @@
-- Creates a channel with 10 messages in chronological order
INSERT INTO comms_channels (id, name, channel_type, owner_id, created_at)
-VALUES ('aaaaaaaa-0000-0000-0000-000000000001', 'test channel', 'public', 'user1', '2024-01-01T10:00:00Z');
+VALUES ('aaaaaaaa-0000-0000-0000-000000000001', 'test channel', 'public', 'macro|[email protected]', '2024-01-01T10:00:00Z');
INSERT INTO comms_messages (id, channel_id, sender_id, content, created_at)
VALUES
-- 10 messages in chronological order in the same channel
- ('bbbbbbbb-0000-0000-0000-000000000001', 'aaaaaaaa-0000-0000-0000-000000000001', 'user1', 'Message 1',
+ ('bbbbbbbb-0000-0000-0000-000000000001', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 1',
'2024-01-01T10:00:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000002', 'aaaaaaaa-0000-0000-0000-000000000001', 'user2', 'Message 2',
+ ('bbbbbbbb-0000-0000-0000-000000000002', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 2',
'2024-01-01T10:01:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000003', 'aaaaaaaa-0000-0000-0000-000000000001', 'user3', 'Message 3',
+ ('bbbbbbbb-0000-0000-0000-000000000003', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 3',
'2024-01-01T10:02:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000004', 'aaaaaaaa-0000-0000-0000-000000000001', 'user4', 'Message 4',
+ ('bbbbbbbb-0000-0000-0000-000000000004', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 4',
'2024-01-01T10:03:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000005', 'aaaaaaaa-0000-0000-0000-000000000001', 'user5', 'Message 5',
+ ('bbbbbbbb-0000-0000-0000-000000000005', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 5',
'2024-01-01T10:04:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000006', 'aaaaaaaa-0000-0000-0000-000000000001', 'user1', 'Message 6',
+ ('bbbbbbbb-0000-0000-0000-000000000006', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 6',
'2024-01-01T10:05:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000007', 'aaaaaaaa-0000-0000-0000-000000000001', 'user2', 'Message 7',
+ ('bbbbbbbb-0000-0000-0000-000000000007', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 7',
'2024-01-01T10:06:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000008', 'aaaaaaaa-0000-0000-0000-000000000001', 'user3', 'Message 8',
+ ('bbbbbbbb-0000-0000-0000-000000000008', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 8',
'2024-01-01T10:07:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000009', 'aaaaaaaa-0000-0000-0000-000000000001', 'user4', 'Message 9',
+ ('bbbbbbbb-0000-0000-0000-000000000009', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 9',
'2024-01-01T10:08:00Z'),
- ('bbbbbbbb-0000-0000-0000-000000000010', 'aaaaaaaa-0000-0000-0000-000000000001', 'user5', 'Message 10',
+ ('bbbbbbbb-0000-0000-0000-000000000010', 'aaaaaaaa-0000-0000-0000-000000000001', 'macro|[email protected]', 'Message 10',
'2024-01-01T10:09:00Z');
diff --git a/rust/cloud-storage/comms_db_client/src/messages/create_message.rs b/rust/cloud-storage/comms_db_client/src/messages/create_message.rs
index 081cb5cad3..219058ca04 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/create_message.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/create_message.rs
@@ -1,5 +1,6 @@
use crate::model::Message;
use anyhow::{Context, Result};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Executor, Postgres};
use uuid::Uuid;
@@ -18,8 +19,7 @@ where
{
let message_id = macro_uuid::generate_uuid_v7();
- let message = sqlx::query_as!(
- Message,
+ let message = sqlx::query!(
r#"
INSERT INTO comms_messages (id, channel_id, sender_id, content, thread_id)
VALUES ($1, $2, $3, $4, $5)
@@ -40,6 +40,21 @@ where
options.content,
options.thread_id
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(executor)
.await
.context("unable to create message")?;
diff --git a/rust/cloud-storage/comms_db_client/src/messages/delete_message.rs b/rust/cloud-storage/comms_db_client/src/messages/delete_message.rs
index db56baee20..6d1ecb5930 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/delete_message.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/delete_message.rs
@@ -1,12 +1,12 @@
use crate::model::Message;
use anyhow::{Context, Result};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
#[tracing::instrument(skip(db))]
pub async fn delete_message(db: &Pool<Postgres>, message_id: Uuid) -> Result<Message> {
- let message = sqlx::query_as!(
- Message,
+ let message = sqlx::query!(
r#"
UPDATE comms_messages
SET content = $1, updated_at = NOW(), deleted_at = NOW()
@@ -25,6 +25,21 @@ pub async fn delete_message(db: &Pool<Postgres>, message_id: Uuid) -> Result<Mes
"".to_string(),
message_id
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await
.context("unable to delete message")?;
diff --git a/rust/cloud-storage/comms_db_client/src/messages/get_messages.rs b/rust/cloud-storage/comms_db_client/src/messages/get_messages.rs
index 289822b697..c39f7c7ea5 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/get_messages.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/get_messages.rs
@@ -1,5 +1,6 @@
use crate::model::Message;
use anyhow::{Context, Result};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -11,8 +12,7 @@ pub async fn get_messages(
since: Option<chrono::DateTime<chrono::Utc>>,
limit: Option<i64>,
) -> Result<Vec<Message>> {
- let messages = sqlx::query_as!(
- Message,
+ let messages = sqlx::query!(
r#"
SELECT
id,
@@ -34,6 +34,21 @@ pub async fn get_messages(
since,
limit
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_all(db)
.await
.context("unable to get messages")?;
diff --git a/rust/cloud-storage/comms_db_client/src/messages/patch_message.rs b/rust/cloud-storage/comms_db_client/src/messages/patch_message.rs
index 1f43b41203..88b3b7c2c2 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/patch_message.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/patch_message.rs
@@ -1,6 +1,7 @@
use crate::model::{Attachment, Message};
use anyhow::{Context, Result};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -10,8 +11,7 @@ pub async fn patch_message(
message_id: Uuid,
content: &str,
) -> Result<Message> {
- let message = sqlx::query_as!(
- Message,
+ let message = sqlx::query!(
r#"
UPDATE comms_messages
SET content = $1, updated_at = NOW(), edited_at = NOW()
@@ -30,6 +30,21 @@ pub async fn patch_message(
content,
message_id
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await
.context("unable to update message")?;
@@ -44,8 +59,7 @@ pub async fn patch_message_attachments(
attachments: Vec<Attachment>,
) -> Result<Message> {
let has_attachments = !attachments.is_empty();
- let message = sqlx::query_as!(
- Message,
+ let message = sqlx::query!(
r#"
UPDATE comms_messages
SET
@@ -70,6 +84,21 @@ pub async fn patch_message_attachments(
message_id,
has_attachments
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await
.context("unable to update message")?;
diff --git a/rust/cloud-storage/comms_db_client/src/messages/read_message_with_context.rs b/rust/cloud-storage/comms_db_client/src/messages/read_message_with_context.rs
index 6b0f820d61..7abe9ef134 100644
--- a/rust/cloud-storage/comms_db_client/src/messages/read_message_with_context.rs
+++ b/rust/cloud-storage/comms_db_client/src/messages/read_message_with_context.rs
@@ -1,5 +1,6 @@
use crate::model::Message;
use anyhow::{Context, Result};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -11,8 +12,7 @@ pub async fn get_messages_with_context(
before: i64,
after: i64,
) -> Result<Vec<Message>> {
- let msg = sqlx::query_as!(
- Message,
+ let msg = sqlx::query!(
r#"
SELECT
id,
@@ -29,6 +29,21 @@ pub async fn get_messages_with_context(
"#,
message_id
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await;
@@ -38,8 +53,7 @@ pub async fn get_messages_with_context(
let msg = msg.context("fetch message")?;
- let mut before = sqlx::query_as!(
- Message,
+ let mut before = sqlx::query!(
r#"
SELECT
id,
@@ -61,6 +75,21 @@ pub async fn get_messages_with_context(
message_id,
before
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_all(db)
.await
.context("fetch message before")?
@@ -68,8 +97,7 @@ pub async fn get_messages_with_context(
.rev()
.collect::<Vec<_>>();
- let mut after = sqlx::query_as!(
- Message,
+ let mut after = sqlx::query!(
r#"
SELECT
id,
@@ -91,6 +119,21 @@ pub async fn get_messages_with_context(
message_id,
after
)
+ .try_map(|row| {
+ Ok(Message {
+ id: row.id,
+ channel_id: row.channel_id,
+ thread_id: row.thread_id,
+ sender_id: MacroUserIdStr::parse_from_str(&row.sender_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_all(db)
.await
.context("fetch message after")?;
diff --git a/rust/cloud-storage/comms_db_client/src/model/mod.rs b/rust/cloud-storage/comms_db_client/src/model/mod.rs
index 88ab4a5a98..22ef908768 100644
--- a/rust/cloud-storage/comms_db_client/src/model/mod.rs
+++ b/rust/cloud-storage/comms_db_client/src/model/mod.rs
@@ -1,3 +1,4 @@
+use macro_user_id::user_id::MacroUserIdStr;
use model::comms::ChannelType;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -18,7 +19,8 @@ pub struct Message {
pub channel_id: Uuid,
pub thread_id: Option<Uuid>,
/// id of the user who sent the message
- pub sender_id: String,
+ #[schema(value_type = String)]
+ pub sender_id: MacroUserIdStr<'static>,
/// string content of the message
pub content: String,
pub created_at: chrono::DateTime<chrono::Utc>,
diff --git a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
index f8e42d92b3..2dad04e578 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs
@@ -9,6 +9,8 @@ use axum::extract::Json;
use axum::{extract::State, http::StatusCode};
use axum_extra::extract::Cached;
use comms_db_client::participants::add_participant::{AddParticipantOptions, add_participant};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::comms::{ChannelType, ParticipantRole};
use model::document_storage_service_internal::UpdateUserChannelPermissionsRequest;
use model_notifications::CommonChannelMetadata;
@@ -102,7 +104,9 @@ pub async fn handler(
comms_notification::dispatch_notifications_for_invite(
&ctx,
&channel_id,
- channel_admin.context.user_id.as_str(),
+ &MacroUserIdStr::parse_from_str(&channel_admin.context.user_id)
+ .map_err(|_e| (StatusCode::BAD_REQUEST, "Invalid macro user id".to_string()))?
+ .into_owned(),
req.participants.clone(),
metadata.clone(),
)
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
index 8aee4a9d11..9863419fce 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channel_transcript.rs
@@ -41,7 +41,7 @@ pub async fn get_channel_transcript(
InsightContextLog {
name: "message".to_string(),
metadata: vec![
- ("sender_id".to_string(), msg.sender_id.clone()),
+ ("sender_id".to_string(), msg.sender_id.to_string()),
("created_at".to_string(), msg.created_at.to_rfc3339()),
],
content: msg.content.clone(),
diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rs
index 8ca88c893b..9e59c1790b 100644
--- a/rust/cloud-storage/comms_service/src/notification.rs
+++ b/rust/cloud-storage/comms_service/src/notification.rs
@@ -4,6 +4,7 @@ use comms_db_client::{
model::{Message, SimpleMention},
participants::get_participants::get_channel_participants_for_thread_id,
};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{comms::ChannelParticipant, document_storage_service_internal::DocumentMetadata};
use model_entity::EntityType;
use model_notifications::{
@@ -27,7 +28,7 @@ pub struct ChannelMessageEvent<'a> {
pub struct ChannelInviteEvent<'a> {
channel_id: &'a Uuid,
- invited_by_user_id: &'a str,
+ invited_by_user_id: &'a MacroUserIdStr<'static>,
recipient_user_ids: &'a [String],
common: &'a CommonChannelMetadata,
}
@@ -46,13 +47,13 @@ fn recipients_excluding<'a>(
fn create_notification_queue_message(
channel_id: &Uuid,
- sender_id: &str,
+ sender_id: MacroUserIdStr<'static>,
recipients: &[String],
notification_event: NotificationEvent,
) -> NotificationQueueMessage {
NotificationQueueMessage {
notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),
- sender_id: Some(sender_id.to_string()),
+ sender_id: Some(sender_id),
recipient_ids: Some(recipients.to_vec()),
notification_event,
}
@@ -65,13 +66,13 @@ impl<'a> ChannelInviteEvent<'a> {
if !self.recipient_user_ids.is_empty() {
notifications.push(create_notification_queue_message(
self.channel_id,
- self.invited_by_user_id,
+ self.invited_by_user_id.copied().into_owned(),
&recipients_excluding(
self.recipient_user_ids.iter().map(|m| m.as_str()),
- once(self.invited_by_user_id),
+ once(self.invited_by_user_id.as_ref()),
),
NotificationEvent::ChannelInvite(ChannelInviteMetadata {
- invited_by: self.invited_by_user_id.to_string(),
+ invited_by: self.invited_by_user_id.clone(),
common: self.common.clone(),
}),
));
@@ -88,10 +89,10 @@ impl ChannelMessageEvent<'_> {
if !self.user_mentions.is_empty() {
notifications.push(create_notification_queue_message(
self.channel_id,
- &self.message.sender_id,
+ self.message.sender_id.clone(),
&recipients_excluding(
self.user_mentions.iter().map(|m| m.as_str()),
- once(self.message.sender_id.as_str()),
+ once(self.message.sender_id.0.as_ref()),
),
NotificationEvent::ChannelMention(ChannelMentionMetadata {
message_content: self.message.content.clone(),
@@ -105,13 +106,13 @@ impl ChannelMessageEvent<'_> {
if !self.document_mentions.is_empty() {
let recipients_excluding_mentions = recipients_excluding(
self.participants.iter().map(|p| p.user_id.as_str()),
- once(self.message.sender_id.as_str()),
+ once(self.message.sender_id.0.as_ref()),
);
for mention in self.document_mentions {
notifications.push(create_notification_queue_message(
self.channel_id,
- &self.message.sender_id,
+ self.message.sender_id.clone(),
&recipients_excluding_mentions,
NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(
DocumentMentionMetadata {
@@ -125,9 +126,8 @@ impl ChannelMessageEvent<'_> {
}
}
- let sender_and_mentions = once(&self.message.sender_id)
- .chain(self.user_mentions)
- .map(String::as_str)
+ let sender_and_mentions = once(self.message.sender_id.0.as_ref())
+ .chain(self.user_mentions.iter().map(String::as_str))
.collect::<Vec<&str>>();
// MessageSend and Invite notifications are sent to all participants except the sender and
@@ -143,7 +143,7 @@ impl ChannelMessageEvent<'_> {
if !self.thread_participants.is_empty() {
notifications.push(create_notification_queue_message(
self.channel_id,
- &self.message.sender_id,
+ self.message.sender_id.clone(),
&recipients_excluding(
self.thread_participants.iter().map(|p| p.as_str()),
sender_and_mentions,
@@ -164,7 +164,7 @@ impl ChannelMessageEvent<'_> {
(0, None) => {
notifications.push(create_notification_queue_message(
self.channel_id,
- &self.message.sender_id,
+ self.message.sender_id.clone(),
&recipients_without_sender_and_mentions,
NotificationEvent::ChannelInvite(ChannelInviteMetadata {
invited_by: self.message.sender_id.clone(),
@@ -176,11 +176,11 @@ impl ChannelMessageEvent<'_> {
(_, None) => {
notifications.push(create_notification_queue_message(
self.channel_id,
- &self.message.sender_id,
+ self.message.sender_id.clone(),
&recipients_without_sender_and_mentions,
NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {
message_id: self.message.id.to_string(),
- sender: self.message.sender_id.to_string(),
+ sender: self.message.sender_id.clone(),
message_content: self.message.content.to_string(),
common: self.channel_metadata.clone(),
}),
@@ -195,7 +195,7 @@ impl ChannelMessageEvent<'_> {
pub async fn dispatch_notifications_for_invite(
api_context: &AppState,
channel_id: &Uuid,
- invited_by_user_id: &str,
+ invited_by_user_id: &MacroUserIdStr<'static>,
recipient_user_ids: Vec<String>,
common: CommonChannelMetadata,
) -> anyhow::Result<()> {
@@ -301,10 +301,14 @@ mod tests {
}
}
- fn message(channel_id: Uuid, sender_id: &str, thread_id: Option<Uuid>) -> Message {
+ fn message(
+ channel_id: Uuid,
+ sender_id: MacroUserIdStr<'static>,
+ thread_id: Option<Uuid>,
+ ) -> Message {
Message {
id: Uuid::new_v4(),
- sender_id: sender_id.to_string(),
+ sender_id,
content: "test".to_string(),
thread_id,
channel_id,
@@ -318,7 +322,9 @@ mod tests {
fn doc_metadata(name: &str) -> DocumentMetadata {
DocumentMetadata {
item_name: name.to_string(),
- item_owner: "owner".to_string(),
+ item_owner: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
file_type: Some("pdf".to_string()),
item_id: "id".to_string(),
}
@@ -370,11 +376,17 @@ mod tests {
fn sender_excluded_from_all_recipients() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
- participant("bob", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
- let msg = message(channel_id, "sender", None);
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ None,
+ );
let metadata = private_metadata();
let event = ChannelMessageEvent {
@@ -408,7 +420,13 @@ mod tests {
participant("sender", channel_id),
participant("alice", channel_id),
];
- let msg = message(channel_id, "sender", None);
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ None,
+ );
let metadata = private_metadata();
let event = ChannelMessageEvent {
@@ -439,7 +457,13 @@ mod tests {
participant("sender", channel_id),
participant("alice", channel_id),
];
- let msg = message(channel_id, "sender", None);
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ None,
+ );
let metadata = private_metadata();
let event = ChannelMessageEvent {
@@ -471,7 +495,13 @@ mod tests {
participant("alice", channel_id),
participant("bob", channel_id),
];
- let msg = message(channel_id, "sender", None);
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ None,
+ );
let metadata = private_metadata();
let user_mentions = vec!["alice".to_string()];
@@ -517,19 +547,25 @@ mod tests {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
- participant("bob", channel_id),
- participant("charlie", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
- let msg = message(channel_id, "sender", Some(thread_id));
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ Some(thread_id),
+ );
let metadata = private_metadata();
- let user_mentions = vec!["alice".to_string()];
+ let user_mentions = vec!["macro|[email protected]".to_string()];
let thread_participants = vec![
- "sender".to_string(),
- "alice".to_string(),
- "bob".to_string(),
- "charlie".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
];
let event = ChannelMessageEvent {
@@ -557,21 +593,27 @@ mod tests {
.expect("should have reply notification");
let recipients = reply.recipient_ids.as_ref().unwrap();
- assert!(!recipients.contains(&"sender".to_string()));
- assert!(!recipients.contains(&"alice".to_string()));
- assert!(recipients.contains(&"bob".to_string()));
- assert!(recipients.contains(&"charlie".to_string()));
+ assert!(!recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(!recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(recipients.contains(&"macro|[email protected]".to_string()));
}
#[test]
fn document_mentions_exclude_sender() {
let channel_id = Uuid::new_v4();
let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
- participant("bob", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
+ participant("macro|[email protected]", channel_id),
];
- let msg = message(channel_id, "sender", None);
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ None,
+ );
let metadata = private_metadata();
let doc_mentions = vec![doc_metadata("test.pdf")];
@@ -600,9 +642,9 @@ mod tests {
.expect("should have document notification");
let recipients = doc_notif.recipient_ids.as_ref().unwrap();
- assert!(!recipients.contains(&"sender".to_string()));
- assert!(recipients.contains(&"alice".to_string()));
- assert!(recipients.contains(&"bob".to_string()));
+ assert!(!recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(recipients.contains(&"macro|[email protected]".to_string()));
+ assert!(recipients.contains(&"macro|[email protected]".to_string()));
}
#[test]
@@ -613,7 +655,13 @@ mod tests {
participant("sender", channel_id),
participant("alice", channel_id),
];
- let msg = message(channel_id, "sender", Some(thread_id));
+ let msg = message(
+ channel_id,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ Some(thread_id),
+ );
let metadata = private_metadata();
let event = ChannelMessageEvent {
diff --git a/rust/cloud-storage/delete_document_worker/src/process/handle.rs b/rust/cloud-storage/delete_document_worker/src/process/handle.rs
index c013c9303e..3ec9192897 100644
--- a/rust/cloud-storage/delete_document_worker/src/process/handle.rs
+++ b/rust/cloud-storage/delete_document_worker/src/process/handle.rs
@@ -35,7 +35,7 @@ pub async fn handle(
)?;
let shared_document = document.clone();
- user_id = Some(shared_document.owner);
+ user_id = Some(shared_document.owner.to_string());
tracing::trace!(document_id=%document_id, user_id=?user_id, file_type=?document.file_type, "retrieved document");
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs
index e91e6e2ee4..11c7ae3cac 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs
@@ -6,13 +6,13 @@ use macro_db_client::dcs::copy_messages::copy_messages;
use macro_db_client::dcs::create_chat::create_chat_v2;
use axum::{
- Extension, Json,
+ Json,
extract::{self, Path, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;
-use model::{response::StringIDResponse, user::UserContext};
+use model::{response::StringIDResponse, user::axum_extractor::MacroUserExtractor};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -37,7 +37,7 @@ pub struct Params {
pub async fn copy_chat_handler(
_access: ChatAccessLevelExtractor<ViewAccessLevel>,
State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(Params { chat_id }): Path<Params>,
extract::Json(req): extract::Json<CopyChatRequest>,
) -> Result<Response, Response> {
@@ -48,17 +48,17 @@ pub async fn copy_chat_handler(
Ok((StatusCode::OK, Json(string_id_response)).into_response())
}
-#[tracing::instrument(skip(state, user_context, req), fields(user_id=?user_context.user_id, chat_id))]
+#[tracing::instrument(skip(state, user_context, req), fields(user_id=?user_context.macro_user_id, chat_id))]
pub async fn copy_chat_v2(
state: &ApiContext,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
chat_id: String,
req: CopyChatRequest,
) -> Result<StringIDResponse, (StatusCode, String)> {
// 1. create share permission
let share_permission = SharePermissionV2::new_chat_share_permission();
// 2. create new chat
- let old_chat = get_chat(state, &chat_id, &user_context.user_id)
+ let old_chat = get_chat(state, &chat_id, &user_context.user_context.user_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get chat");
@@ -83,7 +83,7 @@ pub async fn copy_chat_v2(
)
})?;
- if !project.user_id.eq(&user_context.user_id) {
+ if !project.user_id.eq(&user_context.macro_user_id) {
None
} else {
Some(project.id)
@@ -95,7 +95,7 @@ pub async fn copy_chat_v2(
let model = old_chat.model.unwrap_or(FALLBACK_MODEL);
let chat_id = create_chat_v2(
&state.db,
- user_context.user_id.as_str(),
+ user_context.macro_user_id,
req.name.as_str(),
model,
project_id.as_deref(),
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs
index 12754ef9e4..371c1f6c25 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs
@@ -13,7 +13,7 @@ use crate::{
use anyhow::Context;
use axum::{
Json,
- extract::{Extension, State},
+ extract::State,
http::StatusCode,
response::{IntoResponse, Response},
};
@@ -21,8 +21,8 @@ use macro_db_client::dcs::create_chat;
use macro_middleware::cloud_storage::ensure_access::{
get_users_access_level_v2, project::ProjectBodyAccessLevelExtractor,
};
-use model::chat::NewChatAttachment;
-use model::{chat::AttachmentType, response::StringIDResponse, user::UserContext};
+use model::{chat::AttachmentType, response::StringIDResponse};
+use model::{chat::NewChatAttachment, user::axum_extractor::MacroUserExtractor};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::EditAccessLevel;
use sqs_client::search::SearchQueueMessage;
@@ -38,10 +38,10 @@ use tracing::Instrument;
(status = 500, body=String),
)
)]
-#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(state, user_context), fields(user_id=%user_context.macro_user_id))]
pub(in crate::api) async fn create_chat_handler(
State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateChatRequest>,
) -> Result<Response, Response> {
let req = project.into_inner();
@@ -51,7 +51,7 @@ pub(in crate::api) async fn create_chat_handler(
get_users_access_level_v2(
&state.db,
&state.comms_service_client,
- &user_context.user_id,
+ user_context.macro_user_id.as_ref(),
&attachment.attachment_id,
"document",
)
@@ -59,7 +59,7 @@ pub(in crate::api) async fn create_chat_handler(
.map_err(|err| {
tracing::error!(
error = ?err,
- user_id = %user_context.user_id,
+ user_id = %user_context.macro_user_id,
attachment_id = %attachment.attachment_id,
"failed to verify document access"
);
@@ -71,7 +71,7 @@ pub(in crate::api) async fn create_chat_handler(
})?
.ok_or_else(|| {
tracing::error!(
- user_id = %user_context.user_id,
+ user_id = %user_context.macro_user_id,
attachment_id = %attachment.attachment_id,
"user has no access to document"
);
@@ -94,7 +94,7 @@ pub(in crate::api) async fn create_chat_handler(
#[tracing::instrument(
skip(ctx, user_context, req),
fields(
- user_id = %user_context.user_id,
+ user_id = %user_context.macro_user_id,
project_id = ?req.project_id,
model = ?req.model,
attachment_count = req.attachments.as_ref().map(|a| a.len()).unwrap_or(0),
@@ -102,7 +102,7 @@ pub(in crate::api) async fn create_chat_handler(
)]
pub async fn create_user_chat_v2(
ctx: &ApiContext,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
req: CreateChatRequest,
) -> Result<StringIDResponse, (StatusCode, String)> {
let chat_name = req.name.unwrap_or(DEFAULT_CHAT_NAME.to_string());
@@ -141,7 +141,7 @@ pub async fn create_user_chat_v2(
let chat = create_chat::create_chat_v2(
&ctx.db,
- &user_context.user_id,
+ user_context.macro_user_id.clone(),
&chat_name,
req.model.unwrap_or(FALLBACK_MODEL),
req.project_id.as_deref(),
@@ -174,7 +174,7 @@ pub async fn create_user_chat_v2(
macro_project_utils::ProjectModifiedArgs {
project_id: req.project_id.clone(),
old_project_id: None,
- user_id: user_context.user_id.clone(),
+ user_id: user_context.macro_user_id.to_string(),
},
)
.await;
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index fe5448613d..c9dc196e91 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -74,12 +74,13 @@ mockall = { workspace = true }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
+model_user = { path = "../model_user", features = ["axum"] }
models_bulk_upload = { path = "../models_bulk_upload" }
models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
-properties = { path = "../properties" }
models_soup = { path = "../models_soup", features = ["schema"] }
+properties = { path = "../properties" }
rayon = "1.10.0"
redis = { workspace = true, features = [
"aio",
diff --git a/rust/cloud-storage/document_storage_service/src/api/channel/update_channel_share_permission.rs b/rust/cloud-storage/document_storage_service/src/api/channel/update_channel_share_permission.rs
index 0fe115fcf3..977f4187ba 100644
--- a/rust/cloud-storage/document_storage_service/src/api/channel/update_channel_share_permission.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/channel/update_channel_share_permission.rs
@@ -48,7 +48,7 @@ pub async fn handler(
let user_access_level = get_users_access_level_v2(
&ctx.db,
&ctx.comms_service_client,
- &req.user_id,
+ req.user_id.0.as_ref(),
&req.item_id,
&req.item_type,
)
@@ -145,7 +145,7 @@ pub async fn handler(
.into_response()
})?
.into_iter()
- .filter(|p| p.user_id != req.user_id && p.left_at.is_none())
+ .filter(|p| p.user_id != req.user_id.0.as_ref() && p.left_at.is_none())
.map(|p| p.user_id)
.collect::<Vec<_>>();
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
index 98505ecf29..859cc480df 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
@@ -2,6 +2,8 @@ use crate::api::context::ApiContext;
use axum::{http::StatusCode, response::Response};
use document_sub_type::DocumentSubType;
use macro_db_client::history::upsert_user_history;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::{DocumentResponse, DocumentResponseMetadata};
use model::{document::FileTypeExt, sync_service::SyncServiceVersionID};
use model::{
@@ -17,7 +19,7 @@ use system_properties::SystemPropertiesService;
#[tracing::instrument(skip(ctx))]
pub async fn copy_document<'a>(
ctx: &'a ApiContext,
- user_id: &'a str,
+ user_id: MacroUserIdStr<'static>,
original_document_metadata: &'a DocumentMetadata,
updated_document_name: &'a str,
file_type: Option<&'a FileType>,
@@ -29,7 +31,7 @@ pub async fn copy_document<'a>(
let updated_document_metadata = match macro_db_client::document::v2::copy::copy_document(
&ctx.db,
original_document_metadata,
- user_id,
+ user_id.clone(),
updated_document_name,
file_type,
&share_permission,
@@ -70,7 +72,7 @@ pub async fn copy_document<'a>(
// Since we now store a pdf version of docx files (when the conversion is successful)
// we need to also copy this over into the new dss file
- let url_encoded_owner = urlencoding::encode(&original_document_metadata.owner);
+ let url_encoded_owner = urlencoding::encode(original_document_metadata.owner.as_ref());
// Get the source document key
let source_key = format!(
"{}/{}/{}.pdf",
@@ -131,7 +133,7 @@ pub async fn copy_document<'a>(
})?
.0;
- let url_encoded_owner = urlencoding::encode(&original_document_metadata.owner);
+ let url_encoded_owner = urlencoding::encode(original_document_metadata.owner.as_ref());
let file_type_str = file_type.map(|s| s.as_str());
// Get the source document key
@@ -143,7 +145,7 @@ pub async fn copy_document<'a>(
);
let dest_key = build_cloud_storage_bucket_document_key(
- user_id,
+ user_id.as_ref(),
&updated_document_metadata.document_id,
updated_document_metadata.document_version_id,
file_type_str,
@@ -209,7 +211,7 @@ pub async fn copy_document<'a>(
.0
};
- let url_encoded_owner = urlencoding::encode(&original_document_metadata.owner);
+ let url_encoded_owner = urlencoding::encode(original_document_metadata.owner.as_ref());
let file_type_str = file_type.map(|s| s.as_str());
// Get the source document key
@@ -221,7 +223,7 @@ pub async fn copy_document<'a>(
);
let dest_key = build_cloud_storage_bucket_document_key(
- user_id,
+ user_id.as_ref(),
&updated_document_metadata.document_id,
updated_document_metadata.document_version_id,
file_type_str,
@@ -270,7 +272,7 @@ pub async fn copy_document<'a>(
};
if let Err(e) = upsert_user_history(
&mut transaction,
- user_id,
+ user_id.copied(),
&updated_document_metadata.document_id,
"document",
)
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs
index 8afc3624a1..deba32c0b3 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs
@@ -19,7 +19,7 @@ use model::{
DocumentBasic, DocumentMetadata, FileType, FileTypeExt, response::GetDocumentResponse,
},
response::{ErrorResponse, GenericErrorResponse, GenericResponse},
- user::UserContext,
+ user::axum_extractor::MacroUserExtractor,
};
use models_permissions::share_permission::access_level::ViewAccessLevel;
@@ -52,11 +52,11 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user_context, document_context, req, _access), fields(user_id=?user_context.user_id, document_version_id=?params.version_id))]
+#[tracing::instrument(skip(state, user_context, document_context, req, _access), fields(user_id=%user_context.macro_user_id, document_version_id=?params.version_id))]
pub(in crate::api) async fn copy_document_handler(
_access: DocumentAccessExtractor<ViewAccessLevel>,
State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
document_context: Extension<DocumentBasic>,
Path(Params { document_id }): Path<Params>,
Query(params): Query<CopyDocumentQueryParams>,
@@ -121,7 +121,7 @@ pub(in crate::api) async fn copy_document_handler(
.send(StatusCode::INTERNAL_SERVER_ERROR)
})?;
- if !project.user_id.eq(&user_context.user_id) {
+ if !project.user_id.eq(&user_context.macro_user_id) {
// Do not copy the project id of the document
document_metadata.project_id = None;
document_metadata.project_name = None;
@@ -144,7 +144,7 @@ pub(in crate::api) async fn copy_document_handler(
match copy_document_v2::copy_document(
&state,
- user_context.user_id.as_str(),
+ user_context.macro_user_id.clone(),
&document_metadata,
&req.document_name,
file_type.as_ref(),
@@ -161,7 +161,7 @@ pub(in crate::api) async fn copy_document_handler(
copy_document_cleanup::copy_document_cleanup(
&state.db,
&state.s3_client,
- user_context.user_id.clone(),
+ user_context.macro_user_id.to_string(),
document_id,
)
.await;
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs
index 737f21dee6..7cfb5705e1 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs
@@ -1,13 +1,3 @@
-use std::str::FromStr;
-
-use axum::{Extension, extract::State, http::StatusCode, response::IntoResponse};
-use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;
-use models_opensearch::SearchEntityType;
-use models_permissions::share_permission::access_level::EditAccessLevel;
-use sqs_client::search::SearchQueueMessage;
-use sqs_client::search::name::EntityName;
-use tracing::Instrument;
-
use crate::api::middleware::internal_access::InternalUser;
use crate::api::{
context::ApiContext,
@@ -16,13 +6,21 @@ use crate::api::{
utils::{self},
},
};
+use axum::{Extension, extract::State, http::StatusCode, response::IntoResponse};
+use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;
use model::document::FileTypeExt;
use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};
use model::{
document::FileType,
response::{GenericErrorResponse, GenericResponse},
- user::UserContext,
};
+use model_user::axum_extractor::MacroUserExtractor;
+use models_opensearch::SearchEntityType;
+use models_permissions::share_permission::access_level::EditAccessLevel;
+use sqs_client::search::SearchQueueMessage;
+use sqs_client::search::name::EntityName;
+use std::str::FromStr;
+use tracing::Instrument;
/// Handles creating a document
#[utoipa::path(
@@ -38,12 +36,12 @@ use model::{
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]
#[axum::debug_handler(state = ApiContext)]
pub(in crate::api) async fn create_document_handler(
State(state): State<ApiContext>,
internal_user: Option<Extension<InternalUser>>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateDocumentRequest>,
) -> impl IntoResponse {
let req = project.into_inner();
@@ -93,7 +91,7 @@ pub(in crate::api) async fn create_document_handler(
id: req.id.as_deref(),
sha: &req.sha,
document_name: &document_name,
- owner: &user_context.user_id,
+ owner: user_context.macro_user_id,
file_type,
job_id: req.job_id.as_deref(),
project_id: req.project_id.as_deref(),
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
index 1d0bd52f93..4820a8c4d8 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
@@ -2,6 +2,8 @@ use crate::api::context::ApiContext;
use axum::http::StatusCode;
use chrono::{DateTime, Utc};
use document_sub_type::DocumentSubType;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::CreateDocumentResponseData;
use model::document::response::{DocumentResponse, DocumentResponseMetadata};
use model::document::{ContentType, FileType, build_cloud_storage_bucket_document_key};
@@ -14,7 +16,7 @@ pub struct CreateDocumentParams<'a> {
pub id: Option<&'a str>,
pub sha: &'a str,
pub document_name: &'a str,
- pub owner: &'a str,
+ pub owner: MacroUserIdStr<'a>,
pub file_type: Option<FileType>,
pub job_id: Option<&'a str>,
pub project_id: Option<&'a str>,
@@ -45,6 +47,8 @@ pub async fn create_document(
is_task,
} = params;
+ let owner = owner.into_owned();
+
tracing::trace!("creating document v2");
let share_permission = SharePermissionV2::new_document_share_permission(file_type);
@@ -56,7 +60,7 @@ pub async fn create_document(
id,
sha,
document_name,
- user_id: owner,
+ user_id: owner.clone(),
file_type,
project_id,
project_name: None,
@@ -105,7 +109,7 @@ pub async fn create_document(
}
let key = build_cloud_storage_bucket_document_key(
- &document_metadata.owner,
+ document_metadata.owner.as_ref(),
&document_metadata.document_id,
document_metadata.document_version_id,
file_type.as_ref().map(|s| s.as_str()),
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
index f735858e01..0d54364cdc 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
@@ -188,7 +188,7 @@ pub async fn permanently_delete_document_handler(
// Queue document for deletion
state
.sqs_client
- .enqueue_document_delete(document_context.owner.as_str(), &document_id)
+ .enqueue_document_delete(document_context.owner.as_ref(), &document_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "unable to enqueue document delete");
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
index a5eeb6c23b..5283ceec2a 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/export_document.rs
@@ -85,7 +85,7 @@ pub async fn handler(
_ => {
export_basic_document(
&state,
- &document_context.owner,
+ document_context.owner.as_ref(),
&document_context.document_id,
file_type,
)
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
index 960a304b22..6415bebc20 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/get_document_key.rs
@@ -77,7 +77,7 @@ pub async fn get_document_key_handler(
};
build_cloud_storage_bucket_document_key(
- &document_context.owner,
+ document_context.owner.as_ref(),
&document_id,
document_version_id,
Some(file_type.as_str()),
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs b/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
index e682ed4a66..132fc34edb 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/initialize_user_documents.rs
@@ -1,15 +1,15 @@
use crate::api::context::ApiContext;
use axum::{
- Extension,
extract::State,
response::{IntoResponse, Json, Response},
};
use futures::StreamExt;
+use macro_user_id::cowlike::CowLike;
use model::{
document::{BasicDocument, build_cloud_storage_bucket_document_key},
response::{ErrorResponse, GenericErrorResponse, GenericSuccessResponse},
- user::UserContext,
};
+use model_user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::SharePermissionV2;
use reqwest::StatusCode;
@@ -31,14 +31,13 @@ const CANVAS_TEMPLATE: &str = include_str!("./template/canvas_template.canvas");
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(state, user_context), fields(user_id=?user_context.macro_user_id))]
pub async fn handler(
State(state): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
) -> Result<Response, Response> {
tracing::info!("initialize user documents");
let start_time = std::time::Instant::now();
- let user_id = user_context.user_id.as_str();
tracing::debug!("initializing user documents");
// Contains all documents that will be referenced in the markdown file
@@ -81,7 +80,7 @@ pub async fn handler(
let project =
macro_db_client::document::initialize_onboarding_documents::create_project_transaction(
&mut transaction,
- user_id,
+ user_context.macro_user_id.copied(),
PROJECT_NAME,
None,
&share_permission,
@@ -104,7 +103,7 @@ pub async fn handler(
let db_documents =
macro_db_client::document::initialize_onboarding_documents::create_onboarding_documents(
&mut transaction,
- user_id,
+ user_context.macro_user_id.clone(),
&project.id,
&share_permission,
documents,
@@ -159,6 +158,7 @@ pub async fn handler(
let s3_client = shared_s3_client.clone(); // Clone the client for parallel usage
let markdown_template = shared_markdown_template.clone();
let canvas_template = shared_canvas_template.clone();
+ let user_id = user_context.macro_user_id.clone();
async move {
let uri_document_name = urlencoding::encode(document.document_name.as_str());
let deref_file_type = document.file_type.as_deref();
@@ -169,7 +169,7 @@ pub async fn handler(
};
let target_key = build_cloud_storage_bucket_document_key(
- user_id,
+ user_id.as_ref(),
&document.document_id,
document.document_version_id,
deref_file_type,
@@ -215,18 +215,21 @@ pub async fn handler(
tracing::trace!(elapsed_time=?start_time.elapsed(), "copied documents");
// Set the onboarding status to true so we don't do this again
- macro_db_client::user::onboarding_status::set_onboarding_status(&mut transaction, user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to set onboarding status");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to set onboarding status",
- }),
- )
- .into_response()
- })?;
+ macro_db_client::user::onboarding_status::set_onboarding_status(
+ &mut transaction,
+ user_context.macro_user_id.as_ref(),
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to set onboarding status");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "failed to set onboarding status",
+ }),
+ )
+ .into_response()
+ })?;
transaction.commit().await.map_err(|e| {
tracing::error!(error=?e, "failed to commit transaction");
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
index 37f90d2dc0..a285750ec8 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/location.rs
@@ -154,7 +154,7 @@ pub async fn get_location_handler_v3(
let response_data = get_presigned_url_by_type(
&state,
- &document_context.owner,
+ document_context.owner.as_ref(),
&document_id,
file_type,
params.document_version_id,
@@ -208,7 +208,7 @@ pub async fn get_location_handler(
let response_data = get_presigned_url_by_type(
&state,
- &document_context.owner,
+ document_context.owner.as_ref(),
&document_id,
file_type,
params.document_version_id,
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
index 190c8c4026..67cc851b20 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
@@ -161,7 +161,7 @@ pub async fn save_document_handler(
// If the document is a monaco file, we will need to generate a presigned url to save the file
let presigned_url: Option<String> = if file_type == FileType::Py || file_type == FileType::Js {
let key = build_cloud_storage_bucket_document_key(
- &document_metadata.owner,
+ document_metadata.owner.as_ref(),
&document_metadata.document_id,
document_metadata.document_version_id,
Some(file_type.as_str()),
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
index d3a3023e76..3d4af964c3 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
@@ -115,7 +115,7 @@ pub async fn handler(
};
let key = build_cloud_storage_bucket_document_key(
- &document.owner,
+ document.owner.as_ref(),
&document.document_id,
document.document_version_id,
Some(file_type.as_str()),
diff --git a/rust/cloud-storage/document_storage_service/src/api/history/upsert_history.rs b/rust/cloud-storage/document_storage_service/src/api/history/upsert_history.rs
index 017385a168..923a75950f 100644
--- a/rust/cloud-storage/document_storage_service/src/api/history/upsert_history.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/history/upsert_history.rs
@@ -2,6 +2,7 @@ use crate::api::context::ApiContext;
use axum::extract::State;
use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};
use macro_middleware::cloud_storage::ensure_access::history::HistoryAccessExtractor;
+use macro_user_id::user_id::MacroUserIdStr;
use model::response::{
GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,
};
@@ -76,13 +77,20 @@ pub async fn upsert_history_handler(
// If a user id is present in the UserContext, add the item to the user's history
if !user_id.is_empty()
- && let Err(e) = macro_db_client::history::upsert_user_history(
- &mut transaction,
- &user_context.user_id,
- item_id.as_str(),
- item_type.as_str(),
- )
- .await
+ && let Err(e) = {
+ match MacroUserIdStr::parse_from_str(&user_context.user_id) {
+ Ok(id) => {
+ macro_db_client::history::upsert_user_history(
+ &mut transaction,
+ id,
+ item_id.as_str(),
+ item_type.as_str(),
+ )
+ .await
+ }
+ Err(e) => Err(anyhow::Error::from(e)),
+ }
+ }
{
tracing::error!(error=?e, "unable to upsert history");
return GenericResponse::builder()
diff --git a/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs b/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
index 39aab6d591..74afaef7d8 100644
--- a/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/instructions/create_instructions.rs
@@ -1,12 +1,10 @@
use crate::{
api::context::ApiContext, model::response::instructions::CreateInstructionsDocumentResponse,
};
-use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
+use axum::{Json, extract::State, http::StatusCode, response::IntoResponse};
use macro_db_client::instructions::create::CreateInstructionsError;
-use model::{
- response::{GenericErrorResponse, GenericResponse},
- user::UserContext,
-};
+use model::response::{GenericErrorResponse, GenericResponse};
+use model_user::axum_extractor::MacroUserExtractor;
/// Creates an instructions document for the current user
#[utoipa::path(
@@ -19,15 +17,15 @@ use model::{
(status = 500, body = GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.macro_user_id))]
pub async fn create_instructions_handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
) -> impl IntoResponse {
// Create the instructions document - database handles uniqueness constraint
match macro_db_client::instructions::create::create_instructions_document(
&ctx.db,
- &user_context.user_id,
+ user_context.macro_user_id.clone(),
)
.await
{
@@ -40,7 +38,7 @@ pub async fn create_instructions_handler(
.is_error(true)
.send(StatusCode::CONFLICT),
Err(CreateInstructionsError::DatabaseError(err)) => {
- tracing::error!(error=?err, user_id=?user_context.user_id, "failed to create instructions document");
+ tracing::error!(error=?err, user_id=%user_context.macro_user_id, "failed to create instructions document");
GenericResponse::builder()
.message("Failed to create instructions document")
.is_error(true)
diff --git a/rust/cloud-storage/document_storage_service/src/api/instructions/get_instructions.rs b/rust/cloud-storage/document_storage_service/src/api/instructions/get_instructions.rs
index ffda8df554..62a11d7b2d 100644
--- a/rust/cloud-storage/document_storage_service/src/api/instructions/get_instructions.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/instructions/get_instructions.rs
@@ -1,10 +1,11 @@
use crate::{
api::context::ApiContext, model::response::instructions::GetInstructionsDocumentResponse,
};
-use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
+use axum::{Json, extract::State, http::StatusCode, response::IntoResponse};
+use macro_user_id::cowlike::CowLike;
use model::{
response::{GenericErrorResponse, GenericResponse},
- user::UserContext,
+ user::axum_extractor::MacroUserExtractor,
};
/// Gets the instructions document for the current user
@@ -18,14 +19,14 @@ use model::{
(status = 500, body = GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.macro_user_id))]
pub async fn get_instructions_handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
) -> impl IntoResponse {
match macro_db_client::instructions::get::get_instructions_document(
&ctx.db,
- &user_context.user_id,
+ user_context.macro_user_id.copied(),
)
.await
{
@@ -38,7 +39,7 @@ pub async fn get_instructions_handler(
.is_error(true)
.send(StatusCode::NOT_FOUND),
Err(err) => {
- tracing::error!(error=?err, user_id=?user_context.user_id, "failed to get instructions document");
+ tracing::error!(error=?err, user_id=%user_context.macro_user_id, "failed to get instructions document");
GenericResponse::builder()
.message("Failed to get instructions document")
.is_error(true)
diff --git a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs b/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
index 12aef76881..2c875910e0 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
@@ -8,6 +8,7 @@ use axum::{
response::IntoResponse,
};
use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::user::UserContext;
use model::{
document::DocumentBasic,
@@ -54,16 +55,24 @@ pub async fn handler(
if !req.mentions.is_empty() {
let metadata = DocumentMentionMetadata {
- document_name: document_context.document_name.clone(),
- owner: document_context.owner.clone(),
- file_type: document_context.file_type.clone(),
+ document_name: document_context.0.document_name,
+ owner: document_context.0.owner,
+ file_type: document_context.0.file_type,
metadata: req.metadata,
};
+ let Ok(sender_id) =
+ MacroUserIdStr::parse_from_str(&user_context.user_id).map(CowLike::into_owned)
+ else {
+ return GenericResponse::builder()
+ .message("invalid macro user id")
+ .is_error(true)
+ .send(StatusCode::BAD_REQUEST);
+ };
let notification_queue_message = NotificationQueueMessage {
notification_entity: EntityType::Document.with_entity_string(document_id),
notification_event: NotificationEvent::DocumentMention(metadata),
- sender_id: Some(user_context.user_id.clone()),
+ sender_id: Some(sender_id),
recipient_ids: Some(req.mentions.clone()),
};
diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs
index 54809400ac..9281bfcfba 100644
--- a/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/projects/create_project.rs
@@ -1,6 +1,5 @@
use crate::api::context::ApiContext;
use axum::{
- Extension,
extract::State,
http::StatusCode,
response::{IntoResponse, Json, Response},
@@ -9,7 +8,7 @@ use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLe
use model::{
project::{Project, request::CreateProjectRequest, response::CreateProjectResponse},
response::{GenericErrorResponse, GenericResponse},
- user::UserContext,
+ user::axum_extractor::MacroUserExtractor,
};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::EditAccessLevel;
@@ -29,10 +28,10 @@ use tracing::Instrument;
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, project), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context, project), fields(user_id=?user_context.macro_user_id))]
pub async fn create_project_handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateProjectRequest>,
) -> Result<Response, Response> {
let req = project.into_inner();
@@ -59,14 +58,14 @@ pub async fn create_project_handler(
async fn create_project_v2(
ctx: ApiContext,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
req: CreateProjectRequest,
) -> Result<Project, (StatusCode, String)> {
let share_permission = SharePermissionV2::new_project_share_permission();
let project = match macro_db_client::projects::create_project_v2(
ctx.db.clone(),
- &user_context.user_id,
+ user_context.macro_user_id.clone(),
&req.name,
req.project_parent_id.clone(),
&share_permission,
@@ -89,7 +88,7 @@ async fn create_project_v2(
macro_project_utils::ProjectModifiedArgs {
project_id: None,
old_project_id: Some(project_id.to_string()),
- user_id: user_context.user_id.clone(),
+ user_id: user_context.user_context.user_id.clone(),
},
)
.await;
@@ -99,7 +98,7 @@ async fn create_project_v2(
tokio::spawn({
let sqs_client = ctx.sqs_client.clone();
let project_id = project.id.clone();
- let macro_user_id = user_context.user_id.clone();
+ let macro_user_id = user_context.user_context.user_id.clone();
async move {
tracing::trace!("sending message to search extractor queue");
let _ = sqs_client
diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/get_project.rs b/rust/cloud-storage/document_storage_service/src/api/projects/get_project.rs
index 8850b485d7..cea0b4dead 100644
--- a/rust/cloud-storage/document_storage_service/src/api/projects/get_project.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/projects/get_project.rs
@@ -10,6 +10,7 @@ use model::project::response::{
};
use model::response::{ErrorResponse, GenericErrorResponse, GenericResponse};
use model::user::UserContext;
+use model::user::axum_extractor::MacroUserExtractor;
use models_permissions::share_permission::access_level::ViewAccessLevel;
use sqlx::PgPool;
@@ -33,17 +34,17 @@ pub struct Params {
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(db, user_context, id), fields(user_id=?user_context.user_id, project_id=?id))]
+#[tracing::instrument(skip(db, user_context, id), fields(user_id=?user_context.macro_user_id, project_id=?id))]
pub async fn get_project_content_handler(
ProjectAccessLevelExtractor { access_level, .. }: ProjectAccessLevelExtractor<ViewAccessLevel>,
State(db): State<PgPool>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
Path(Params { id }): Path<Params>,
) -> Result<Response, Response> {
let content = macro_db_client::projects::get_project::get_project_content_v2(
&db,
id.as_str(),
- user_context.user_id.as_str(),
+ user_context.macro_user_id,
access_level,
)
.await
diff --git a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
index fe5aaf9e96..d2b311e309 100644
--- a/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/projects/upload_folder.rs
@@ -1,5 +1,3 @@
-use std::{str::FromStr, sync::Arc};
-
use crate::{
api::context::{ApiContext, InternalFlag},
service::{self},
@@ -11,7 +9,7 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
-
+use macro_user_id::user_id::MacroUserIdStr;
use model::{
document::{
ContentType, DocumentMetadata, FileType, build_cloud_storage_bucket_document_key,
@@ -22,7 +20,7 @@ use model::{
UploadFolderResponseData, UploadFolderWithIdsResponse,
},
response::{GenericErrorResponse, GenericResponse, PresignedUrl, TypedSuccessResponse},
- user::UserContext,
+ user::{UserContext, axum_extractor::MacroUserExtractor},
};
use models_bulk_upload::{
MarkProjectUploadedRequest, MarkProjectUploadedResponse, S3ObjectInfo,
@@ -30,6 +28,7 @@ use models_bulk_upload::{
};
use models_permissions::share_permission::SharePermissionV2;
use sqlx::{Pool, Postgres};
+use std::{str::FromStr, sync::Arc};
use uuid::Uuid;
type UploadExtractFolderResponse = TypedSuccessResponse<UploadExtractFolderResponseData>;
@@ -120,19 +119,18 @@ pub async fn upload_extract_folder_handler(
(status = 500, body=GenericErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, req), fields(user_id=?user_context.user_id))]
+#[tracing::instrument(skip(ctx, user_context, req), fields(user_id=%user_context.macro_user_id))]
pub async fn upload_folder_handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ user_context: MacroUserExtractor,
internal_context: Option<Extension<InternalFlag>>,
extract::Json(req): extract::Json<UploadFolderRequest>,
) -> impl IntoResponse {
- let user_id = user_context.user_id.as_str();
let internal = internal_context.is_some_and(|state| state.internal);
upload_folder_handler_inner(
ctx.s3_client.clone(),
ctx.db.clone(),
- user_id,
+ user_context.macro_user_id,
internal,
req,
)
@@ -145,7 +143,7 @@ pub async fn upload_folder_handler(
async fn upload_folder_handler_inner(
s3_client: Arc<service::s3::S3>,
db: Pool<Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
internal: bool,
req: UploadFolderRequest,
) -> impl IntoResponse + use<> {
@@ -189,7 +187,7 @@ async fn upload_folder_handler_inner(
documents,
} = match macro_db_client::projects::upload_folder::upload_folder_with_ids(
&mut transaction,
- user_id,
+ user_id.clone(),
&share_permission,
root_folder,
&req.root_folder_name,
@@ -216,7 +214,7 @@ async fn upload_folder_handler_inner(
tracing::error!(error=?err, "error building s3 destination map");
cleanup(
db.clone(),
- user_id,
+ user_id.as_ref(),
&project_ids,
&documents
.iter()
@@ -237,7 +235,7 @@ async fn upload_folder_handler_inner(
tracing::error!(error=?e, "error committing transaction");
cleanup(
db.clone(),
- user_id,
+ user_id.as_ref(),
&project_ids,
&documents
.iter()
@@ -276,7 +274,7 @@ async fn build_documents(
let sha = document.sha.clone().context("document needs a sha")?;
if file_type != Some(FileType::Docx) {
let key = build_cloud_storage_bucket_document_key(
- &document.owner,
+ document.owner.as_ref(),
&document.document_id,
document.document_version_id,
file_type.as_ref().map(|s| s.as_str()),
@@ -318,7 +316,7 @@ async fn build_documents(
}
let key = build_docx_staging_bucket_document_key(
- &document.owner,
+ document.owner.as_ref(),
&document.document_id,
document.document_version_id,
);
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
index 4c9366d429..ed91744595 100644
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
+++ b/rust/cloud-storage/document_storage_service/src/bin/backfill_useritemaccess/document.rs
@@ -21,7 +21,7 @@ async fn process_single_document(
// Add row for the owner
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
- user_id: user_id.clone(),
+ user_id: user_id.to_string(),
item_id: document_id.clone(),
item_type: "document".to_string(),
access_level: AccessLevel::Owner,
@@ -54,7 +54,7 @@ async fn process_single_document(
})?;
for participant in participants {
- if participant.user_id != user_id {
+ if participant.user_id != user_id.as_ref() {
generated_items.push(UserItemAccess {
id: macro_uuid::generate_uuid_v7(),
user_id: participant.user_id,
diff --git a/rust/cloud-storage/email_service/src/api/internal/get_thread_owner.rs b/rust/cloud-storage/email_service/src/api/internal/get_thread_owner.rs
index 19fb9df3a2..b3e6653a69 100644
--- a/rust/cloud-storage/email_service/src/api/internal/get_thread_owner.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/get_thread_owner.rs
@@ -3,6 +3,8 @@ use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::response::ErrorResponse;
use models_email::service::thread::GetThreadOwnerResponse;
use uuid::Uuid;
@@ -33,6 +35,17 @@ pub async fn handler(
)
.into_response()
})?;
+ let user_id = MacroUserIdStr::parse_from_str(&user_id)
+ .map_err(|_e| {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "invalid macro user id",
+ }),
+ )
+ .into_response()
+ })?
+ .into_owned();
Ok((StatusCode::OK, Json(GetThreadOwnerResponse { user_id })).into_response())
}
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
index 304c8e8bfc..2965e4d317 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
@@ -570,9 +570,8 @@ async fn send_notifications(
.unwrap_or_else(|| contact.email.clone())
});
- let sender_id = sender_contact
- .and_then(|contact| MacroUserIdStr::try_from_email(&contact.email).ok())
- .map(|id| id.to_string());
+ let sender_id =
+ sender_contact.and_then(|contact| MacroUserIdStr::try_from_email(&contact.email).ok());
let notification_metadata = NewEmailMetadata {
sender,
diff --git a/rust/cloud-storage/macro_db_client/src/activity/get_recent_activities.rs b/rust/cloud-storage/macro_db_client/src/activity/get_recent_activities.rs
index 3d567ad810..2dbf2bdcc1 100644
--- a/rust/cloud-storage/macro_db_client/src/activity/get_recent_activities.rs
+++ b/rust/cloud-storage/macro_db_client/src/activity/get_recent_activities.rs
@@ -1,4 +1,5 @@
use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{activity::Activity, chat::Chat, document::BasicDocument};
use sqlx::{Pool, Postgres, Row};
@@ -135,7 +136,7 @@ pub async fn get_recent_activities(
let document_version_id: String = r.get("document_version_id");
Some(Activity::Document(BasicDocument {
document_id: id,
- owner: user_id,
+ owner: MacroUserIdStr::parse_from_str(&user_id).ok()?.into_owned(),
document_version_id: document_version_id.parse::<i64>().unwrap(),
document_name: name,
created_at,
diff --git a/rust/cloud-storage/macro_db_client/src/chat/mod.rs b/rust/cloud-storage/macro_db_client/src/chat/mod.rs
index e1135d0bff..7e262ccbbb 100644
--- a/rust/cloud-storage/macro_db_client/src/chat/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/chat/mod.rs
@@ -1,3 +1,4 @@
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::chat::ChatBasic;
use sqlx::{Pool, Postgres};
use std::collections::HashSet;
@@ -10,8 +11,7 @@ pub mod read;
pub mod revert_delete;
pub async fn get_basic_chat(db: &Pool<Postgres>, chat_id: &str) -> Result<ChatBasic, sqlx::Error> {
- let chat: ChatBasic = sqlx::query_as!(
- ChatBasic,
+ let chat: ChatBasic = sqlx::query!(
r#"
SELECT
c.id as "id",
@@ -26,6 +26,17 @@ pub async fn get_basic_chat(db: &Pool<Postgres>, chat_id: &str) -> Result<ChatBa
"#,
chat_id,
)
+ .try_map(|r| {
+ Ok(ChatBasic {
+ id: r.id,
+ name: r.name,
+ user_id: MacroUserIdStr::parse_from_str(&r.user_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ project_id: r.project_id,
+ deleted_at: r.deleted_at,
+ })
+ })
.fetch_one(db)
.await?;
diff --git a/rust/cloud-storage/macro_db_client/src/convert/mod.rs b/rust/cloud-storage/macro_db_client/src/convert/mod.rs
index 043115351a..0fec30dec8 100644
--- a/rust/cloud-storage/macro_db_client/src/convert/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/convert/mod.rs
@@ -1,3 +1,4 @@
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::DocumentMetadata;
/// Gets all docx files
@@ -76,23 +77,27 @@ pub async fn get_docx_files(
limit,
offset
)
- .map(|row| DocumentMetadata {
- document_id: row.document_id,
- document_version_id: row.document_version_id,
- owner: row.owner,
- document_name: row.document_name,
- file_type: row.file_type,
- created_at: row.created_at,
- updated_at: row.updated_at,
- document_bom: row.document_bom,
- project_id: row.project_id,
- project_name: row.project_name,
- sha: None,
- branched_from_id: None,
- branched_from_version_id: None,
- document_family_id: None,
- modification_data: None,
- sub_type: None,
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ document_bom: row.document_bom,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ sha: None,
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ modification_data: None,
+ sub_type: None,
+ })
})
.fetch_all(db)
.await?;
diff --git a/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs b/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs
index e730a97e9d..730b14adf6 100644
--- a/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs
+++ b/rust/cloud-storage/macro_db_client/src/dcs/create_chat.rs
@@ -1,6 +1,7 @@
use super::append_attachment_to_chat::append_attachment_to_chat;
use crate::history::{upsert_item_last_accessed, upsert_user_history};
use ai::types::Model;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{IDWithTimeStamps, chat::NewChatAttachment};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -11,7 +12,7 @@ use sqlx::{Pool, Postgres};
#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]
pub async fn create_chat_v2(
db: &Pool<Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
name: &str,
model: Model,
project_id: Option<&str>,
@@ -30,7 +31,7 @@ pub async fn create_chat_v2(
VALUES ($1, $2, $3, $4, $5)
RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
"#,
- &user_id,
+ user_id.as_ref(),
&name,
model.to_string(),
project_id,
@@ -57,7 +58,7 @@ pub async fn create_chat_v2(
.await?;
// tracking
- upsert_user_history(&mut transaction, user_id, &chat.id, "chat").await?;
+ upsert_user_history(&mut transaction, user_id.copied(), &chat.id, "chat").await?;
upsert_item_last_accessed(&mut transaction, &chat.id, "chat").await?;
// add attachment rows
@@ -67,7 +68,7 @@ pub async fn create_chat_v2(
crate::item_access::insert::insert_user_item_access(
&mut transaction,
- user_id,
+ user_id.copied(),
&chat.id,
"chat",
AccessLevel::Owner,
diff --git a/rust/cloud-storage/macro_db_client/src/document/copy_document/mod.rs b/rust/cloud-storage/macro_db_client/src/document/copy_document/mod.rs
index f3f6d11b44..072f979465 100644
--- a/rust/cloud-storage/macro_db_client/src/document/copy_document/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/copy_document/mod.rs
@@ -2,6 +2,7 @@ use crate::{
document::document_bom::create_bom_parts, share_permission::create::create_document_permission,
};
use document_sub_type::DocumentSubType;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::{
BomPart, DocumentMetadata, FileType, IDWithTimeStamps, VersionIDWithTimeStamps,
VersionIDWithTimeStampsNoSha,
@@ -16,7 +17,7 @@ pub mod copy_pdf_parts;
pub async fn copy_document(
db: Pool<Postgres>,
original_document: &DocumentMetadata,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
new_document_name: &str,
file_type: &FileType,
document_share_permissions: &SharePermissionV2,
@@ -67,7 +68,7 @@ pub async fn copy_document(
pub(in crate::document) async fn copy_docx_document(
transaction: &mut Transaction<'_, Postgres>,
original_document: &DocumentMetadata,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
new_document_name: &str,
) -> anyhow::Result<DocumentMetadata> {
let original_document_id = &original_document.document_id;
@@ -80,7 +81,7 @@ pub(in crate::document) async fn copy_docx_document(
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
"#,
- &user_id,
+ user_id.as_ref(),
&new_document_name,
original_document.file_type,
original_document.document_family_id,
@@ -129,7 +130,7 @@ pub(in crate::document) async fn copy_docx_document(
Ok(DocumentMetadata {
document_id: document.id.clone(),
- owner: user_id.to_string(),
+ owner: user_id,
document_name: new_document_name.to_string(),
file_type: original_document.file_type.clone(),
sha: None,
@@ -152,7 +153,7 @@ pub(in crate::document) async fn copy_docx_document(
pub(in crate::document) async fn copy_non_docx_document(
transaction: &mut Transaction<'_, Postgres>,
original_document: &DocumentMetadata,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
new_document_name: &str,
) -> anyhow::Result<DocumentMetadata> {
let original_document_id = &original_document.document_id;
@@ -173,7 +174,7 @@ pub(in crate::document) async fn copy_non_docx_document(
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
"#,
- &user_id,
+ user_id.as_ref(),
&new_document_name,
original_document.file_type,
original_document.document_family_id,
@@ -250,7 +251,7 @@ pub(in crate::document) async fn copy_non_docx_document(
Ok(DocumentMetadata {
document_id: document.id.clone(),
- owner: user_id.to_string(),
+ owner: user_id,
document_name: new_document_name.to_string(),
file_type: original_document.file_type.clone(),
sha: Some(document_instance.sha),
@@ -282,7 +283,7 @@ mod tests {
&DocumentMetadata::new_document(
"document-one",
1,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"name",
Some(FileType::Txt),
"sha",
@@ -295,7 +296,7 @@ mod tests {
None,
None,
),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"new name",
)
.await?;
@@ -307,7 +308,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert_eq!(document_metadata.sha.unwrap(), "sha");
assert_eq!(document_metadata.document_name, "new name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.branched_from_id.unwrap(), "document-one");
assert_eq!(document_metadata.branched_from_version_id.unwrap(), 1);
assert_eq!(
@@ -325,7 +326,7 @@ mod tests {
&DocumentMetadata::new_docx(
"document-one",
1,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"name",
"docx",
None,
@@ -336,7 +337,7 @@ mod tests {
None,
None,
),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"new name",
&FileType::Docx,
&SharePermissionV2::new_document_share_permission(Some(FileType::Docx)),
@@ -346,7 +347,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert!(document_metadata.sha.is_none());
assert_eq!(document_metadata.document_name, "new name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.branched_from_id.unwrap(), "document-one");
assert_eq!(document_metadata.branched_from_version_id.unwrap(), 1);
@@ -361,7 +362,7 @@ mod tests {
&DocumentMetadata::new_docx(
"document-one",
1,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"name",
"docx",
None,
@@ -372,7 +373,7 @@ mod tests {
None,
None,
),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"new name",
)
.await?;
@@ -384,7 +385,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert!(document_metadata.sha.is_none());
assert_eq!(document_metadata.document_name, "new name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.branched_from_id.unwrap(), "document-one");
assert_eq!(document_metadata.branched_from_version_id.unwrap(), 1);
diff --git a/rust/cloud-storage/macro_db_client/src/document/create_blank_docx.rs b/rust/cloud-storage/macro_db_client/src/document/create_blank_docx.rs
index 59e2880735..432fe8194b 100644
--- a/rust/cloud-storage/macro_db_client/src/document/create_blank_docx.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/create_blank_docx.rs
@@ -1,3 +1,5 @@
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::FileType;
use model::document::SaveBomPart;
use models_permissions::share_permission::SharePermissionV2;
@@ -18,7 +20,7 @@ use tracing::instrument;
pub async fn create_blank_docx(
db: Pool<Postgres>,
document_name: &str,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
project_id: Option<&str>,
share_permission: &SharePermissionV2,
bom_parts: Vec<SaveBomPart>,
@@ -53,7 +55,7 @@ pub async fn create_blank_docx(
VALUES ($1, $2, $3, $4)
RETURNING id;
"#,
- user_id,
+ user_id.as_ref(),
document_name,
"docx", // hard coded file type as it's create blank docx
project_id,
@@ -126,7 +128,7 @@ pub async fn create_blank_docx(
.await?;
// Add item to user history for creator
- upsert_user_history(&mut transaction, user_id, &document.id, "document").await?;
+ upsert_user_history(&mut transaction, user_id.copied(), &document.id, "document").await?;
upsert_item_last_accessed(&mut transaction, &document.id, "document").await?;
if let Err(err) = transaction.commit().await {
@@ -143,7 +145,7 @@ pub async fn create_blank_docx(
Ok(DocumentMetadata {
document_id: document.id,
document_version_id: document_version.id,
- owner: user_id.to_string(),
+ owner: user_id,
document_name: document_name.to_string(),
file_type: Some(FileType::Docx.as_str().to_string()),
sha: None,
@@ -171,7 +173,7 @@ mod tests {
let document_metadata = create_blank_docx(
pool.clone(),
"document-name",
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
None,
&SharePermissionV2::new_document_share_permission(Some(FileType::Docx)),
vec![SaveBomPart {
@@ -183,7 +185,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert_eq!(document_metadata.document_name, "document-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
Ok(())
}
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs b/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
index 3f7f7c439b..a18bbddc2c 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
@@ -1,4 +1,5 @@
use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::DocumentMetadata;
use sqlx::{Pool, Postgres};
@@ -24,8 +25,7 @@ pub async fn get_all_documents(
return Ok((vec![], 0));
}
- let documents = sqlx::query_as!(
- DocumentMetadata,
+ let documents = sqlx::query!(
r#"
SELECT
d.id as document_id,
@@ -105,6 +105,28 @@ pub async fn get_all_documents(
limit,
offset
)
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ sha: row.sha,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ document_bom: row.document_bom,
+ modification_data: row.modification_data,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sub_type: row.sub_type,
+ })
+ })
.fetch_all(db)
.await?;
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_document.rs b/rust/cloud-storage/macro_db_client/src/document/get_document.rs
index 9479c3a734..4a027843e6 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_document.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_document.rs
@@ -1,3 +1,4 @@
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres, Transaction};
use document_sub_type::DocumentSubType;
@@ -129,8 +130,7 @@ pub async fn get_basic_document(
db: &Pool<Postgres>,
document_id: &str,
) -> Result<DocumentBasic, sqlx::Error> {
- let document: DocumentBasic = sqlx::query_as!(
- DocumentBasic,
+ let document: DocumentBasic = sqlx::query!(
r#"
SELECT
d.id as "document_id",
@@ -150,6 +150,21 @@ pub async fn get_basic_document(
"#,
document_id,
)
+ .try_map(|row| {
+ Ok(DocumentBasic {
+ document_id: row.document_id,
+ document_name: row.document_name,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ file_type: row.file_type,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ project_id: row.project_id,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await?;
@@ -164,8 +179,7 @@ pub async fn get_basic_documents(
return Ok(Vec::new());
}
- let documents: Vec<DocumentBasic> = sqlx::query_as!(
- DocumentBasic,
+ let documents: Vec<DocumentBasic> = sqlx::query!(
r#"
SELECT
d.id as "document_id",
@@ -184,6 +198,21 @@ pub async fn get_basic_documents(
"#,
document_ids,
)
+ .try_map(|row| {
+ Ok(DocumentBasic {
+ document_id: row.document_id,
+ document_name: row.document_name,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ file_type: row.file_type,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ project_id: row.project_id,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_all(db)
.await?;
@@ -195,8 +224,7 @@ pub async fn get_deleted_document_info(
db: &Pool<Postgres>,
document_id: &str,
) -> Result<DocumentBasic, sqlx::Error> {
- let document: DocumentBasic = sqlx::query_as!(
- DocumentBasic,
+ let document: DocumentBasic = sqlx::query!(
r#"
SELECT
d.id as "document_id",
@@ -215,6 +243,21 @@ pub async fn get_deleted_document_info(
"#,
document_id,
)
+ .try_map(|row| {
+ Ok(DocumentBasic {
+ document_id: row.document_id,
+ document_name: row.document_name,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ file_type: row.file_type,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ project_id: row.project_id,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await?;
@@ -227,8 +270,7 @@ pub async fn get_document(
db: &Pool<Postgres>,
document_id: &str,
) -> anyhow::Result<DocumentMetadata> {
- let document_metadata: DocumentMetadata = sqlx::query_as!(
- DocumentMetadata,
+ let document_metadata: DocumentMetadata = sqlx::query!(
r#"
SELECT
d.id as "document_id",
@@ -309,6 +351,28 @@ pub async fn get_document(
"#,
document_id,
)
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ sha: row.sha,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ document_bom: row.document_bom,
+ modification_data: row.modification_data,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sub_type: row.sub_type,
+ })
+ })
.fetch_one(db)
.await?;
@@ -321,8 +385,7 @@ pub async fn get_document_version(
document_id: &str,
document_version_id: i64,
) -> anyhow::Result<DocumentMetadata> {
- let document_metadata: DocumentMetadata = sqlx::query_as!(
- DocumentMetadata,
+ let document_metadata: DocumentMetadata = sqlx::query!(
r#"
SELECT
d.id as "document_id",
@@ -402,6 +465,28 @@ pub async fn get_document_version(
document_id,
document_version_id,
)
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ sha: row.sha,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ document_bom: row.document_bom,
+ modification_data: row.modification_data,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sub_type: row.sub_type,
+ })
+ })
.fetch_one(db)
.await?;
@@ -537,8 +622,9 @@ mod tests {
get_basic_document(&pool, "document-one")
.await
.unwrap()
- .owner,
- "macro|[email protected]".to_string(),
+ .owner
+ .as_ref(),
);
}
@@ -561,7 +647,7 @@ mod tests {
document_metadata.document_name,
"test_document_name".to_string()
);
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
}
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
@@ -576,7 +662,7 @@ mod tests {
document_metadata.document_name,
"test_document_name".to_string()
);
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
}
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
@@ -593,7 +679,7 @@ mod tests {
document_metadata.document_name,
"test_document_name".to_string()
);
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
}
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
diff --git a/rust/cloud-storage/macro_db_client/src/document/initialize_onboarding_documents.rs b/rust/cloud-storage/macro_db_client/src/document/initialize_onboarding_documents.rs
index 6a3cdd968c..7d039867b7 100644
--- a/rust/cloud-storage/macro_db_client/src/document/initialize_onboarding_documents.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/initialize_onboarding_documents.rs
@@ -1,6 +1,8 @@
use super::insert_bom_parts;
use crate::history::upsert_user_history;
use crate::share_permission::create::{create_document_permission, create_project_permission};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::{BasicDocument, FileType};
use model::document::{ID, SaveBomPart, VersionID};
use model::project::Project;
@@ -12,7 +14,7 @@ use sqlx::{Postgres, Transaction};
#[tracing::instrument(skip(transaction))]
pub async fn create_project_transaction(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
project_name: &str,
parent_id: Option<String>,
share_permission: &SharePermissionV2,
@@ -26,7 +28,7 @@ pub async fn create_project_transaction(
"updatedAt"::timestamptz as updated_at, "parentId" as parent_id
"#,
project_name,
- user_id,
+ user_id.as_ref(),
parent_id,
)
.fetch_one(transaction.as_mut())
@@ -34,7 +36,7 @@ pub async fn create_project_transaction(
// Create share permission
create_project_permission(transaction, &project.id, share_permission).await?;
- upsert_user_history(transaction, user_id, &project.id, "project").await?;
+ upsert_user_history(transaction, user_id.copied(), &project.id, "project").await?;
crate::item_access::insert::insert_user_item_access(
transaction,
@@ -54,7 +56,7 @@ pub async fn create_project_transaction(
#[tracing::instrument(skip(transaction, document_names))]
pub async fn create_onboarding_documents(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
project_id: &str,
share_permission: &SharePermissionV2,
document_names: Vec<(String, String)>,
@@ -144,7 +146,7 @@ pub async fn create_onboarding_documents(
documents.push(BasicDocument {
document_id: document_id.to_string(),
document_version_id: *document_version_id,
- owner: user_id.to_string(),
+ owner: user_id.clone(),
document_name: document_names.0.to_string(),
file_type: Some(document_names.1.to_string()),
sha: None,
@@ -166,7 +168,7 @@ pub async fn create_onboarding_documents(
#[tracing::instrument(skip(transaction))]
pub async fn create_onboarding_docx(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
project_id: &str,
share_permission: &SharePermissionV2,
document_name: &str,
@@ -179,7 +181,7 @@ pub async fn create_onboarding_docx(
VALUES ($1, $2, $3, $4)
RETURNING id;
"#,
- user_id,
+ user_id.as_ref(),
document_name,
"docx", // hard coded file type as it's create blank docx
project_id,
@@ -203,12 +205,12 @@ pub async fn create_onboarding_docx(
insert_bom_parts(transaction, &document.id, document_bom.id, bom_parts).await?;
// Add item to user history for creator
- upsert_user_history(transaction, user_id, &document.id, "document").await?;
+ upsert_user_history(transaction, user_id.copied(), &document.id, "document").await?;
Ok(BasicDocument {
document_id: document.id,
document_version_id: document_bom.id,
- owner: user_id.to_string(),
+ owner: user_id,
document_name: document_name.to_string(),
file_type: Some(FileType::Docx.as_str().to_string()),
sha: None,
diff --git a/rust/cloud-storage/macro_db_client/src/document/save_document.rs b/rust/cloud-storage/macro_db_client/src/document/save_document.rs
index 4db6ad1de4..dab9f7fca0 100644
--- a/rust/cloud-storage/macro_db_client/src/document/save_document.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/save_document.rs
@@ -1,11 +1,11 @@
use document_sub_type::DocumentSubType;
-use sqlx::{PgPool, Postgres, Transaction, types::Uuid};
-
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::{
BomPart, DocumentBasic, DocumentMetadata, FileType, SaveBomPart, VersionIDWithTimeStamps,
VersionIDWithTimeStampsNoSha, VersionIDWithTimeStampsOptionalSha,
modification_data::{PdfModificationData, ThreadPlaceable},
};
+use sqlx::{PgPool, Postgres, Transaction, types::Uuid};
// A comprehensive function that inserts both comment and highlight data
async fn insert_all_comment_data(
@@ -121,7 +121,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
VALUES ($1, $2, $3, $4, $5)
RETURNING id
"#,
- document.owner,
+ document.owner.as_ref(),
document.document_id,
create_time,
create_time,
@@ -144,7 +144,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
"#,
Uuid::parse_str(&thread.head_id).unwrap(),
document.document_id,
- document.owner,
+ document.owner.as_ref(),
thread.page,
thread.original_page,
thread.original_index,
@@ -182,7 +182,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
RETURNING id
"#,
thread_id,
- document.owner,
+ document.owner.as_ref(),
comment.sender,
comment.content,
created_at,
@@ -222,7 +222,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
VALUES ($1, $2, $3, $4, $5)
RETURNING id
"#,
- document.owner,
+ document.owner.as_ref(),
document.document_id,
first_comment_time,
last_comment_time,
@@ -254,7 +254,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
RETURNING id
"#,
thread_id,
- document.owner,
+ document.owner.as_ref(),
comment.sender,
comment.content,
created_at,
@@ -298,7 +298,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
"#,
highlight_uuid,
document.document_id,
- document.owner,
+ document.owner.as_ref(),
highlight.page_num as i32,
highlight.color.red,
highlight.color.green,
@@ -327,7 +327,7 @@ DELETE FROM "PdfHighlightAnchor" WHERE "documentId" = $1;
RETURNING uuid
"#,
document.document_id,
- document.owner,
+ document.owner.as_ref(),
highlight.page_num as i32,
highlight.color.red,
highlight.color.green,
@@ -450,8 +450,7 @@ pub async fn save_document(
) -> anyhow::Result<DocumentMetadata> {
let mut transaction = db.begin().await?;
- let document = sqlx::query_as!(
- DocumentBasic,
+ let document = sqlx::query!(
r#"
UPDATE "Document" SET "updatedAt" = NOW()
WHERE id = $1
@@ -463,6 +462,21 @@ pub async fn save_document(
"#,
document_id
)
+ .try_map(|row| {
+ Ok(DocumentBasic {
+ document_id: row.document_id,
+ document_name: row.document_name,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ file_type: row.file_type,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ project_id: row.project_id,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(&mut *transaction)
.await?;
@@ -617,7 +631,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert_eq!(document_metadata.document_version_id, 3);
assert_eq!(document_metadata.file_type, Some("txt".to_string()));
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
Ok(())
}
@@ -644,7 +658,7 @@ mod tests {
"test_document_name".to_string()
);
assert_eq!(document_metadata.document_version_id, 3);
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
let bom_parts: Vec<BomPart> =
serde_json::from_value(document_metadata.document_bom.unwrap()).unwrap();
assert_eq!(bom_parts[0].sha, "sha-1");
diff --git a/rust/cloud-storage/macro_db_client/src/document/v2/copy.rs b/rust/cloud-storage/macro_db_client/src/document/v2/copy.rs
index f2e13c275f..f622aaee54 100644
--- a/rust/cloud-storage/macro_db_client/src/document/v2/copy.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/v2/copy.rs
@@ -2,6 +2,7 @@ use crate::{
document::copy_document::{copy_docx_document, copy_non_docx_document},
share_permission::create::create_document_permission,
};
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::{DocumentMetadata, FileType};
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -12,7 +13,7 @@ use sqlx::{Pool, Postgres};
pub async fn copy_document(
db: &Pool<Postgres>,
original_document: &DocumentMetadata,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
new_document_name: &str,
file_type: Option<&FileType>,
document_share_permissions: &SharePermissionV2,
@@ -23,7 +24,7 @@ pub async fn copy_document(
copy_docx_document(
&mut transaction,
original_document,
- user_id,
+ user_id.clone(),
new_document_name,
)
.await
@@ -32,7 +33,7 @@ pub async fn copy_document(
copy_non_docx_document(
&mut transaction,
original_document,
- user_id,
+ user_id.clone(),
new_document_name,
)
.await
@@ -82,7 +83,7 @@ mod tests {
&DocumentMetadata::new_docx(
"document-one",
1,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"name",
"docx",
None,
@@ -93,7 +94,7 @@ mod tests {
None,
None,
),
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"new name",
Some(&FileType::Docx),
&SharePermissionV2::new_document_share_permission(Some(FileType::Docx)),
@@ -103,7 +104,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert!(document_metadata.sha.is_none());
assert_eq!(document_metadata.document_name, "new name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.branched_from_id.unwrap(), "document-one");
assert_eq!(document_metadata.branched_from_version_id.unwrap(), 1);
diff --git a/rust/cloud-storage/macro_db_client/src/document/v2/create.rs b/rust/cloud-storage/macro_db_client/src/document/v2/create.rs
index 4be52faf4a..69ad6ca28f 100644
--- a/rust/cloud-storage/macro_db_client/src/document/v2/create.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/v2/create.rs
@@ -1,6 +1,8 @@
use crate::history::{upsert_item_last_accessed_timestamp, upsert_user_history_timestamp};
use crate::share_permission::create::create_document_permission;
use document_sub_type::DocumentSubType;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model::document::DocumentMetadata;
use model::document::FileType;
use model::document::ID;
@@ -19,7 +21,7 @@ pub struct CreateDocumentArgs<'a> {
pub id: Option<&'a str>,
pub sha: &'a str,
pub document_name: &'a str,
- pub user_id: &'a str,
+ pub user_id: MacroUserIdStr<'static>,
pub file_type: Option<FileType>,
pub project_id: Option<&'a str>,
pub project_name: Option<&'a str>,
@@ -107,7 +109,7 @@ pub async fn create_document_txn(
insert_document_with_id(
transaction,
id,
- user_id,
+ user_id.copied(),
document_name,
file_type,
project_id,
@@ -118,7 +120,7 @@ pub async fn create_document_txn(
} else {
insert_document_no_id(
transaction,
- user_id,
+ user_id.copied(),
document_name,
file_type,
project_id,
@@ -196,15 +198,21 @@ pub async fn create_document_txn(
// Add item to user history for creator
if !skip_history {
- upsert_user_history_timestamp(transaction, user_id, &document_id, "document", created_at)
- .await?;
+ upsert_user_history_timestamp(
+ transaction,
+ user_id.copied(),
+ &document_id,
+ "document",
+ created_at,
+ )
+ .await?;
upsert_item_last_accessed_timestamp(transaction, &document_id, "document", created_at)
.await?;
}
crate::item_access::insert::insert_user_item_access(
transaction,
- user_id,
+ user_id.copied(),
&document_id,
"document",
AccessLevel::Owner,
@@ -243,7 +251,7 @@ pub async fn create_document_txn(
#[instrument(skip(transaction))]
async fn insert_document_no_id(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
document_name: &str,
file_type: Option<FileType>,
project_id: Option<&str>,
@@ -256,7 +264,7 @@ async fn insert_document_no_id(
VALUES ($1, $2, $3, $4, $5, $5)
RETURNING id;
"#,
- user_id,
+ user_id.as_ref(),
document_name,
file_type.map(|file_type| file_type.as_str().to_string()),
project_id,
@@ -274,7 +282,7 @@ async fn insert_document_no_id(
async fn insert_document_with_id(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
id: &str,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
document_name: &str,
file_type: Option<FileType>,
project_id: Option<&str>,
@@ -286,7 +294,7 @@ async fn insert_document_with_id(
VALUES ($1, $2, $3, $4, $5, $6, $6)
"#,
id,
- user_id,
+ user_id.as_ref(),
document_name,
file_type.map(|file_type| file_type.as_str().to_string()),
project_id,
@@ -342,7 +350,7 @@ mod tests {
id: None,
sha: "sha",
document_name: "document-name",
- user_id: "macro|[email protected]",
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
file_type: Some(FileType::Pdf),
project_id: Some("project-one"),
project_name: None,
@@ -359,7 +367,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert_eq!(document_metadata.document_name, "document-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));
assert_eq!(document_metadata.project_name.as_deref(), Some("name"));
assert_eq!(document_metadata.created_at, Some(ts));
@@ -371,7 +379,7 @@ mod tests {
id: None,
sha: "sha",
document_name: "document-name",
- user_id: "macro|[email protected]",
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
file_type: Some(FileType::Docx),
project_id: None,
project_name: None,
@@ -388,7 +396,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert_eq!(document_metadata.document_name, "document-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
Ok(())
}
@@ -412,7 +420,7 @@ mod tests {
id: Some("20f603c2-99db-aaaa-0000-1d8b9f95a52f"),
sha: "sha",
document_name: "document-name",
- user_id: "macro|[email protected]",
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
file_type: Some(FileType::Pdf),
project_id: Some("project-one"),
project_name: None,
@@ -432,7 +440,7 @@ mod tests {
"20f603c2-99db-aaaa-0000-1d8b9f95a52f"
);
assert_eq!(document_metadata.document_name, "document-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));
assert_eq!(document_metadata.project_name.as_deref(), Some("name"));
assert_eq!(document_metadata.created_at, Some(ts));
@@ -444,7 +452,7 @@ mod tests {
id: Some("20f603c2-99db-4f02-aaaa-1d8b9f95a52f"),
sha: "sha",
document_name: "document-name",
- user_id: "macro|[email protected]",
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
file_type: Some(FileType::Docx),
project_id: None,
project_name: None,
@@ -464,7 +472,7 @@ mod tests {
"20f603c2-99db-4f02-aaaa-1d8b9f95a52f"
);
assert_eq!(document_metadata.document_name, "document-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
Ok(())
}
@@ -477,7 +485,8 @@ mod tests {
id: None,
sha: "sha",
document_name: "document-name",
- user_id: "macro|[email protected]",
+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap(),
file_type: Some(FileType::Pdf),
project_id: None,
project_name: None,
@@ -503,7 +512,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_user_with_documents")))]
async fn test_insert_document_with_duplicate_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let test_id = "duplicate-document-id";
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// First, create a document with the test ID
let mut transaction = pool.begin().await?;
@@ -514,7 +523,7 @@ mod tests {
insert_document_with_id(
&mut transaction,
test_id,
- user_id,
+ user_id.clone(),
"First Document",
Some(FileType::Pdf),
None,
@@ -530,7 +539,7 @@ mod tests {
let result = insert_document_with_id(
&mut transaction,
test_id,
- user_id,
+ user_id.clone(),
"Second Document with Same ID",
Some(FileType::Pdf),
None,
diff --git a/rust/cloud-storage/macro_db_client/src/document/v2/edit.rs b/rust/cloud-storage/macro_db_client/src/document/v2/edit.rs
index 854e257dea..c6f9c9c817 100644
--- a/rust/cloud-storage/macro_db_client/src/document/v2/edit.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/v2/edit.rs
@@ -94,7 +94,7 @@ mod tests {
assert!(!document_metadata.document_id.is_empty());
assert!(document_metadata.document_version_id > 0);
assert_eq!(document_metadata.document_name, "new-name".to_string());
- assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
+ assert_eq!(document_metadata.owner.as_ref(), "macro|[email protected]");
assert_eq!(
document_metadata.project_id,
Some("new-project".to_string())
diff --git a/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs b/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs
index afd0752fed..cbf32af633 100644
--- a/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs
+++ b/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs
@@ -1,4 +1,5 @@
use chrono::{DateTime, Utc};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Postgres, Transaction};
/// Upserts an item into the ItemLastAccessed table
@@ -40,7 +41,7 @@ pub async fn upsert_item_last_accessed_timestamp(
#[tracing::instrument(skip(transaction))]
pub async fn upsert_user_history(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
item_id: &str,
item_type: &str,
) -> anyhow::Result<()> {
@@ -51,7 +52,7 @@ pub async fn upsert_user_history(
#[tracing::instrument(skip(transaction))]
pub async fn upsert_user_history_timestamp(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
item_id: &str,
item_type: &str,
timestamp: &DateTime<Utc>,
@@ -63,7 +64,7 @@ pub async fn upsert_user_history_timestamp(
ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE
SET "updatedAt" = $4;
"#,
- user_id,
+ user_id.as_ref(),
item_id,
item_type,
timestamp.naive_utc()
@@ -78,7 +79,7 @@ pub async fn upsert_user_history_timestamp(
#[tracing::instrument(skip(transaction))]
async fn insert_user_history_batch(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
item_ids: &Vec<String>,
item_type: &str,
timestamp: DateTime<Utc>,
@@ -111,13 +112,13 @@ async fn insert_user_history_batch(
#[tracing::instrument(skip(transaction))]
pub async fn add_user_history_for_project_tree(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
project_ids: &Vec<String>,
document_ids: &Vec<String>,
) -> anyhow::Result<()> {
let now: DateTime<Utc> = Utc::now();
- insert_user_history_batch(transaction, user_id, project_ids, "project", now).await?;
+ insert_user_history_batch(transaction, user_id.copied(), project_ids, "project", now).await?;
insert_user_history_batch(transaction, user_id, document_ids, "document", now).await?;
Ok(())
@@ -166,7 +167,7 @@ mod tests {
let mut transaction = pool.begin().await.unwrap();
upsert_user_history(
&mut transaction,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"document-one",
"document",
)
@@ -190,7 +191,7 @@ mod tests {
let mut transaction = pool.begin().await.unwrap();
upsert_user_history(
&mut transaction,
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"document-two",
"document",
)
@@ -214,7 +215,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_history")))]
async fn test_add_user_history_for_project_tree(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let mut transaction = pool.begin().await?;
@@ -225,7 +226,7 @@ mod tests {
FROM "UserHistory"
WHERE "userId" = $1 AND "itemId" = $2
"#,
- user_id,
+ user_id.as_ref(),
"document-one"
)
.fetch_one(&mut *transaction)
@@ -235,8 +236,13 @@ mod tests {
let document_ids = vec!["document-one".to_string(), "document-two".to_string()];
// Call function under test
- add_user_history_for_project_tree(&mut transaction, user_id, &project_ids, &document_ids)
- .await?;
+ add_user_history_for_project_tree(
+ &mut transaction,
+ user_id.clone(),
+ &project_ids,
+ &document_ids,
+ )
+ .await?;
// Confirm document-one was updated
let updated = sqlx::query!(
@@ -245,7 +251,7 @@ mod tests {
FROM "UserHistory"
WHERE "userId" = $1 AND "itemId" = $2
"#,
- user_id,
+ user_id.as_ref(),
"document-one"
)
.fetch_one(&mut *transaction)
@@ -264,7 +270,7 @@ mod tests {
FROM "UserHistory"
WHERE "userId" = $1 AND "itemId" = $2
"#,
- user_id,
+ user_id.as_ref(),
"document-two"
)
.fetch_one(&mut *transaction)
@@ -279,7 +285,7 @@ mod tests {
FROM "UserHistory"
WHERE "userId" = $1 AND "itemId" = $2 AND "itemType" = 'project'
"#,
- user_id,
+ user_id.as_ref(),
"project-alpha"
)
.fetch_one(&mut *transaction)
diff --git a/rust/cloud-storage/macro_db_client/src/instructions/create.rs b/rust/cloud-storage/macro_db_client/src/instructions/create.rs
index 5380e0bc27..467865e4f1 100644
--- a/rust/cloud-storage/macro_db_client/src/instructions/create.rs
+++ b/rust/cloud-storage/macro_db_client/src/instructions/create.rs
@@ -1,4 +1,5 @@
use crate::{document::v2::create::create_document, instructions::get::get_instructions_document};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::FileType;
use models_dcs::constants::INSTRUCTIONS_FILE_NAME;
use models_permissions::share_permission::SharePermissionV2;
@@ -16,7 +17,7 @@ pub enum CreateInstructionsError {
#[instrument(skip(db))]
pub async fn create_instructions_document(
db: &sqlx::Pool<sqlx::Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
) -> Result<String, CreateInstructionsError> {
tracing::trace!("creating instructions document");
@@ -26,7 +27,7 @@ pub async fn create_instructions_document(
id: None,
sha: "",
document_name: INSTRUCTIONS_FILE_NAME,
- user_id,
+ user_id: user_id.clone(),
file_type: Some(FileType::Md),
project_id: None,
project_name: None,
@@ -41,7 +42,7 @@ pub async fn create_instructions_document(
let document_id = document_metadata.document_id;
- let insert_result = insert_instructions_document(db, user_id, &document_id).await;
+ let insert_result = insert_instructions_document(db, user_id.copied(), &document_id).await;
match insert_result {
Ok(_) => (),
@@ -49,7 +50,7 @@ pub async fn create_instructions_document(
match err {
CreateInstructionsError::UserAlreadyHasInstructions => {
// Check if the instructions document has been deleted but the instructions table row still exists
- let exists = get_instructions_document(db, user_id)
+ let exists = get_instructions_document(db, user_id.copied())
.await
.map(|doc_id| doc_id.is_some())?;
@@ -61,7 +62,7 @@ pub async fn create_instructions_document(
// Otherwise we can safely delete the instructions row
sqlx::query!(
r#"DELETE FROM "InstructionsDocuments" WHERE "userId" = $1"#,
- user_id
+ user_id.as_ref()
)
.execute(db)
.await
@@ -87,7 +88,7 @@ pub async fn create_instructions_document(
#[instrument(skip(db))]
pub async fn insert_instructions_document(
db: &sqlx::Pool<sqlx::Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
document_id: &str,
) -> Result<(), CreateInstructionsError> {
tracing::trace!("inserting instructions document");
@@ -98,7 +99,7 @@ pub async fn insert_instructions_document(
VALUES ($1, $2)
"#,
document_id,
- user_id,
+ user_id.as_ref(),
)
.execute(db)
.await;
@@ -132,9 +133,9 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
async fn test_create_instructions_document_success(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let result = create_instructions_document(&pool, user_id).await;
+ let result = create_instructions_document(&pool, user_id.clone()).await;
match result {
Ok(document_id) => {
@@ -144,7 +145,7 @@ mod tests {
// Verify it's in the instructions table
let instructions_doc = sqlx::query!(
r#"SELECT "documentId" as "document_id" FROM "InstructionsDocuments" WHERE "userId" = $1"#,
- user_id
+ user_id.as_ref()
)
.fetch_one(&pool)
.await?;
@@ -161,7 +162,7 @@ mod tests {
assert_eq!(document.name, INSTRUCTIONS_FILE_NAME);
assert_eq!(document.file_type.as_deref(), Some("md"));
- assert_eq!(document.owner, user_id);
+ assert_eq!(document.owner.as_str(), user_id.as_ref());
Ok(())
}
@@ -173,10 +174,10 @@ mod tests {
async fn test_create_instructions_document_duplicate_user(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// First creation should succeed
- let result1 = create_instructions_document(&pool, user_id).await;
+ let result1 = create_instructions_document(&pool, user_id.clone()).await;
match result1 {
Ok(document_id) => {
// Verify the document exists
@@ -205,13 +206,13 @@ mod tests {
async fn test_create_instructions_document_different_users(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
- let user1 = "macro|[email protected]";
- let user2 = "macro|[email protected]";
+ let user1 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user2 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// Add second user to the database (only if it doesn't exist)
let _ = sqlx::query!(
r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING"#,
- user2,
+ user2.as_ref(),
)
.execute(&pool)
diff --git a/rust/cloud-storage/macro_db_client/src/instructions/get.rs b/rust/cloud-storage/macro_db_client/src/instructions/get.rs
index 311cd24000..5d0c9424ee 100644
--- a/rust/cloud-storage/macro_db_client/src/instructions/get.rs
+++ b/rust/cloud-storage/macro_db_client/src/instructions/get.rs
@@ -1,10 +1,11 @@
+use macro_user_id::user_id::MacroUserIdStr;
use tracing::instrument;
/// Gets the instructions document ID for a user
#[instrument(skip(db))]
pub async fn get_instructions_document(
db: &sqlx::Pool<sqlx::Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
) -> anyhow::Result<Option<String>> {
tracing::trace!("getting instructions document");
@@ -15,7 +16,7 @@ pub async fn get_instructions_document(
JOIN "Document" d ON d."id" = id."documentId"
WHERE "userId" = $1 AND d."deletedAt" IS NULL
"#,
- user_id,
+ user_id.as_ref(),
)
.fetch_optional(db)
.await
@@ -31,14 +32,15 @@ pub async fn get_instructions_document(
mod tests {
use super::*;
use crate::instructions::create::create_instructions_document;
+ use macro_user_id::cowlike::CowLike;
use sqlx::{Pool, Postgres};
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
async fn test_get_instructions_document_exists(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// First create an instructions document
- let created_document_id = create_instructions_document(&pool, user_id)
+ let created_document_id = create_instructions_document(&pool, user_id.clone())
.await
.map_err(|e| anyhow::anyhow!("Failed to create instructions document: {:?}", e))?;
@@ -53,7 +55,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_documents")))]
async fn test_get_instructions_document_not_exists(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// Try to get instructions document without creating one first
let result = get_instructions_document(&pool, user_id).await?;
@@ -67,20 +69,20 @@ mod tests {
async fn test_get_instructions_document_different_users(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
- let user1 = "macro|[email protected]";
- let user2 = "macro|[email protected]";
+ let user1 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user2 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// Add second user to the database (only if it doesn't exist)
let _ = sqlx::query!(
r#"INSERT INTO "User" (id, email) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING"#,
- user2,
+ user2.as_ref(),
)
.execute(&pool)
.await;
// Create instructions document for user1 only
- let user1_document_id = create_instructions_document(&pool, user1)
+ let user1_document_id = create_instructions_document(&pool, user1.clone())
.await
.map_err(|e| anyhow::anyhow!("Failed to create instructions document: {:?}", e))?;
@@ -100,7 +102,7 @@ mod tests {
async fn test_get_instructions_document_nonexistent_user(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
- let nonexistent_user = "nonexistent|[email protected]";
+ let nonexistent_user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
// Should return None for non-existent user
let result = get_instructions_document(&pool, nonexistent_user).await?;
diff --git a/rust/cloud-storage/macro_db_client/src/item_access/insert.rs b/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
index 686c4f5427..3d58bb0ad4 100644
--- a/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
+++ b/rust/cloud-storage/macro_db_client/src/item_access/insert.rs
@@ -1,3 +1,4 @@
+use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::user_item_access::UserItemAccess;
use sqlx::{Executor, Postgres, Transaction};
@@ -6,7 +7,7 @@ use uuid::Uuid;
#[tracing::instrument(skip(transaction))]
pub async fn insert_user_item_access(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
item_id: &str,
item_type: &str,
access_level: AccessLevel,
@@ -38,7 +39,7 @@ pub async fn insert_user_item_access(
)
"#,
id,
- user_id,
+ user_id.as_ref(),
item_id,
item_type,
access_level as _,
@@ -253,7 +254,7 @@ mod tests {
#[sqlx::test(fixtures(path = "../../fixtures", scripts("user_item_access.sql")))]
async fn test_insert_user_item_access(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let user_id = "test-user";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let item_id = "new-test-item";
let item_type = "document";
let access_level = AccessLevel::Edit;
@@ -264,7 +265,7 @@ mod tests {
// Insert a new record
insert_user_item_access(
&mut transaction,
- user_id,
+ user_id.clone(),
item_id,
item_type,
access_level,
@@ -280,7 +281,7 @@ mod tests {
WHERE "user_id" = $1 AND "item_id" = $2 AND "item_type" = $3
AND "access_level"::text = $4 AND "granted_from_channel_id" = $5
"#,
- user_id,
+ user_id.as_ref(),
item_id,
item_type,
access_level.to_string(),
diff --git a/rust/cloud-storage/macro_db_client/src/notification/mod.rs b/rust/cloud-storage/macro_db_client/src/notification/mod.rs
index 5da3786ce4..04547ab86c 100644
--- a/rust/cloud-storage/macro_db_client/src/notification/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/notification/mod.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_user_id::user_id::MacroUserIdStr;
use crate::document::get_basic_documents;
use crate::{
@@ -15,7 +16,7 @@ pub mod project;
pub struct BasicCloudStorageItemMetadata {
pub item_id: String,
pub item_name: String,
- pub item_owner: String,
+ pub item_owner: MacroUserIdStr<'static>,
pub file_type: Option<String>,
}
diff --git a/rust/cloud-storage/macro_db_client/src/projects/create_project.rs b/rust/cloud-storage/macro_db_client/src/projects/create_project.rs
index 8a294d7b3b..1e115e13de 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/create_project.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/create_project.rs
@@ -1,4 +1,5 @@
use crate::{history::upsert_user_history, share_permission};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::project::Project;
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -7,7 +8,7 @@ use sqlx::{Pool, Postgres};
#[tracing::instrument(skip(db))]
pub async fn create_project_v2(
db: Pool<Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
project_name: &str,
parent_id: Option<String>,
share_permission: &SharePermissionV2,
@@ -22,7 +23,7 @@ pub async fn create_project_v2(
"updatedAt"::timestamptz as updated_at, "parentId" as parent_id
"#,
project_name,
- user_id,
+ user_id.as_ref(),
parent_id,
)
.fetch_one(transaction.as_mut())
@@ -36,7 +37,7 @@ pub async fn create_project_v2(
)
.await?;
- upsert_user_history(&mut transaction, user_id, &project.id, "project").await?;
+ upsert_user_history(&mut transaction, user_id.copied(), &project.id, "project").await?;
crate::item_access::insert::insert_user_item_access(
&mut transaction,
diff --git a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_basic_project.rs b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_basic_project.rs
index d95bd8e5a9..5a8c40c5cf 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_basic_project.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_basic_project.rs
@@ -1,3 +1,4 @@
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use model::project::BasicProject;
@@ -7,8 +8,7 @@ pub async fn get_basic_project(
db: &Pool<Postgres>,
project_id: &str,
) -> Result<BasicProject, sqlx::Error> {
- let result = sqlx::query_as!(
- BasicProject,
+ let result = sqlx::query!(
r#"
SELECT
p.id,
@@ -21,6 +21,17 @@ pub async fn get_basic_project(
"#,
project_id
)
+ .try_map(|row| {
+ Ok(BasicProject {
+ id: row.id,
+ user_id: MacroUserIdStr::parse_from_str(&row.user_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ parent_id: row.parent_id,
+ name: row.name,
+ deleted_at: row.deleted_at,
+ })
+ })
.fetch_one(db)
.await?;
diff --git a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_project_content.rs b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_project_content.rs
index f28bab2251..f6e1485432 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_project_content.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_project_content.rs
@@ -1,8 +1,8 @@
-use sqlx::{Pool, Postgres};
-
use super::get_sub_items;
+use macro_user_id::user_id::MacroUserIdStr;
use model::item::{Item, ItemWithUserAccessLevel};
use models_permissions::share_permission::access_level::AccessLevel;
+use sqlx::{Pool, Postgres};
/// Gets the content of a project to a depth of 1.
/// This includes the projects sub-projects as well as the documents/chats in the project.
@@ -12,7 +12,7 @@ use models_permissions::share_permission::access_level::AccessLevel;
pub async fn get_project_content_v2(
db: &Pool<Postgres>,
project_id: &str,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
project_user_access_level: AccessLevel,
) -> anyhow::Result<Vec<ItemWithUserAccessLevel>> {
let mut transaction = db.begin().await?;
@@ -21,7 +21,7 @@ pub async fn get_project_content_v2(
let sub_projects: Vec<ItemWithUserAccessLevel> = sub_projects
.into_iter()
.map(|p| {
- let user_access_level = match p.user_id == user_id {
+ let user_access_level = match p.user_id == user_id.as_ref() {
true => AccessLevel::Owner,
false => project_user_access_level,
};
@@ -51,7 +51,7 @@ pub async fn get_project_content_v2(
let sub_chats: Vec<ItemWithUserAccessLevel> = sub_chats
.into_iter()
.map(|c| {
- let user_access_level = match c.user_id == user_id {
+ let user_access_level = match c.user_id == user_id.as_ref() {
true => AccessLevel::Owner,
false => project_user_access_level,
};
@@ -82,8 +82,13 @@ mod tests {
scripts("users", "projects", "documents", "chats")
))]
async fn test_get_project_content_v2(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let result =
- get_project_content_v2(&pool, "p1", "macro|[email protected]", AccessLevel::View).await?;
+ let result = get_project_content_v2(
+ &pool,
+ "p1",
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ AccessLevel::View,
+ )
+ .await?;
let mapped_result: Vec<(String, String)> = result
.into_iter()
diff --git a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_sub_items.rs b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_sub_items.rs
index d0ad72f8ba..4517ccf965 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/get_project/get_sub_items.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/get_project/get_sub_items.rs
@@ -1,4 +1,5 @@
use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{chat::Chat, document::BasicDocument, project::Project};
/// Gets all deleted sub-projects of a given project.
@@ -119,12 +120,14 @@ pub async fn get_sub_documents(
"#,
project_id,
)
- .map(|row| {
- BasicDocument {
+ .try_map(|row| {
+ Ok(BasicDocument {
document_id: row.document_id,
document_name: row.document_name,
document_version_id: row.document_version_id,
- owner: row.owner,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
file_type: row.file_type,
project_id: row.project_id,
sha: None,
@@ -135,7 +138,7 @@ pub async fn get_sub_documents(
updated_at: row.updated_at,
deleted_at: None, // Don't care about the deleted_at
sub_type: row.sub_type,
- }
+ })
})
.fetch_all(transaction.as_mut())
.await?;
diff --git a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
index bdd6ea1dcd..4ad92c095a 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
@@ -5,6 +5,7 @@ use crate::{
history::add_user_history_for_project_tree, share_permission::create::create_project_permission,
};
use async_recursion::async_recursion;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::{
document::{DocumentMetadata, FileType, FileTypeExt},
folder::{FileSystemNode, FileSystemNodeWithIds, UploadFolderWithIdsResponse},
@@ -19,7 +20,7 @@ use sqlx::{Pool, Postgres, Transaction};
#[tracing::instrument(skip(transaction, root_folder), fields(root_folder=?root_folder))]
pub async fn upload_folder_with_ids(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
share_permission: &SharePermissionV2,
root_folder: &FileSystemNode,
root_folder_name: &str,
@@ -29,7 +30,7 @@ pub async fn upload_folder_with_ids(
// Create root project
let root_project = create_project(
transaction,
- user_id,
+ user_id.copied(),
share_permission,
root_folder_name,
parent_id.map(|s| s.to_string()),
@@ -52,7 +53,7 @@ pub async fn upload_folder_with_ids(
let extended_node = traverse_with_ids(
transaction,
node,
- user_id,
+ user_id.clone(),
share_permission,
name,
Some((root_project.id.as_str(), root_project.name.as_str())),
@@ -95,7 +96,7 @@ pub async fn upload_folder_with_ids(
async fn traverse_with_ids(
transaction: &mut Transaction<'_, Postgres>,
node: &FileSystemNode,
- user_id: &str,
+ user_id: MacroUserIdStr<'static>,
share_permission: &SharePermissionV2,
key: &str,
parent_project: Option<(&str, &str)>, // id, name
@@ -142,7 +143,7 @@ async fn traverse_with_ids(
if let Some((project_id, _)) = parent_project {
let project = create_project(
transaction,
- user_id,
+ user_id.copied(),
share_permission,
key,
Some(project_id.to_string()),
@@ -159,7 +160,7 @@ async fn traverse_with_ids(
let extended_node = traverse_with_ids(
transaction,
sub_node,
- user_id,
+ user_id.clone(),
share_permission,
name,
Some((project.id.as_str(), project.name.as_str())),
@@ -187,7 +188,7 @@ async fn traverse_with_ids(
/// Creates a project for the folder traversal
async fn create_project(
transaction: &mut Transaction<'_, Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
share_permission: &SharePermissionV2,
name: &str,
parent_id: Option<String>,
@@ -202,7 +203,7 @@ async fn create_project(
"updatedAt"::timestamptz as updated_at, "parentId" as parent_id
"#,
name,
- user_id,
+ user_id.as_ref(),
parent_id,
upload_request_id
)
@@ -409,7 +410,7 @@ mod tests {
#[sqlx::test]
async fn test_upload_folder_preserves_structure(pool: Pool<Postgres>) -> anyhow::Result<()> {
// Create test data
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let upload_request_id = "upload_request_id";
let (folder_tree, root_folder_name) = create_test_folder_structure();
let share_permission = create_test_permission(&pool).await?;
@@ -424,7 +425,7 @@ mod tests {
..
} = upload_folder_with_ids(
&mut transaction,
- &user_id,
+ user_id,
&share_permission,
&folder_tree,
&root_folder_name,
@@ -645,7 +646,7 @@ mod tests {
let empty_folder = FileSystemNode::Folder(HashMap::new());
let upload_request_id = "upload_request_id";
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let share_permission = create_test_permission(&pool).await?;
// Start a transaction
@@ -658,7 +659,7 @@ mod tests {
..
} = upload_folder_with_ids(
&mut transaction,
- &user_id,
+ user_id,
&share_permission,
&empty_folder,
&root_folder_name,
@@ -779,7 +780,7 @@ mod tests {
root_content.insert("root_file.txt".to_string(), FileSystemNode::File(root_file));
let folder_tree = FileSystemNode::Folder(root_content);
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let share_permission = create_test_permission(&pool).await?;
// Start a transaction
@@ -792,7 +793,7 @@ mod tests {
..
} = upload_folder_with_ids(
&mut transaction,
- &user_id,
+ user_id,
&share_permission,
&folder_tree,
&root_folder_name,
@@ -922,7 +923,7 @@ mod tests {
);
let folder_tree = FileSystemNode::Folder(root_content);
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let share_permission = create_test_permission(&pool).await?;
// Start a transaction
@@ -935,7 +936,7 @@ mod tests {
documents,
} = upload_folder_with_ids(
&mut transaction,
- &user_id,
+ user_id,
&share_permission,
&folder_tree,
&root_folder_name,
@@ -1129,7 +1130,7 @@ mod tests {
async fn test_upload_request_id_set_for_root_and_subprojects(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let upload_request_id = "upload_request_test_id";
let (folder_tree, root_folder_name) = create_test_folder_structure();
let share_permission = create_test_permission(&pool).await?;
@@ -1194,7 +1195,7 @@ mod tests {
let root_folder_name = "Conflicting Names Test";
let upload_request_id = "conflict_test_123";
- let user_id = "macro|[email protected]";
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let share_permission = create_test_permission(&pool).await?;
// Create a file called "Report.pdf"
diff --git a/rust/cloud-storage/macro_db_client/src/share_permission/create.rs b/rust/cloud-storage/macro_db_client/src/share_permission/create.rs
index 37f0a4effc..d150d79ddc 100644
--- a/rust/cloud-storage/macro_db_client/src/share_permission/create.rs
+++ b/rust/cloud-storage/macro_db_client/src/share_permission/create.rs
@@ -1,4 +1,5 @@
use super::channel_permission::create::create_channel_share_permissions;
+use macro_user_id::user_id::MacroUserIdStr;
use model::thread::EmailThreadPermission;
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -148,7 +149,7 @@ pub async fn create_macro_permission(
#[tracing::instrument(skip(transaction))]
pub async fn create_thread_permission(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
- user_id: &str,
+ user_id: MacroUserIdStr<'_>,
thread_id: &str,
share_permission: &SharePermissionV2,
) -> anyhow::Result<EmailThreadPermission> {
@@ -161,7 +162,7 @@ pub async fn create_thread_permission(
"#,
thread_id,
updated_share_permission.id,
- user_id,
+ user_id.as_ref(),
)
.execute(transaction.as_mut())
.await
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/chat.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/chat.rs
index f25229c293..6f9474d6dd 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/chat.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/chat.rs
@@ -8,7 +8,7 @@ use axum::{
http::request::Parts,
};
use comms_service_client::CommsServiceClient;
-use model::{chat::ChatBasic, user::UserContext};
+use model::{chat::ChatBasic, user::axum_extractor::MacroUserExtractor};
use models_permissions::share_permission::access_level::AccessLevel;
use sqlx::PgPool;
@@ -35,7 +35,11 @@ where
let db = PgPool::from_ref(state);
let comms_client = <Arc<CommsServiceClient>>::from_ref(state);
- let user_context: Extension<UserContext> = parts
+ let MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ } = parts
.extract()
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
@@ -45,7 +49,7 @@ where
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
- if chat_context.user_id == user_context.user_id {
+ if chat_context.user_id == macro_user_id {
return Ok(Self {
access_level: AccessLevel::Owner,
desired: PhantomData,
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
index 52865c3124..e98e030dba 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/document.rs
@@ -1,7 +1,7 @@
use std::{marker::PhantomData, sync::Arc};
use axum::{
- Extension, async_trait,
+ Extension, RequestPartsExt, async_trait,
extract::{FromRef, FromRequestParts},
http::request::Parts,
};
@@ -10,7 +10,7 @@ use sqlx::PgPool;
use super::get_users_access_level_v2;
use crate::cloud_storage::ensure_access::{AccessLevelErr, BuildAccessLevel};
-use model::{document::DocumentBasic, user::UserContext};
+use model::{document::DocumentBasic, user::axum_extractor::MacroUserExtractor};
use models_permissions::share_permission::access_level::AccessLevel;
#[derive(Debug)]
@@ -34,16 +34,20 @@ where
let db = PgPool::from_ref(state);
let comms_client = <Arc<CommsServiceClient>>::from_ref(state);
- let user_context: Extension<UserContext> =
- <Extension<UserContext>>::from_request_parts(parts, state)
- .await
- .map_err(|_| AccessLevelErr::InternalErr)?;
+ let MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ } = parts
+ .extract()
+ .await
+ .map_err(|_| AccessLevelErr::InternalErr)?;
let document_context: Extension<DocumentBasic> =
<Extension<DocumentBasic>>::from_request_parts(parts, state)
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
- if document_context.owner == user_context.user_id {
+ if document_context.owner == macro_user_id {
return Ok(Self {
access_level: AccessLevel::Owner,
desired: PhantomData,
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/project.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/project.rs
index d744e3c5fd..9980665a73 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/project.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/ensure_access/project.rs
@@ -6,7 +6,10 @@ use axum::{
http::request::Parts,
};
use comms_service_client::CommsServiceClient;
-use model::{project::BasicProject, user::UserContext};
+use model::{
+ project::BasicProject,
+ user::{UserContext, axum_extractor::MacroUserExtractor},
+};
use models_permissions::share_permission::access_level::AccessLevel;
use serde::{Deserialize, de::DeserializeOwned};
use sqlx::PgPool;
@@ -34,7 +37,11 @@ where
let db = PgPool::from_ref(state);
let comms_client = <Arc<CommsServiceClient>>::from_ref(state);
- let user_context: Extension<UserContext> = parts
+ let MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ } = parts
.extract()
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
@@ -44,7 +51,7 @@ where
.await
.map_err(|_| AccessLevelErr::InternalErr)?;
- if project_context.user_id == user_context.user_id {
+ if project_context.user_id == macro_user_id {
return Ok(Self {
access_level: AccessLevel::Owner,
desired: PhantomData,
diff --git a/rust/cloud-storage/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs b/rust/cloud-storage/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
index b0cef8c31e..0e07cd74d2 100644
--- a/rust/cloud-storage/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
+++ b/rust/cloud-storage/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs
@@ -5,6 +5,7 @@ use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::Response;
use email_service_client::EmailServiceClient;
+use macro_user_id::cowlike::CowLike;
use model::thread::EmailThreadPermission;
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
@@ -58,14 +59,14 @@ pub async fn insert_thread_share_permissions(
.await
.context("Failed to get thread owner from email-service")?;
- let owner_id = owner_result.user_id.to_string();
+ let owner_id = owner_result.user_id;
// Create a new share permission
let share_permission = SharePermissionV2 {
id: macro_uuid::generate_uuid_v7().to_string(),
is_public: false,
public_access_level: None,
- owner: owner_id.clone(),
+ owner: owner_id.to_string(),
channel_share_permissions: None,
};
@@ -73,7 +74,7 @@ pub async fn insert_thread_share_permissions(
let permission = macro_db_client::share_permission::create::create_thread_permission(
&mut tx,
- &owner_id,
+ owner_id.copied(),
thread_id,
&share_permission,
)
@@ -83,7 +84,7 @@ pub async fn insert_thread_share_permissions(
// insert UserItemAccess for owner
macro_db_client::item_access::insert::insert_user_item_access(
&mut tx,
- &owner_id,
+ owner_id,
thread_id,
"thread",
AccessLevel::Owner,
diff --git a/rust/cloud-storage/macro_share_permissions/Cargo.toml b/rust/cloud-storage/macro_share_permissions/Cargo.toml
index ea2454cb09..84a95d599f 100644
--- a/rust/cloud-storage/macro_share_permissions/Cargo.toml
+++ b/rust/cloud-storage/macro_share_permissions/Cargo.toml
@@ -9,6 +9,7 @@ version = "0.1.0"
anyhow = { workspace = true }
comms_service_client = { path = "../comms_service_client" }
macro_db_client = { path = "../macro_db_client" }
+macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
diff --git a/rust/cloud-storage/macro_share_permissions/src/notification.rs b/rust/cloud-storage/macro_share_permissions/src/notification.rs
index 25bb58870a..9d14e840bc 100644
--- a/rust/cloud-storage/macro_share_permissions/src/notification.rs
+++ b/rust/cloud-storage/macro_share_permissions/src/notification.rs
@@ -1,4 +1,5 @@
use anyhow::Context;
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use model_notifications::{
ItemSharedMetadata, ItemSharedOrganizationMetadata, NotificationEvent, NotificationQueueMessage,
@@ -16,10 +17,10 @@ pub struct ItemShareNotifications {
/// Generates a share notification event to be sent to notification queue
/// Returns two notifcaitons (<individual_user_notification>, <organization_notification>)
pub fn create_notifications_from_item_shared(
- item_id: &str, // The id of the item that was shared
- item_type: &str, // The type of the item that was shared
- item_name: Option<String>, // The name/title of the shared item
- user_id: &str, // The user id that performed the edit
+ item_id: &str, // The id of the item that was shared
+ item_type: &str, // The type of the item that was shared
+ item_name: Option<String>, // The name/title of the shared item
+ user_id: MacroUserIdStr<'static>, // The user id that performed the edit
// The user ids that were added to the share permission
user_ids: &[String],
// The user ids that were added to the organization share permission
@@ -33,7 +34,7 @@ pub fn create_notifications_from_item_shared(
NotificationQueueMessage {
notification_entity: entity_type.with_entity_string(item_id.to_string()),
notification_event: event_type,
- sender_id: Some(user_id.to_string()),
+ sender_id: Some(user_id.clone()),
recipient_ids: Some(recipients.to_vec()),
}
};
@@ -44,7 +45,7 @@ pub fn create_notifications_from_item_shared(
item_type: entity_type,
item_id: item_id.to_string(),
item_name: item_name.clone(),
- shared_by: user_id.to_string(),
+ shared_by: user_id.clone(),
permission_level: permission_level.clone(),
};
@@ -62,7 +63,7 @@ pub fn create_notifications_from_item_shared(
item_type: entity_type,
item_id: item_id.to_string(),
item_name,
- shared_by: user_id.to_string(),
+ shared_by: user_id.clone(),
permission_level,
};
Some(build_message(
diff --git a/rust/cloud-storage/macro_user_id/src/lowercased.rs b/rust/cloud-storage/macro_user_id/src/lowercased.rs
index 6cd1ddad1f..d960ccba05 100644
--- a/rust/cloud-storage/macro_user_id/src/lowercased.rs
+++ b/rust/cloud-storage/macro_user_id/src/lowercased.rs
@@ -5,7 +5,7 @@ use std::sync::Arc;
/// The lowercase struct upholds the invariant that its contents are guaranteed to be
/// lowercased unicode characters
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Lowercase<'a>(ArcCowStr<'a>);
impl<'a> Lowercase<'a> {
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 0985793ec5..dc8f638d18 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -64,7 +64,7 @@ where
/// This is a value which is guaranteed to be unmodified from its original input
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(try_from = "String", into = "String")]
-pub struct MacroUserIdStr<'a>(pub MacroUserId<ArcCowStr<'a>>);
+pub struct MacroUserIdStr<'a>(pub MacroUserId<Lowercase<'a>>);
/// Deserialize a MacroUserId to a guaranteed borrowed lifetime from the 'de argument
#[derive(Debug, Clone, Deserialize)]
@@ -80,7 +80,7 @@ impl<'a> std::fmt::Display for MacroUserIdStr<'a> {
}
impl<'a> Deref for MacroUserIdStr<'a> {
- type Target = MacroUserId<ArcCowStr<'a>>;
+ type Target = MacroUserId<Lowercase<'a>>;
fn deref(&self) -> &Self::Target {
&self.0
@@ -91,7 +91,9 @@ impl<'a> MacroUserIdStr<'a> {
/// parse the inner value from the input string
#[tracing::instrument(err)]
pub fn parse_from_str(s: &'a str) -> Result<Self, ParseErr> {
- MacroUserId::parse_from_str(s).map(MacroUserIdStr)
+ MacroUserId::parse_from_str(s)
+ .map(|id| id.lowercase())
+ .map(MacroUserIdStr)
}
}
@@ -108,6 +110,7 @@ impl TryFrom<String> for MacroUserIdStr<'static> {
fn try_from(value: String) -> Result<Self, Self::Error> {
MacroUserId::parse_from_str(&value)
.map(CowLike::into_owned)
+ .map(|i| i.lowercase())
.map(MacroUserIdStr)
}
}
diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.toml
index 099c1f2bdc..3b98422966 100644
--- a/rust/cloud-storage/model/Cargo.toml
+++ b/rust/cloud-storage/model/Cargo.toml
@@ -15,6 +15,8 @@ anyhow = { workspace = true }
axum = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
+document_sub_type = { path = "../document_sub_type" }
+macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response" }
model_file_type = { path = "../model_file_type", features = ["utoipa"] }
model_user = { path = "../model_user" }
@@ -34,4 +36,3 @@ thiserror.workspace = true
tracing = { workspace = true }
utoipa = { workspace = true, features = ["axum_extras", "chrono"] }
uuid = { workspace = true }
-document_sub_type = { path = "../document_sub_type" }
diff --git a/rust/cloud-storage/model/src/activity/map_item.rs b/rust/cloud-storage/model/src/activity/map_item.rs
index cf57a3ae73..bb16ec846c 100644
--- a/rust/cloud-storage/model/src/activity/map_item.rs
+++ b/rust/cloud-storage/model/src/activity/map_item.rs
@@ -1,4 +1,5 @@
use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use crate::{chat::Chat, document::BasicDocument};
@@ -23,7 +24,7 @@ pub fn map_document_item(
) -> anyhow::Result<BasicDocument> {
Ok(BasicDocument {
document_id: id,
- owner: user_id,
+ owner: MacroUserIdStr::parse_from_str(&user_id)?.into_owned(),
document_version_id: document_version_id.unwrap().parse::<i64>().unwrap(),
document_name: name,
created_at,
diff --git a/rust/cloud-storage/model/src/chat/mod.rs b/rust/cloud-storage/model/src/chat/mod.rs
index 4e76a63b83..7cf232663b 100644
--- a/rust/cloud-storage/model/src/chat/mod.rs
+++ b/rust/cloud-storage/model/src/chat/mod.rs
@@ -3,6 +3,7 @@ pub mod preview;
pub mod utils;
use chrono::serde::ts_seconds_option;
+use macro_user_id::user_id::MacroUserIdStr;
pub use message::*;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -50,7 +51,7 @@ pub struct Chat {
pub struct ChatBasic {
pub id: String,
pub name: String,
- pub user_id: String,
+ pub user_id: MacroUserIdStr<'static>,
pub project_id: Option<String>,
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}
diff --git a/rust/cloud-storage/model/src/comms/mod.rs b/rust/cloud-storage/model/src/comms/mod.rs
index 7e0d03da5e..e9fce3798c 100644
--- a/rust/cloud-storage/model/src/comms/mod.rs
+++ b/rust/cloud-storage/model/src/comms/mod.rs
@@ -1,4 +1,5 @@
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use serde::{Deserialize, Serialize};
use sqlx::Type;
use std::collections::HashMap;
@@ -163,7 +164,8 @@ pub struct Message {
pub id: Uuid,
pub channel_id: Uuid,
pub thread_id: Option<Uuid>,
- pub sender_id: String,
+ #[schema(value_type = String)]
+ pub sender_id: MacroUserIdStr<'static>,
pub content: String,
pub created_at: chrono::DateTime<chrono::Utc>,
pub updated_at: chrono::DateTime<chrono::Utc>,
diff --git a/rust/cloud-storage/model/src/document/basic.rs b/rust/cloud-storage/model/src/document/basic.rs
index a205e7bcdc..574bea89be 100644
--- a/rust/cloud-storage/model/src/document/basic.rs
+++ b/rust/cloud-storage/model/src/document/basic.rs
@@ -4,6 +4,7 @@ use crate::document::FileTypeExt;
use super::file_type::FileType;
use chrono::serde::ts_seconds_option;
+use macro_user_id::user_id::MacroUserIdStr;
use utoipa::ToSchema;
#[derive(sqlx::FromRow, serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
@@ -101,12 +102,13 @@ pub struct VersionIDWithTimeStamps {
}
/// Returns basic information of a document used for some db queries
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema, Default)]
-#[serde(default, rename_all = "camelCase")]
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]
+#[serde(rename_all = "camelCase")]
pub struct DocumentBasic {
pub document_id: String,
pub document_name: String,
- pub owner: String,
+ #[schema(value_type = String)]
+ pub owner: MacroUserIdStr<'static>,
#[serde(skip_serializing_if = "Option::is_none")]
pub file_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rs
index e627067c03..9f057433da 100644
--- a/rust/cloud-storage/model/src/document/mod.rs
+++ b/rust/cloud-storage/model/src/document/mod.rs
@@ -2,6 +2,7 @@ use chrono::serde::ts_seconds_option;
pub mod list;
pub mod response;
use document_sub_type::DocumentSubType;
+use macro_user_id::user_id::MacroUserIdStr;
use utoipa::ToSchema;
mod file_type;
@@ -47,7 +48,9 @@ pub struct BasicDocument {
/// the file type
pub document_version_id: i64,
/// The owner of the document
- pub owner: String,
+ #[schema(value_type = String)]
+ #[sqlx(try_from = "String")]
+ pub owner: MacroUserIdStr<'static>,
/// The name of the document
#[serde(rename = "name", alias = "documentName")]
pub document_name: String,
@@ -118,15 +121,7 @@ pub struct BackfillSearchDocumentInformation {
pub file_type: FileType,
}
#[derive(
- sqlx::FromRow,
- serde::Serialize,
- serde::Deserialize,
- Eq,
- PartialEq,
- Debug,
- Clone,
- ToSchema,
- Default,
+ sqlx::FromRow, serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DocumentMetadata {
@@ -137,7 +132,9 @@ pub struct DocumentMetadata {
/// the file type
pub document_version_id: i64,
/// The owner of the document
- pub owner: String,
+ #[schema(value_type = String)]
+ #[sqlx(try_from = "String")]
+ pub owner: MacroUserIdStr<'static>,
/// The name of the document
pub document_name: String,
/// The file type of the document (file extension)
@@ -194,7 +191,7 @@ impl DocumentMetadata {
pub fn new_docx(
document_id: &str,
document_bom_id: i64,
- owner: &str,
+ owner: MacroUserIdStr<'static>,
document_name: &str,
file_type: &str,
document_family_id: Option<i64>,
@@ -207,7 +204,7 @@ impl DocumentMetadata {
) -> Self {
Self {
document_id: document_id.to_string(),
- owner: owner.to_string(),
+ owner,
document_name: document_name.to_string(),
file_type: Some(file_type.to_string()),
sha: None,
@@ -233,7 +230,7 @@ impl DocumentMetadata {
pub fn new_document(
document_id: &str,
document_instance_id: i64,
- owner: &str,
+ owner: MacroUserIdStr<'static>,
document_name: &str,
file_type: Option<FileType>,
sha: &str,
@@ -248,7 +245,7 @@ impl DocumentMetadata {
) -> Self {
Self {
document_id: document_id.to_string(),
- owner: owner.to_string(),
+ owner,
document_name: document_name.to_string(),
file_type: file_type.map(|s| s.as_str().to_string()),
sha: Some(sha.to_string()),
@@ -273,7 +270,7 @@ impl DocumentMetadata {
pub fn document(
document_id: &str,
document_instance_id: i64,
- owner: &str,
+ owner: MacroUserIdStr<'static>,
document_name: &str,
file_type: Option<&str>,
sha: &str,
@@ -289,7 +286,7 @@ impl DocumentMetadata {
) -> Self {
Self {
document_id: document_id.to_string(),
- owner: owner.to_string(),
+ owner,
document_name: document_name.to_string(),
file_type: file_type.map(|s| s.to_string()),
sha: Some(sha.to_string()),
diff --git a/rust/cloud-storage/model/src/document/response/mod.rs b/rust/cloud-storage/model/src/document/response/mod.rs
index 46a70817e6..481566fbf2 100644
--- a/rust/cloud-storage/model/src/document/response/mod.rs
+++ b/rust/cloud-storage/model/src/document/response/mod.rs
@@ -2,6 +2,7 @@ mod location;
use document_sub_type::DocumentSubType;
pub use location::*;
+use macro_user_id::user_id::MacroUserIdStr;
use std::str::FromStr;
use crate::document::{BomPart, FileType};
@@ -92,7 +93,8 @@ pub struct DocumentResponseMetadata {
/// the file type
pub document_version_id: i64,
/// The owner of the document
- pub owner: String,
+ #[schema(value_type = String)]
+ pub owner: MacroUserIdStr<'static>,
/// The name of the document
pub document_name: String,
/// The file type of the document
diff --git a/rust/cloud-storage/model/src/document_storage_service_internal.rs b/rust/cloud-storage/model/src/document_storage_service_internal.rs
index 752dd4d28d..59d4ccaedd 100644
--- a/rust/cloud-storage/model/src/document_storage_service_internal.rs
+++ b/rust/cloud-storage/model/src/document_storage_service_internal.rs
@@ -1,4 +1,5 @@
use crate::item::{ShareableItem, UserAccessibleItem};
+use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::channel_share_permission::UpdateOperation;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -9,7 +10,7 @@ pub struct UpdateChannelSharePermissionRequest {
/// The id of the channel to add/remove from the share permissions
pub channel_id: String,
/// The user who initiated the update
- pub user_id: String,
+ pub user_id: MacroUserIdStr<'static>,
/// The item id
pub item_id: String,
/// The item type
@@ -64,6 +65,6 @@ pub struct GetDocumentsMetadataResponse {
pub struct DocumentMetadata {
pub item_id: String,
pub item_name: String,
- pub item_owner: String,
+ pub item_owner: MacroUserIdStr<'static>,
pub file_type: Option<String>,
}
diff --git a/rust/cloud-storage/model/src/item/map_item.rs b/rust/cloud-storage/model/src/item/map_item.rs
index ede9958d92..0d8ee50c0f 100644
--- a/rust/cloud-storage/model/src/item/map_item.rs
+++ b/rust/cloud-storage/model/src/item/map_item.rs
@@ -1,4 +1,5 @@
use document_sub_type::DocumentSubType;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use crate::{chat::Chat, document::BasicDocument, project::Project};
@@ -24,7 +25,7 @@ pub fn map_document_item(
) -> anyhow::Result<BasicDocument> {
Ok(BasicDocument {
document_id: id,
- owner: user_id,
+ owner: MacroUserIdStr::parse_from_str(&user_id)?.into_owned(),
document_version_id: document_version_id.unwrap().parse::<i64>().unwrap(),
document_name: name,
created_at,
diff --git a/rust/cloud-storage/model/src/item/tests.rs b/rust/cloud-storage/model/src/item/tests.rs
index 736e34966c..14f47e1752 100644
--- a/rust/cloud-storage/model/src/item/tests.rs
+++ b/rust/cloud-storage/model/src/item/tests.rs
@@ -6,6 +6,7 @@
* as a normal rust type.
*/
use super::*;
+use macro_user_id::user_id::MacroUserIdStr;
use utoipa::ToSchema;
#[test]
fn test_expected_schema() {
@@ -110,7 +111,7 @@ fn test_document_serde() {
let doc = BasicDocument {
document_id: "doc123".to_string(),
document_version_id: 1,
- owner: "user1".to_string(),
+ owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
document_name: "Test Document".to_string(),
file_type: Some("pdf".to_string()),
sha: Some("abc123".to_string()),
diff --git a/rust/cloud-storage/model/src/project/mod.rs b/rust/cloud-storage/model/src/project/mod.rs
index be80be549f..01a1e33dff 100644
--- a/rust/cloud-storage/model/src/project/mod.rs
+++ b/rust/cloud-storage/model/src/project/mod.rs
@@ -1,4 +1,5 @@
use chrono::serde::ts_seconds_option;
+use macro_user_id::user_id::MacroUserIdStr;
use models_bulk_upload::ProjectDocumentStatus;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -49,7 +50,9 @@ pub struct PendingProject {
#[serde(rename_all = "camelCase")]
pub struct BasicProject {
pub id: String,
- pub user_id: String,
+ #[schema(value_type = String)]
+ #[sqlx(try_from = "String")]
+ pub user_id: MacroUserIdStr<'static>,
pub parent_id: Option<String>,
pub name: String,
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index b96902e26f..ee754fbf84 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -151,7 +151,8 @@ pub struct UserNotification {
/// If the notification is "done"
pub done: bool,
/// user id of the macro user who generated the notification
- pub sender_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub sender_id: Option<MacroUserIdStr<'static>>,
#[serde(flatten)]
pub temporal: NotificationTemporalData,
#[serde(flatten)]
@@ -197,7 +198,8 @@ pub struct Notification {
#[serde(flatten)]
pub notification_entity: Entity<'static>,
pub service_sender: String,
- pub sender_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub sender_id: Option<MacroUserIdStr<'static>>,
#[serde(flatten)]
pub temporal: NotificationTemporalData,
#[serde(flatten)]
@@ -237,7 +239,7 @@ pub struct NotificationQueueMessage {
pub notification_entity: Entity<'static>,
#[serde(flatten, rename = "metadata")]
pub notification_event: NotificationEvent,
- pub sender_id: Option<String>,
+ pub sender_id: Option<MacroUserIdStr<'static>>,
pub recipient_ids: Option<Vec<String>>,
}
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 0dcc840d66..db35d1eb7f 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -1,11 +1,10 @@
use crate::NotificationEventType;
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use models_comms::ChannelType;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use utoipa::ToSchema;
-type UserId = String;
-
/// Common metadata for notifications on channels
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -24,7 +23,8 @@ pub struct CommonChannelMetadata {
#[serde(rename_all = "camelCase")]
pub struct ChannelInviteMetadata {
#[serde(alias = "invited_by")]
- pub invited_by: UserId,
+ #[schema(value_type = String)]
+ pub invited_by: MacroUserIdStr<'static>,
#[serde(flatten)]
pub common: CommonChannelMetadata,
}
@@ -35,7 +35,8 @@ pub struct ChannelMessageSendMetadata {
/// The user who sent the message
#[serde(alias = "invited_by")]
#[serde(alias = "invitedBy")]
- pub sender: UserId,
+ #[schema(value_type = String)]
+ pub sender: MacroUserIdStr<'static>,
/// The content of the message
#[serde(default)]
#[serde(alias = "message_content")]
@@ -64,7 +65,8 @@ pub struct ItemSharedMetadata {
#[serde(alias = "item_name")]
pub item_name: Option<String>,
#[serde(alias = "shared_by")]
- pub shared_by: UserId,
+ #[schema(value_type = String)]
+ pub shared_by: MacroUserIdStr<'static>,
/// Permission level granted (read, write, admin, etc.)
#[serde(alias = "permission_level")]
pub permission_level: Option<String>,
@@ -88,7 +90,8 @@ pub struct ItemSharedOrganizationMetadata {
pub item_name: Option<String>,
/// The user who shared the item
#[serde(alias = "shared_by")]
- pub shared_by: UserId,
+ #[schema(value_type = String)]
+ pub shared_by: MacroUserIdStr<'static>,
/// Permission level granted (read, write, admin, etc.)
#[serde(alias = "permission_level")]
pub permission_level: Option<String>,
@@ -105,7 +108,8 @@ pub struct InviteToTeamMetadata {
pub team_id: String,
/// The user who sent the invitation
#[serde(alias = "invited_by")]
- pub invited_by: UserId,
+ #[schema(value_type = String)]
+ pub invited_by: MacroUserIdStr<'static>,
/// Role/permission level in the team
pub role: Option<String>,
}
@@ -138,7 +142,8 @@ pub struct ChannelReplyMetadata {
pub message_id: String,
/// The sender id of the reply
#[serde(alias = "user_id")]
- pub user_id: String,
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
/// The message content
#[serde(alias = "message_content")]
pub message_content: String,
@@ -153,7 +158,8 @@ pub struct DocumentMentionMetadata {
#[serde(alias = "document_name")]
pub document_name: String,
/// The owner of the document
- pub owner: UserId,
+ #[schema(value_type = String)]
+ pub owner: MacroUserIdStr<'static>,
/// The file type of the document
#[serde(alias = "file_type")]
pub file_type: Option<String>,
diff --git a/rust/cloud-storage/model_notifications/src/raw.rs b/rust/cloud-storage/model_notifications/src/raw.rs
index e95984d7df..9f40a059b6 100644
--- a/rust/cloud-storage/model_notifications/src/raw.rs
+++ b/rust/cloud-storage/model_notifications/src/raw.rs
@@ -4,6 +4,7 @@ use crate::{
};
use anyhow::Context;
use chrono::{DateTime, serde::ts_seconds_option};
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
use serde::{Deserialize, Serialize};
@@ -32,7 +33,8 @@ pub struct RawNotification {
/// Custom metadata that may be needed for the notification
pub metadata: Option<serde_json::Value>,
/// user id of the macro user who generated the notification
- pub sender_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub sender_id: Option<MacroUserIdStr<'static>>,
}
/// NOTE: This should only be used for deserialization from the db
@@ -68,7 +70,8 @@ pub struct RawUserNotification {
/// Custom metadata that may be provided from the notification
pub notification_metadata: Option<serde_json::Value>,
/// user id of the macro user who generated the notification
- pub sender_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub sender_id: Option<MacroUserIdStr<'static>>,
/// The time the notification was updated.
/// This is the exact same as created_at and only used to make soup
/// bettter on the frontend.
diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rs
index 2521e8383a..e1a3a32340 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -3,6 +3,7 @@ use crate::service::attachment::{Attachment, AttachmentMacro};
use crate::service::contact::Contact;
use crate::service::message::MessageWithBodyReplyless;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Identify, SimpleSortMethod, SortOn};
use models_permissions::share_permission::access_level::AccessLevel;
use schemars::JsonSchema;
@@ -339,5 +340,6 @@ pub struct UserThreadIds {
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct GetThreadOwnerResponse {
- pub user_id: String,
+ #[schema(value_type = String)]
+ pub user_id: MacroUserIdStr<'static>,
}
diff --git a/rust/cloud-storage/models_permissions/src/share_permission/mod.rs b/rust/cloud-storage/models_permissions/src/share_permission/mod.rs
index a89e608e9b..f5c18cae60 100644
--- a/rust/cloud-storage/models_permissions/src/share_permission/mod.rs
+++ b/rust/cloud-storage/models_permissions/src/share_permission/mod.rs
@@ -4,7 +4,6 @@ use crate::share_permission::channel_share_permission::{
};
use model_file_type::FileType;
use utoipa::ToSchema;
-
pub mod access_level;
pub mod channel_share_permission;
pub mod user_permission;
diff --git a/rust/cloud-storage/notification_db_client/src/notification/create.rs b/rust/cloud-storage/notification_db_client/src/notification/create.rs
index 09c0726a2f..55decde2c2 100644
--- a/rust/cloud-storage/notification_db_client/src/notification/create.rs
+++ b/rust/cloud-storage/notification_db_client/src/notification/create.rs
@@ -21,7 +21,7 @@ pub async fn create_notification(
entity_type,
notification.service_sender,
notification.metadata,
- notification.sender_id,
+ notification.sender_id.as_ref().map(|id| id.as_ref()),
)
.fetch_one(&pool)
.await?;
@@ -58,7 +58,7 @@ pub async fn create_notification_transaction(
entity_type,
notification.service_sender,
notification.metadata,
- notification.sender_id,
+ notification.sender_id.as_ref().map(|id| id.as_ref()),
)
.fetch_one( transaction.as_mut())
.await?;
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
index 0c569251e9..a0974ce805 100644
--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
@@ -1,5 +1,6 @@
use std::str::FromStr;
+use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};
use model_entity::EntityType;
use model_notifications::RawUserNotification;
use models_pagination::{CreatedAt, Query};
@@ -61,7 +62,13 @@ pub async fn get_all_user_notifications(
viewed_at: row.viewed_at,
deleted_at: row.deleted_at,
notification_metadata: row.notification_metadata,
- sender_id: row.sender_id,
+ sender_id: row
+ .sender_id
+ .map(|s| {
+ Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())
+ })
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,
updated_at: row.updated_at,
})
})
@@ -133,7 +140,13 @@ pub async fn get_all_user_notifications_by_event_item_ids(
viewed_at: row.viewed_at,
deleted_at: row.deleted_at,
notification_metadata: row.notification_metadata,
- sender_id: row.sender_id,
+ sender_id: row
+ .sender_id
+ .map(|s| {
+ Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())
+ })
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,
updated_at: row.updated_at,
})
})
diff --git a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs b/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
index f63d3524ed..0462d0741e 100644
--- a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
@@ -1,12 +1,11 @@
use crate::{api::context::ApiContext, model::notification::CreateNotification};
use axum::{
- Extension, Json,
+ Json,
extract::{self, State},
http::StatusCode,
response::{IntoResponse, Response},
};
-use model::response::ErrorResponse;
-use model::user::UserContext;
+use model::{response::ErrorResponse, user::axum_extractor::MacroUserExtractor};
use model_notifications::{
Notification, NotificationEvent, NotificationEventType, RawNotification,
};
@@ -22,10 +21,10 @@ use std::str::FromStr;
(status = 200, body=Notification),
)
)]
-#[tracing::instrument(skip(ctx, user_context, req))]
+#[tracing::instrument(skip(ctx, macro_user, req))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ macro_user: MacroUserExtractor,
extract::Json(req): extract::Json<CreateNotification>,
) -> Result<Response, Response> {
let id = macro_uuid::generate_uuid_v7();
@@ -60,7 +59,7 @@ pub async fn handler(
id,
notification_entity: req.entity,
service_sender: req.service_sender,
- sender_id: Some(user_context.user_id.clone()),
+ sender_id: Some(macro_user.macro_user_id),
temporal: Default::default(),
notification_event,
};
diff --git a/rust/cloud-storage/notification_service/src/notification/process.rs b/rust/cloud-storage/notification_service/src/notification/process.rs
index 3fcba810a7..4f8a9a40fb 100644
--- a/rust/cloud-storage/notification_service/src/notification/process.rs
+++ b/rust/cloud-storage/notification_service/src/notification/process.rs
@@ -105,7 +105,8 @@ pub(crate) async fn process_message(
);
let user_ids =
- filter_sender_id_from_recipient_ids(sender_id, recipient_ids).unwrap_or_default();
+ filter_sender_id_from_recipient_ids(sender_id.map(|r| r.as_ref()), recipient_ids)
+ .unwrap_or_default();
// If there are no users to notify, we can skip the notification
if user_ids.is_empty() {
diff --git a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs b/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
index c453431ef2..284501396b 100644
--- a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
+++ b/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
use macro_cache_client::MacroCache;
+use macro_user_id::email::ReadEmailParts;
use model_notifications::{Notification, NotificationEventType};
/// Performs a basic rate limit check on the notification
@@ -18,23 +19,23 @@ pub async fn rate_limit(
.as_ref()
.context("expected sender id to be present in channel invite notification")?;
- let email = sender_id.replace("macro|", "");
+ let email = sender_id.email_part();
let channel_invite_rate_limit = macro_cache_client
- .get_channel_invite_rate_limit(&email)
+ .get_channel_invite_rate_limit(email.email_str())
.await
.context("unable to get channel invite rate limit")?;
if let Some(channel_invite_rate_limit) = channel_invite_rate_limit
&& channel_invite_rate_limit >= 10
{
- tracing::error!(email=%email, "rate limit channel invite exceeded");
+ tracing::error!(email=%email.email_str(), "rate limit channel invite exceeded");
return Ok(true);
}
tracing::trace!("incrementing channel invite rate limit");
macro_cache_client
- .increment_channel_invite_rate_limit(&email, 3600) // 1 hour
+ .increment_channel_invite_rate_limit(email.email_str(), 3600) // 1 hour
.await
.context("unable to increment channel invite rate limit")?;
@@ -48,23 +49,23 @@ pub async fn rate_limit(
.as_ref()
.context("expected sender id to be present in invite to team notification")?;
- let email = sender_id.replace("macro|", "");
+ let email = sender_id.email_part();
let invite_to_team_rate_limit = macro_cache_client
- .get_invite_to_team_rate_limit(&email)
+ .get_invite_to_team_rate_limit(email.email_str())
.await
.context("unable to get invite to team rate limit")?;
if let Some(invite_to_team_rate_limit) = invite_to_team_rate_limit
&& invite_to_team_rate_limit >= 5
{
- tracing::error!(email=%email, "rate limit invite to team exceeded");
+ tracing::error!(email=%email.email_str(), "rate limit invite to team exceeded");
return Ok(true);
}
tracing::trace!("incrementing invite to team rate limit");
macro_cache_client
- .increment_invite_to_team_rate_limit(&email, 3600) // 1 hour
+ .increment_invite_to_team_rate_limit(email.email_str(), 3600) // 1 hour
.await
.context("unable to increment invite to team rate limit")?;
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
index 3ec41f655d..c8dc3b46f3 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
@@ -2,6 +2,7 @@ use std::collections::HashSet;
use anyhow::Context;
use authentication_service_client::AuthServiceClient;
+use macro_user_id::email::ReadEmailParts;
use model_notifications::{NotificationEventType, NotificationWithRecipient};
use notification_db_client::user_notification::get::should_email::should_email_based_on_user_notification_bulk;
@@ -125,16 +126,17 @@ async fn filter_by_rate_limit(
) -> anyhow::Result<Vec<String>> {
match notification.inner.notification_event.event_type() {
NotificationEventType::ChannelInvite => {
- let invited_by_email = notification
+ let sender_id = notification
.inner
.sender_id
.as_ref()
- .map(|sender_id| sender_id.replace("macro|", ""))
.context("unable to get sender id")?;
+ let invited_by_email = sender_id.email_part();
+
let channel_invited_rate_limit = queue_worker_context
.macro_cache_client
- .get_channel_invited_rate_limit_bulk(emails, &invited_by_email)
+ .get_channel_invited_rate_limit_bulk(emails, invited_by_email.email_str())
.await
.context("unable to get channel invited rate limit")?;
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
index 5f79992108..6ce2be94d7 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
@@ -5,6 +5,7 @@ use anyhow::Context;
use filter::filter_emails;
use futures::StreamExt;
use macro_env::Environment;
+use macro_user_id::email::ReadEmailParts;
use model_notifications::{NotificationEventType, NotificationWithRecipient};
use crate::{env::SENDER_ADDRESS, notification::context::QueueWorkerContext};
@@ -36,7 +37,7 @@ pub async fn process_email_notifications(
return Ok(());
}
- if !sender_id.unwrap().ends_with("@macro.com") {
+ if sender_id.unwrap().email_part().domain_part() != "macro.com" {
tracing::info!(
"not sending notification emails for non-macro users in non-prod environment"
);
@@ -72,7 +73,7 @@ pub async fn process_email_notifications(
.inner
.sender_id
.as_ref()
- .map(|s| s.replace("macro|", ""))
+ .map(|s| s.email_part().email_str().to_string())
.context("sender id should exist")?;
notification_db_client::channel_notification_email_sent::upsert::upsert_channel_notification_email_sent_bulk(
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs b/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
index 3f45ba5483..0e63639a22 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
@@ -5,6 +5,7 @@ use crate::{
};
use anyhow::Context;
use macro_env::{Environment, ext::frontend_url::FrontendUrl};
+use macro_user_id::email::ReadEmailParts;
use model_entity::EntityType;
use model_notifications::{
ChannelInviteMetadata, ChannelMessageSendMetadata, NotificationEventType,
@@ -56,12 +57,6 @@ pub fn fill_email_template(
let mut item_name =
metadata_utils::get_metadata_value::<String>(notification, "item_name")?;
- let sender = notification
- .inner
- .sender_id
- .clone()
- .context("notification does not have sender id")?;
-
let item_url = get_item_share_url(notification).context("unable to create item url")?;
if matches!(
@@ -74,7 +69,14 @@ pub fn fill_email_template(
item_name = format!("{}.{}", item_name, file_type);
}
- let sender = sender.replace("macro|", "");
+ let sender = notification
+ .inner
+ .sender_id
+ .as_ref()
+ .context("notification does not have sender id")?
+ .email_part()
+ .email_str()
+ .to_string();
Ok(item_share::fill_item_share_template(
&item_url,
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
index b1e9d2e08e..bc6e46ee9f 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
@@ -13,299 +13,6 @@ use sns_client::{APNSPushNotification, Aps};
use std::str::FromStr;
use thiserror::Error;
-/// Given a notification, this generates a push notification object
-/// Returns (message_json, message_attributes) if the notification is valid
-/// Returns Err if the notification is invalid
-/// NOTE: @synoet - I think push notifications should be generated using the new
-/// [NotificationEvnet] type instead of the [NotificationWithRecipient] type
-/// Simmilarly, each of these should implement some sort of PushDisplay trait
-// pub fn generate_push_notification(notification: &NotificationWithRecipient) {
-// let (title, message, open_route): (String, String, String) = match notification
-// .inner
-// .notification_event
-// .event_type()
-// {
-// NotificationEventType::ChannelInvite => {
-// let metadata = if let Some(metadata) = notification
-// .inner
-// .notification_event
-// .metadata_json()
-// .as_ref()
-// {
-// metadata.clone()
-// } else {
-// return Err(anyhow::anyhow!("notification does not have metadata"));
-// };
-// let metadata: ChannelInviteMetadata = serde_json::from_value(metadata.clone())?;
-
-// let title = format!(
-// "{} invited you to join {}",
-// metadata.invited_by, metadata.common.channel_name
-// );
-
-// let open_route = format!(
-// "/channel/{}",
-// notification.inner.notification_entity.entity_id
-// );
-
-// (title, "".to_string(), open_route)
-// }
-// NotificationEventType::ChannelMessageSend => {
-// let metadata = if let Some(metadata) = notification
-// .inner
-// .notification_event
-// .metadata_json()
-// .as_ref()
-// {
-// metadata.clone()
-// } else {
-// return Err(anyhow::anyhow!("notification does not have metadata"));
-// };
-// let metadata: ChannelMessageSendMetadata = serde_json::from_value(metadata.clone())?;
-// let message: String = metadata.message_content;
-// let email = notification
-// .inner
-// .sender_id
-// .clone()
-// .context("expected sender id")?
-// .replace("macro|", "");
-
-// let message_item = if message.is_empty() {
-// "an attachment"
-// } else {
-// "a message"
-// };
-
-// let channel_name = metadata.common.channel_name;
-
-// let title = match metadata.common.channel_type {
-// ChannelType::DirectMessage => {
-// format!("{} sent you {}", email, message_item)
-// }
-// _ => {
-// format!("{} sent {} to #{}", email, message_item, channel_name)
-// }
-// };
-
-// let message_id = format!("?message_id={}", metadata.message_id);
-
-// let open_route = format!(
-// "/channel/{}{}",
-// notification.inner.notification_entity.entity_id, message_id
-// );
-
-// (title, message, open_route)
-// }
-// NotificationEventType::ChannelMessageReply => {
-// let metadata = if let Some(metadata) = notification
-// .inner
-// .notification_event
-// .metadata_json()
-// .as_ref()
-// {
-// metadata.clone()
-// } else {
-// return Err(anyhow::anyhow!("notification does not have metadata"));
-// };
-// let metadata: ChannelReplyMetadata = serde_json::from_value(metadata.clone())?;
-// let message = metadata.message_content;
-
-// let email = notification
-// .inner
-// .sender_id
-// .clone()
-// .context("expected sender id")?
-// .replace("macro|", "");
-
-// let title = format!("{} replied to thread", email);
-// let open_route = format!(
-// "/channel/{}?message_id={}&thread_id={}",
-// notification.inner.notification_entity.entity_id,
-// metadata.message_id,
-// metadata.thread_id
-// );
-
-// (title, message, open_route)
-// }
-// NotificationEventType::ChannelMention => {
-// let channel_metadata = if let Some(channel_metadata) =
-// &notification.inner.notification_event.metadata_json()
-// {
-// channel_metadata.clone()
-// } else {
-// return Err(anyhow::anyhow!("no channel metadata was provided"));
-// };
-
-// let metadata: ChannelMentionMetadata = serde_json::from_value(channel_metadata)?;
-
-// let email = notification
-// .inner
-// .sender_id
-// .clone()
-// .context("expected sender id")?
-// .replace("macro|", "");
-
-// let message = metadata.message_content;
-
-// let title = format!(
-// "{} mentioned you in #{}",
-// email, metadata.common.channel_name
-// );
-
-// let thread_id = if let Some(thread_id) = metadata.thread_id {
-// format!("&thread_id={}", thread_id)
-// } else {
-// "".to_string()
-// };
-
-// let open_route = format!(
-// "/channel/{}?message_id={}{}",
-// notification.inner.notification_entity.entity_id, metadata.message_id, thread_id
-// );
-
-// (title, message, open_route)
-// }
-// NotificationEventType::DocumentMention => {
-// let document_metadata = if let Some(document_metadata) =
-// &notification.inner.notification_event.metadata_json()
-// {
-// document_metadata.clone()
-// } else {
-// return Err(anyhow::anyhow!("no document metadata was provided"));
-// };
-
-// let metadata: DocumentMentionMetadata = serde_json::from_value(document_metadata)?;
-
-// let sender_id = notification
-// .inner
-// .sender_id
-// .as_ref()
-// .context("expected sender id")?;
-
-// if let Some(file_type) = metadata.file_type {
-// let email = sender_id.replace("macro|", "");
-// let message = format!(
-// "{} mentioned you in {}.{}",
-// email, metadata.document_name, file_type
-// );
-// let file_type = FileType::from_str(file_type.as_str())?;
-
-// let block_route = if file_type.is_image() {
-// "image"
-// } else {
-// match file_type {
-// FileType::Pdf => "pdf",
-// FileType::Docx => "write",
-// FileType::Md => "md",
-// _ => "code", // Default to code block
-// }
-// };
-
-// let open_route = format!(
-// "/{}/{}",
-// block_route, notification.inner.notification_entity.entity_id
-// );
-
-// ("New Mention".to_string(), message, open_route)
-// } else {
-// return Err(anyhow::anyhow!("no file type was provided"));
-// }
-// }
-// // no push notifs for email yet
-
-// // NotificationEventType::NewEmail => {
-// // let metadata = if let Some(metadata) = notification.inner.notification_event.metadata_as_json().as_ref() {
-// // metadata.clone()
-// // } else {
-// // return Err(anyhow::anyhow!("notification does not have metadata"));
-// // };
-// // let metadata: NewEmailMetadata = serde_json::from_value(metadata)?;
-// //
-// // let title = if let Some(from_email) = metadata.sender {
-// // format!("New email from {}", from_email)
-// // } else {
-// // "New email".to_string()
-// // };
-// // let message = metadata.subject;
-// // let open_route = format!(
-// // "/email/{}?message_id={}",
-// // metadata.thread_id, notification.inner.notification_entity.event_item_id
-// // );
-// //
-// // (title, message, open_route)
-// // }
-// _ => return Ok(None), // unsupported push notification
-// };
-
-// tracing::trace!(message=?message, "created message");
-
-// let collapse_key = format!(
-// "{}{}",
-// notification.inner.notification_entity.entity_id,
-// notification.inner.notification_event.event_type()
-// );
-
-// // hash the collapse key to shorten it
-// let mut hasher = DefaultHasher::new();
-// collapse_key.hash(&mut hasher);
-// let hash = hasher.finish();
-// let collapse_key = format!("{:x}", hash);
-
-// let push_notification_data = PushNotificationData {
-// notification_entity: notification.inner.notification_entity.clone(),
-// sender_id: notification.inner.sender_id.clone(),
-// open_route: open_route.clone(),
-// };
-
-// let notification_body = serde_json::json!({
-// "title": title,
-// "body": message,
-// });
-
-// let apns = APNSPushNotification {
-// aps: Aps {
-// alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
-// title: Some(title),
-// body: Some(message),
-// ..Default::default()
-// })),
-// ..Default::default()
-// },
-// push_notification_data: push_notification_data.clone(),
-// };
-
-// let message_json = serde_json::json!({
-// "default": serde_json::json!({
-// "notification": notification_body
-// }).to_string(),
-// "APNS": serde_json::to_string(&apns).unwrap_or_else(|_| serde_json::json!({
-// "aps": apns.aps
-// }).to_string()),
-// "GCM": serde_json::json!({
-// "fcmV1Message": {
-// "message": {
-// "android": {
-// "notification": notification_body,
-// "priority": "normal", // options are normal and high
-// "collapse_key": collapse_key.clone()
-// },
-// "data": push_notification_data,
-// },
-// }
-// }).to_string()
-// });
-
-// Ok(Some((
-// SnsPayload {
-// default: todo!(),
-// apns: todo!(),
-// apns_sandbox: todo!(),
-// gcm: todo!(),
-// },
-// // build_message_attributes(&collapse_key),
-// )))
-// }
-
#[derive(Debug, Error)]
pub enum NotificationErr {
#[error("The sender_id field was None for a notification which must have a sender")]
@@ -368,18 +75,16 @@ pub fn generate_apns_notification<T: XmlFormatter>(
) -> Result<Option<APNSPushNotification<PushNotificationData>>, NotificationErr> {
let create_push_data = |route: Route| PushNotificationData {
notification_entity: notif.inner.notification_entity.clone(),
- sender_id: notif.inner.sender_id.clone(),
+ sender_id: notif.inner.sender_id.as_ref().map(|x| x.to_string()),
open_route: route.0,
};
let parse_user = || -> Result<MacroUserIdStr<'_>, NotificationErr> {
- Ok(MacroUserIdStr::parse_from_str(
- notif
- .inner
- .sender_id
- .as_ref()
- .ok_or(NotificationErr::SenderDoesntExist)?,
- )?)
+ notif
+ .inner
+ .sender_id
+ .clone()
+ .ok_or(NotificationErr::SenderDoesntExist)
};
Ok(match &notif.inner.notification_event {
@@ -499,7 +204,11 @@ impl BuildNotification for ChannelMessageSendMetadata {
alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
title: Some(match self.common.channel_type {
ChannelType::DirectMessage => self.common.channel_name.to_string(),
- _ => format!("{} <{}>", self.sender, self.common.channel_name),
+ _ => format!(
+ "{} <{}>",
+ self.sender.email_part().local_part(),
+ self.common.channel_name
+ ),
}),
body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),
..Default::default()
diff --git a/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs b/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs
index a2d413bc0f..7730f478d9 100644
--- a/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs
+++ b/rust/cloud-storage/notification_service/src/notification/user_ids/utils.rs
@@ -1,7 +1,7 @@
use anyhow::{Result, anyhow};
pub fn filter_sender_id_from_recipient_ids(
- sender_id: Option<&String>,
+ sender_id: Option<&str>,
recipient_ids: Option<&Vec<String>>,
) -> Result<Vec<String>> {
let user_id = sender_id.ok_or(anyhow!("no sender id provided"))?;
@@ -22,6 +22,8 @@ pub fn filter_sender_id_from_recipient_ids(
#[cfg(test)]
mod tests {
+ use macro_user_id::user_id::MacroUserIdStr;
+
use super::*;
#[test]
@@ -32,17 +34,18 @@ mod tests {
"user2".to_string(),
"user3".to_string(),
]);
- let filtered =
- filter_sender_id_from_recipient_ids(sender_id.as_ref(), recipient_ids.as_ref())?;
+ let filtered = filter_sender_id_from_recipient_ids(
+ sender_id.as_ref().map(|x| x.as_str()),
+ recipient_ids.as_ref(),
+ )?;
assert_eq!(filtered, vec!["user2".to_string(), "user3".to_string()]);
Ok(())
}
#[test]
fn test_filter_sender_id_no_sender() {
- let sender_id: Option<&String> = None;
let recipient_ids = Some(vec!["user1".to_string(), "user2".to_string()]);
- let result = filter_sender_id_from_recipient_ids(sender_id, recipient_ids.as_ref());
+ let result = filter_sender_id_from_recipient_ids(None, recipient_ids.as_ref());
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err.to_string(), "no sender id provided");
@@ -51,9 +54,12 @@ mod tests {
#[test]
fn test_filter_sender_id_no_recipients() {
- let sender_id = Some("user1".to_string());
+ let sender_id = Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
let recipient_ids: Option<&Vec<String>> = None;
- let result = filter_sender_id_from_recipient_ids(sender_id.as_ref(), recipient_ids);
+ let result = filter_sender_id_from_recipient_ids(
+ sender_id.as_ref().map(|x| x.as_ref()),
+ recipient_ids,
+ );
assert!(result.is_err());
if let Err(err) = result {
assert_eq!(err.to_string(), "no recipient ids provided");
@@ -62,14 +68,16 @@ mod tests {
#[test]
fn test_filter_duplicate_recipients() -> Result<()> {
- let sender_id = Some("user1".to_string());
+ let sender_id = Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
let recipient_ids = Some(vec![
"user2".to_string(),
"user2".to_string(),
"user2".to_string(),
]);
- let filtered =
- filter_sender_id_from_recipient_ids(sender_id.as_ref(), recipient_ids.as_ref())?;
+ let filtered = filter_sender_id_from_recipient_ids(
+ sender_id.as_ref().map(|x| x.as_ref()),
+ recipient_ids.as_ref(),
+ )?;
assert_eq!(filtered, vec!["user2".to_string()]);
Ok(())
}
diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/port.rs b/rust/cloud-storage/roles_and_permissions/src/domain/port.rs
index 8c6653e1b6..d60dffead6 100644
--- a/rust/cloud-storage/roles_and_permissions/src/domain/port.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/domain/port.rs
@@ -2,7 +2,7 @@
use std::collections::HashSet;
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use crate::domain::model::{Permission, RoleId, SubscriptionStatus, UserRolesAndPermissionsError};
@@ -15,7 +15,7 @@ pub trait UserRepository: Clone + Send + Sync + 'static {
fn get_user_id_by_email(
&self,
email: &Email<Lowercase<'_>>,
- ) -> impl Future<Output = Result<MacroUserId<Lowercase<'_>>, UserRolesAndPermissionsError>> + Send;
+ ) -> impl Future<Output = Result<MacroUserIdStr<'_>, UserRolesAndPermissionsError>> + Send;
}
/// The UserRolesAndPermissionsRepository defines a set of actions to perform on the users roles and permissions
@@ -23,18 +23,18 @@ pub trait UserRolesAndPermissionsRepository: Clone + Send + Sync + 'static {
/// Gets the permissiosn for a MacroUserID
fn get_user_permissions(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<HashSet<Permission>, UserRolesAndPermissionsError>> + Send;
/// Adds roles with the provided ids to a user
fn add_roles_to_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &[RoleId],
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send;
/// Removes roles from a user
fn remove_roles_from_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &[RoleId],
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send;
}
@@ -51,14 +51,14 @@ pub trait UserRolesAndPermissionsService: Clone + Send + Sync + 'static {
/// Given a user id, upserts the roles for the user
fn dangerous_upsert_roles_for_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: non_empty::NonEmpty<&[RoleId]>,
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send;
/// Removes roles from a user
fn dangerous_remove_roles_from_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &non_empty::NonEmpty<&[RoleId]>,
) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send;
}
diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs b/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs
index b0358b997d..212b39d748 100644
--- a/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs
@@ -10,12 +10,10 @@ impl UserRepository for MockUserRepository {
async fn get_user_id_by_email(
&self,
email: &Email<Lowercase<'_>>,
- ) -> Result<MacroUserId<Lowercase<'_>>, UserRolesAndPermissionsError> {
+ ) -> Result<MacroUserIdStr<'_>, UserRolesAndPermissionsError> {
match email.email_str() {
"[email protected]" => Err(UserRolesAndPermissionsError::UserDoesNotExist),
- "[email protected]" => Ok(MacroUserId::parse_from_str("macro|[email protected]")
- .unwrap()
- .lowercase()),
+ "[email protected]" => Ok(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
_ => Err(UserRolesAndPermissionsError::StorageLayerError(
anyhow::anyhow!("unexpected email"),
)),
@@ -29,14 +27,14 @@ struct MockUserRolesAndPermissionsRepository {}
impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository {
async fn get_user_permissions(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
) -> Result<HashSet<Permission>, UserRolesAndPermissionsError> {
Ok(HashSet::new())
}
async fn add_roles_to_user(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
_role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
Ok(())
@@ -44,7 +42,7 @@ impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository
async fn remove_roles_from_user(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
_role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
Ok(())
@@ -56,7 +54,7 @@ async fn test_get_user_permissions() -> anyhow::Result<()> {
let user_roles_and_permissions_repository = MockUserRolesAndPermissionsRepository::default();
let permissions = user_roles_and_permissions_repository
- .get_user_permissions(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_user_permissions(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert_eq!(permissions.len(), 0);
@@ -105,7 +103,7 @@ async fn test_add_roles_to_user() -> anyhow::Result<()> {
user_roles_and_permissions_repository
.add_roles_to_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
@@ -122,7 +120,7 @@ async fn test_remove_roles_from_user() -> anyhow::Result<()> {
// Remove role
user_roles_and_permissions_repository
.remove_roles_from_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/service.rs b/rust/cloud-storage/roles_and_permissions/src/domain/service.rs
index 69dd3eba82..3d4e30782c 100644
--- a/rust/cloud-storage/roles_and_permissions/src/domain/service.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/domain/service.rs
@@ -1,5 +1,5 @@
//! Contains the service logic for roles and permissions
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use crate::domain::{
model::{RoleId, SubscriptionStatus, UserRolesAndPermissionsError},
@@ -69,7 +69,7 @@ where
async fn dangerous_upsert_roles_for_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: non_empty::NonEmpty<&[RoleId]>,
) -> Result<(), UserRolesAndPermissionsError> {
self.user_roles_and_permissions_repository
@@ -79,7 +79,7 @@ where
async fn dangerous_remove_roles_from_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &non_empty::NonEmpty<&[RoleId]>,
) -> Result<(), UserRolesAndPermissionsError> {
self.user_roles_and_permissions_repository
diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs b/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs
index 71d9ce1190..812843d464 100644
--- a/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs
@@ -1,14 +1,10 @@
+//! Tests for the service logic for roles and permissions
+use super::*;
+use crate::domain::model::Permission;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
-use super::UserRolesAndPermissionsServiceImpl;
-use crate::domain::model::Permission;
-
-///! Tests for the service logic for roles and permissions
-use super::*;
-
use macro_user_id::email::ReadEmailParts;
-use macro_user_id::user_id::MacroUserId;
#[derive(Debug, Clone, Default)]
struct MockUserRepository {}
@@ -17,12 +13,10 @@ impl UserRepository for MockUserRepository {
async fn get_user_id_by_email(
&self,
email: &Email<Lowercase<'_>>,
- ) -> Result<MacroUserId<Lowercase<'_>>, UserRolesAndPermissionsError> {
+ ) -> Result<MacroUserIdStr<'_>, UserRolesAndPermissionsError> {
match email.email_str() {
"[email protected]" => Err(UserRolesAndPermissionsError::UserDoesNotExist),
- "[email protected]" => Ok(MacroUserId::parse_from_str("macro|[email protected]")
- .unwrap()
- .lowercase()),
+ "[email protected]" => Ok(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
_ => Err(UserRolesAndPermissionsError::StorageLayerError(
anyhow::anyhow!("unexpected email"),
)),
@@ -49,14 +43,14 @@ impl MockUserRolesAndPermissionsRepository {
impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository {
async fn get_user_permissions(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
) -> Result<HashSet<Permission>, UserRolesAndPermissionsError> {
Ok(HashSet::new())
}
async fn add_roles_to_user(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
_role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
*self.add_roles_to_user_calls.lock().unwrap() += 1;
@@ -65,7 +59,7 @@ impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository
async fn remove_roles_from_user(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_id: &MacroUserIdStr<'_>,
_role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
*self.remove_roles_from_user_calls.lock().unwrap() += 1;
diff --git a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs
index 72279dd36c..854be28de3 100644
--- a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs
@@ -9,7 +9,7 @@ use macro_user_id::{
cowlike::CowLike,
email::{Email, ReadEmailParts},
lowercased::Lowercase,
- user_id::MacroUserId,
+ user_id::MacroUserIdStr,
};
use sqlx::PgPool;
@@ -35,7 +35,7 @@ impl MacroDB {
async fn get_user_id_from_email<'a>(
&self,
email: &Email<Lowercase<'a>>,
- ) -> Result<MacroUserId<Lowercase<'a>>, anyhow::Error> {
+ ) -> Result<MacroUserIdStr<'a>, anyhow::Error> {
let email: &str = email.email_str();
let user_id = sqlx::query!(
r#"
@@ -47,13 +47,13 @@ impl MacroDB {
.fetch_one(&self.pool)
.await?;
- Ok(MacroUserId::parse_from_str(user_id.as_str()).map(|id| id.into_owned().lowercase())?)
+ Ok(MacroUserIdStr::parse_from_str(user_id.as_str()).map(|id| id.into_owned())?)
}
/// Add roles to the user
async fn add_roles_to_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
roles: &[impl ToString],
) -> Result<(), UserRolesAndPermissionsError> {
let roles = roles.iter().map(|r| r.to_string()).collect::<Vec<_>>();
@@ -76,7 +76,7 @@ impl MacroDB {
/// Remove roles from the user
async fn remove_roles_from_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
roles: &[impl ToString],
) -> Result<(), UserRolesAndPermissionsError> {
let roles = roles.iter().map(|r| r.to_string()).collect::<Vec<_>>();
@@ -97,7 +97,7 @@ impl MacroDB {
/// Get the current permissions for a user
async fn get_user_permissions(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<HashSet<Permission>, UserRolesAndPermissionsError> {
let user_permissions: Vec<Permission> = sqlx::query!(
r#"
@@ -139,14 +139,14 @@ impl From<sqlx::Error> for UserRolesAndPermissionsError {
impl UserRolesAndPermissionsRepository for MacroDB {
async fn get_user_permissions(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<HashSet<Permission>, UserRolesAndPermissionsError> {
self.get_user_permissions(user_id).await
}
async fn add_roles_to_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
self.add_roles_to_user(user_id, role_ids).await
@@ -154,7 +154,7 @@ impl UserRolesAndPermissionsRepository for MacroDB {
async fn remove_roles_from_user(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
role_ids: &[RoleId],
) -> Result<(), UserRolesAndPermissionsError> {
self.remove_roles_from_user(user_id, role_ids).await
@@ -166,7 +166,7 @@ impl UserRepository for MacroDB {
async fn get_user_id_by_email(
&self,
email: &Email<Lowercase<'_>>,
- ) -> Result<MacroUserId<Lowercase<'_>>, UserRolesAndPermissionsError> {
+ ) -> Result<MacroUserIdStr<'_>, UserRolesAndPermissionsError> {
self.get_user_id_from_email(email)
.await
.map(|id| id.into_owned())
diff --git a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs
index 4add7250d9..88e2c77c1a 100644
--- a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs
+++ b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs
@@ -42,13 +42,13 @@ async fn test_add_roles_to_user(pool: Pool<Postgres>) -> anyhow::Result<()> {
macro_db
.add_roles_to_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
let permissions = macro_db
- .get_user_permissions(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_user_permissions(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let permissions = permissions
@@ -62,13 +62,13 @@ async fn test_add_roles_to_user(pool: Pool<Postgres>) -> anyhow::Result<()> {
// add role to user that already has role
macro_db
.add_roles_to_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
let permissions = macro_db
- .get_user_permissions(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_user_permissions(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let permissions = permissions
@@ -81,7 +81,7 @@ async fn test_add_roles_to_user(pool: Pool<Postgres>) -> anyhow::Result<()> {
// add role to user that doesn't exist
let err = macro_db
.add_roles_to_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await
@@ -105,13 +105,13 @@ async fn test_remove_roles_from_user(pool: Pool<Postgres>) -> anyhow::Result<()>
// Remove role
macro_db
.remove_roles_from_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
let permissions = macro_db
- .get_user_permissions(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_user_permissions(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let permissions = permissions
@@ -125,13 +125,13 @@ async fn test_remove_roles_from_user(pool: Pool<Postgres>) -> anyhow::Result<()>
// Remove role that doesn't exist
macro_db
.remove_roles_from_user(
- &MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,
&roles,
)
.await?;
let permissions = macro_db
- .get_user_permissions(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_user_permissions(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let permissions = permissions
diff --git a/rust/cloud-storage/scribe/src/channel/client.rs b/rust/cloud-storage/scribe/src/channel/client.rs
index a960724f63..0176dcc4c1 100644
--- a/rust/cloud-storage/scribe/src/channel/client.rs
+++ b/rust/cloud-storage/scribe/src/channel/client.rs
@@ -102,7 +102,7 @@ impl ChannelClient {
name: "message".to_string(),
metadata: vec![
("message_id".to_string(), msg.id.to_string()),
- ("sender_id".to_string(), msg.sender_id.clone()),
+ ("sender_id".to_string(), msg.sender_id.to_string()),
("created_at".to_string(), msg.created_at.to_rfc3339()),
],
content: msg.content.clone(),
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 25bb473667..9d07225d67 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -6,10 +6,10 @@ publish = false
version = "0.1.0"
[features]
+backfill_names = ["comms_db_client", "email_db_client"]
default = ["processing", "service"]
processing = []
service = ["macro_db_client"]
-backfill_names = ["email_db_client", "comms_db_client"]
[[bin]]
name = "backfill_chat"
@@ -53,9 +53,11 @@ macro_env = { path = "../macro_env" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
mention_utils = { path = "../mention_utils" }
model = { path = "../model" }
+models_opensearch = { path = "../models_opensearch" }
models_search = { path = "../models_search" }
nom = { workspace = true }
opensearch_client = { path = "../opensearch_client" }
@@ -78,4 +80,3 @@ tracing = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
-models_opensearch = { path = "../models_opensearch" }
diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
index b641d863af..75821e0666 100644
--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs
@@ -254,7 +254,7 @@ fn generate_upserts(
raw_content: Some(result.raw_content),
document_name: document_name.clone(),
content: result.content,
- owner_id: document_info.owner.clone(),
+ owner_id: document_info.owner.to_string(),
file_type: file_type.to_string(),
updated_at_seconds: updated_at,
})
@@ -320,6 +320,8 @@ pub async fn update_search_with_sync_document(
#[cfg(test)]
mod tests {
+ use macro_user_id::user_id::MacroUserIdStr;
+
use super::*;
#[tokio::test]
@@ -327,10 +329,20 @@ mod tests {
let document_info = DocumentMetadata {
document_id: "AAA".to_string(),
document_version_id: 0,
- owner: "fake|[email protected]".to_string(),
+ owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
document_name: "test_document".to_string(),
file_type: Some("md".to_string()),
- ..Default::default()
+ sha: None,
+ project_id: None,
+ project_name: None,
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ document_bom: None,
+ modification_data: None,
+ created_at: None,
+ updated_at: None,
+ sub_type: None,
};
let markdown_result = vec![
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 34ee692a55..40579fe490 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -2,7 +2,7 @@
use std::collections::HashMap;
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use roles_and_permissions::domain::model::UserRolesAndPermissionsError;
#[derive(Eq, PartialEq, Debug, Clone, PartialOrd, sqlx::Type, Copy, std::cmp::Ord)]
@@ -31,7 +31,7 @@ impl std::fmt::Display for TeamRole {
#[derive(Debug, Clone)]
pub struct TeamMember<'a> {
/// The user id of the team member
- pub user_id: MacroUserId<Lowercase<'a>>,
+ pub user_id: MacroUserIdStr<'a>,
/// The role of the team member
pub role: TeamRole,
}
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 37419e5265..b8743c6108 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -1,6 +1,6 @@
//! Contains the domain logic for teams
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use crate::domain::model::{
CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, RemoveTeamInviteError,
@@ -13,7 +13,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
/// Gets the stripe customer id for a user
fn get_stripe_customer_id(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<stripe::CustomerId>, TeamError>> + Send;
/// Gets the subscription id for a team
@@ -25,7 +25,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
/// Creates a new team
fn create_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
@@ -35,7 +35,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
fn invite_users_to_team(
&self,
team_id: &uuid::Uuid,
- invited_by: &MacroUserId<Lowercase<'_>>,
+ invited_by: &MacroUserIdStr<'_>,
emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
@@ -43,7 +43,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
fn remove_user_from_team(
&self,
team_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), RemoveUserFromTeamError>> + Send;
///Gets a team invite by id
@@ -82,13 +82,13 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
fn accept_team_invite(
&self,
team_invite_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<TeamMember<'static>, TeamError>> + Send;
/// Checks if a user is a member (not owner) of any team
fn is_user_member_of_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<bool, TeamError>> + Send;
/// Gets the members of the team.
@@ -104,8 +104,8 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
fn bulk_is_member_of_other_team(
&self,
ignore_team_ids: non_empty::NonEmpty<&[uuid::Uuid]>,
- users: non_empty::NonEmpty<&[MacroUserId<Lowercase<'_>>]>,
- ) -> impl Future<Output = Result<Vec<MacroUserId<Lowercase<'_>>>, TeamError>> + Send;
+ users: non_empty::NonEmpty<&[MacroUserIdStr<'_>]>,
+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'_>>, TeamError>> + Send;
}
/// The TeamService defines a set of actions to perform on the teams
@@ -113,7 +113,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
/// Creates a new team
fn create_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
@@ -123,7 +123,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
fn invite_users_to_team(
&self,
team_id: &uuid::Uuid,
- invited_by: &MacroUserId<Lowercase<'_>>,
+ invited_by: &MacroUserIdStr<'_>,
emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
@@ -131,13 +131,13 @@ pub trait TeamService: Clone + Send + Sync + 'static {
fn remove_user_from_team(
&self,
team_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<(), RemoveUserFromTeamError>> + Send;
/// Rejects an invitation to join a team.
fn reject_invitation(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_invite_id: &uuid::Uuid,
) -> impl Future<Output = Result<(), RemoveTeamInviteError>> + Send;
@@ -158,7 +158,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
fn join_team(
&self,
team_invite_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<TeamMember<'_>, JoinTeamError>> + Send;
/// Revokes permissions for all team members (not owner)
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 707399a4b9..584c53fdab 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -2,7 +2,7 @@
use std::{collections::HashSet, str::FromStr};
-use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
use roles_and_permissions::domain::{model::RoleId, port::UserRolesAndPermissionsService};
use crate::domain::{
@@ -59,7 +59,7 @@ where
{
async fn create_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> Result<Team, CreateTeamError> {
self.team_repository.create_team(user_id, team_name).await
@@ -68,7 +68,7 @@ where
async fn invite_users_to_team(
&self,
team_id: &uuid::Uuid,
- invited_by: &MacroUserId<Lowercase<'_>>,
+ invited_by: &MacroUserIdStr<'_>,
emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
let invited = self
@@ -130,7 +130,7 @@ where
async fn remove_user_from_team(
&self,
team_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<(), RemoveUserFromTeamError> {
let result = self
.team_repository
@@ -168,7 +168,7 @@ where
async fn reject_invitation(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_invite_id: &uuid::Uuid,
) -> Result<(), RemoveTeamInviteError> {
let team_invite = self
@@ -277,7 +277,7 @@ where
async fn join_team(
&self,
team_invite_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<TeamMember<'_>, JoinTeamError> {
let team_member = self
.team_repository
@@ -307,8 +307,7 @@ where
return Ok(());
}
- let members: Vec<MacroUserId<Lowercase<'_>>> =
- members.into_iter().map(|m| m.user_id).collect();
+ let members: Vec<MacroUserIdStr<'_>> = members.into_iter().map(|m| m.user_id).collect();
// Ignore the current team
let ignore_team_ids = vec![*team_id];
@@ -323,7 +322,7 @@ where
let members_of_team: HashSet<&str> = members_of_team.iter().map(|m| m.as_ref()).collect();
// Get all members that are not in the other team
- let members_to_revoke: Vec<MacroUserId<Lowercase<'_>>> = members
+ let members_to_revoke: Vec<_> = members
.into_iter()
.filter(|m| !members_of_team.contains(m.as_ref()))
.collect();
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index c7e918ed94..5414c5d257 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -1,13 +1,4 @@
//! Implementation for TeamRepository using MacroDB.
-
-#[cfg(test)]
-mod test;
-
-use std::str::FromStr;
-
-use macro_user_id::{cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserId};
-use sqlx::PgPool;
-
use crate::domain::{
model::{
CreateTeamError, InviteUsersToTeamError, RemoveTeamInviteError, RemoveUserFromTeamError,
@@ -15,6 +6,14 @@ use crate::domain::{
},
team_repo::TeamRepository,
};
+use macro_user_id::{
+ cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
+};
+use sqlx::PgPool;
+use std::str::FromStr;
+
+#[cfg(test)]
+mod test;
/// The TeamRepositoryImpl struct is a wrapper around sqlx::PgPool connected to macrodb.
#[derive(Clone)]
@@ -35,7 +34,7 @@ impl TeamRepositoryImpl {
async fn get_team_owner(
&self,
team_id: &uuid::Uuid,
- ) -> Result<MacroUserId<Lowercase<'_>>, anyhow::Error> {
+ ) -> Result<MacroUserIdStr<'_>, anyhow::Error> {
let owner_id = sqlx::query!(
r#"
SELECT owner_id
@@ -48,12 +47,12 @@ impl TeamRepositoryImpl {
.fetch_one(&self.pool)
.await?;
- Ok(MacroUserId::parse_from_str(owner_id.as_str()).map(|id| id.into_owned().lowercase())?)
+ Ok(MacroUserIdStr::parse_from_str(owner_id.as_str()).map(|id| id.into_owned())?)
}
async fn create_team_inner(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> Result<Team, sqlx::Error> {
let mut transaction = self.pool.begin().await?;
@@ -127,7 +126,7 @@ impl From<sqlx::Error> for RemoveTeamInviteError {
impl TeamRepository for TeamRepositoryImpl {
async fn get_stripe_customer_id(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<Option<stripe::CustomerId>, TeamError> {
let stripe_customer_id = sqlx::query!(
r#"
@@ -184,7 +183,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn create_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> Result<Team, CreateTeamError> {
if team_name.is_empty() || team_name.len() > 50 {
@@ -199,7 +198,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn invite_users_to_team(
&self,
team_id: &uuid::Uuid,
- invited_by: &MacroUserId<Lowercase<'_>>,
+ invited_by: &MacroUserIdStr<'_>,
emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
// Convert emails to strings and macro_user_ids once
@@ -289,7 +288,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn remove_user_from_team(
&self,
team_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<(), RemoveUserFromTeamError> {
let owner_id = self.get_team_owner(team_id).await?;
@@ -455,7 +454,7 @@ impl TeamRepository for TeamRepositoryImpl {
.into_iter()
.map(|row| {
let user_id =
- MacroUserId::parse_from_str(&row.user_id).map(|id| id.into_owned().lowercase());
+ MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned());
if let Ok(user_id) = user_id {
Ok(TeamMember {
@@ -479,7 +478,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn accept_team_invite(
&self,
team_invite_id: &uuid::Uuid,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<TeamMember<'static>, TeamError> {
let mut transaction = self.pool.begin().await?;
@@ -535,7 +534,7 @@ impl TeamRepository for TeamRepositoryImpl {
async fn is_user_member_of_team(
&self,
- user_id: &MacroUserId<Lowercase<'_>>,
+ user_id: &MacroUserIdStr<'_>,
) -> Result<bool, TeamError> {
let team_member: Option<()> = sqlx::query!(
r#"
@@ -571,7 +570,7 @@ impl TeamRepository for TeamRepositoryImpl {
.into_iter()
.map(|row| {
let user_id =
- MacroUserId::parse_from_str(&row.user_id).map(|id| id.into_owned().lowercase());
+ MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned());
if let Ok(user_id) = user_id {
Ok(TeamMember {
@@ -595,8 +594,8 @@ impl TeamRepository for TeamRepositoryImpl {
async fn bulk_is_member_of_other_team(
&self,
ignore_team_ids: non_empty::NonEmpty<&[uuid::Uuid]>,
- users: non_empty::NonEmpty<&[MacroUserId<Lowercase<'_>>]>,
- ) -> Result<Vec<MacroUserId<Lowercase<'_>>>, TeamError> {
+ users: non_empty::NonEmpty<&[MacroUserIdStr<'_>]>,
+ ) -> Result<Vec<MacroUserIdStr<'_>>, TeamError> {
let result = sqlx::query!(
r#"
SELECT user_id
@@ -617,11 +616,9 @@ impl TeamRepository for TeamRepositoryImpl {
.fetch_all(&self.pool)
.await?;
- let members: Vec<Result<MacroUserId<Lowercase<'_>>, _>> = result
+ let members: Vec<Result<_, _>> = result
.into_iter()
- .map(|row| {
- MacroUserId::parse_from_str(&row.user_id).map(|id| id.into_owned().lowercase())
- })
+ .map(|row| MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned()))
.collect();
let members = members
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
index 2977023791..c2ae1200fc 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
@@ -1,4 +1,5 @@
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
use sqlx::{Pool, Postgres};
///! Tests for the team_repo implementation for teams
@@ -12,7 +13,7 @@ async fn test_get_stripe_customer_id(pool: Pool<Postgres>) -> anyhow::Result<()>
let team_repo = TeamRepositoryImpl::new(pool);
let stripe_customer_id = team_repo
- .get_stripe_customer_id(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_stripe_customer_id(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
let expected_stripe_customer_id = stripe::CustomerId::from_str("cus_1234").unwrap();
@@ -20,7 +21,7 @@ async fn test_get_stripe_customer_id(pool: Pool<Postgres>) -> anyhow::Result<()>
assert_eq!(stripe_customer_id, Some(expected_stripe_customer_id));
let stripe_customer_id = team_repo
- .get_stripe_customer_id(&MacroUserId::parse_from_str("macro|[email protected]")?.lowercase())
+ .get_stripe_customer_id(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
.await?;
assert!(stripe_customer_id.is_none());
@@ -74,7 +75,7 @@ async fn test_get_team_subscription_id(pool: Pool<Postgres>) -> anyhow::Result<(
async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let result = team_repo.create_team(&user_id, "team1").await?;
assert!(!result.id.to_string().is_empty());
@@ -100,7 +101,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
@@ -138,12 +139,12 @@ async fn test_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Result<()>
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
team_repo.remove_user_from_team(&team_id, &user_id).await?;
// Try to remove user that isn't on team
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.remove_user_from_team(&team_id, &user_id)
@@ -154,7 +155,7 @@ async fn test_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Result<()>
assert!(err.to_string().contains("not in the team"));
// Try to remove owner
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let err = team_repo
.remove_user_from_team(&team_id, &user_id)
@@ -319,7 +320,7 @@ async fn test_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_invite_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let team_member = team_repo
.accept_team_invite(&team_invite_id, &user_id)
@@ -347,13 +348,13 @@ async fn test_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
async fn test_is_user_member_of_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(!is_member);
- let user_id = MacroUserId::parse_from_str("macro|[email protected]")?.lowercase();
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
@@ -400,8 +401,8 @@ async fn test_bulk_is_member_of_other_team(pool: Pool<Postgres>) -> anyhow::Resu
)?];
let users = vec![
- MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
- MacroUserId::parse_from_str("macro|[email protected]")?.lowercase(),
+ MacroUserIdStr::parse_from_str("macro|[email protected]")?,
+ MacroUserIdStr::parse_from_str("macro|[email protected]")?,
];
let ignore_team_ids = non_empty::NonEmpty::new(ignore_team_ids.as_slice())?;
@@ -418,7 +419,7 @@ async fn test_bulk_is_member_of_other_team(pool: Pool<Postgres>) -> anyhow::Resu
"33333333-3333-3333-3333-333333333333",
)?];
- let users = vec![MacroUserId::parse_from_str("macro|[email protected]")?.lowercase()];
+ let users = vec![MacroUserIdStr::parse_from_str("macro|[email protected]")?];
let ignore_team_ids = non_empty::NonEmpty::new(ignore_team_ids.as_slice())?;
let users = non_empty::NonEmpty::new(users.as_slice())?;