Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions reflection-app/src/document_view.blp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ menu primary_menu {
}
}

section {
item {
label: _("_Export Document…");
action: "document.export";
}
}

section {
item {
label: _("_New Window");
Expand Down
25 changes: 24 additions & 1 deletion reflection-app/src/document_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::cell::{Cell, RefCell};
use reflection_doc::document::{Document, DocumentId};

use adw::{prelude::*, subclass::prelude::*};
use gtk::{gdk, gio::prelude::ApplicationExtManual, glib, glib::clone};
use gtk::{gdk, gio::prelude::ApplicationExtManual, glib, glib::clone, gio};

use crate::{
ConnectionPopover, ReflectionApplication, ReflectionTextBuffer, TextView,
Expand Down Expand Up @@ -81,6 +81,9 @@ mod imp {
klass.install_action("window.zoom-one", None, |window, _, _| {
window.set_font_scale(0.0);
});
klass.install_action_async("document.export", None, |obj, _, _| async move {
obj.export_document().await
});

klass.add_binding_action(
gdk::Key::plus,
Expand Down Expand Up @@ -286,4 +289,24 @@ impl DocumentView {
.property("document", document)
.build()
}

pub async fn export_document(&self) {
let window: Option<gtk::Window> = self.root().and_downcast();
let Some(document) = self.document() else {
return;
};
let initial_name = if let Some(mut name) = document.name() {
name.push_str(".bin");
name
} else {
"Empty Document.bin".to_string()
};
let dialog = gtk::FileDialog::builder().modal(true).initial_name(initial_name).build();

let Ok(file) = dialog.save_future(window.as_ref()).await else {
return;
};
let contents = document.export().await;
file.replace_contents_future(contents, None, false, gio::FileCreateFlags::NONE).await.unwrap();
}
}
6 changes: 6 additions & 0 deletions reflection-doc/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,12 @@ impl Document {

self.service().documents().remove(&self.id());
}

pub async fn export(&self) -> Vec<u8> {
let doc = self.imp().crdt_doc.get().expect("crdt_doc to be set");

doc.export(ExportMode::Snapshot).unwrap()
}
}

unsafe impl Send for Document {}
Expand Down
12 changes: 6 additions & 6 deletions reflection-node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ authors = [
thiserror = "2.0.17"
chrono = "0.4.42"
ciborium = "0.2.2"
p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436" }
p2panda-discovery = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436", package = "p2panda-discovery-next" }
p2panda-net = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436", package = "p2panda-net-next" }
p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436", features = ["sqlite"], default-features = false }
p2panda-stream = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436" }
p2panda-sync = { git = "https://github.com/p2panda/p2panda", rev = "a83a80b2ce0733c9437ceeaae33503d3b3742436", package = "p2panda-sync-next" }
p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c" }
p2panda-discovery = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c" }
p2panda-net = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c" }
p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c", features = ["sqlite"], default-features = false }
p2panda-stream = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c" }
p2panda-sync = { git = "https://github.com/p2panda/p2panda", rev = "d9bff24ce2805302fcbc6554fbaba51b278e918c" }
serde = { version = "1.0.228", features = ["derive"] }
serde_bytes = "0.11.19"
sqlx = { version = "0.8.6", features = ["runtime-tokio", "sqlite", "chrono"], default-features = false }
Expand Down
8 changes: 4 additions & 4 deletions reflection-node/src/author_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::topic::SubscribableTopic;
use chrono::Utc;
use p2panda_core::cbor::{DecodeError, decode_cbor, encode_cbor};
use p2panda_core::{PrivateKey, PublicKey};
use p2panda_net::streams::EphemeralStream;
use p2panda_net::gossip::GossipHandle;
use tokio::sync::{Mutex, RwLock};
use tracing::error;

Expand Down Expand Up @@ -47,7 +47,7 @@ pub struct AuthorTracker<T> {
last_ping: Mutex<HashMap<PublicKey, Instant>>,
subscribable_topic: Arc<T>,
node: Arc<NodeInner>,
tx: RwLock<Option<EphemeralStream>>,
tx: RwLock<Option<GossipHandle>>,
}

impl<T: SubscribableTopic> AuthorTracker<T> {
Expand All @@ -60,7 +60,7 @@ impl<T: SubscribableTopic> AuthorTracker<T> {
})
}

pub async fn set_topic_tx(&self, tx: Option<EphemeralStream>) {
pub async fn set_topic_tx(&self, tx: Option<GossipHandle>) {
let mut tx_guard = self.tx.write().await;
// Send good bye message to the network
if let Some(tx) = tx_guard.as_ref() {
Expand Down Expand Up @@ -174,7 +174,7 @@ impl<T: SubscribableTopic> AuthorTracker<T> {
}
}

async fn send_message(private_key: &PrivateKey, tx: &EphemeralStream, message: AuthorMessage) {
async fn send_message(private_key: &PrivateKey, tx: &GossipHandle, message: AuthorMessage) {
// FIXME: We need to add the current time to the message,
// because iroh doesn't broadcast twice the same message message.
let author_message = match encode_cbor(&(&message, SystemTime::now())) {
Expand Down
1 change: 1 addition & 0 deletions reflection-node/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod author_tracker;
mod ephemerial_operation;
mod network;
pub mod node;
mod node_inner;
mod operation;
Expand Down
123 changes: 123 additions & 0 deletions reflection-node/src/network.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
use std::sync::LazyLock;

use thiserror::Error;
use tracing::error;

use p2panda_core::Hash;
use p2panda_core::PrivateKey;
use p2panda_net::address_book::{AddressBook, AddressBookError};
use p2panda_net::gossip::{Gossip, GossipError};
use p2panda_net::iroh_endpoint::{Endpoint, EndpointError};
use p2panda_net::iroh_mdns::{MdnsDiscovery, MdnsDiscoveryError, MdnsDiscoveryMode};
use p2panda_net::{TopicId, addrs::NodeInfo};

use crate::operation::ReflectionExtensions;
use crate::operation_store::OperationStore;
use crate::topic_store::{LogId, TopicStore};

static RELAY_URL: LazyLock<iroh::RelayUrl> = LazyLock::new(|| {
"https://euc1-1.relay.n0.iroh-canary.iroh.link"
.parse()
.expect("valid relay URL")
});

static BOOTSTRAP_NODE: LazyLock<NodeInfo> = LazyLock::new(|| {
let endpoint_addr = iroh::EndpointAddr::new(
"7ccdbeed587a8ec8c71cdc9b98e941ac597e11b0216aac1387ef81089a4930b2"
.parse()
.expect("valid bootstrap node id"),
)
.with_relay_url(RELAY_URL.clone());
NodeInfo::from(endpoint_addr).bootstrap()
});

type TopicSyncManager = p2panda_sync::manager::TopicSyncManager<
TopicId,
p2panda_store::SqliteStore<LogId, ReflectionExtensions>,
TopicStore,
LogId,
ReflectionExtensions,
>;
pub type LogSync = p2panda_net::sync::LogSync<
p2panda_store::SqliteStore<LogId, ReflectionExtensions>,
LogId,
ReflectionExtensions,
TopicStore,
>;
pub type LogSyncError = p2panda_net::sync::LogSyncError<TopicSyncManager>;
pub type SyncHandle = p2panda_net::sync::SyncHandle<TopicSyncManager>;
pub type SyncHandleError = p2panda_net::sync::SyncHandleError<TopicSyncManager>;

#[derive(Error, Debug)]
pub enum NetworkError {
#[error(transparent)]
Gossip(#[from] GossipError),
#[error(transparent)]
LogSync(#[from] LogSyncError),
#[error(transparent)]
AddressBook(#[from] AddressBookError),
#[error(transparent)]
MdnsDiscovery(#[from] MdnsDiscoveryError),
#[error(transparent)]
Endpoint(#[from] EndpointError),
}

#[allow(dead_code)]
pub struct Network {
pub(crate) mdns_discovery: MdnsDiscovery,
pub(crate) gossip: Gossip,
pub(crate) log_sync: LogSync,
pub(crate) endpoint: Endpoint,
}

// FIXME: Endpoint, LogSync, MdnsDiscovery, and Gossip should implement debug
impl std::fmt::Debug for Network {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Network").finish()
}
}

impl Network {
pub async fn new(
private_key: &PrivateKey,
network_id: &Hash,
topic_store: &TopicStore,
operation_store: &OperationStore,
) -> Result<Self, NetworkError> {
let address_book = AddressBook::builder().spawn().await?;

if let Err(error) = address_book.insert_node_info(BOOTSTRAP_NODE.clone()).await {
error!("Failed to add bootstrap node to the address book: {error}");
}

let endpoint = Endpoint::builder(address_book.clone())
.network_id(network_id.into())
.private_key(private_key.clone())
.relay_url(RELAY_URL.clone())
.spawn()
.await?;

let mdns_discovery = MdnsDiscovery::builder(address_book.clone(), endpoint.clone())
.mode(MdnsDiscoveryMode::Active)
.spawn()
.await?;
let gossip = Gossip::builder(address_book.clone(), endpoint.clone())
.spawn()
.await?;
let log_sync = LogSync::builder(
operation_store.clone_inner(),
topic_store.clone(),
endpoint.clone(),
gossip.clone(),
)
.spawn()
.await?;

Ok(Network {
mdns_discovery,
gossip,
log_sync,
endpoint,
})
}
}
Loading
Loading