Rust implementation of NextGraph, a Decentralized and local-first web 3.0 ecosystem
https://nextgraph.org
byzantine-fault-tolerancecrdtsdappsdecentralizede2eeeventual-consistencyjson-ldlocal-firstmarkdownocapoffline-firstp2pp2p-networkprivacy-protectionrdfrich-text-editorself-hostedsemantic-websparqlweb3collaboration
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
211 lines
7.3 KiB
211 lines
7.3 KiB
1 year ago
|
/*
|
||
8 months ago
|
* Copyright (c) 2022-2024 Niko Bonnieure, Par le Peuple, NextGraph.org developers
|
||
1 year ago
|
* All rights reserved.
|
||
|
* Licensed under the Apache License, Version 2.0
|
||
|
* <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
|
||
|
* or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
|
||
|
* at your option. All files in the project carrying such
|
||
|
* notice may not be copied, modified, or distributed except
|
||
|
* according to those terms.
|
||
|
*/
|
||
|
|
||
1 year ago
|
use async_std::stream::StreamExt;
|
||
6 months ago
|
use async_std::sync::Mutex;
|
||
2 years ago
|
use futures::{channel::mpsc, SinkExt};
|
||
6 months ago
|
use std::any::TypeId;
|
||
1 year ago
|
use std::sync::Arc;
|
||
2 years ago
|
|
||
1 year ago
|
use crate::utils::{spawn_and_log_error, Receiver, ResultSend, Sender};
|
||
1 year ago
|
use crate::{connection::*, errors::ProtocolError, types::ProtocolMessage};
|
||
2 years ago
|
use std::marker::PhantomData;
|
||
|
|
||
1 year ago
|
impl TryFrom<ProtocolMessage> for () {
|
||
|
type Error = ProtocolError;
|
||
6 months ago
|
fn try_from(_msg: ProtocolMessage) -> Result<Self, Self::Error> {
|
||
1 year ago
|
Ok(())
|
||
|
}
|
||
2 years ago
|
}
|
||
|
|
||
|
#[async_trait::async_trait]
|
||
1 year ago
|
pub trait EActor: Send + Sync + std::fmt::Debug {
|
||
|
async fn respond(
|
||
|
&mut self,
|
||
|
msg: ProtocolMessage,
|
||
|
fsm: Arc<Mutex<NoiseFSM>>,
|
||
|
) -> Result<(), ProtocolError>;
|
||
2 years ago
|
}
|
||
|
|
||
1 year ago
|
#[derive(Debug)]
|
||
|
pub struct Actor<
|
||
|
'a,
|
||
1 year ago
|
A: Into<ProtocolMessage> + std::fmt::Debug,
|
||
1 year ago
|
B: TryFrom<ProtocolMessage, Error = ProtocolError> + std::fmt::Debug + Sync,
|
||
1 year ago
|
> {
|
||
2 years ago
|
id: i64,
|
||
|
phantom_a: PhantomData<&'a A>,
|
||
|
phantom_b: PhantomData<&'a B>,
|
||
1 year ago
|
receiver: Option<Receiver<ConnectionCommand>>,
|
||
2 years ago
|
receiver_tx: Sender<ConnectionCommand>,
|
||
1 year ago
|
initiator: bool,
|
||
2 years ago
|
}
|
||
|
|
||
1 year ago
|
pub enum SoS<B> {
|
||
|
Single(B),
|
||
1 year ago
|
Stream(Receiver<B>),
|
||
|
}
|
||
|
|
||
|
impl<B> SoS<B> {
|
||
|
pub fn is_single(&self) -> bool {
|
||
6 months ago
|
if let Self::Single(_b) = self {
|
||
1 year ago
|
true
|
||
|
} else {
|
||
|
false
|
||
|
}
|
||
|
}
|
||
|
pub fn is_stream(&self) -> bool {
|
||
|
!self.is_single()
|
||
|
}
|
||
|
pub fn unwrap_single(self) -> B {
|
||
|
match self {
|
||
|
Self::Single(s) => s,
|
||
6 months ago
|
Self::Stream(_s) => {
|
||
1 year ago
|
panic!("called `unwrap_single()` on a `Stream` value")
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
pub fn unwrap_stream(self) -> Receiver<B> {
|
||
|
match self {
|
||
|
Self::Stream(s) => s,
|
||
6 months ago
|
Self::Single(_s) => {
|
||
1 year ago
|
panic!("called `unwrap_stream()` on a `Single` value")
|
||
|
}
|
||
|
}
|
||
|
}
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
impl<
|
||
1 year ago
|
A: Into<ProtocolMessage> + std::fmt::Debug + 'static,
|
||
|
B: TryFrom<ProtocolMessage, Error = ProtocolError> + Sync + Send + std::fmt::Debug + 'static,
|
||
1 year ago
|
> Actor<'_, A, B>
|
||
|
{
|
||
|
pub fn new(id: i64, initiator: bool) -> Self {
|
||
6 months ago
|
let (receiver_tx, receiver) = mpsc::unbounded::<ConnectionCommand>();
|
||
2 years ago
|
Self {
|
||
|
id,
|
||
1 year ago
|
receiver: Some(receiver),
|
||
2 years ago
|
receiver_tx,
|
||
|
phantom_a: PhantomData,
|
||
|
phantom_b: PhantomData,
|
||
1 year ago
|
initiator,
|
||
|
}
|
||
|
}
|
||
|
|
||
1 year ago
|
// pub fn verify(&self, msg: ProtocolMessage) -> bool {
|
||
|
// self.initiator && msg.type_id() == TypeId::of::<B>()
|
||
|
// || !self.initiator && msg.type_id() == TypeId::of::<A>()
|
||
|
// }
|
||
1 year ago
|
|
||
1 year ago
|
pub fn detach_receiver(&mut self) -> Receiver<ConnectionCommand> {
|
||
|
self.receiver.take().unwrap()
|
||
|
}
|
||
|
|
||
1 year ago
|
pub async fn request(
|
||
|
&mut self,
|
||
1 year ago
|
msg: ProtocolMessage,
|
||
1 year ago
|
fsm: Arc<Mutex<NoiseFSM>>,
|
||
1 year ago
|
) -> Result<SoS<B>, ProtocolError> {
|
||
1 year ago
|
fsm.lock().await.send(msg).await?;
|
||
1 year ago
|
let mut receiver = self.receiver.take().unwrap();
|
||
|
match receiver.next().await {
|
||
|
Some(ConnectionCommand::Msg(msg)) => {
|
||
1 year ago
|
if let ProtocolMessage::ClientMessage(ref bm) = msg {
|
||
1 year ago
|
if bm.result() == Into::<u16>::into(ProtocolError::PartialContent)
|
||
1 year ago
|
&& TypeId::of::<B>() != TypeId::of::<()>()
|
||
|
{
|
||
1 year ago
|
let (mut b_sender, b_receiver) = mpsc::unbounded::<B>();
|
||
6 months ago
|
let response = msg.try_into().map_err(|_e| ProtocolError::ActorError)?;
|
||
1 year ago
|
b_sender
|
||
|
.send(response)
|
||
|
.await
|
||
6 months ago
|
.map_err(|_err| ProtocolError::IoError)?;
|
||
1 year ago
|
async fn pump_stream<C: TryFrom<ProtocolMessage, Error = ProtocolError>>(
|
||
|
mut actor_receiver: Receiver<ConnectionCommand>,
|
||
|
mut sos_sender: Sender<C>,
|
||
|
fsm: Arc<Mutex<NoiseFSM>>,
|
||
|
id: i64,
|
||
|
) -> ResultSend<()> {
|
||
|
async move {
|
||
|
while let Some(ConnectionCommand::Msg(msg)) =
|
||
|
actor_receiver.next().await
|
||
|
{
|
||
1 year ago
|
if let ProtocolMessage::ClientMessage(ref bm) = msg {
|
||
1 year ago
|
if bm.result()
|
||
|
== Into::<u16>::into(ProtocolError::EndOfStream)
|
||
|
{
|
||
1 year ago
|
break;
|
||
|
}
|
||
|
let response = msg.try_into();
|
||
|
if response.is_err() {
|
||
|
// TODO deal with errors.
|
||
|
break;
|
||
|
}
|
||
1 year ago
|
if sos_sender.send(response.unwrap()).await.is_err() {
|
||
|
break;
|
||
|
}
|
||
1 year ago
|
} else {
|
||
1 year ago
|
// todo deal with error (not a ClientMessage)
|
||
1 year ago
|
break;
|
||
|
}
|
||
|
}
|
||
|
fsm.lock().await.remove_actor(id).await;
|
||
|
}
|
||
|
.await;
|
||
|
Ok(())
|
||
|
}
|
||
|
spawn_and_log_error(pump_stream::<B>(
|
||
|
receiver,
|
||
|
b_sender,
|
||
|
Arc::clone(&fsm),
|
||
|
self.id,
|
||
|
));
|
||
|
return Ok(SoS::<B>::Stream(b_receiver));
|
||
|
}
|
||
|
}
|
||
|
fsm.lock().await.remove_actor(self.id).await;
|
||
|
let response: B = msg.try_into()?;
|
||
|
Ok(SoS::<B>::Single(response))
|
||
|
}
|
||
1 year ago
|
Some(ConnectionCommand::ProtocolError(e)) => Err(e),
|
||
|
Some(ConnectionCommand::Error(e)) => Err(e.into()),
|
||
|
Some(ConnectionCommand::Close) => Err(ProtocolError::Closing),
|
||
1 year ago
|
_ => Err(ProtocolError::ActorError),
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
1 year ago
|
pub fn new_responder() -> Box<Self> {
|
||
|
Box::new(Self::new(0, false))
|
||
|
}
|
||
|
|
||
|
pub fn get_receiver_tx(&self) -> Sender<ConnectionCommand> {
|
||
|
self.receiver_tx.clone()
|
||
|
}
|
||
|
}
|
||
|
|
||
6 months ago
|
#[cfg(test)]
|
||
1 year ago
|
mod test {
|
||
|
|
||
|
use crate::actor::*;
|
||
|
use crate::actors::*;
|
||
|
|
||
|
#[async_std::test]
|
||
|
pub async fn test_actor() {
|
||
6 months ago
|
let _a = Actor::<Noise, Noise>::new(1, true);
|
||
1 year ago
|
// a.handle(ProtocolMessage::Start(StartProtocol::Client(
|
||
|
// ClientHello::Noise3(Noise::V0(NoiseV0 { data: vec![] })),
|
||
|
// )))
|
||
|
// .await;
|
||
|
// a.handle(ProtocolMessage::Noise(Noise::V0(NoiseV0 { data: vec![] })))
|
||
|
// .await;
|
||
2 years ago
|
}
|
||
|
}
|