use async_trait::async_trait;
use bp7::EndpointID;
use enum_dispatch::enum_dispatch;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::Sender;
use tokio::sync::oneshot;
use tcp::TCPConnector;
use ws::WebsocketConnector;
pub mod processing;
pub mod tcp;
pub mod ws;
pub mod ws_client;
mod base64 {
use base64::prelude::*;
use serde::{Deserialize, Serialize};
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
let base64 = BASE64_STANDARD.encode(v);
String::serialize(&base64, s)
}
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
let base64 = String::deserialize(d)?;
BASE64_STANDARD
.decode(base64.as_bytes())
.map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(tag = "type")]
pub enum Packet {
Register(Register),
Beacon(Beacon),
ForwardData(ForwardData),
Registered(Registered),
Error(Error),
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Beacon {
pub eid: EndpointID,
pub addr: String,
#[serde(with = "base64")]
pub service_block: Vec<u8>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Registered {
pub eid: EndpointID,
pub nodeid: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Error {
pub reason: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Register {
pub name: String,
pub enable_beacon: bool,
pub port: Option<u16>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ForwardData {
pub src: String,
pub dst: String,
pub bundle_id: String,
#[serde(with = "base64")]
pub data: Vec<u8>,
}
struct Connection<A> {
tx: Sender<A>,
close: Option<oneshot::Sender<()>>,
}
#[enum_dispatch]
pub enum ConnectorEnum {
WebsocketConnector,
TCPConnector,
}
#[async_trait]
#[enum_dispatch(ConnectorEnum)]
pub trait Connector {
async fn setup(&mut self);
fn name(&self) -> &str;
fn send_packet(&self, dest: &str, packet: &Packet) -> bool;
fn close(&self, dest: &str);
}