mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
fix(ffi): atomic compound outline edits, validated anchors, shared graph
- indent, outdent and merge run in one Graph::transaction, so a failure part-way no longer duplicates merged text or strands siblings. - Placements check that the anchor block exists and is on the target page. - SynapseGraph holds Arc<Mutex<Graph>> and exposes shared() (not bridged) for the sync client. - docs: rustup's cargo must come first in PATH; sync wording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3266ddda3a
commit
268e152efc
5 files changed
+208
-49
No files matched your search
@@ -9,6 +9,7 @@ import 'dto.dart';
|
|||||||
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
|
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
|
||||||
|
|
||||||
// These functions are ignored because they are not marked as `pub`: `asset_dto`, `lock`, `outline`, `page_view`, `parse_date`, `parse_day`, `parse_id`
|
// These functions are ignored because they are not marked as `pub`: `asset_dto`, `lock`, `outline`, `page_view`, `parse_date`, `parse_day`, `parse_id`
|
||||||
|
// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `shared`
|
||||||
|
|
||||||
// Rust type: RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
|
// Rust type: RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
|
||||||
abstract class SynapseGraph implements RustOpaqueInterface {
|
abstract class SynapseGraph implements RustOpaqueInterface {
|
||||||
|
|||||||
@@ -5,14 +5,17 @@ use anyhow::{Context, Result, anyhow, bail};
|
|||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use flutter_rust_bridge::frb;
|
use flutter_rust_bridge::frb;
|
||||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||||
use std::sync::{Mutex, MutexGuard};
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
use synapse_core::{Graph, NewPage, Page, PageId, journal_title};
|
use synapse_core::{Graph, NewPage, Page, PageId, journal_title};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
/// An open graph. Opaque to Dart; every call locks the graph for its duration, so calls are
|
/// An open graph. Opaque to Dart; every call locks the graph for its duration, so calls are
|
||||||
/// short and coarse-grained. The app serialises writes on its side to keep their order.
|
/// short and coarse-grained. The app serialises writes on its side to keep their order.
|
||||||
|
///
|
||||||
|
/// The graph is held as `Arc<Mutex<Graph>>` (the core `Graph` is `Send` but not `Sync`), the
|
||||||
|
/// same shape `synapse-sync`'s `SyncClient` takes, so a sync client can share it.
|
||||||
pub struct SynapseGraph {
|
pub struct SynapseGraph {
|
||||||
graph: Mutex<Graph>,
|
graph: Arc<Mutex<Graph>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SynapseGraph {
|
impl SynapseGraph {
|
||||||
@@ -20,10 +23,16 @@ impl SynapseGraph {
|
|||||||
pub fn open(dir: String) -> Result<SynapseGraph> {
|
pub fn open(dir: String) -> Result<SynapseGraph> {
|
||||||
let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?;
|
let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?;
|
||||||
Ok(SynapseGraph {
|
Ok(SynapseGraph {
|
||||||
graph: Mutex::new(graph),
|
graph: Arc::new(Mutex::new(graph)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The shared graph, for Rust-side services such as the sync client.
|
||||||
|
#[frb(ignore)]
|
||||||
|
pub fn shared(&self) -> Arc<Mutex<Graph>> {
|
||||||
|
Arc::clone(&self.graph)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn lock(&self) -> MutexGuard<'_, Graph> {
|
pub(crate) fn lock(&self) -> MutexGuard<'_, Graph> {
|
||||||
self.graph.lock().unwrap_or_else(|e| e.into_inner())
|
self.graph.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
//! Outliner editing. Structural operations return the page's refreshed outline so the UI can
|
//! Outliner editing. Structural operations return the page's refreshed outline so the UI can
|
||||||
//! re-sync to the authoritative order after its optimistic update.
|
//! re-sync to the authoritative order after its optimistic update.
|
||||||
//!
|
//!
|
||||||
//! The core exposes single-block primitives, each in its own transaction; compound edits here
|
//! Compound edits (indent, outdent, merge) are sequences of core primitives run inside one
|
||||||
//! (indent, outdent, merge) are sequences of them. See the crate docs for the core helper that
|
//! `Graph::transaction`, so a failure part-way leaves the outline untouched.
|
||||||
//! would make them atomic.
|
|
||||||
|
|
||||||
use super::dto::*;
|
use super::dto::*;
|
||||||
use super::graph::{SynapseGraph, outline, parse_id};
|
use super::graph::{SynapseGraph, outline, parse_id};
|
||||||
@@ -41,8 +40,9 @@ impl SynapseGraph {
|
|||||||
pub fn move_block(&self, id: String, page_id: String, place: Place) -> Result<Vec<BlockDto>> {
|
pub fn move_block(&self, id: String, page_id: String, place: Place) -> Result<Vec<BlockDto>> {
|
||||||
let g = self.lock();
|
let g = self.lock();
|
||||||
let page = parse_id(&page_id)?;
|
let page = parse_id(&page_id)?;
|
||||||
|
let b = get(&g, parse_id(&id)?)?;
|
||||||
let at = placement(&g, page, &place)?;
|
let at = placement(&g, page, &place)?;
|
||||||
g.move_block(parse_id(&id)?, page, at)?;
|
g.move_block(b.id, page, at)?;
|
||||||
outline(&g, page)
|
outline(&g, page)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,15 +50,19 @@ impl SynapseGraph {
|
|||||||
pub fn indent_block(&self, id: String) -> Result<Vec<BlockDto>> {
|
pub fn indent_block(&self, id: String) -> Result<Vec<BlockDto>> {
|
||||||
let g = self.lock();
|
let g = self.lock();
|
||||||
let b = get(&g, parse_id(&id)?)?;
|
let b = get(&g, parse_id(&id)?)?;
|
||||||
let sibs = siblings(&g, &b)?;
|
g.transaction(|g| {
|
||||||
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
|
let sibs = siblings(g, &b)?;
|
||||||
if i > 0 {
|
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
|
||||||
let prev = &sibs[i - 1];
|
if i > 0 {
|
||||||
if prev.collapsed {
|
let prev = &sibs[i - 1];
|
||||||
g.set_collapsed(prev.id, false)?;
|
if prev.collapsed {
|
||||||
|
g.set_collapsed(prev.id, false)?;
|
||||||
|
}
|
||||||
|
fail_point("indent")?;
|
||||||
|
g.move_block(b.id, b.page_id, Placement::LastChildOf(Some(prev.id)))?;
|
||||||
}
|
}
|
||||||
g.move_block(b.id, b.page_id, Placement::LastChildOf(Some(prev.id)))?;
|
Ok(())
|
||||||
}
|
})?;
|
||||||
outline(&g, b.page_id)
|
outline(&g, b.page_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,15 +74,19 @@ impl SynapseGraph {
|
|||||||
let Some(parent) = b.parent_id else {
|
let Some(parent) = b.parent_id else {
|
||||||
return outline(&g, b.page_id);
|
return outline(&g, b.page_id);
|
||||||
};
|
};
|
||||||
let sibs = siblings(&g, &b)?;
|
g.transaction(|g| {
|
||||||
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
|
let sibs = siblings(g, &b)?;
|
||||||
g.move_block(b.id, b.page_id, Placement::After(parent))?;
|
let i = sibs.iter().position(|s| s.id == b.id).unwrap_or(0);
|
||||||
for s in &sibs[i + 1..] {
|
g.move_block(b.id, b.page_id, Placement::After(parent))?;
|
||||||
g.move_block(s.id, b.page_id, Placement::LastChildOf(Some(b.id)))?;
|
for s in &sibs[i + 1..] {
|
||||||
}
|
fail_point("outdent")?;
|
||||||
if b.collapsed && i + 1 < sibs.len() {
|
g.move_block(s.id, b.page_id, Placement::LastChildOf(Some(b.id)))?;
|
||||||
g.set_collapsed(b.id, false)?;
|
}
|
||||||
}
|
if b.collapsed && i + 1 < sibs.len() {
|
||||||
|
g.set_collapsed(b.id, false)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
outline(&g, b.page_id)
|
outline(&g, b.page_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,27 +100,30 @@ impl SynapseGraph {
|
|||||||
if b.id == target.id {
|
if b.id == target.id {
|
||||||
bail!("cannot merge a block into itself");
|
bail!("cannot merge a block into itself");
|
||||||
}
|
}
|
||||||
if !b.content.is_empty() {
|
g.transaction(|g| {
|
||||||
g.update_block(target.id, &format!("{}{}", target.content, b.content))?;
|
if !b.content.is_empty() {
|
||||||
}
|
g.update_block(target.id, &format!("{}{}", target.content, b.content))?;
|
||||||
let children: Vec<BlockId> = g
|
}
|
||||||
.page_tree(b.page_id)?
|
fail_point("merge")?;
|
||||||
.into_iter()
|
let children: Vec<BlockId> = g
|
||||||
.filter(|(_, c)| c.parent_id == Some(b.id))
|
.page_tree(b.page_id)?
|
||||||
.map(|(_, c)| c.id)
|
.into_iter()
|
||||||
.collect();
|
.filter(|(_, c)| c.parent_id == Some(b.id))
|
||||||
if !children.is_empty() && target.collapsed && b.parent_id != Some(target.id) {
|
.map(|(_, c)| c.id)
|
||||||
g.set_collapsed(target.id, false)?;
|
.collect();
|
||||||
}
|
if !children.is_empty() && target.collapsed && b.parent_id != Some(target.id) {
|
||||||
let at = if b.parent_id == Some(target.id) {
|
g.set_collapsed(target.id, false)?;
|
||||||
Placement::Before(b.id)
|
}
|
||||||
} else {
|
let at = if b.parent_id == Some(target.id) {
|
||||||
Placement::LastChildOf(Some(target.id))
|
Placement::Before(b.id)
|
||||||
};
|
} else {
|
||||||
for c in children {
|
Placement::LastChildOf(Some(target.id))
|
||||||
g.move_block(c, target.page_id, at)?;
|
};
|
||||||
}
|
for c in children {
|
||||||
g.delete_block(b.id)?;
|
g.move_block(c, target.page_id, at)?;
|
||||||
|
}
|
||||||
|
g.delete_block(b.id)
|
||||||
|
})?;
|
||||||
outline(&g, target.page_id)
|
outline(&g, target.page_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +141,7 @@ fn get(g: &Graph, id: BlockId) -> Result<Block> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Siblings of `b` (including itself) in order.
|
/// Siblings of `b` (including itself) in order.
|
||||||
fn siblings(g: &Graph, b: &Block) -> Result<Vec<Block>> {
|
fn siblings(g: &Graph, b: &Block) -> synapse_core::Result<Vec<Block>> {
|
||||||
Ok(g.page_tree(b.page_id)?
|
Ok(g.page_tree(b.page_id)?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(_, s)| s.parent_id == b.parent_id)
|
.filter(|(_, s)| s.parent_id == b.parent_id)
|
||||||
@@ -138,8 +149,15 @@ fn siblings(g: &Graph, b: &Block) -> Result<Vec<Block>> {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolves a UI placement, checking that the anchor block exists and lives on `page`.
|
||||||
fn placement(g: &Graph, page: PageId, place: &Place) -> Result<Placement> {
|
fn placement(g: &Graph, page: PageId, place: &Place) -> Result<Placement> {
|
||||||
let anchor = place.anchor.as_deref().map(parse_id).transpose()?;
|
let anchor = place.anchor.as_deref().map(parse_id).transpose()?;
|
||||||
|
if let Some(a) = anchor {
|
||||||
|
let b = get(g, a)?;
|
||||||
|
if b.page_id != page {
|
||||||
|
bail!("anchor block {a} is not on page {page}");
|
||||||
|
}
|
||||||
|
}
|
||||||
let need = |a: Option<BlockId>| match a {
|
let need = |a: Option<BlockId>| match a {
|
||||||
Some(a) => Ok(a),
|
Some(a) => Ok(a),
|
||||||
None => Err(anyhow::anyhow!("{:?} needs an anchor block", place.kind)),
|
None => Err(anyhow::anyhow!("{:?} needs an anchor block", place.kind)),
|
||||||
@@ -161,3 +179,128 @@ fn placement(g: &Graph, page: PageId, place: &Place) -> Result<Placement> {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Test hook: lets tests make a compound edit fail part-way. A no-op in normal builds.
|
||||||
|
#[cfg(not(test))]
|
||||||
|
#[inline(always)]
|
||||||
|
fn fail_point(_: &str) -> synapse_core::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
thread_local! {
|
||||||
|
static FAIL_AT: std::cell::RefCell<Option<&'static str>> = const { std::cell::RefCell::new(None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn fail_point(name: &str) -> synapse_core::Result<()> {
|
||||||
|
if FAIL_AT.with(|f| *f.borrow() == Some(name)) {
|
||||||
|
return Err(synapse_core::Error::Invalid(format!(
|
||||||
|
"injected failure at {name}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn open() -> (tempfile::TempDir, SynapseGraph) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = SynapseGraph::open(dir.path().to_string_lossy().into_owned()).unwrap();
|
||||||
|
(dir, g)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn page(g: &SynapseGraph, rows: &[&str]) -> (String, Vec<String>) {
|
||||||
|
let p = g.open_page("P".into()).unwrap().page.id;
|
||||||
|
let ids = rows
|
||||||
|
.iter()
|
||||||
|
.map(|c| {
|
||||||
|
let place = Place {
|
||||||
|
kind: PlaceKind::LastChildOf,
|
||||||
|
anchor: None,
|
||||||
|
};
|
||||||
|
g.insert_block(p.clone(), place, (*c).into()).unwrap().id
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
(p, ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shape(g: &SynapseGraph, p: &str) -> Vec<(u32, String)> {
|
||||||
|
g.outline(p.into())
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|b| (b.depth, b.content))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failing<T>(at: &'static str, f: impl FnOnce() -> T) -> T {
|
||||||
|
FAIL_AT.with(|x| *x.borrow_mut() = Some(at));
|
||||||
|
let out = f();
|
||||||
|
FAIL_AT.with(|x| *x.borrow_mut() = None);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_merge_leaves_text_and_children_untouched() {
|
||||||
|
let (_d, g) = open();
|
||||||
|
let (p, ids) = page(&g, &["a", "b", "kid"]);
|
||||||
|
g.indent_block(ids[2].clone()).unwrap();
|
||||||
|
let before = shape(&g, &p);
|
||||||
|
assert!(failing("merge", || g.merge_block(ids[1].clone(), ids[0].clone())).is_err());
|
||||||
|
assert_eq!(shape(&g, &p), before, "no duplicated text, no lost block");
|
||||||
|
g.merge_block(ids[1].clone(), ids[0].clone()).unwrap();
|
||||||
|
assert_eq!(shape(&g, &p), vec![(0, "ab".into()), (1, "kid".into())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_outdent_does_not_strand_siblings() {
|
||||||
|
let (_d, g) = open();
|
||||||
|
let (p, ids) = page(&g, &["p", "a", "b", "c"]);
|
||||||
|
for id in &ids[1..] {
|
||||||
|
g.indent_block(id.clone()).unwrap();
|
||||||
|
}
|
||||||
|
let before = shape(&g, &p);
|
||||||
|
assert!(failing("outdent", || g.outdent_block(ids[1].clone())).is_err());
|
||||||
|
assert_eq!(shape(&g, &p), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failed_indent_keeps_collapsed_state() {
|
||||||
|
let (_d, g) = open();
|
||||||
|
let (p, ids) = page(&g, &["a", "a1", "b"]);
|
||||||
|
g.indent_block(ids[1].clone()).unwrap();
|
||||||
|
g.set_collapsed(ids[0].clone(), true).unwrap();
|
||||||
|
assert!(failing("indent", || g.indent_block(ids[2].clone())).is_err());
|
||||||
|
let rows = g.outline(p).unwrap();
|
||||||
|
assert!(rows[0].collapsed, "collapse change rolled back");
|
||||||
|
assert_eq!(rows[2].depth, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn placement_rejects_missing_or_foreign_anchors() {
|
||||||
|
let (_d, g) = open();
|
||||||
|
let (p, ids) = page(&g, &["a"]);
|
||||||
|
let other = g.open_page("Q".into()).unwrap().page.id;
|
||||||
|
let after = |anchor: &str| Place {
|
||||||
|
kind: PlaceKind::After,
|
||||||
|
anchor: Some(anchor.into()),
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
g.insert_block(other.clone(), after(&ids[0]), "x".into())
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let missing = uuid::Uuid::now_v7().to_string();
|
||||||
|
assert!(
|
||||||
|
g.insert_block(p.clone(), after(&missing), "x".into())
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let child = Place {
|
||||||
|
kind: PlaceKind::LastChildOf,
|
||||||
|
anchor: Some(missing),
|
||||||
|
};
|
||||||
|
assert!(g.move_block(ids[0].clone(), p.clone(), child).is_err());
|
||||||
|
assert_eq!(shape(&g, &p), vec![(0, "a".into())]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-2
@@ -14,8 +14,12 @@
|
|||||||
switcher, shell), `theme/`.
|
switcher, shell), `theme/`.
|
||||||
|
|
||||||
## Toolchain
|
## Toolchain
|
||||||
- Flutter stable (3.47+) on `PATH`, Rust stable, `cargo install flutter_rust_bridge_codegen
|
- Flutter stable (3.47+) on `PATH`, Rust stable via rustup, `cargo install
|
||||||
--version 2.13.0 --locked`.
|
flutter_rust_bridge_codegen --version 2.13.0 --locked`.
|
||||||
|
- rustup's `~/.cargo/bin` must come **before** `/usr/bin` in `PATH`. Fedora's packaged `cargo`
|
||||||
|
(rust 1.99) cannot reuse artifacts built by rustup's toolchain (1.97) and cargokit picks up
|
||||||
|
whichever `cargo` is first: `export PATH="$HOME/.cargo/bin:$PATH"` (check with
|
||||||
|
`cargo --version`), or remove the distro `cargo`/`rust` packages.
|
||||||
- Linux desktop: `clang cmake ninja-build gtk3-devel` (Fedora) / `clang cmake ninja-build
|
- Linux desktop: `clang cmake ninja-build gtk3-devel` (Fedora) / `clang cmake ninja-build
|
||||||
libgtk-3-dev` (Debian/Ubuntu).
|
libgtk-3-dev` (Debian/Ubuntu).
|
||||||
- Android: Android SDK + NDK (cargokit installs the Rust targets with rustup).
|
- Android: Android SDK + NDK (cargokit installs the Rust targets with rustup).
|
||||||
|
|||||||
+3
-1
@@ -79,7 +79,9 @@ sync on SSE hint, when ops are pending or when due; on failure exponential backo
|
|||||||
with jitter); "offline" (connect/timeout errors) never loses edits, they stay pending. Call
|
with jitter); "offline" (connect/timeout errors) never loses edits, they stay pending. Call
|
||||||
`trigger()` after local edits to sync without waiting for the poll.
|
`trigger()` after local edits to sync without waiting for the poll.
|
||||||
|
|
||||||
The graph is shared as `Arc<Mutex<Graph>>`; the client locks it only for short DB steps.
|
The graph is shared as `Arc<Mutex<Graph>>`; the client locks it only for short DB steps. In the
|
||||||
|
app, `synapse_ffi::api::graph::SynapseGraph::shared()` returns that same `Arc` to build a
|
||||||
|
`SyncClient` next to the FFI handle.
|
||||||
|
|
||||||
## Limits / not in v1
|
## Limits / not in v1
|
||||||
- Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list;
|
- Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list;
|
||||||
|
|||||||
Reference in new issue
Block a user