Use enum_delegate crate (#2554)

This commit is contained in:
Nutomic 2022-11-16 22:51:05 +00:00 committed by GitHub
parent 24756af84b
commit 63c237d6df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 66 additions and 55 deletions

50
Cargo.lock generated
View file

@ -4,11 +4,10 @@ version = 3
[[package]] [[package]]
name = "activitypub_federation" name = "activitypub_federation"
version = "0.2.3" version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd9ae511df7135c271dca3ef3751f5528891c965e47d8d7a70fed9d2f1e5b6b1" checksum = "85eee18b953107c2ce1f9e217b533464b061c4416179aa65c6adb102379fbaff"
dependencies = [ dependencies = [
"activitypub_federation_derive",
"actix-web", "actix-web",
"anyhow", "anyhow",
"async-trait", "async-trait",
@ -17,6 +16,7 @@ dependencies = [
"chrono", "chrono",
"derive_builder 0.11.2", "derive_builder 0.11.2",
"dyn-clone", "dyn-clone",
"enum_delegate",
"http", "http",
"http-signature-normalization-actix", "http-signature-normalization-actix",
"http-signature-normalization-reqwest", "http-signature-normalization-reqwest",
@ -33,17 +33,6 @@ dependencies = [
"url", "url",
] ]
[[package]]
name = "activitypub_federation_derive"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07520b54fc0f22ad30b90399b2a2689c6e5c113df0642ca3fa2f7ee823e54126"
dependencies = [
"proc-macro2 1.0.47",
"quote 1.0.21",
"syn 1.0.103",
]
[[package]] [[package]]
name = "activitystreams-kinds" name = "activitystreams-kinds"
version = "0.2.1" version = "0.2.1"
@ -665,9 +654,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.22" version = "0.4.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys", "js-sys",
@ -1348,6 +1337,30 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "enum_delegate"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8ea75f31022cba043afe037940d73684327e915f88f62478e778c3de914cd0a"
dependencies = [
"enum_delegate_lib",
"proc-macro2 1.0.47",
"quote 1.0.21",
"syn 1.0.103",
]
[[package]]
name = "enum_delegate_lib"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e1f6c3800b304a6be0012039e2a45a322a093539c45ab818d9e6895a39c90fe"
dependencies = [
"proc-macro2 1.0.47",
"quote 1.0.21",
"rand 0.8.5",
"syn 1.0.103",
]
[[package]] [[package]]
name = "event-listener" name = "event-listener"
version = "2.5.3" version = "2.5.3"
@ -2107,6 +2120,7 @@ dependencies = [
"async-trait", "async-trait",
"chrono", "chrono",
"diesel", "diesel",
"enum_delegate",
"futures", "futures",
"html2md", "html2md",
"http", "http",
@ -2715,9 +2729,9 @@ dependencies = [
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.15.0" version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1" checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
[[package]] [[package]]
name = "openssl" name = "openssl"

View file

@ -49,7 +49,7 @@ lemmy_db_schema = { version = "=0.16.5", path = "./crates/db_schema" }
lemmy_api_common = { version = "=0.16.5", path = "crates/api_common" } lemmy_api_common = { version = "=0.16.5", path = "crates/api_common" }
lemmy_websocket = { version = "=0.16.5", path = "./crates/websocket" } lemmy_websocket = { version = "=0.16.5", path = "./crates/websocket" }
lemmy_routes = { version = "=0.16.5", path = "./crates/routes" } lemmy_routes = { version = "=0.16.5", path = "./crates/routes" }
activitypub_federation = "0.2.3" activitypub_federation = "0.3.2"
diesel = "2.0.2" diesel = "2.0.2"
diesel_migrations = "2.0.0" diesel_migrations = "2.0.0"
diesel-async = "0.1.1" diesel-async = "0.1.1"

View file

@ -22,7 +22,7 @@ lemmy_db_views_moderator = { version = "=0.16.5", path = "../db_views_moderator"
lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] } lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] }
lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] } lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] }
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.3.2"
diesel = "2.0.2" diesel = "2.0.2"
bcrypt = "0.13.0" bcrypt = "0.13.0"
chrono = { version = "0.4.22", features = ["serde"], default-features = false } chrono = { version = "0.4.22", features = ["serde"], default-features = false }

View file

@ -16,7 +16,7 @@ lemmy_db_views = { version = "=0.16.5", path = "../db_views", features = ["full"
lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] } lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] }
lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] } lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] }
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.3.2"
bcrypt = "0.13.0" bcrypt = "0.13.0"
serde_json = { version = "1.0.87", features = ["preserve_order"] } serde_json = { version = "1.0.87", features = ["preserve_order"] }
serde = { version = "1.0.147", features = ["derive"] } serde = { version = "1.0.147", features = ["derive"] }

View file

@ -77,14 +77,8 @@ impl PerformCrud for Register {
let check = context let check = context
.chat_server() .chat_server()
.send(CheckCaptcha { .send(CheckCaptcha {
uuid: data uuid: data.captcha_uuid.to_owned().unwrap_or_default(),
.captcha_uuid answer: data.captcha_answer.to_owned().unwrap_or_default(),
.to_owned()
.unwrap_or_else(|| "".to_string()),
answer: data
.captcha_answer
.to_owned()
.unwrap_or_else(|| "".to_string()),
}) })
.await?; .await?;
if !check { if !check {

View file

@ -20,7 +20,7 @@ lemmy_db_views = { version = "=0.16.5", path = "../db_views", features = ["full"
lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] } lemmy_db_views_actor = { version = "=0.16.5", path = "../db_views_actor", features = ["full"] }
lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] } lemmy_api_common = { version = "=0.16.5", path = "../api_common", features = ["full"] }
lemmy_websocket = { version = "=0.16.5", path = "../websocket" } lemmy_websocket = { version = "=0.16.5", path = "../websocket" }
activitypub_federation = "0.2.3" activitypub_federation = "0.3.2"
diesel = "2.0.2" diesel = "2.0.2"
activitystreams-kinds = "0.2.1" activitystreams-kinds = "0.2.1"
chrono = { version = "0.4.22", features = ["serde"], default-features = false } chrono = { version = "0.4.22", features = ["serde"], default-features = false }
@ -45,6 +45,7 @@ reqwest = { version = "0.11.12", features = ["json"] }
html2md = "0.2.13" html2md = "0.2.13"
once_cell = "1.15.0" once_cell = "1.15.0"
tokio = "1.21.2" tokio = "1.21.2"
enum_delegate = "0.2.0"
[dev-dependencies] [dev-dependencies]
serial_test = "0.9.0" serial_test = "0.9.0"

View file

@ -32,5 +32,5 @@ async fn get_comment_notif_recipients(
// anyway. // anyway.
// TODO: for compatibility with other projects, it would be much better to read this from cc or tags // TODO: for compatibility with other projects, it would be much better to read this from cc or tags
let mentions = scrape_text_for_mentions(&comment.content); let mentions = scrape_text_for_mentions(&comment.content);
send_local_notifs(mentions, comment, &*actor, &post, do_send_email, context).await send_local_notifs(mentions, comment, &actor, &post, do_send_email, context).await
} }

View file

@ -63,7 +63,7 @@ impl CreateOrUpdatePost {
let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into(); let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into();
let create_or_update = CreateOrUpdatePost::new(post, actor, &community, kind, context).await?; let create_or_update = CreateOrUpdatePost::new(post, actor, &community, kind, context).await?;
let activity = AnnouncableActivities::CreateOrUpdatePost(Box::new(create_or_update)); let activity = AnnouncableActivities::CreateOrUpdatePost(create_or_update);
send_activity_in_community(activity, actor, &community, vec![], context).await?; send_activity_in_community(activity, actor, &community, vec![], context).await?;
Ok(()) Ok(())
} }

View file

@ -27,7 +27,7 @@ use crate::{
objects::page::Page, objects::page::Page,
}, },
}; };
use activitypub_federation::{deser::context::WithContext, traits::activity_handler}; use activitypub_federation::{data::Data, deser::context::WithContext, traits::ActivityHandler};
use lemmy_utils::error::LemmyError; use lemmy_utils::error::LemmyError;
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -35,7 +35,7 @@ use url::Url;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
pub enum SharedInboxActivities { pub enum SharedInboxActivities {
PersonInboxActivities(Box<WithContext<PersonInboxActivities>>), PersonInboxActivities(Box<WithContext<PersonInboxActivities>>),
GroupInboxActivities(Box<WithContext<GroupInboxActivities>>), GroupInboxActivities(Box<WithContext<GroupInboxActivities>>),
@ -43,7 +43,7 @@ pub enum SharedInboxActivities {
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
pub enum GroupInboxActivities { pub enum GroupInboxActivities {
FollowCommunity(FollowCommunity), FollowCommunity(FollowCommunity),
UndoFollowCommunity(UndoFollowCommunity), UndoFollowCommunity(UndoFollowCommunity),
@ -54,7 +54,7 @@ pub enum GroupInboxActivities {
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
pub enum PersonInboxActivities { pub enum PersonInboxActivities {
AcceptFollowCommunity(AcceptFollowCommunity), AcceptFollowCommunity(AcceptFollowCommunity),
CreateOrUpdatePrivateMessage(CreateOrUpdatePrivateMessage), CreateOrUpdatePrivateMessage(CreateOrUpdatePrivateMessage),
@ -68,18 +68,18 @@ pub enum PersonInboxActivities {
/// inbox can fall through to be parsed as GroupInboxActivities::AnnouncableActivities. /// inbox can fall through to be parsed as GroupInboxActivities::AnnouncableActivities.
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
pub enum PersonInboxActivitiesWithAnnouncable { pub enum PersonInboxActivitiesWithAnnouncable {
PersonInboxActivities(PersonInboxActivities), PersonInboxActivities(Box<PersonInboxActivities>),
AnnouncableActivities(AnnouncableActivities), AnnouncableActivities(Box<AnnouncableActivities>),
} }
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
pub enum AnnouncableActivities { pub enum AnnouncableActivities {
CreateOrUpdateComment(CreateOrUpdateComment), CreateOrUpdateComment(CreateOrUpdateComment),
CreateOrUpdatePost(Box<CreateOrUpdatePost>), CreateOrUpdatePost(CreateOrUpdatePost),
Vote(Vote), Vote(Vote),
UndoVote(UndoVote), UndoVote(UndoVote),
Delete(Delete), Delete(Delete),
@ -95,7 +95,7 @@ pub enum AnnouncableActivities {
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)] #[serde(untagged)]
#[activity_handler(LemmyContext, LemmyError)] #[enum_delegate::implement(ActivityHandler)]
#[allow(clippy::enum_variant_names)] #[allow(clippy::enum_variant_names)]
pub enum SiteInboxActivities { pub enum SiteInboxActivities {
BlockUser(BlockUser), BlockUser(BlockUser),

View file

@ -72,7 +72,7 @@ impl ApubObject for ApubCommunityOutbox {
let create = let create =
CreateOrUpdatePost::new(post, &person, &data.0, CreateOrUpdateType::Create, &data.1) CreateOrUpdatePost::new(post, &person, &data.0, CreateOrUpdateType::Create, &data.1)
.await?; .await?;
let announcable = AnnouncableActivities::CreateOrUpdatePost(Box::new(create)); let announcable = AnnouncableActivities::CreateOrUpdatePost(create);
let announce = AnnounceActivity::new(announcable.try_into()?, &data.0, &data.1)?; let announce = AnnounceActivity::new(announcable.try_into()?, &data.0, &data.1)?;
ordered_items.push(announce); ordered_items.push(announce);
} }

View file

@ -28,7 +28,7 @@ pub(crate) async fn get_apub_comment(
} }
if !comment.deleted && !comment.removed { if !comment.deleted && !comment.removed {
Ok(create_apub_response(&comment.into_apub(&**context).await?)) Ok(create_apub_response(&comment.into_apub(&context).await?))
} else { } else {
Ok(create_apub_tombstone_response(comment.ap_id.clone())) Ok(create_apub_tombstone_response(comment.ap_id.clone()))
} }

View file

@ -39,7 +39,7 @@ pub(crate) async fn get_apub_community_http(
.into(); .into();
if !community.deleted && !community.removed { if !community.deleted && !community.removed {
let apub = community.into_apub(&**context).await?; let apub = community.into_apub(&context).await?;
Ok(create_apub_response(&apub)) Ok(create_apub_response(&apub))
} else { } else {

View file

@ -32,7 +32,6 @@ mod post;
pub mod routes; pub mod routes;
pub mod site; pub mod site;
#[tracing::instrument(skip_all)]
pub async fn shared_inbox( pub async fn shared_inbox(
request: HttpRequest, request: HttpRequest,
payload: String, payload: String,
@ -55,7 +54,7 @@ where
for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>, for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>,
{ {
let activity_value: Value = serde_json::from_str(&payload)?; let activity_value: Value = serde_json::from_str(&payload)?;
debug!("Received activity {:#}", payload.as_str()); debug!("Parsing activity {}", payload);
let activity: Activity = serde_json::from_value(activity_value.clone())?; let activity: Activity = serde_json::from_value(activity_value.clone())?;
// Log the activity, so we avoid receiving and parsing it twice. // Log the activity, so we avoid receiving and parsing it twice.
let insert = insert_activity(activity.id(), activity_value, false, true, context.pool()).await?; let insert = insert_activity(activity.id(), activity_value, false, true, context.pool()).await?;

View file

@ -24,7 +24,7 @@ url = { version = "2.3.1", features = ["serde"] }
strum = "0.24.1" strum = "0.24.1"
strum_macros = "0.24.3" strum_macros = "0.24.3"
serde_json = { version = "1.0.87", features = ["preserve_order"], optional = true } serde_json = { version = "1.0.87", features = ["preserve_order"], optional = true }
activitypub_federation = { version = "0.2.3", optional = true } activitypub_federation = {version = "0.3.2", optional = true }
lemmy_utils = { version = "=0.16.5", path = "../utils", optional = true } lemmy_utils = { version = "=0.16.5", path = "../utils", optional = true }
bcrypt = { version = "0.13.0", optional = true } bcrypt = { version = "0.13.0", optional = true }
diesel = { version = "2.0.2", features = ["postgres","chrono", "serde_json"], optional = true } diesel = { version = "2.0.2", features = ["postgres","chrono", "serde_json"], optional = true }

View file

@ -25,11 +25,14 @@ static CLEAN_URL_PARAMS_REGEX: Lazy<Regex> = Lazy::new(|| {
}); });
pub fn naive_from_unix(time: i64) -> NaiveDateTime { pub fn naive_from_unix(time: i64) -> NaiveDateTime {
NaiveDateTime::from_timestamp(time, 0) NaiveDateTime::from_timestamp_opt(time, 0).expect("convert datetime")
} }
pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> { pub fn convert_datetime(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
DateTime::<FixedOffset>::from_utc(datetime, FixedOffset::east(0)) DateTime::<FixedOffset>::from_utc(
datetime,
FixedOffset::east_opt(0).expect("create fixed offset"),
)
} }
pub fn remove_slurs(test: &str, slur_regex: &Option<Regex>) -> String { pub fn remove_slurs(test: &str, slur_regex: &Option<Regex>) -> String {

View file

@ -41,8 +41,8 @@ impl RootSpanBuilder for QuieterRootSpanBuilder {
handle_error(span, response.status(), error.as_response_error()); handle_error(span, response.status(), error.as_response_error());
} else { } else {
let code: i32 = response.response().status().as_u16().into(); let code: i32 = response.response().status().as_u16().into();
span.record("http.status_code", &code); span.record("http.status_code", code);
span.record("otel.status_code", &"OK"); span.record("otel.status_code", "OK");
} }
} }
Err(error) => { Err(error) => {
@ -56,12 +56,12 @@ impl RootSpanBuilder for QuieterRootSpanBuilder {
fn handle_error(span: Span, status_code: StatusCode, response_error: &dyn ResponseError) { fn handle_error(span: Span, status_code: StatusCode, response_error: &dyn ResponseError) {
let code: i32 = status_code.as_u16().into(); let code: i32 = status_code.as_u16().into();
span.record("http.status_code", &code); span.record("http.status_code", code);
if status_code.is_client_error() { if status_code.is_client_error() {
span.record("otel.status_code", &"OK"); span.record("otel.status_code", "OK");
} else { } else {
span.record("otel.status_code", &"ERROR"); span.record("otel.status_code", "ERROR");
} }
// pre-formatting errors is a workaround for https://github.com/tokio-rs/tracing/issues/1565 // pre-formatting errors is a workaround for https://github.com/tokio-rs/tracing/issues/1565