Broadcast asynchronously

This commit is contained in:
Kitaiti Makoto 2022-05-05 04:34:04 +09:00
parent 9016995d92
commit ce4b216722

View File

@ -1,12 +1,13 @@
use activitypub::{Activity, Link, Object}; use activitypub::{Activity, Link, Object};
use array_tool::vec::Uniq; use array_tool::vec::Uniq;
use reqwest::{blocking::ClientBuilder, header::HeaderValue, Url}; use reqwest::{header::HeaderValue, ClientBuilder, Url};
use rocket::{ use rocket::{
http::Status, http::Status,
request::{FromRequest, Request}, request::{FromRequest, Request},
response::{Responder, Response}, response::{Responder, Response},
Outcome, Outcome,
}; };
use tokio::{runtime, sync::mpsc};
use tracing::{debug, warn}; use tracing::{debug, warn};
use self::sign::Signable; use self::sign::Signable;
@ -139,6 +140,12 @@ where
.connect_timeout(std::time::Duration::from_secs(5)) .connect_timeout(std::time::Duration::from_secs(5))
.build() .build()
.expect("Can't build client"); .expect("Can't build client");
let rt = runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Error while initializing tokio runtime for federation");
rt.block_on(async {
let (tx, mut rx) = mpsc::channel(32);
for inbox in boxes { for inbox in boxes {
let body = signed.to_string(); let body = signed.to_string();
let mut headers = request::headers(); let mut headers = request::headers();
@ -159,26 +166,37 @@ where
} }
headers.insert("Host", host_header_value.unwrap()); headers.insert("Host", host_header_value.unwrap());
headers.insert("Digest", request::Digest::digest(&body)); headers.insert("Digest", request::Digest::digest(&body));
let _ = client headers.insert(
.post(&inbox)
.headers(headers.clone())
.header(
"Signature", "Signature",
request::signature(sender, &headers, ("post", url.path(), url.query())) request::signature(sender, &headers, ("post", url.path(), url.query()))
.expect("activity_pub::broadcast: request signature error"), .expect("activity_pub::broadcast: request signature error"),
) );
let client = client.clone();
let tx = tx.clone();
rt.spawn(async move {
let _ = tx.send(
client
.post(&inbox)
.headers(headers.clone())
.body(body) .body(body)
.send() .send()
.await,
);
});
}
while let Some(request) = rx.recv().await {
let _ = request
.map(move |r| { .map(move |r| {
if r.status().is_success() { if r.status().is_success() {
debug!("Successfully sent activity to inbox ({})", &inbox); debug!("Successfully sent activity to inbox ({})", &r.url());
} else { } else {
warn!("Error while sending to inbox ({} {:?})", &inbox, &r) warn!("Error while sending to inbox ({} {:?})", &r.url(), &r)
} }
debug!("Response: \"{:?}\"\n", r); debug!("Response: \"{:?}\"\n", r);
}) })
.map_err(|e| warn!("Error while sending to inbox ({:?})", e)); .map_err(|e| warn!("Error while sending to inbox ({:?})", e));
} }
});
} }
#[derive(Shrinkwrap, Clone, Serialize, Deserialize)] #[derive(Shrinkwrap, Clone, Serialize, Deserialize)]