refactor(client): isolate legacy cloud codecs

Move the legacy cloud codecs into a host adapter.
Use typed account and document routes for remote operations.
Match durable receipts to each local write sequence.
Check the client dependency graphs and source boundaries in CI.
This commit is contained in:
DarkSky committed 2026-12-05 22:47:16 +09:00
1 parent 3268dcd7e1
commit 3a5b980fe5
81 files changed
+5443 -2309

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
# Working in `packages/common/store/` (for agents)
`packages/common/store/` (`affine-store`) holds the client storage and sans-I/O sync domain crate.
`packages/common/store/` (`affine-store`) holds client storage, CRDT metadata, and protocol-neutral remote domain types.
This directory belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`.
## Domain boundaries and invariants
@@ -17,7 +17,7 @@ This directory belongs to the client Cargo workspace rooted at `packages/fronten
- This crate is the sole writer for AFFiNE root workspace metadata (`meta.pages` and `spaces[pageId]`) and workspace SQLite/IndexedDB tables.
It exposes `WorkspaceDirectory` as a store-domain query and mutation service, and does not define editor port traits.
It also owns the pure-protocol `auth` module so iOS and Android thin hosts can share endpoint canonicalization, RFC 3339 normalization, and token validation without depending on `affine-client` (which pulls UI and editor crates).
It defines account scopes, typed document routes, and commit receipts. Cloud wire codecs belong in `affine-compat-v027`.
When recovering an existing workspace via `WorkspaceDb::from_root_update_v1`, pass all persisted `db$*` table updates (including `db$docProperties` when present) at construction time; tables omitted from `initial_db_tables` are treated as confirmed absent on disk.
- Keep SQLite schema migrations frozen at the `0.27.5` five-step contract and share `<spaceId>.db` in place with legacy clients.
+282
View File
@@ -0,0 +1,282 @@
use std::{fmt, str::FromStr};
use crate::{
StoreError, StoreResult,
directory::DocId,
workspace_db::{TableDocId, UserdataTableName, WorkspaceDbTableName},
};
/// The canonical HTTP or HTTPS origin of a server.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CanonicalOrigin(String);
impl CanonicalOrigin {
pub fn parse(endpoint: &str) -> StoreResult<Self> {
let invalid = || StoreError::InvalidPath("expected an HTTP or HTTPS origin".into());
let url = url::Url::parse(endpoint.trim()).map_err(|_| invalid())?;
if !matches!(url.scheme(), "http" | "https") || url.host().is_none() {
return Err(invalid());
}
Ok(Self(url.origin().ascii_serialization()))
}
pub fn matches_transport_endpoint(&self, endpoint: &str) -> bool {
let Ok(url) = url::Url::parse(endpoint) else {
return false;
};
if !url.username().is_empty() || url.password().is_some() {
return false;
}
let origin = url.origin().ascii_serialization();
match url.scheme() {
"http" | "https" => self.0 == origin,
"ws" => self.0.strip_prefix("http:") == origin.strip_prefix("ws:"),
"wss" => self.0.strip_prefix("https:") == origin.strip_prefix("wss:"),
_ => false,
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for CanonicalOrigin {
type Err = StoreError;
fn from_str(endpoint: &str) -> StoreResult<Self> {
Self::parse(endpoint)
}
}
impl fmt::Display for CanonicalOrigin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AccountScope {
pub origin: CanonicalOrigin,
pub user_id: String,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum SpaceKind {
Workspace(String),
Userspace(String),
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum WorkspaceTableKind {
Database(WorkspaceDbTableName),
UserSettings,
DocIntegrationRef,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum WorkspaceResource {
Root,
Page(String),
Table(WorkspaceTableKind),
UserFavorite,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum UserspaceResource {
EditorSetting,
}
/// A resource and its space form one route. The enum prevents a cross-space pairing.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum DocRoute {
Workspace {
id: String,
resource: WorkspaceResource,
},
Userspace {
id: String,
resource: UserspaceResource,
},
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DocAddress {
pub scope: AccountScope,
pub route: DocRoute,
}
impl DocAddress {
pub fn space(&self) -> SpaceKind {
match &self.route {
DocRoute::Workspace { id, .. } => SpaceKind::Workspace(id.clone()),
DocRoute::Userspace { id, .. } => SpaceKind::Userspace(id.clone()),
}
}
/// Interpret a storage key within a known workspace.
pub fn from_workspace_storage_key(
scope: AccountScope,
workspace_id: &str,
key: &str,
) -> Option<Self> {
let resource = if key == workspace_id {
WorkspaceResource::Root
} else {
match TableDocId::parse(key, &scope.user_id) {
Some(TableDocId::Db(table)) => {
WorkspaceResource::Table(WorkspaceTableKind::Database(table))
}
Some(TableDocId::Userdata(UserdataTableName::Favorite)) => {
WorkspaceResource::UserFavorite
}
Some(TableDocId::Userdata(UserdataTableName::Settings)) => {
WorkspaceResource::Table(WorkspaceTableKind::UserSettings)
}
Some(TableDocId::Userdata(UserdataTableName::DocIntegrationRef)) => {
WorkspaceResource::Table(WorkspaceTableKind::DocIntegrationRef)
}
None if DocId::is_canonical(key) => WorkspaceResource::Page(key.into()),
None => return None,
}
};
Some(Self {
scope,
route: DocRoute::Workspace {
id: workspace_id.into(),
resource,
},
})
}
/// Find the local storage key for a route in this account and workspace.
pub fn workspace_storage_key(
&self,
scope: &AccountScope,
workspace_id: &str,
) -> Option<String> {
if &self.scope != scope {
return None;
}
let DocRoute::Workspace { id, resource } = &self.route else {
return None;
};
if id != workspace_id {
return None;
}
Some(match resource {
WorkspaceResource::Root => id.clone(),
WorkspaceResource::Page(page) if page != id && DocId::is_canonical(page) => {
page.clone()
}
WorkspaceResource::Page(_) => return None,
WorkspaceResource::Table(table) => match table {
WorkspaceTableKind::Database(table) => table.local_doc_id(),
WorkspaceTableKind::UserSettings => {
UserdataTableName::Settings.local_doc_id(&scope.user_id)
}
WorkspaceTableKind::DocIntegrationRef => {
UserdataTableName::DocIntegrationRef.local_doc_id(&scope.user_id)
}
},
WorkspaceResource::UserFavorite => {
UserdataTableName::Favorite.local_doc_id(&scope.user_id)
}
})
}
}
/// The monotonic sequence of a local commit.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct LocalSeq(pub u64);
/// Proof that a peer durably accepted this commit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommitReceipt {
pub address: DocAddress,
pub seq: LocalSeq,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn websocket_endpoint_must_match_the_account_origin() {
let scope = CanonicalOrigin::parse("https://example.org:8443").unwrap();
for (url, matches) in [
("wss://EXAMPLE.org:8443/socket.io/?EIO=4", true),
("https://example.org:8443/sync", true),
("ws://example.org:8443/sync", false),
("wss://example.org/sync", false),
("wss://example.org.evil.test:8443/sync", false),
("wss://person:secret@example.org:8443/sync", false),
] {
assert_eq!(scope.matches_transport_endpoint(url), matches, "{url}");
}
}
#[test]
fn normalizes_http_origins_and_rejects_non_http_origins() {
for (input, expected) in [
(
" HTTPS://EXAMPLE.COM:443/path?q=1#f ",
Some("https://example.com"),
),
("http://[::1]:80/", Some("http://[::1]")),
("https://[::1]:8443", Some("https://[::1]:8443")),
(
"https://bücher.example/",
Some("https://xn--bcher-kva.example"),
),
("file:///tmp/a", None),
("//example.com", None),
("about:blank", None),
] {
let actual = CanonicalOrigin::parse(input).ok();
assert_eq!(actual.as_ref().map(CanonicalOrigin::as_str), expected);
}
}
#[test]
fn identical_space_ids_do_not_alias_across_spaces_or_accounts() {
let scope = AccountScope {
origin: CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "alice".into(),
};
let favorite = DocAddress {
scope: scope.clone(),
route: DocRoute::Workspace {
id: "same-id".into(),
resource: WorkspaceResource::UserFavorite,
},
};
let setting = DocAddress {
scope,
route: DocRoute::Userspace {
id: "same-id".into(),
resource: UserspaceResource::EditorSetting,
},
};
assert_ne!(favorite, setting);
assert_ne!(favorite.space(), setting.space());
let mut other_account = favorite.clone();
other_account.scope.user_id = "bob".into();
assert_ne!(favorite, other_account);
let mut forged_page = favorite.clone();
forged_page.route = DocRoute::Workspace {
id: "same-id".into(),
resource: WorkspaceResource::Page("db$folders".into()),
};
assert!(
forged_page
.workspace_storage_key(&favorite.scope, "same-id")
.is_none()
);
assert!(
favorite
.workspace_storage_key(&other_account.scope, "same-id")
.is_none()
);
}
}
+99
View File
@@ -0,0 +1,99 @@
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use sha2::{Digest, Sha256};
/// Compute the canonical content-addressed blob key (base64url-no-pad SHA-256) for `bytes`.
pub fn compute_blob_key(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
URL_SAFE_NO_PAD.encode(digest)
}
/// Compute the 64-character lowercase hexadecimal SHA-256 digest of `bytes`.
pub fn compute_sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(64);
for b in digest {
use std::fmt::Write as _;
let _ = write!(&mut hex, "{b:02x}");
}
hex
}
/// Inspect raw image bytes (PNG, GIF, JPEG, or WebP) and return `(width, height)` in pixels.
///
/// Pure in-memory header parser with zero external dependencies and full `wasm32` compatibility.
pub fn detect_image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
// PNG: 8-byte signature + IHDR chunk (width at 16..20, height at 20..24, big-endian).
if bytes.len() >= 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
if w > 0 && h > 0 {
return Some((w, h));
}
}
// GIF87a / GIF89a: width at 6..8, height at 8..10 (little-endian).
if bytes.len() >= 10 && (bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")) {
let w = u32::from(u16::from_le_bytes([bytes[6], bytes[7]]));
let h = u32::from(u16::from_le_bytes([bytes[8], bytes[9]]));
if w > 0 && h > 0 {
return Some((w, h));
}
}
// WebP (RIFF....WEBP): VP8X extended header.
if bytes.len() >= 30
&& &bytes[0..4] == b"RIFF"
&& &bytes[8..12] == b"WEBP"
&& &bytes[12..16] == b"VP8X"
{
let w =
1 + (u32::from(bytes[24]) | (u32::from(bytes[25]) << 8) | (u32::from(bytes[26]) << 16));
let h =
1 + (u32::from(bytes[27]) | (u32::from(bytes[28]) << 8) | (u32::from(bytes[29]) << 16));
if w > 0 && h > 0 {
return Some((w, h));
}
}
// JPEG: scan SOF0..SOF2 markers (`0xFF 0xC0..=0xC2`).
if bytes.len() >= 4 && bytes[0] == 0xFF && bytes[1] == 0xD8 {
let mut i = 2usize;
while i + 4 <= bytes.len() {
if bytes[i] != 0xFF {
break;
}
let marker = bytes[i + 1];
i += 2;
if marker == 0xD9 || marker == 0xDA {
break;
}
if i + 2 > bytes.len() {
break;
}
let seg_len = usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]]));
if seg_len < 2 || i + seg_len > bytes.len() {
break;
}
if matches!(marker, 0xC0..=0xC2) && seg_len >= 7 {
let h = u32::from(u16::from_be_bytes([bytes[i + 3], bytes[i + 4]]));
let w = u32::from(u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]));
if w > 0 && h > 0 {
return Some((w, h));
}
}
i += seg_len;
}
}
None
}
/// The document that authorizes a blob read.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BlobSource {
CurrentDoc {
workspace_id: String,
doc_id: String,
},
History {
workspace_id: String,
doc_id: String,
timestamp_ms: i64,
},
}
+5 -1
View File
@@ -21,7 +21,7 @@ pub struct DocId(String);
impl DocId {
pub fn new(id: impl Into<String>) -> StoreResult<Self> {
let id = id.into();
if id.is_empty() || id.starts_with("db$") || id.starts_with("userdata$") {
if !Self::is_canonical(&id) {
return Err(StoreError::InvalidProtocol(format!(
"invalid canonical DocId: {id:?}"
)));
@@ -29,6 +29,10 @@ impl DocId {
Ok(Self(id))
}
pub(crate) fn is_canonical(id: &str) -> bool {
!id.is_empty() && !id.starts_with("db$") && !id.starts_with("userdata$")
}
pub fn as_str(&self) -> &str {
&self.0
}
+27 -34
View File
@@ -10,7 +10,7 @@ pub fn merge_crdt_updates_v1(updates: &[&[u8]]) -> StoreResult<Vec<u8>> {
.map_err(|err| StoreError::InvalidBinary(err.to_string()))
}
/// Bidirectional document ID converter matching `packages/common/nbstore/src/utils/id-converter.ts`.
/// Resolves legacy IndexedDB keys and root and page GUID aliases.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IdConverter {
space_id: String,
@@ -47,19 +47,6 @@ impl IdConverter {
converter
}
/// Build a converter from explicit bidirectional maps.
pub fn from_maps(
space_id: impl Into<String>,
old_to_new: BTreeMap<String, String>,
new_to_old: BTreeMap<String, String>,
) -> Self {
Self {
space_id: space_id.into(),
old_to_new,
new_to_old,
}
}
/// Extract page-to-subdoc GUID aliases from an encoded root YDoc update.
pub fn from_root_doc_bytes(
space_id: impl Into<String>,
@@ -119,8 +106,8 @@ impl IdConverter {
.collect()
}
/// Convert a local normalized document ID to the legacy/wire document ID.
pub fn new_id_to_old_id(&self, new_id: &str) -> String {
/// Convert a local normalized document ID to the legacy IndexedDB key.
pub fn legacy_storage_key(&self, new_id: &str) -> String {
if let Some(rest) = new_id.strip_prefix("db$") {
return format!("db${}${rest}", self.space_id);
}
@@ -133,8 +120,8 @@ impl IdConverter {
.unwrap_or_else(|| new_id.to_string())
}
/// Convert a legacy/wire document ID to the local normalized document ID.
pub fn old_id_to_new_id(&self, old_id: &str) -> String {
/// Convert a legacy IndexedDB key to the local normalized document ID.
pub fn local_storage_key(&self, old_id: &str) -> String {
let db_prefix = format!("db${}$", self.space_id);
if let Some(rest) = old_id.strip_prefix(&db_prefix) {
return format!("db${rest}");
@@ -228,26 +215,26 @@ mod tests {
),
];
for (local_id, wire_id) in cases {
for (local_id, legacy_key) in cases {
assert_eq!(
converter.new_id_to_old_id(local_id),
wire_id,
converter.legacy_storage_key(local_id),
legacy_key,
"new->old for {local_id}"
);
assert_eq!(
converter.old_id_to_new_id(wire_id),
converter.local_storage_key(legacy_key),
local_id,
"old->new for {wire_id}"
"old->new for {legacy_key}"
);
}
// Foreign space db$ and userdata$ IDs must pass through unchanged.
assert_eq!(
converter.old_id_to_new_id("db$other-ws$folders"),
converter.local_storage_key("db$other-ws$folders"),
"db$other-ws$folders"
);
assert_eq!(
converter.old_id_to_new_id("userdata$u1$other-ws$favorite"),
converter.local_storage_key("userdata$u1$other-ws$favorite"),
"userdata$u1$other-ws$favorite"
);
}
@@ -308,12 +295,12 @@ mod tests {
let converter =
IdConverter::from_root_doc_bytes("space-1", Some("legacy-root"), Some(&commit.update))
.unwrap();
assert_eq!(converter.new_id_to_old_id("space-1"), "legacy-root");
assert_eq!(converter.old_id_to_new_id("legacy-root"), "space-1");
assert_eq!(converter.new_id_to_old_id("page-1"), "old-guid-1");
assert_eq!(converter.old_id_to_new_id("old-guid-1"), "page-1");
assert_eq!(converter.new_id_to_old_id("page-2"), "page-2");
assert_eq!(converter.old_id_to_new_id("page-2"), "page-2");
assert_eq!(converter.legacy_storage_key("space-1"), "legacy-root");
assert_eq!(converter.local_storage_key("legacy-root"), "space-1");
assert_eq!(converter.legacy_storage_key("page-1"), "old-guid-1");
assert_eq!(converter.local_storage_key("old-guid-1"), "page-1");
assert_eq!(converter.legacy_storage_key("page-2"), "page-2");
assert_eq!(converter.local_storage_key("page-2"), "page-2");
}
#[test]
@@ -433,10 +420,16 @@ mod tests {
// 3-segment and 4-segment userdata$ conversion parity.
let conv = IdConverter::new("ws");
assert_eq!(conv.old_id_to_new_id("userdata$u$ws$fav"), "userdata$u$fav");
assert_eq!(conv.new_id_to_old_id("userdata$u$fav"), "userdata$u$ws$fav");
assert_eq!(
conv.old_id_to_new_id("userdata$u$other"),
conv.local_storage_key("userdata$u$ws$fav"),
"userdata$u$fav"
);
assert_eq!(
conv.legacy_storage_key("userdata$u$fav"),
"userdata$u$ws$fav"
);
assert_eq!(
conv.local_storage_key("userdata$u$other"),
"userdata$u$other"
);
}
+1 -1
View File
@@ -15,8 +15,8 @@ use std::{
use y_octo::{merge_updates_v1, validate_update_v1};
use crate::{
SpaceType,
error::{StoreError, StoreResult},
sync::SpaceType,
workspace_db::PendingDocUpdate,
};
+2 -2
View File
@@ -91,7 +91,7 @@ impl IdbV1DocStorage {
/// Read a document by normalized local `doc_id`, resolving legacy GUIDs via [`IdConverter`].
pub fn get_doc(&self, doc_id: &str) -> StoreResult<Option<IdbV1DocRecord>> {
let converter = self.id_converter()?;
let old_id = converter.new_id_to_old_id(doc_id);
let old_id = converter.legacy_storage_key(doc_id);
let Some(bin) = self.raw_get_doc(&old_id)? else {
return Ok(None);
};
@@ -133,7 +133,7 @@ impl IdbV1DocStorage {
for old_id in old_ids {
if self.workspace_rows.contains_key(&old_id) || old_id == self.space_id {
out.insert(
converter.old_id_to_new_id(&old_id),
converter.local_storage_key(&old_id),
IDB_V1_CONST_TIMESTAMP_MS,
);
}
+15 -4
View File
@@ -1,19 +1,30 @@
#![forbid(unsafe_code)]
pub mod api_client;
pub mod auth;
pub mod blob_api;
pub mod address;
pub mod blob;
pub mod clock;
pub mod directory;
pub mod error;
pub mod id_converter;
pub mod idb;
pub mod peer;
pub mod share_ingest;
mod space_type;
#[cfg(not(target_family = "wasm"))]
pub mod sqlite;
pub mod sync;
pub mod workspace_db;
pub use address::{
AccountScope, CanonicalOrigin, CommitReceipt, DocAddress, DocRoute, LocalSeq, SpaceKind,
UserspaceResource, WorkspaceResource, WorkspaceTableKind,
};
pub use clock::{Clock, ManualClock};
pub use error::{StoreError, StoreResult};
pub use id_converter::IdConverter;
pub use peer::{
DocDiff, PeerFailureReason, PeerOperation, PeerSyncEvent, PeerSyncState, PushIntent,
};
pub use space_type::SpaceType;
/// The user ID for an unsigned local workspace.
pub const LOCAL_USER_ID: &str = "__local__";
+97
View File
@@ -0,0 +1,97 @@
use std::collections::BTreeMap;
use crate::{CommitReceipt, DocAddress};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PeerSyncState {
Offline,
Connecting,
Ready,
ReconnectScheduled { next_attempt_at_ms: i64 },
AuthRequired,
PermissionRevoked,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PushIntent {
Create,
Update,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PeerOperation {
Connect,
Load,
Subscribe,
InspectInventory,
Push,
Delete,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PeerFailureReason {
TransientNetwork,
RateLimited { retry_after_ms: Option<u64> },
QuotaExceeded,
ReadOnly,
Protocol,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocDiff {
pub state_vector_v1: Vec<u8>,
pub update_v1: Vec<u8>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PeerSyncEvent {
Ready,
Subscribed {
addresses: Vec<DocAddress>,
},
Loaded {
address: DocAddress,
diff: DocDiff,
timestamp_ms: i64,
},
Missing {
address: DocAddress,
},
Committed {
receipt: CommitReceipt,
timestamp_ms: i64,
},
Inventory {
timestamps: BTreeMap<DocAddress, i64>,
},
Deleted {
addresses: Vec<DocAddress>,
},
Updated {
address: DocAddress,
updates_v1: Vec<Vec<u8>>,
timestamp_ms: i64,
},
Invalidated {
inventory_changed: bool,
},
AwarenessRequested {
address: DocAddress,
},
Awareness {
address: DocAddress,
update_v1: Vec<u8>,
},
AuthRequired {
address: Option<DocAddress>,
},
PermissionRevoked {
address: Option<DocAddress>,
},
RequestFailed {
operation: PeerOperation,
address: Option<DocAddress>,
reason: PeerFailureReason,
},
Disconnected,
}
+17
View File
@@ -0,0 +1,17 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpaceType {
Workspace,
Userspace,
}
impl SpaceType {
pub const fn as_str(self) -> &'static str {
match self {
Self::Workspace => "workspace",
Self::Userspace => "userspace",
}
}
}
+53 -46
View File
@@ -7,7 +7,7 @@ use super::{
DocClock, PeerWorkspaceState, SqliteDocStorage, WorkspaceDocInventory, millis_to_naive_utc,
naive_utc_to_millis,
};
use crate::error::StoreResult;
use crate::{AccountScope, PeerSyncEvent, error::StoreResult};
fn row_to_doc_clock(row: &sqlx::sqlite::SqliteRow) -> StoreResult<DocClock> {
Ok(DocClock {
@@ -370,57 +370,52 @@ impl SqliteDocStorage {
tx.commit().await?;
Ok(())
}
/// Persist inbound `SpaceSyncEvent` document updates atomically inside a single
/// Persist inbound `PeerSyncEvent` document updates atomically inside a single
/// `BEGIN IMMEDIATE` transaction via [`Self::push_updates_batch`], then advance both
/// `remote_clock` and `pulled_remote_clock` in `peer_clocks` using each event's server
/// `timestamp` (distinct from `local_now_ms`).
pub async fn persist_inbound_sync_events(
&self,
peer: &str,
events: &[crate::sync::SpaceSyncEvent],
scope: &AccountScope,
workspace_id: &str,
events: &[PeerSyncEvent],
local_now_ms: i64,
) -> StoreResult<Vec<(String, NaiveDateTime)>> {
let mut batch = Vec::new();
let mut remote_clocks: HashMap<String, i64> = HashMap::new();
for event in events {
match event {
crate::sync::SpaceSyncEvent::DocLoaded {
doc_id,
missing,
timestamp,
..
} => {
remote_clocks
.entry(doc_id.clone())
.and_modify(|ts| *ts = (*ts).max(*timestamp))
.or_insert(*timestamp);
if !missing.is_empty() && missing.as_slice() != [0, 0] {
batch.push(crate::workspace_db::PendingDocUpdate {
doc_id: doc_id.clone(),
update: missing.clone(),
});
}
let (address, updates, timestamp_ms) = match event {
PeerSyncEvent::Loaded {
address,
diff,
timestamp_ms,
} => (
address,
std::slice::from_ref(&diff.update_v1),
*timestamp_ms,
),
PeerSyncEvent::Updated {
address,
updates_v1,
timestamp_ms,
} => (address, updates_v1.as_slice(), *timestamp_ms),
_ => continue,
};
let Some(doc_id) = address.workspace_storage_key(scope, workspace_id) else {
continue;
};
remote_clocks
.entry(doc_id.clone())
.and_modify(|ts| *ts = (*ts).max(timestamp_ms))
.or_insert(timestamp_ms);
for update in updates {
if !update.is_empty() && update.as_slice() != [0, 0] {
batch.push(crate::workspace_db::PendingDocUpdate {
doc_id: doc_id.clone(),
update: update.clone(),
});
}
crate::sync::SpaceSyncEvent::RemoteDocUpdates {
doc_id,
updates,
timestamp,
..
} => {
remote_clocks
.entry(doc_id.clone())
.and_modify(|ts| *ts = (*ts).max(*timestamp))
.or_insert(*timestamp);
for update in updates {
if !update.is_empty() && update.as_slice() != [0, 0] {
batch.push(crate::workspace_db::PendingDocUpdate {
doc_id: doc_id.clone(),
update: update.clone(),
});
}
}
}
_ => {}
}
}
let persisted = self.push_updates_batch(&batch, None, local_now_ms).await?;
@@ -508,14 +503,26 @@ mod tests {
storage.connect().await.unwrap();
let mut ws = crate::workspace_db::WorkspaceDb::new("ws-sync", "u1", 1);
let init = ws.initialize_meta().unwrap().unwrap();
let events = vec![crate::sync::SpaceSyncEvent::DocLoaded {
doc_id: "ws-sync".into(),
missing: init.clone(),
state: vec![],
timestamp: 42_000,
let scope = AccountScope {
origin: crate::CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "u1".into(),
};
let events = [PeerSyncEvent::Loaded {
address: crate::DocAddress {
scope: scope.clone(),
route: crate::DocRoute::Workspace {
id: "ws-sync".into(),
resource: crate::WorkspaceResource::Root,
},
},
diff: crate::DocDiff {
update_v1: init,
state_vector_v1: Vec::new(),
},
timestamp_ms: 42_000,
}];
let persisted = storage
.persist_inbound_sync_events("cloud", &events, 50_000)
.persist_inbound_sync_events("cloud", &scope, "ws-sync", &events, 50_000)
.await
.unwrap();
assert_eq!(persisted.len(), 1);
@@ -4,6 +4,8 @@ mod root_doc_page_tags;
pub mod share_destinations;
pub mod tables;
pub use crate::LOCAL_USER_ID;
pub use favorites::{FavoriteKind, FavoritePosition, FavoriteRecord, FavoriteRef};
pub use root_doc::{
CreatePageOutcome, PageIdSource, PageMetaEntry, RemoteRootApply, WorkspaceRootDoc,
@@ -12,9 +14,9 @@ pub use root_doc::{
pub use share_destinations::{CollectionFilter, NavigationEdit, WorkspaceCollection, WorkspaceTag};
pub use tables::{
DELETED_FLAG_KEY, DocCustomPropertyInfoRow, DocIntegrationRefRow, DocPropertiesRow,
ExplorerIconRow, FavoriteRow, FolderRow, LOCAL_USER_ID, PinnedCollectionRow, SettingsRow,
TableDocId, USERDATA_TABLE_NAMES, UserdataTableName, WORKSPACE_DB_TABLE_NAMES,
WorkspaceDbTableName, YjsTableDoc,
ExplorerIconRow, FavoriteRow, FolderRow, PinnedCollectionRow, SettingsRow, TableDocId,
USERDATA_TABLE_NAMES, UserdataTableName, WORKSPACE_DB_TABLE_NAMES, WorkspaceDbTableName,
YjsTableDoc,
};
use std::collections::BTreeMap;
@@ -24,9 +26,6 @@ use serde_json::Value as JsonValue;
use crate::error::StoreResult;
/// Protocol version 1: creating a document writes both `meta.pages` and `spaces[pageId]` atomically.
pub const WORKSPACE_SYNC_PROTOCOL_VERSION: u8 = 1;
/// Pending encoded v1 update produced by a local `WorkspaceDb` mutation, ready for host
/// persistence and sync enqueueing.
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -129,10 +129,6 @@ impl UserdataTableName {
}
}
/// The user ID of `userdata$` tables in a local workspace or without an account
/// (`0.27.5` `WorkspaceDBService.userdataDB$`).
pub const LOCAL_USER_ID: &str = "__local__";
/// A `db$` or `userdata$` table document.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum TableDocId {
@@ -5,7 +5,7 @@
#![cfg(not(target_family = "wasm"))]
use affine_store::{
blob_api::{compute_blob_key, detect_image_dimensions},
blob::{compute_blob_key, detect_image_dimensions},
directory::{CreateDocId, CreateDocRequest, DocMode, WorkspaceDirectory},
sqlite::{SetBlob, SqliteDocStorage, millis_to_naive_utc, resolve_workspace_db_path},
workspace_db::{WorkspaceDb, WorkspaceDbTableName},
+2 -1
View File
@@ -5,7 +5,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98
## Workspace boundaries and four-domain guards
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/tokens`, `../ui/ui`, `../ui/kit`, `../common/store`, `legacy-import`, `client`, `mobile`, `desktop`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/editor`, `../../blocksuite/crates/playground`, `../../blocksuite/crates/preview`, `hosts/android`, and `hosts/ios`).
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/tokens`, `../ui/ui`, `../ui/kit`, `../common/store`, `legacy-import`, `client`, `compat-v027`, `mobile`, `desktop`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/editor`, `../../blocksuite/crates/playground`, `../../blocksuite/crates/preview`, `hosts/android`, and `hosts/ios`).
Never use directory wildcards that can scan asset directories.
- `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`.
Those legacy crates remain members of the root `Cargo.toml` workspace.
@@ -13,6 +13,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98
`native/` and `mobile-native/` also carry a `rustfmt.toml` file that matches the repository root byte-for-byte.
- Client trees (`packages/frontend/`, `packages/ui/`, `blocksuite/crates/`, and `packages/common/store/`) share byte-identical `1.98.1` `rust-toolchain.toml` and client `rustfmt.toml` files.
- `scripts/check-invariants.sh` discovers client workspace members from `cargo metadata --locked --no-deps`, enforces four-domain acyclic dependencies (zero reverse edges), checks domain isolation, wall-clock isolation, zero tester branches, module structure, LOC ceilings, toolchain/rustfmt alignment, `workspace_root` resolution, `rustup show active-toolchain` for legacy (`1.97.1`) and client (`1.98.1`) directories, workflow YAML validity, `CARGO_ENCODED_RUSTFLAGS=""` link-flag isolation, and that every harness snapshot ID prefix in `scripts/check-snapshot-prefixes.mjs` still occurs in non-test Rust sources under `blocksuite/crates/*/src` and `packages/frontend/desktop/src`.
- Client core crates must not depend on `affine-compat-v027`. The invariant script checks the native and Wasm normal dependency graphs. It also builds the core crates without the compatibility adapter.
- See `packages/ui/AGENTS.md`, `blocksuite/crates/AGENTS.md`, and `packages/common/store/AGENTS.md` for domain-specific invariants.
### Performance guardrail and theme/style oracle
+17
View File
@@ -28,6 +28,7 @@ name = "affine-android-host"
version = "0.1.0"
dependencies = [
"affine-client",
"affine-compat-v027",
"affine-legacy-import",
"affine-mobile",
"affine-store",
@@ -67,6 +68,21 @@ dependencies = [
"y-octo",
]
[[package]]
name = "affine-compat-v027"
version = "0.1.0"
dependencies = [
"affine-client",
"affine-store",
"base64 0.22.1",
"blocksuite-playground-doc",
"chrono",
"serde",
"serde_json",
"tokio",
"url",
]
[[package]]
name = "affine-desktop"
version = "0.1.0"
@@ -96,6 +112,7 @@ name = "affine-ios-host"
version = "0.1.0"
dependencies = [
"affine-client",
"affine-compat-v027",
"affine-legacy-import",
"affine-mobile",
"affine-store",
+2
View File
@@ -7,6 +7,7 @@ members = [
"../common/store",
"legacy-import",
"client",
"compat-v027",
"mobile",
"desktop",
"../../blocksuite/crates/doc",
@@ -23,6 +24,7 @@ default-members = [
"../common/store",
"legacy-import",
"client",
"compat-v027",
"mobile",
"desktop",
"../../blocksuite/crates/doc",
+2
View File
@@ -6,6 +6,8 @@ This crate belongs to the client Cargo workspace rooted at `packages/frontend/Ca
## Domain boundaries and invariants
- Keep `#![forbid(unsafe_code)]` at the crate root.
- Define remote session, catalog, document, and blob ports in `remote/`.
A host supplies the document peer. Keep legacy wire formats and HTTP code out of this crate.
- Remain strictly device-neutral: never import `ui::Window`, view elements, or mobile-only shell concepts.
- Enforce `F3`: only `HostKind::Native` allows adding cross-origin self-hosted servers; `HostKind::Web` rejects self-hosted server addition.
- Keep `StoreBackedDocDirectory` (`WorkspaceDocDirectory` implementation) aligned with the root-registration and anti-resurrection invariants (`F1`): persist `root_registered` immediately upon root write success, support in-session `intent_id` idempotent replay, and return `Err(DirectoryError::NotFound)` on replaying deleted intents.
-16
View File
@@ -13,22 +13,6 @@ workspace = true
default = ["cloud-sync"]
cloud-sync = []
[[test]]
name = "doc_sync_peer_protocol"
required-features = ["cloud-sync"]
[[test]]
name = "lazy_hydration_remote_sync_persistence"
required-features = ["cloud-sync"]
[[test]]
name = "persistence_cancellation_and_tombstones"
required-features = ["cloud-sync"]
[[test]]
name = "workspace_sync_and_blobs"
required-features = ["cloud-sync"]
[dependencies]
affine-legacy-import = { path = "../legacy-import" }
affine-store = { path = "../../common/store" }
+49 -484
View File
@@ -1,197 +1,31 @@
//! Pure sans-I/O authentication state machine and `0.27.5` `StoredAuthTokenPair` codec.
//!
//! ## Single Refresh Owner Architecture
//! Native platform hosts (`hosts/ios` `LegacyAuthBridge` and `hosts/android` `AuthSessionStore`)
//! are the sole I/O owners for Keychain/Keystore persistence and single-flight network
//! `/api/auth/session/{exchange,refresh,revoke}` execution. [`AuthController`] performs zero
//! network I/O and zero credential writes; host coordinators feed outcomes into
//! [`AuthController::apply_native_tokens`], [`AuthController::clear_native_session`], and
//! [`AuthController::apply_session_response`].
//! Account state and credentials for a workspace session.
#[cfg(feature = "cloud-sync")]
use affine_store::sync::SocketAuthMode;
use affine_store::{
api_client::{
ApiHttpRequest, ApiRequestContext, AuthSessionMeta, AuthSessionUser, AuthTokenPairResponse,
build_get_auth_session_request, decode_auth_session_response,
},
auth::{
MAX_EXPIRES_IN_SECS, parse_and_validate_token_pair_response, validate_token_pair_fields,
},
};
use serde::{Deserialize, Serialize};
use crate::{HostKind, remote::AccountProfile};
use crate::{
ClientError, ClientResult,
host::{HostBridge, HostKind},
};
/// Seconds between Unix epoch (`1970-01-01T00:00:00Z`) and Apple CoreFoundation / `Date`
/// reference epoch (`2001-01-01T00:00:00Z`).
pub const APPLE_CF_EPOCH_OFFSET_SECS: f64 = 978_307_200.0;
/// Native host storage format selector preventing iOS CF-epoch integer-second ambiguity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NativeAuthPlatform {
/// iOS Keychain JSON (`accessExpiresAt` encoded as 2001 CoreFoundation epoch seconds).
Ios,
/// Android DataStore JSON (`accessExpiresAt` encoded as 1970 Unix milliseconds).
Android,
}
/// Canonical `0.27.5` persisted native token pair (`StoredAuthTokenPair`).
///
/// Stores `version = 1`, absolute `accessExpiresAt` (Unix ms in memory / Android DataStore,
/// convertible losslessly to/from iOS 2001 CF epoch seconds), and nested `session: { id, absoluteExpiresAt }`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredAuthTokenPair {
pub version: u32,
pub token_type: String,
pub access_token: String,
pub access_expires_at: i64,
pub refresh_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_expires_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session: Option<AuthSessionMeta>,
}
/// Alias preserving compatibility for callers referring to `NativeTokenPair`.
pub type NativeTokenPair = StoredAuthTokenPair;
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IosKeychainTokenPairWire {
version: u32,
token_type: String,
access_token: String,
access_expires_at: f64,
refresh_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
refresh_expires_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
session: Option<AuthSessionMeta>,
}
impl StoredAuthTokenPair {
/// Maximum `expires_in` accepted from a native token endpoint (`24h`, matching `0.27.5`
/// `AuthPlugin.swift` / `AuthPlugin.kt`).
pub const MAX_EXPIRES_IN_SECS: u64 = MAX_EXPIRES_IN_SECS;
fn validate_invariant_fields(&self) -> ClientResult<()> {
validate_token_pair_fields(
self.version,
&self.token_type,
&self.access_token,
&self.refresh_token,
self.refresh_expires_at.as_deref(),
self.session.as_ref(),
)
.map_err(|err| ClientError::InvalidAuthPayload(err.to_string()))
}
/// Validate and convert a server [`AuthTokenPairResponse`] into a [`StoredAuthTokenPair`]
/// using an explicit deterministic `now_ms`.
///
/// Rejects non-`Bearer` `token_type`, empty tokens, out-of-range `expires_in`
/// (`1..=86_400`), and malformed RFC 3339 timestamps.
pub fn from_wire(parsed: AuthTokenPairResponse, now_ms: i64) -> ClientResult<Self> {
let validated = parse_and_validate_token_pair_response(parsed, now_ms)
.map_err(|err| ClientError::InvalidAuthPayload(err.to_string()))?;
Ok(Self {
version: validated.version,
token_type: validated.token_type,
access_token: validated.access_token,
access_expires_at: validated.access_expires_at_ms,
refresh_token: validated.refresh_token,
refresh_expires_at: validated.refresh_expires_at,
session: validated.session,
})
}
pub fn session_id(&self) -> Option<&str> {
self.session.as_ref().map(|s| s.id.as_str())
}
pub fn access_expires_at_unix_ms(&self) -> i64 {
self.access_expires_at
}
/// Convert `access_expires_at` (Unix ms) to iOS `Date` / CF 2001 epoch seconds.
pub fn access_expires_at_ios_cf_secs(&self) -> f64 {
(self.access_expires_at as f64 / 1_000.0) - APPLE_CF_EPOCH_OFFSET_SECS
}
/// Convert iOS `Date` / CF 2001 epoch seconds back to Unix milliseconds.
pub fn unix_ms_from_ios_cf_secs(cf_secs: f64) -> i64 {
((cf_secs + APPLE_CF_EPOCH_OFFSET_SECS) * 1_000.0).round() as i64
}
/// Serialize to the exact `0.27.5` Android DataStore JSON format (Unix ms `accessExpiresAt`).
pub fn to_android_datastore_json(&self) -> ClientResult<String> {
Ok(serde_json::to_string(self)?)
}
/// Deserialize from the exact `0.27.5` Android DataStore JSON format.
pub fn from_android_datastore_json(raw: &str) -> ClientResult<Self> {
let pair: Self = serde_json::from_str(raw)?;
pair.validate_invariant_fields()?;
Ok(pair)
}
/// Serialize to the exact `0.27.5` iOS Keychain JSON format (2001 CF epoch seconds `accessExpiresAt`).
pub fn to_ios_keychain_json(&self) -> ClientResult<String> {
let wire = IosKeychainTokenPairWire {
version: self.version,
token_type: self.token_type.clone(),
access_token: self.access_token.clone(),
access_expires_at: self.access_expires_at_ios_cf_secs(),
refresh_token: self.refresh_token.clone(),
refresh_expires_at: self.refresh_expires_at.clone(),
session: self.session.clone(),
};
Ok(serde_json::to_string(&wire)?)
}
/// Deserialize from the exact `0.27.5` iOS Keychain JSON format.
pub fn from_ios_keychain_json(raw: &str) -> ClientResult<Self> {
let wire: IosKeychainTokenPairWire = serde_json::from_str(raw)?;
if !wire.access_expires_at.is_finite() {
return Err(ClientError::InvalidAuthPayload(
"iOS accessExpiresAt must be finite".into(),
));
}
let pair = Self {
version: wire.version,
token_type: wire.token_type,
access_token: wire.access_token,
access_expires_at: Self::unix_ms_from_ios_cf_secs(wire.access_expires_at),
refresh_token: wire.refresh_token,
refresh_expires_at: wire.refresh_expires_at,
session: wire.session,
};
pair.validate_invariant_fields()?;
Ok(pair)
}
}
/// Active session state for a single server.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthSessionState {
SignedOut,
Authenticated { user: AuthSessionUser },
Authenticated { user: AccountProfile },
}
#[derive(Clone, Copy)]
pub enum ConnectionAuth<'a> {
Browser,
Native(Option<&'a str>),
SignedOut,
}
/// Pure sans-I/O per-server authentication state machine.
#[derive(Clone, Debug)]
pub struct AuthController {
server_id: String,
base_url: String,
#[cfg(feature = "cloud-sync")]
host_kind: HostKind,
state: AuthSessionState,
native_tokens: Option<StoredAuthTokenPair>,
#[cfg(feature = "cloud-sync")]
access_token: Option<String>,
mutation_epoch: u64,
#[cfg(feature = "cloud-sync")]
signed_out: bool,
}
impl AuthController {
@@ -200,13 +34,19 @@ impl AuthController {
base_url: impl Into<String>,
host_kind: HostKind,
) -> Self {
#[cfg(not(feature = "cloud-sync"))]
let _ = host_kind;
Self {
server_id: server_id.into(),
base_url: base_url.into().trim().trim_end_matches('/').to_string(),
#[cfg(feature = "cloud-sync")]
host_kind,
state: AuthSessionState::SignedOut,
native_tokens: None,
#[cfg(feature = "cloud-sync")]
access_token: None,
mutation_epoch: 0,
#[cfg(feature = "cloud-sync")]
signed_out: false,
}
}
@@ -218,11 +58,6 @@ impl AuthController {
&self.base_url
}
/// Endpoint-scoped credential key (`auth:<canonical_base_url>`) isolating credentials by URL.
pub fn credential_key(&self) -> String {
format!("auth:{}", self.base_url)
}
pub fn mutation_epoch(&self) -> u64 {
self.mutation_epoch
}
@@ -231,310 +66,40 @@ impl AuthController {
&self.state
}
pub fn native_tokens(&self) -> Option<&StoredAuthTokenPair> {
self.native_tokens.as_ref()
}
/// Hydrate offline cached user profile (for example from `global-state:<serverId>-auth`)
/// so transient `5xx`/`429`/network failures preserve the cached signed-in UI state.
pub fn set_cached_user(&mut self, user: AuthSessionUser) {
self.state = AuthSessionState::Authenticated { user };
}
/// Sync newly exchanged or refreshed tokens produced by the native host coordinator.
pub fn apply_native_tokens(&mut self, pair: StoredAuthTokenPair) {
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.native_tokens = Some(pair);
}
/// Clear in-memory tokens and transition to `SignedOut` after host-owned revoke/sign-out.
pub fn clear_native_session(&mut self) {
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.native_tokens = None;
self.state = AuthSessionState::SignedOut;
}
/// Build the frozen [`ApiRequestContext`] for this host kind and current credential state.
pub fn api_context(&self) -> ApiRequestContext {
match self.host_kind {
HostKind::Web => ApiRequestContext::web(),
HostKind::Native => ApiRequestContext::native(
self.native_tokens.as_ref().map(|t| t.access_token.clone()),
),
pub fn apply_profile(&mut self, epoch: u64, user: Option<AccountProfile>) -> bool {
if epoch != self.mutation_epoch {
return false;
}
}
/// Build the Socket.IO `40` CONNECT [`SocketAuthMode`] for `SpaceSyncEngine`.
///
/// Native hosts without stored tokens return [`SocketAuthMode::Unauthenticated`] and never
/// fall back to [`SocketAuthMode::WebCookie`].
#[cfg(feature = "cloud-sync")]
pub fn socket_auth_mode(&self) -> SocketAuthMode {
match self.host_kind {
HostKind::Web => SocketAuthMode::WebCookie,
HostKind::Native => match &self.native_tokens {
Some(tokens) => SocketAuthMode::NativeJwt {
token: tokens.access_token.clone(),
},
None => SocketAuthMode::Unauthenticated,
},
}
}
/// Build a transport-agnostic `GET /api/auth/session` request for the host to execute.
pub fn build_session_request(&self) -> ApiHttpRequest {
build_get_auth_session_request(&self.api_context())
}
/// Build a `GET /api/auth/session` request paired with the current `mutation_epoch` so
/// late responses arriving after sign-out or token rotation can be discarded safely.
pub fn build_fenced_session_request(&self) -> (u64, ApiHttpRequest) {
(self.mutation_epoch, self.build_session_request())
}
/// Apply a fenced `GET /api/auth/session` response only when `request_epoch` still matches
/// [`Self::mutation_epoch`]. Returns `Ok(None)` without mutating state on stale epochs.
pub fn apply_fenced_session_response(
&mut self,
request_epoch: u64,
status: u16,
body: &[u8],
) -> ClientResult<Option<AuthSessionState>> {
if request_epoch != self.mutation_epoch {
return Ok(None);
}
self.apply_session_response(status, body).map(Some)
}
/// Apply a `GET /api/auth/session` HTTP response to [`AuthSessionState`].
///
/// Transitions to `SignedOut` ONLY on `401`/`403` or `200 { user: null }`. Any other error
/// status (`>= 400`, including `429` and `5xx`) returns `Err` and preserves `self.state`.
pub fn apply_session_response(
&mut self,
status: u16,
body: &[u8],
) -> ClientResult<AuthSessionState> {
if status == 401 || status == 403 {
self.state = AuthSessionState::SignedOut;
return Ok(self.state.clone());
}
if status >= 400 {
return Err(ClientError::Host(format!(
"fetch session failed with transient HTTP {status}"
)));
}
let decoded = decode_auth_session_response(body)?;
self.state = match decoded.user {
self.state = match user {
Some(user) => AuthSessionState::Authenticated { user },
None => AuthSessionState::SignedOut,
};
Ok(self.state.clone())
true
}
/// Load stored native credentials from [`HostBridge`] using the explicit [`NativeAuthPlatform`]
/// codec.
///
/// - Performs strictly read-only vault access (`&dyn HostBridge`): platform hosts remain the
/// sole owners of Keychain / DataStore writes and deletes.
/// - When the host vault returns `None` or unparseable JSON, clears in-memory `native_tokens`
/// and transitions to `SignedOut` without mutating host storage.
pub fn load_stored_credentials(
&mut self,
host: &dyn HostBridge,
platform: NativeAuthPlatform,
) -> ClientResult<bool> {
if self.host_kind != HostKind::Native {
return Ok(false);
#[cfg(feature = "cloud-sync")]
pub(crate) fn set_access_token(&mut self, token: Option<String>) {
self.signed_out = false;
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.access_token = token;
}
#[cfg(feature = "cloud-sync")]
pub(crate) fn clear_session(&mut self) {
self.signed_out = true;
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.access_token = None;
self.state = AuthSessionState::SignedOut;
}
#[cfg(feature = "cloud-sync")]
pub(crate) fn connection_auth(&self) -> ConnectionAuth<'_> {
if self.signed_out {
return ConnectionAuth::SignedOut;
}
let key = self.credential_key();
let Some(raw) = host.read_credential(&key)? else {
self.clear_native_session();
return Ok(false);
};
let parsed = match platform {
NativeAuthPlatform::Ios => StoredAuthTokenPair::from_ios_keychain_json(&raw),
NativeAuthPlatform::Android => StoredAuthTokenPair::from_android_datastore_json(&raw),
};
match parsed {
Ok(pair) => {
self.apply_native_tokens(pair);
Ok(true)
}
Err(_) => {
self.clear_native_session();
Ok(false)
}
match self.host_kind {
HostKind::Web => ConnectionAuth::Browser,
HostKind::Native => ConnectionAuth::Native(self.access_token.as_deref()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::host::MemoryHostBridge;
#[test]
fn ios_integer_and_fractional_cf_epoch_seconds_decode_explicitly_without_android_ambiguity() {
let mut host = MemoryHostBridge::new(HostKind::Native, "inst-ios");
let mut auth =
AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native);
// Integer CF epoch seconds (Swift JSONEncoder emits `800000000` without `.0`).
let ios_int = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-int","accessExpiresAt":800000000,"refreshToken":"rt-int","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-int","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), ios_int);
assert!(
auth.load_stored_credentials(&mut host, NativeAuthPlatform::Ios)
.unwrap()
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_778_307_200_000
);
// Fractional CF epoch seconds `800000000.5` -> `1778307200500` ms.
let ios_frac = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-frac","accessExpiresAt":800000000.5,"refreshToken":"rt-frac","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-frac","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), ios_frac);
assert!(
auth.load_stored_credentials(&mut host, NativeAuthPlatform::Ios)
.unwrap()
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_778_307_200_500
);
// Android DataStore fixture (`1970` Unix ms) roundtrips cleanly with Android selector.
let android_json = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-and","accessExpiresAt":1795622400000,"refreshToken":"rt-and","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-and","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), android_json);
assert!(
auth.load_stored_credentials(&mut host, NativeAuthPlatform::Android)
.unwrap()
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_795_622_400_000
);
}
#[test]
fn deleted_host_credential_clears_stale_jwt_and_from_wire_validates_fields() {
let mut host = MemoryHostBridge::new(HostKind::Native, "inst-1");
let mut auth =
AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native);
let valid_wire = AuthTokenPairResponse {
token_type: Some("Bearer".into()),
access_token: "at-1".into(),
refresh_token: "rt-1".into(),
expires_in: Some(3600),
refresh_expires_at: Some("2026-12-01T00:00:00Z".into()),
session: Some(AuthSessionMeta {
id: "sess-1".into(),
absolute_expires_at: Some("2027-01-01T00:00:00Z".into()),
}),
session_id: None,
};
let pair = StoredAuthTokenPair::from_wire(valid_wire.clone(), 1_700_000_000_000).unwrap();
auth.apply_native_tokens(pair);
#[cfg(feature = "cloud-sync")]
assert_eq!(
auth.socket_auth_mode(),
SocketAuthMode::NativeJwt {
token: "at-1".into()
}
);
// Host vault has no credential (deleted by host coordinator) -> clears in-memory JWT.
assert!(
!auth
.load_stored_credentials(&mut host, NativeAuthPlatform::Android)
.unwrap()
);
#[cfg(feature = "cloud-sync")]
assert_eq!(auth.socket_auth_mode(), SocketAuthMode::Unauthenticated);
assert_eq!(auth.state(), &AuthSessionState::SignedOut);
// `from_wire` rejects non-Bearer, zero expiresIn, and malformed RFC3339 timestamps.
let mut bad_type = valid_wire.clone();
bad_type.token_type = Some("Basic".into());
assert!(StoredAuthTokenPair::from_wire(bad_type, 1_000).is_err());
let mut zero_exp = valid_wire.clone();
zero_exp.expires_in = Some(0);
assert!(StoredAuthTokenPair::from_wire(zero_exp, 1_000).is_err());
let mut bad_refresh_ts = valid_wire.clone();
bad_refresh_ts.refresh_expires_at = Some("not-a-date".into());
assert!(StoredAuthTokenPair::from_wire(bad_refresh_ts, 1_000).is_err());
let mut bad_abs_ts = valid_wire.clone();
bad_abs_ts.session.as_mut().unwrap().absolute_expires_at = Some("2027-99-99".into());
assert!(StoredAuthTokenPair::from_wire(bad_abs_ts, 1_000).is_err());
// Non-ASCII UTF-8 boundary and impossible calendar dates never panic and return Err.
let mut non_ascii_ts = valid_wire.clone();
non_ascii_ts.refresh_expires_at = Some("2026-12-01T00:00:0é0Z".into());
assert!(StoredAuthTokenPair::from_wire(non_ascii_ts, 1_000).is_err());
let mut feb_31_ts = valid_wire.clone();
feb_31_ts.refresh_expires_at = Some("2026-02-31T00:00:00Z".into());
assert!(StoredAuthTokenPair::from_wire(feb_31_ts, 1_000).is_err());
// Excess `expiresIn` (> 86_400) and empty tokens are rejected.
let mut huge_exp = valid_wire.clone();
huge_exp.expires_in = Some(86_401);
assert!(StoredAuthTokenPair::from_wire(huge_exp, 1_000).is_err());
let mut empty_tok = valid_wire;
empty_tok.access_token = String::new();
assert!(StoredAuthTokenPair::from_wire(empty_tok, 1_000).is_err());
// Corrupt JSON in host vault leaves vault untouched while clearing in-memory state.
host.seed_credential(auth.credential_key(), "{corrupt");
assert!(
!auth
.load_stored_credentials(&host, NativeAuthPlatform::Android)
.unwrap()
);
assert_eq!(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
Some("{corrupt")
);
// Epoch-fenced session responses ignore stale in-flight completions after sign-out/rotation.
let (stale_epoch, _req) = auth.build_fenced_session_request();
auth.clear_native_session();
assert_eq!(
auth.apply_fenced_session_response(
stale_epoch,
200,
br#"{"user":{"id":"u-stale","name":"Stale"}}"#,
)
.unwrap(),
None
);
assert_eq!(auth.state(), &AuthSessionState::SignedOut);
// Sans-I/O session response: 503/429 preserves cached user; 401/403 signs out.
auth.set_cached_user(AuthSessionUser {
id: "u1".into(),
email: None,
name: Some("Alice".into()),
avatar_url: None,
});
let req = auth.build_session_request();
assert_eq!(req.path, "/api/auth/session");
assert!(auth.apply_session_response(503, b"unavailable").is_err());
assert!(matches!(
auth.state(),
AuthSessionState::Authenticated { .. }
));
assert_eq!(
auth.apply_session_response(401, b"{}").unwrap(),
AuthSessionState::SignedOut
);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
//! in memory, tracks upload queue metadata, and atomically inserts `affine:image` or
//! `affine:attachment` blocks into a [`PageDocSession`] in a single undoable transaction.
use affine_store::blob_api::{compute_blob_key, detect_image_dimensions};
use affine_store::blob::{compute_blob_key, detect_image_dimensions};
use blocksuite_playground_doc::{DocError, schema::BlockSpec, session::PageDocSession};
use serde::{Deserialize, Serialize};
+106 -77
View File
@@ -5,10 +5,7 @@ use std::collections::BTreeMap;
#[cfg(feature = "cloud-sync")]
use affine_store::{
sync::{
DocLifecycleAction, PushDocIntent, SPACE_DELETE_DOC, SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH,
SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS, SpaceSyncEvent, SpaceSyncState,
},
PeerOperation, PeerSyncEvent, PeerSyncState, PushIntent,
workspace_db::{PendingDocUpdate, TableDocId, UserdataTableName, WORKSPACE_DB_TABLE_NAMES},
};
#[cfg(feature = "cloud-sync")]
@@ -37,7 +34,7 @@ enum ManagedDocKind {
#[cfg(feature = "cloud-sync")]
impl WorkspaceSession {
/// Ensure an already-hydrated local document has initiated its incremental `space:load-doc`
/// Ensure an already-hydrated local document has initiated its incremental document load
/// handshake when connected (`Ready`). Marks `load_in_flight` only after dispatch succeeds.
pub(crate) fn ensure_loaded_doc_synced(&mut self, doc_id: &str, now_ms: i64) {
if !self.is_sync_ready()
@@ -60,15 +57,16 @@ impl WorkspaceSession {
doc_id: &str,
now_ms: i64,
) -> ClientResult<T> {
let Some(sync) = &mut self.sync else {
let Some(address) = self.doc_address(doc_id) else {
return Err(ClientError::DocNotFound(doc_id.to_string()));
};
let Ok(can_dispatch) = self.doc_sync.begin_remote_load(doc_id) else {
return Err(ClientError::DocNotFound(doc_id.to_string()));
};
if can_dispatch
&& sync.state() == SpaceSyncState::Ready
&& sync.load_doc(doc_id, None, now_ms).is_ok()
&& let Some(peer) = &mut self.sync
&& peer.state() == PeerSyncState::Ready
&& peer.load(address, now_ms).is_ok()
{
self.doc_sync.mark_load_in_flight(doc_id);
}
@@ -77,10 +75,10 @@ impl WorkspaceSession {
pub(crate) fn poll_invalidation_repair(&mut self, now_ms: i64) {
if let Some(sync) = &mut self.sync
&& sync.state() == SpaceSyncState::Ready
&& sync.state() == PeerSyncState::Ready
&& self.doc_sync.take_due_invalidation_repair(now_ms)
{
if sync.load_doc_timestamps(None, now_ms).is_ok() {
if sync.request_inventory(now_ms).is_ok() {
self.doc_sync.on_invalidation_repair_started();
} else {
self.doc_sync.on_doc_invalidated(now_ms);
@@ -88,7 +86,7 @@ impl WorkspaceSession {
}
}
pub(crate) fn process_sync_events(&mut self, now_ms: i64) -> ClientResult<Vec<SpaceSyncEvent>> {
pub(crate) fn process_sync_events(&mut self, now_ms: i64) -> ClientResult<Vec<PeerSyncEvent>> {
let Some(sync) = &mut self.sync else {
return Ok(Vec::new());
};
@@ -96,81 +94,107 @@ impl WorkspaceSession {
let mut first_err: Option<ClientError> = None;
for ev in &events {
let res: ClientResult<()> = match ev {
SpaceSyncEvent::Joined { .. } => {
PeerSyncEvent::Ready => {
self.handle_joined(now_ms);
Ok(())
}
SpaceSyncEvent::DocLoaded {
doc_id,
missing,
state,
timestamp,
} => self.handle_doc_loaded(doc_id, missing, state, *timestamp, now_ms),
SpaceSyncEvent::DocNotFound { doc_id } => self.handle_doc_not_found(doc_id, now_ms),
SpaceSyncEvent::DocUpdatePushed {
doc_id, timestamp, ..
PeerSyncEvent::Loaded {
address,
diff,
timestamp_ms,
} => {
self.doc_sync.on_doc_update_pushed(doc_id, *timestamp);
Ok(())
let Some(id) = self.local_peer_id(address) else {
continue;
};
self.handle_doc_loaded(
&id,
&diff.update_v1,
&diff.state_vector_v1,
*timestamp_ms,
now_ms,
)
}
SpaceSyncEvent::DocTimestampsLoaded { timestamps } => {
self.handle_doc_timestamps_loaded(timestamps, now_ms);
Ok(())
PeerSyncEvent::Missing { address } => {
let Some(id) = self.local_peer_id(address) else {
continue;
};
self.handle_doc_not_found(&id, now_ms)
}
SpaceSyncEvent::DocDeleted { doc_id } => {
self.doc_sync.mark_delete_acked(doc_id);
Ok(())
}
SpaceSyncEvent::DocLifecycleApplied {
doc_id,
lifecycle,
deleted_doc_ids,
..
PeerSyncEvent::Committed {
receipt,
timestamp_ms,
} => {
if *lifecycle == DocLifecycleAction::Delete {
self.doc_sync.mark_delete_acked(doc_id);
if let Some(ids) = deleted_doc_ids {
for id in ids {
self.doc_sync.mark_delete_acked(id);
}
let Some(id) = self.local_peer_id(&receipt.address) else {
continue;
};
self.doc_sync
.on_doc_update_pushed(&id, receipt.seq.0, *timestamp_ms);
Ok(())
}
PeerSyncEvent::Inventory { timestamps } => {
let timestamps = timestamps
.iter()
.filter_map(|(address, time)| {
self.local_peer_id(address).map(|id| (id, *time))
})
.collect();
self.handle_doc_timestamps_loaded(&timestamps, now_ms);
Ok(())
}
PeerSyncEvent::Deleted { addresses } => {
for address in addresses {
if let Some(id) = self.local_peer_id(address) {
self.doc_sync.mark_delete_acked(&id);
}
}
Ok(())
}
SpaceSyncEvent::RemoteDocUpdates {
doc_id,
updates,
timestamp,
..
} => self.handle_remote_doc_updates(doc_id, updates, *timestamp, now_ms),
SpaceSyncEvent::DocInvalidated {
inventory_changed, ..
PeerSyncEvent::Updated {
address,
updates_v1,
timestamp_ms,
} => {
let Some(id) = self.local_peer_id(address) else {
continue;
};
self.handle_remote_doc_updates(&id, updates_v1, *timestamp_ms, now_ms)
}
PeerSyncEvent::Invalidated { inventory_changed } => {
if !*inventory_changed {
self.doc_sync.on_doc_invalidated(now_ms);
}
Ok(())
}
SpaceSyncEvent::RequestFailed { op, doc_id, .. } => {
self.handle_request_failed(op, doc_id.as_deref(), now_ms);
PeerSyncEvent::RequestFailed {
operation, address, ..
} => {
let id = address
.as_ref()
.and_then(|address| self.local_peer_id(address));
self.handle_request_failed(*operation, id.as_deref(), now_ms);
Ok(())
}
SpaceSyncEvent::PermissionRevoked { doc_id, .. } => {
PeerSyncEvent::PermissionRevoked { address } => {
if self.is_sync_ready() {
if let Some(id) = doc_id {
self.doc_sync.on_doc_permission_revoked(id);
self.unopened_unpushed_docs.remove(id);
if let Some(id) = address
.as_ref()
.and_then(|address| self.local_peer_id(address))
{
self.doc_sync.on_doc_permission_revoked(&id);
self.unopened_unpushed_docs.remove(&id);
}
} else {
self.doc_sync.on_disconnected();
}
Ok(())
}
SpaceSyncEvent::Disconnected { .. } | SpaceSyncEvent::AuthRequired { .. } => {
PeerSyncEvent::Disconnected | PeerSyncEvent::AuthRequired { .. } => {
self.doc_sync.on_disconnected();
Ok(())
}
SpaceSyncEvent::DocsJoined { .. } => Ok(()),
PeerSyncEvent::Subscribed { .. }
| PeerSyncEvent::AwarenessRequested { .. }
| PeerSyncEvent::Awareness { .. } => Ok(()),
};
if let Err(err) = res
&& first_err.is_none()
@@ -185,11 +209,12 @@ impl WorkspaceSession {
}
fn handle_joined(&mut self, now_ms: i64) {
if let Some(sync) = &mut self.sync {
for doc_id in self.doc_sync.pending_delete_doc_ids_to_dispatch() {
if sync.delete_doc(&doc_id, now_ms).is_ok() {
self.doc_sync.mark_delete_in_flight(&doc_id);
}
for doc_id in self.doc_sync.pending_delete_doc_ids_to_dispatch() {
if let Some(address) = self.doc_address(&doc_id)
&& let Some(peer) = &mut self.sync
&& peer.delete(address, now_ms).is_ok()
{
self.doc_sync.mark_delete_in_flight(&doc_id);
}
}
let root_id = self.space_id.clone();
@@ -208,11 +233,12 @@ impl WorkspaceSession {
self.dispatch_incremental_load(&table_doc_id, now_ms);
}
}
if let Some(sync) = &mut self.sync {
for doc_id in self.doc_sync.loading_doc_ids_to_dispatch() {
if sync.load_doc(&doc_id, None, now_ms).is_ok() {
self.doc_sync.mark_load_in_flight(&doc_id);
}
for doc_id in self.doc_sync.loading_doc_ids_to_dispatch() {
if let Some(address) = self.doc_address(&doc_id)
&& let Some(peer) = &mut self.sync
&& peer.load(address, now_ms).is_ok()
{
self.doc_sync.mark_load_in_flight(&doc_id);
}
}
let open_ids: Vec<String> = self.open_docs.keys().cloned().collect();
@@ -230,10 +256,13 @@ impl WorkspaceSession {
fn dispatch_incremental_load(&mut self, doc_id: &str, now_ms: i64) {
let state_vector = self.local_state_vector_for_doc(doc_id);
if let Some(sync) = &mut self.sync
&& sync
.load_doc(doc_id, state_vector.as_deref(), now_ms)
.is_ok()
if let Some(address) = self.doc_address(doc_id)
&& let Some(peer) = &mut self.sync
&& match state_vector {
Some(vector) => peer.diff(address, vector, now_ms),
None => peer.load(address, now_ms),
}
.is_ok()
{
self.doc_sync.mark_load_in_flight(doc_id);
}
@@ -359,7 +388,7 @@ impl WorkspaceSession {
}
match self.local_diff_for_doc(doc_id, remote_sv)? {
Some(diff) if is_non_empty_update(&diff) => {
self.push_reconcile_doc_update(doc_id, diff, PushDocIntent::Update, now_ms)?;
self.push_reconcile_doc_update(doc_id, diff, PushIntent::Update, now_ms)?;
}
Some(_) => {
self.doc_sync.mark_push_clean_after_load(doc_id);
@@ -519,7 +548,7 @@ impl WorkspaceSession {
&& let Some(full) = self.local_full_state_for_doc(doc_id)?
&& is_non_empty_update(&full)
{
self.push_reconcile_doc_update(doc_id, full, PushDocIntent::Create, now_ms)?;
self.push_reconcile_doc_update(doc_id, full, PushIntent::Create, now_ms)?;
}
Ok(())
}
@@ -608,17 +637,17 @@ impl WorkspaceSession {
}
}
fn handle_request_failed(&mut self, op: &str, doc_id: Option<&str>, now_ms: i64) {
fn handle_request_failed(&mut self, op: PeerOperation, doc_id: Option<&str>, now_ms: i64) {
match op {
SPACE_LOAD_DOC | SPACE_JOIN_BATCH => {
PeerOperation::Load | PeerOperation::Subscribe => {
if let Some(id) = doc_id {
self.doc_sync.on_load_request_failed(id);
}
}
SPACE_LOAD_DOC_TIMESTAMPS => {
PeerOperation::InspectInventory => {
self.doc_sync.on_load_timestamps_failed(now_ms);
}
SPACE_DELETE_DOC | SPACE_DOC_LIFECYCLE => {
PeerOperation::Delete => {
if let Some(id) = doc_id {
self.doc_sync.mark_delete_failed(id);
}
@@ -42,7 +42,7 @@ impl DocSyncCoordinator {
self.invalidation.in_flight = true;
}
/// Process `SpaceSyncEvent::DocTimestampsLoaded`, returning document IDs whose server
/// Process the peer inventory, returning document IDs whose server
/// timestamp strictly exceeds the last known `remote_ts`, without creating entries for
/// unmanaged documents.
pub fn on_doc_timestamps_loaded(
+70 -27
View File
@@ -8,7 +8,7 @@ mod invalidation;
#[cfg(not(target_family = "wasm"))]
pub(crate) mod receipts;
use std::collections::{BTreeMap, VecDeque};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
pub(crate) use driver::is_non_empty_update;
@@ -20,7 +20,7 @@ pub(crate) fn parse_table_doc_id(
affine_store::workspace_db::TableDocId::parse(doc_id, user_id)
}
/// Coalescing window for `space:broadcast-doc-invalidation` matching Web `CloudDocStorage` (50 ms).
/// Coalescing window for remote invalidations matching Web `CloudDocStorage` (50 ms).
pub const INVALIDATION_COALESCE_WINDOW_MS: i64 = 50;
/// Maximum number of broadcast updates staged per document while `LoadingRemote` is in flight.
@@ -35,7 +35,7 @@ pub enum DocSyncPhase {
/// Local or known document that has not completed initial handshake in this connection.
#[default]
Idle,
/// Document is absent locally and waiting for a full baseline from `space:load-doc`.
/// Document is absent locally and waiting for a full baseline from document load.
/// Broadcast updates arriving before `DocLoaded` are staged here and never written to SQLite
/// until the complete baseline arrives.
LoadingRemote { staged_deltas: Vec<Vec<u8>> },
@@ -43,7 +43,7 @@ pub enum DocSyncPhase {
Synced,
/// Server returned `DOC_NOT_FOUND` and the document does not exist locally.
MissingOnServer,
/// Permanently deleted locally; `space:delete-doc` is replayed until server-acknowledged and
/// Permanently deleted locally; document deletion is replayed until server-acknowledged and
/// its durable SQLite tombstone is cleared in an atomic flush.
PendingRemoteDelete {
in_flight: bool,
@@ -56,7 +56,7 @@ pub enum DocSyncPhase {
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DocSyncEntry {
pub phase: DocSyncPhase,
/// True while a `space:load-doc` request (or its preceding `space:join-batch`) is in flight.
/// True while a document load request (or its preceding subscription) is in flight.
pub load_in_flight: bool,
/// Highest server timestamp observed for this document (`serverDocTimestamps` in Web).
pub remote_ts: Option<i64>,
@@ -66,8 +66,9 @@ pub struct DocSyncEntry {
pub needs_reconcile_push: bool,
/// True once the server has confirmed this document's baseline in this session.
pub remote_baseline_known: bool,
/// FIFO queue of the sequence numbers of push requests in flight in `SpaceSyncEngine`.
/// FIFO queue of the sequence numbers of push requests in flight in the peer.
pub in_flight_pushes: VecDeque<u64>,
out_of_order_acks: BTreeSet<u64>,
/// Sequence number of the newest push queued for this document.
pub last_push_seq: Option<u64>,
/// Every push of this document up to this sequence number is server-acknowledged.
@@ -95,6 +96,7 @@ impl DocSyncEntry {
if !self.in_flight_pushes.is_empty() {
self.abandoned_push_seq = self.last_push_seq;
self.in_flight_pushes.clear();
self.out_of_order_acks.clear();
}
}
}
@@ -196,15 +198,14 @@ impl DocSyncCoordinator {
.collect()
}
/// Count documents with persisted local changes (`needs_push`) that are not already queued
/// in `SpaceSyncEngine::offline_queue`.
pub fn unqueued_pending_push_count(&self) -> usize {
/// Count updates outside the peer queue and deletes without a server acknowledgement.
#[cfg(feature = "cloud-sync")]
pub(crate) fn pending_unqueued_operation_count(&self) -> usize {
self.entries
.values()
.filter(|e| {
e.needs_push
&& e.in_flight_pushes.is_empty()
&& !matches!(e.phase, DocSyncPhase::PendingRemoteDelete { .. })
.filter(|entry| match entry.phase {
DocSyncPhase::PendingRemoteDelete { acked, .. } => !acked,
_ => entry.needs_push && entry.in_flight_pushes.is_empty(),
})
.count()
}
@@ -268,6 +269,11 @@ impl DocSyncCoordinator {
}
}
#[cfg(feature = "cloud-sync")]
pub(crate) fn next_push_sequence(&self) -> u64 {
self.next_push_seq
}
fn queue_push(&mut self, doc_id: &str) -> u64 {
let seq = self.next_push_seq;
self.next_push_seq = seq.saturating_add(1);
@@ -290,7 +296,7 @@ impl DocSyncCoordinator {
/// Begin remote loading for an absent local document if not already loading or confirmed
/// missing. Returns `true` when the entry is in `LoadingRemote` and ready to dispatch a
/// `space:load-doc` (i.e. `!load_in_flight`).
/// document load (i.e. `!load_in_flight`).
pub fn begin_remote_load(&mut self, doc_id: &str) -> Result<bool, ()> {
let entry = self.entry_mut(doc_id);
if entry.phase == DocSyncPhase::MissingOnServer {
@@ -342,7 +348,7 @@ impl DocSyncCoordinator {
/// If `doc_id` is actively loading a remote baseline (`LoadingRemote` with `load_in_flight`),
/// stage `delta` within bounded limits or mark `stale_reload_needed` once the bound is
/// reached so a follow-up incremental `space:load-doc` reconciles any missed broadcast.
/// reached so a follow-up incremental document load reconciles any missed broadcast.
pub fn stage_remote_delta_if_loading(&mut self, doc_id: &str, delta: &[u8]) -> bool {
let Some(entry) = self.entries.get_mut(doc_id) else {
return false;
@@ -367,7 +373,7 @@ impl DocSyncCoordinator {
/// Mark `doc_id` dirty for reconciliation after a remote broadcast update failed to apply:
/// clears `server_has_state` and reverts `Synced` back to `Idle` so a follow-up incremental
/// `space:load-doc` reconciles the missing state.
/// document load reconciles the missing state.
pub fn on_remote_apply_failed(&mut self, doc_id: &str) {
let entry = self.entry_mut(doc_id);
entry.server_has_state = false;
@@ -376,7 +382,7 @@ impl DocSyncCoordinator {
}
}
/// Transition `doc_id` on `SpaceSyncEvent::DocLoaded`, returning any staged broadcast deltas
/// Transition `doc_id` on a peer load response, returning any staged broadcast deltas
/// accumulated while `LoadingRemote`.
pub fn on_doc_loaded(&mut self, doc_id: &str, timestamp: i64) -> Vec<Vec<u8>> {
let entry = self.entry_mut(doc_id);
@@ -409,7 +415,7 @@ impl DocSyncCoordinator {
}
}
/// Handle `SpaceSyncEvent::DocNotFound`. When `exists_locally` is true and the document has
/// Handle a missing document response. When `exists_locally` is true and the document has
/// unpushed local changes, return `true` so the caller uploads the full local state with
/// `PushDocIntent::Create`. When the document has no unpushed local changes (deleted on
/// another device), mark it `MissingOnServer` without re-uploading.
@@ -441,20 +447,27 @@ impl DocSyncCoordinator {
should_create
}
/// Handle `SpaceSyncEvent::DocUpdatePushed`. Pops one in-flight push. When no push is left in
/// flight, cold-start reconciliation is complete (including the `reconcile_barrier_seq`
/// barrier), and the document is not pending deletion, the server holds the in-memory state.
pub fn on_doc_update_pushed(&mut self, doc_id: &str, timestamp: i64) {
let entry = self.entry_mut(doc_id);
/// Apply the receipt of a specific push. Leave a gap pending until its receipt arrives.
pub fn on_doc_update_pushed(&mut self, doc_id: &str, seq: u64, timestamp: i64) {
let Some(entry) = self.entries.get_mut(doc_id) else {
return;
};
if !entry.in_flight_pushes.contains(&seq) {
return;
}
entry.remote_ts = Some(
entry
.remote_ts
.map_or(timestamp, |prev| prev.max(timestamp)),
);
entry.remote_baseline_known = true;
let popped = entry.in_flight_pushes.pop_front();
if popped.is_some() && entry.in_flight_pushes.is_empty() {
entry.acked_push_seq = entry.last_push_seq;
entry.out_of_order_acks.insert(seq);
while let Some(&first) = entry.in_flight_pushes.front() {
if !entry.out_of_order_acks.remove(&first) {
break;
}
entry.in_flight_pushes.pop_front();
entry.acked_push_seq = Some(first);
}
if matches!(entry.phase, DocSyncPhase::PendingRemoteDelete { .. })
|| entry.needs_reconcile_push
@@ -462,7 +475,7 @@ impl DocSyncCoordinator {
return;
}
if let Some(barrier) = entry.reconcile_barrier_seq {
if popped.is_none_or(|seq| seq < barrier) {
if entry.acked_push_seq.is_none_or(|acked| acked < barrier) {
return;
}
entry.reconcile_barrier_seq = None;
@@ -705,3 +718,33 @@ impl DocSyncCoordinator {
}
}
}
#[cfg(test)]
mod receipt_tests {
use super::*;
#[test]
fn exact_receipt_never_proves_another_document_or_crosses_a_gap() {
let mut coordinator = DocSyncCoordinator::new();
let first = coordinator.mark_local_write("a");
let independent = coordinator.mark_local_write("b");
let last = coordinator.mark_local_write("a");
for (doc, seq) in [
("unknown", first),
("a", independent),
("a", last),
("a", last),
] {
coordinator.on_doc_update_pushed(doc, seq, 100);
}
for seq in [first, last] {
assert!(!coordinator.is_push_acked("a", seq));
}
assert!(!coordinator.is_push_acked("b", independent));
coordinator.on_doc_update_pushed("a", first, 110);
assert!(coordinator.is_push_acked("a", first));
assert!(coordinator.is_push_acked("a", last));
assert!(!coordinator.is_push_acked("b", independent));
}
}
@@ -7,7 +7,7 @@
use std::collections::{BTreeMap, BTreeSet};
use affine_store::blob_api::compute_sha256_hex;
use affine_store::blob::compute_sha256_hex;
use serde::{Deserialize, Serialize};
use thiserror::Error;
+17
View File
@@ -33,6 +33,8 @@ pub trait HostBridge {
fn ws_send(&mut self, handle: WsHandle, text: &str) -> ClientResult<()>;
fn ws_send_binary(&mut self, handle: WsHandle, bytes: &[u8]) -> ClientResult<()>;
fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()>;
fn read_credential(&self, key: &str) -> ClientResult<Option<String>>;
@@ -58,6 +60,7 @@ pub struct MemoryHostBridge {
announcements: Vec<String>,
next_ws: u64,
ws_messages: BTreeMap<WsHandle, Vec<String>>,
ws_binary: BTreeMap<WsHandle, Vec<Vec<u8>>>,
}
impl MemoryHostBridge {
@@ -70,6 +73,7 @@ impl MemoryHostBridge {
announcements: Vec::new(),
next_ws: 1,
ws_messages: BTreeMap::new(),
ws_binary: BTreeMap::new(),
}
}
@@ -82,6 +86,10 @@ impl MemoryHostBridge {
&self.announcements
}
pub fn ws_binary_sent(&self, handle: WsHandle) -> Option<&[Vec<u8>]> {
self.ws_binary.get(&handle).map(Vec::as_slice)
}
pub fn ws_sent(&self, handle: WsHandle) -> Option<&[String]> {
self.ws_messages.get(&handle).map(Vec::as_slice)
}
@@ -107,7 +115,16 @@ impl HostBridge for MemoryHostBridge {
Ok(())
}
fn ws_send_binary(&mut self, handle: WsHandle, bytes: &[u8]) -> ClientResult<()> {
self.ws_binary
.entry(handle)
.or_default()
.push(bytes.to_vec());
Ok(())
}
fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()> {
self.ws_binary.remove(&handle);
self.ws_messages.remove(&handle);
Ok(())
}
+20 -3
View File
@@ -4,6 +4,12 @@
#![forbid(unsafe_code)]
#[cfg(test)]
extern crate self as affine_client;
#[cfg(test)]
#[path = "../tests/support/document_peer.rs"]
mod test_peer;
pub mod accessibility;
pub mod auth;
pub mod blob_ingest;
@@ -17,6 +23,7 @@ pub mod i18n;
pub mod links;
pub mod nav;
pub mod organize;
pub mod remote;
pub mod search;
pub mod server;
pub mod session;
@@ -37,9 +44,7 @@ pub use accessibility::{
AccessibilityBounds, AccessibilityNode, AccessibilityRole, AccessibilityState,
AccessibilityTree, FirstFrameAccessibilityRoot, PlatformAccessibility,
};
pub use auth::{
AuthController, AuthSessionState, NativeAuthPlatform, NativeTokenPair, StoredAuthTokenPair,
};
pub use auth::{AuthController, AuthSessionState};
pub use blob_ingest::{
BlobUploadState, IngestedBlobRecord, InsertedMediaBlock, PickedMediaInput, PickedMediaKind,
ingest_media_into_doc_session, prepare_ingested_blob,
@@ -79,6 +84,12 @@ pub use sqlite_session::SqliteWorkspaceStore;
/// Unified error type for the L3 client domain crate.
#[derive(Debug, Error, Eq, PartialEq)]
pub enum ClientError {
#[error("cloud sync requires a document peer")]
MissingDocumentPeer,
#[error("sync endpoint does not match the workspace account origin")]
SyncOriginMismatch,
#[error("adding cross-origin self-hosted servers is forbidden on Web hosts")]
SelfHostedForbiddenOnWeb,
@@ -94,6 +105,9 @@ pub enum ClientError {
#[error("server `{0}` not found")]
ServerNotFound(String),
#[error("invalid remote server ID `{0}`")]
InvalidServerId(String),
#[error("invalid server URL `{0}`")]
InvalidServerUrl(String),
@@ -118,6 +132,9 @@ pub enum ClientError {
#[error("host bridge error: {0}")]
Host(String),
#[error(transparent)]
Remote(#[from] remote::RemoteError),
#[error("store error: {0}")]
Store(String),
@@ -0,0 +1,51 @@
use affine_store::{AccountScope, DocAddress};
use super::RemoteFuture;
/// A blob read is authorized by a document or one of its historical versions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthorizedBlobSource {
Current(DocAddress),
History {
address: DocAddress,
timestamp_ms: i64,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlobReceiptKind {
Uploaded,
Deleted,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BlobReceipt {
pub scope: AccountScope,
pub workspace_id: String,
pub key: String,
pub kind: BlobReceiptKind,
}
pub trait BlobPort {
fn upload<'a>(
&'a mut self,
scope: &'a AccountScope,
workspace_id: &'a str,
key: &'a str,
mime: &'a str,
bytes: Vec<u8>,
) -> RemoteFuture<'a, BlobReceipt>;
fn download<'a>(
&'a mut self,
source: &'a AuthorizedBlobSource,
key: &'a str,
) -> RemoteFuture<'a, Vec<u8>>;
fn delete<'a>(
&'a mut self,
scope: &'a AccountScope,
workspace_id: &'a str,
key: &'a str,
) -> RemoteFuture<'a, BlobReceipt>;
}
@@ -0,0 +1,51 @@
use affine_store::AccountScope;
use super::RemoteFuture;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RemoteWorkspace {
pub id: String,
pub name: String,
pub read_only: bool,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountProfile {
pub id: String,
pub email: Option<String>,
pub name: Option<String>,
pub avatar_url: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Quota {
pub storage_used_bytes: u64,
pub storage_limit_bytes: Option<u64>,
}
pub trait CatalogPort {
fn list_workspaces<'a>(
&'a mut self,
scope: &'a AccountScope,
) -> RemoteFuture<'a, Vec<RemoteWorkspace>>;
fn create_workspace<'a>(
&'a mut self,
scope: &'a AccountScope,
name: &'a str,
init_update_v1: Option<Vec<u8>>,
) -> RemoteFuture<'a, RemoteWorkspace>;
fn delete_workspace<'a>(
&'a mut self,
scope: &'a AccountScope,
workspace_id: &'a str,
) -> RemoteFuture<'a, ()>;
fn account_profile<'a>(
&'a mut self,
scope: &'a AccountScope,
) -> RemoteFuture<'a, AccountProfile>;
fn quota<'a>(&'a mut self, scope: &'a AccountScope) -> RemoteFuture<'a, Quota>;
}
@@ -0,0 +1,62 @@
use affine_store::{DocAddress, LocalSeq, PeerSyncEvent, PeerSyncState, PushIntent};
use crate::auth::ConnectionAuth;
use super::RemoteResult;
/// One CRDT update and the local commit that produced it.
pub struct PushUpdate {
pub address: DocAddress,
pub seq: LocalSeq,
pub update_v1: Vec<u8>,
pub intent: PushIntent,
}
/// The event loop passes time and I/O completion to a peer.
pub enum PeerInput<'a> {
Connect(ConnectionAuth<'a>),
Opened,
Text(&'a str),
Binary(&'a [u8]),
CredentialsChanged(ConnectionAuth<'a>),
TransportLost(&'a str),
Tick,
}
/// A transport action emitted by the peer for its host to execute.
pub enum PeerTransportAction {
Open { headers: Vec<(String, String)> },
SendText(String),
SendBinary(Vec<u8>),
Close,
}
/// Accept operations for a peer. Completion arrives through `drain_events`.
pub trait DocumentPeer: Send {
fn state(&self) -> PeerSyncState;
fn pending_pushes(&self) -> usize;
fn load(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()>;
fn diff(
&mut self,
address: DocAddress,
state_vector_v1: Vec<u8>,
now_ms: i64,
) -> RemoteResult<()>;
/// Report a durable receipt with the exact address and sequence.
fn push(&mut self, update: PushUpdate, now_ms: i64) -> RemoteResult<()>;
fn subscribe(&mut self, addresses: &[DocAddress], now_ms: i64) -> RemoteResult<()>;
fn unsubscribe(&mut self, addresses: &[DocAddress], now_ms: i64) -> RemoteResult<()>;
fn delete(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()>;
fn discard(&mut self, address: &DocAddress);
fn request_inventory(&mut self, now_ms: i64) -> RemoteResult<()>;
fn request_awareness(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()>;
fn publish_awareness(
&mut self,
address: DocAddress,
update_v1: Vec<u8>,
now_ms: i64,
) -> RemoteResult<()>;
fn drain_events(&mut self) -> Vec<PeerSyncEvent>;
fn on_input(&mut self, input: PeerInput<'_>, now_ms: i64) -> RemoteResult<()>;
fn next_transport_action(&mut self) -> Option<PeerTransportAction>;
}
@@ -0,0 +1,43 @@
//! Device-neutral ports for remote AFFiNE services.
mod blob;
mod catalog;
mod document;
mod session;
use std::{future::Future, pin::Pin};
use thiserror::Error;
pub use blob::{AuthorizedBlobSource, BlobPort, BlobReceipt, BlobReceiptKind};
pub use catalog::{AccountProfile, CatalogPort, Quota, RemoteWorkspace};
pub use document::{DocumentPeer, PeerInput, PeerTransportAction, PushUpdate};
pub use session::{
CaptchaProof, LoginExchange, LoginMethod, LoginPreflight, OAuthStart, RefreshAttempt,
RefreshCredential, SessionCredentials, SessionGrant, SessionInfo, SessionPort,
};
pub type RemoteResult<T> = Result<T, RemoteError>;
pub type RemoteFuture<'a, T> = Pin<Box<dyn Future<Output = RemoteResult<T>> + 'a>>;
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum RemoteError {
#[error("network temporarily unavailable")]
TransientNetwork,
#[error("remote service rate limit reached")]
RateLimited { retry_after_ms: Option<u64> },
#[error("session expired")]
SessionExpired,
#[error("permission revoked")]
PermissionRevoked,
#[error("remote resource is read-only")]
ReadOnly,
#[error("account quota exceeded")]
QuotaExceeded,
#[error("account deleted")]
AccountDeleted,
#[error("server version is unsupported")]
UnsupportedServerVersion,
#[error("invalid remote protocol response: {0}")]
Protocol(String),
}
@@ -0,0 +1,138 @@
use affine_store::{AccountScope, CanonicalOrigin};
use super::RemoteFuture;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LoginMethod {
Password,
VerificationCode,
MagicLink,
OAuth { provider: String },
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoginPreflight {
pub attempt_id: String,
pub methods: Vec<LoginMethod>,
}
pub enum CaptchaProof {
Turnstile { token: String },
Hashcash { token: String, challenge: String },
}
pub enum LoginExchange {
Password {
login: String,
password: String,
},
VerificationCode {
attempt_id: String,
code: String,
},
MagicLink {
login: String,
code: String,
client_nonce: Option<String>,
},
OpenAppCode {
code: String,
device_name: Option<String>,
installation_id: Option<String>,
},
OAuth {
provider: String,
code: String,
state: String,
},
}
pub struct RefreshAttempt {
pub refresh_attempt_id: String,
pub credential: RefreshCredential,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionInfo {
pub id: String,
pub device_name: Option<String>,
pub expires_at_ms: Option<i64>,
}
pub enum RefreshCredential {
Cookie,
RefreshToken(String),
}
pub enum SessionCredentials {
Cookie,
Tokens {
access_token: String,
refresh_token: String,
access_expires_at_ms: Option<i64>,
},
}
pub struct SessionGrant {
pub scope: AccountScope,
pub session: SessionInfo,
pub credentials: SessionCredentials,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OAuthStart {
pub authorization_url: String,
pub state: String,
}
pub trait SessionPort {
fn preflight<'a>(
&'a mut self,
origin: &'a CanonicalOrigin,
login: &'a str,
captcha: Option<CaptchaProof>,
) -> RemoteFuture<'a, LoginPreflight>;
fn send_verification_code<'a>(
&'a mut self,
origin: &'a CanonicalOrigin,
login: &'a str,
captcha: Option<CaptchaProof>,
) -> RemoteFuture<'a, String>;
fn send_magic_link<'a>(
&'a mut self,
origin: &'a CanonicalOrigin,
login: &'a str,
client_nonce: Option<&'a str>,
captcha: Option<CaptchaProof>,
) -> RemoteFuture<'a, ()>;
fn start_oauth<'a>(
&'a mut self,
origin: &'a CanonicalOrigin,
provider: &'a str,
redirect_uri: &'a str,
) -> RemoteFuture<'a, OAuthStart>;
fn exchange<'a>(
&'a mut self,
origin: &'a CanonicalOrigin,
exchange: LoginExchange,
) -> RemoteFuture<'a, SessionGrant>;
/// Retry a lost response with the same attempt ID and credential.
fn refresh<'a>(
&'a mut self,
scope: &'a AccountScope,
attempt: RefreshAttempt,
) -> RemoteFuture<'a, SessionGrant>;
fn sign_out<'a>(
&'a mut self,
scope: &'a AccountScope,
session_id: &'a str,
) -> RemoteFuture<'a, ()>;
fn sessions<'a>(&'a mut self, scope: &'a AccountScope) -> RemoteFuture<'a, Vec<SessionInfo>>;
}
+13
View File
@@ -11,6 +11,10 @@ use crate::{ClientError, ClientResult, host::HostKind};
/// Built-in official AFFiNE Cloud server identifier matching `BUILD_IN_SERVERS`.
pub const DEFAULT_CLOUD_SERVER_ID: &str = "affine-cloud";
pub(crate) fn is_local_server_id(id: &str) -> bool {
matches!(id, "" | "local")
}
/// Registered server entry managed by [`ServerRegistry`].
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -91,6 +95,9 @@ impl ServerRegistry {
return Err(ClientError::SelfHostedForbiddenOnWeb);
}
let id = id.into();
if is_local_server_id(&id) {
return Err(ClientError::InvalidServerId(id));
}
if self.servers.iter().any(|s| s.id == id) {
return Err(ClientError::DuplicateServerId(id));
}
@@ -174,6 +181,12 @@ mod tests {
let mut native = ServerRegistry::new(HostKind::Native, "https://app.affine.pro/");
assert!(native.can_add_self_hosted());
for reserved in ["", "local"] {
assert_eq!(
native.add_self_hosted_server(reserved, "https://notes.example.com", None),
Err(ClientError::InvalidServerId(reserved.into()))
);
}
let added = native
.add_self_hosted_server("self-1", "https://notes.example.com/", None)
.unwrap();
+51 -65
View File
@@ -1,22 +1,19 @@
//! L3 workspace session driver unifying `StoreBackedDocDirectory`, `AuthController`,
//! `SpaceSyncEngine`, cached `PageDocSession`s, and media/blob ingestion.
//! the peer, cached `PageDocSession`s, and media/blob ingestion.
//!
//! Compiles on both native targets and `wasm32-unknown-unknown` with zero system wall-clock calls.
use std::collections::{BTreeMap, BTreeSet, VecDeque};
#[cfg(feature = "cloud-sync")]
use affine_store::{AccountScope, CanonicalOrigin};
use affine_store::{
PushIntent,
directory::WorkspaceDirectory,
sync::PushDocIntent,
workspace_db::{
PendingDocUpdate, WorkspaceDb, derive_page_id_for_op, rotate_doc_session_client_if_required,
},
};
#[cfg(feature = "cloud-sync")]
use affine_store::{
id_converter::IdConverter,
sync::{SpaceSyncConfig, SpaceSyncEngine},
};
use blocksuite_editor::{
DirectoryError, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode, EditorDocSummary,
WorkspaceDocDirectory,
@@ -32,18 +29,16 @@ use serde::{Deserialize, Serialize};
use crate::doc_sync::parse_table_doc_id;
#[cfg(not(target_family = "wasm"))]
use crate::doc_sync::receipts::ClockReceipts;
#[cfg(feature = "cloud-sync")]
use crate::host::WsHandle;
use crate::{
ClientError, ClientResult,
auth::{AuthController, NativeAuthPlatform},
auth::AuthController,
blob_ingest::{
BlobUploadState, IngestedBlobRecord, InsertedMediaBlock, PickedMediaInput,
ingest_generated_media_into_doc_session,
},
doc_directory::StoreBackedDocDirectory,
doc_sync::DocSyncCoordinator,
host::{HostBridge, HostKind},
host::HostKind,
session_ops::RowStamp,
};
@@ -98,9 +93,9 @@ fn generate_media_replica_seed_hex() -> ClientResult<String> {
/// Most documents and bytes of passive remote broadcasts that a SQLite-backed session stages
/// before a flush finds their documents in SQLite.
#[cfg(any(feature = "cloud-sync", test))]
pub(crate) const MAX_UNVERIFIED_REMOTE_DOCS: usize = 64;
pub const MAX_UNVERIFIED_REMOTE_DOCS: usize = 64;
#[cfg(any(feature = "cloud-sync", test))]
pub(crate) const MAX_UNVERIFIED_REMOTE_BYTES: usize = 1024 * 1024;
pub const MAX_UNVERIFIED_REMOTE_BYTES: usize = 1024 * 1024;
/// Most documents whose staged remote bytes a SQLite-backed session dropped before a flush
/// looked them up in SQLite.
#[cfg(any(feature = "cloud-sync", test))]
@@ -121,7 +116,7 @@ pub(crate) struct UnhydratedDelta {
}
/// Complete L3 workspace session driving multi-doc switching, `@` directory queries,
/// auth credential hydration, `SpaceSync` WebSocket transport, and blob ingestion.
/// account state, document sync, and blob ingestion.
pub struct WorkspaceSession {
pub(crate) space_id: String,
/// The user of the `userdata$` tables of this session.
@@ -130,9 +125,11 @@ pub struct WorkspaceSession {
pub(crate) directory: StoreBackedDocDirectory,
pub(crate) auth: AuthController,
#[cfg(feature = "cloud-sync")]
pub(crate) sync: Option<SpaceSyncEngine>,
pub(crate) sync: Option<Box<dyn crate::remote::DocumentPeer>>,
#[cfg(feature = "cloud-sync")]
pub(crate) ws_handle: Option<WsHandle>,
pub(crate) sync_scope: Option<AccountScope>,
#[cfg(feature = "cloud-sync")]
pub(crate) ws_handle: Option<crate::WsHandle>,
pub(crate) open_docs: BTreeMap<String, PageDocSession>,
pub(crate) unopened_unpushed_docs: BTreeMap<String, PageDocSession>,
pub(crate) disk_baseline_doc_ids: BTreeSet<String>,
@@ -156,7 +153,7 @@ pub struct WorkspaceSession {
}
impl WorkspaceSession {
/// Initialize a new in-memory workspace session backed by `WorkspaceDb` + `SpaceSyncEngine`.
/// Initialize a new in-memory workspace session backed by `WorkspaceDb`.
pub fn new(
space_id: impl Into<String>,
user_id: impl Into<String>,
@@ -190,20 +187,7 @@ impl WorkspaceSession {
initial_now_ms: i64,
) -> ClientResult<Self> {
let auth = AuthController::new(server_id, base_url, host_kind);
#[cfg(feature = "cloud-sync")]
let sync = {
let mut sync_cfg = SpaceSyncConfig::workspace(db.space_id(), false);
sync_cfg.auth_mode = auth.socket_auth_mode();
SpaceSyncEngine::new(sync_cfg, IdConverter::new(db.space_id()))
};
Self::from_db(
db,
client_id,
auth,
#[cfg(feature = "cloud-sync")]
Some(sync),
initial_now_ms,
)
Self::from_db(db, client_id, auth, initial_now_ms)
}
/// Open a workspace whose updates are written only to a local store.
@@ -214,26 +198,26 @@ impl WorkspaceSession {
initial_now_ms: i64,
) -> ClientResult<Self> {
let auth = AuthController::new("local", "", host_kind);
Self::from_db(
db,
client_id,
auth,
#[cfg(feature = "cloud-sync")]
None,
initial_now_ms,
)
Self::from_db(db, client_id, auth, initial_now_ms)
}
fn from_db(
db: WorkspaceDb,
client_id: u64,
auth: AuthController,
#[cfg(feature = "cloud-sync")] sync: Option<SpaceSyncEngine>,
initial_now_ms: i64,
) -> ClientResult<Self> {
let space_id = db.space_id().to_string();
let user_id = db.user_id().to_string();
let directory = StoreBackedDocDirectory::new(WorkspaceDirectory::new(db), initial_now_ms);
#[cfg(feature = "cloud-sync")]
let sync_scope = (!crate::server::is_local_server_id(auth.server_id()))
.then(|| CanonicalOrigin::parse(auth.base_url()))
.transpose()?
.map(|origin| AccountScope {
origin,
user_id: user_id.clone(),
});
let media_replica_seed = generate_media_replica_seed_hex()?;
Ok(Self {
space_id,
@@ -242,7 +226,9 @@ impl WorkspaceSession {
directory,
auth,
#[cfg(feature = "cloud-sync")]
sync,
sync: None,
#[cfg(feature = "cloud-sync")]
sync_scope,
#[cfg(feature = "cloud-sync")]
ws_handle: None,
open_docs: BTreeMap::new(),
@@ -309,10 +295,6 @@ impl WorkspaceSession {
&self.auth
}
pub fn auth_mut(&mut self) -> &mut AuthController {
&mut self.auth
}
pub fn directory(&self) -> &StoreBackedDocDirectory {
&self.directory
}
@@ -321,28 +303,32 @@ impl WorkspaceSession {
&mut self.directory
}
/// Hydrate Keychain / Android DataStore credentials via `HostBridge` and update `SpaceSync`.
pub fn hydrate_auth(
/// Connect a workspace to the peer selected by its host.
#[cfg(feature = "cloud-sync")]
pub fn bind_document_peer(
&mut self,
host: &dyn HostBridge,
platform: NativeAuthPlatform,
) -> ClientResult<bool> {
let loaded = self.auth.load_stored_credentials(host, platform)?;
#[cfg(feature = "cloud-sync")]
if let Some(sync) = &mut self.sync {
sync.set_auth_mode(self.auth.socket_auth_mode());
peer: Box<dyn crate::remote::DocumentPeer>,
) -> ClientResult<()> {
if self.sync.is_some() {
return Err(ClientError::Host(
"workspace already has a document peer".into(),
));
}
Ok(loaded)
self.sync_scope = Some(AccountScope {
origin: CanonicalOrigin::parse(self.auth.base_url())?,
user_id: self.user_id.clone(),
});
self.sync = Some(peer);
Ok(())
}
/// Return the offline status of a local workspace.
#[cfg(not(feature = "cloud-sync"))]
pub fn sync_status(&self) -> WorkspaceSyncStatus {
WorkspaceSyncStatus::Offline
}
/// Create a new document in `StoreBackedDocDirectory`, seed its page skeleton, queue its
/// pending updates into `SpaceSyncEngine`, and return both the summary and pending updates
/// pending updates into the peer, and return both the summary and pending updates
/// ready for SQLite WAL persistence.
pub fn create_document(
&mut self,
@@ -427,9 +413,9 @@ impl WorkspaceSession {
});
for item in &pending {
let intent = if item.doc_id == doc_id {
PushDocIntent::Create
PushIntent::Create
} else {
PushDocIntent::Update
PushIntent::Update
};
self.push_local_doc_update(
item.doc_id.as_str(),
@@ -579,21 +565,21 @@ impl WorkspaceSession {
self.directory.query_linked_docs(req)
}
/// Push a local document incremental update into `SpaceSyncEngine` (offline-safe).
/// Push a local document incremental update into the peer (offline-safe).
pub fn queue_doc_update(
&mut self,
doc_id: &str,
update_v1: Vec<u8>,
now_ms: i64,
) -> ClientResult<()> {
let _ = self.push_local_doc_update(doc_id, update_v1, PushDocIntent::Update, now_ms)?;
let _ = self.push_local_doc_update(doc_id, update_v1, PushIntent::Update, now_ms)?;
Ok(())
}
/// Ingest a picked local image or file into the active document at `(parent_id, insert_index)`:
/// stores content-addressed blob bytes + metadata in the local blob map, queues upload,
/// atomically inserts `affine:image` or `affine:attachment` (single-step undoable), and
/// enqueues the CRDT update to `SpaceSyncEngine`.
/// enqueues the CRDT update to the peer.
pub fn ingest_picked_media(
&mut self,
doc_id: &str,
@@ -630,7 +616,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
doc_id,
inserted.update_v1.as_slice(),
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
if !inserted.update_v1.is_empty() && inserted.update_v1.as_slice() != [0, 0] {
@@ -646,7 +632,7 @@ impl WorkspaceSession {
}
/// Undo the last tracked edit on `doc_id` (e.g. single-step rollback of an inserted media block)
/// and enqueue the resulting CRDT update to `SpaceSyncEngine`.
/// and enqueue the resulting CRDT update to the peer.
pub fn undo_doc(&mut self, doc_id: &str, now_ms: i64) -> ClientResult<Option<Vec<u8>>> {
let page = self
.open_docs
@@ -664,7 +650,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
doc_id,
c.update.as_slice(),
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
if !c.update.is_empty() && c.update.as_slice() != [0, 0] {
+91 -483
View File
@@ -12,8 +12,8 @@ pub(crate) use persist::RowProof;
pub(crate) use persist::RowStamp;
#[cfg(feature = "cloud-sync")]
use affine_store::sync::{EngineIoOutput, SpaceSyncOutbound, SpaceSyncState};
use affine_store::{sync::PushDocIntent, workspace_db::PendingDocUpdate};
use affine_store::{LocalSeq, PeerSyncState};
use affine_store::{PushIntent, workspace_db::PendingDocUpdate};
use blocksuite_editor::EditorDocId;
use blocksuite_playground_doc::read::BlockContent;
@@ -26,95 +26,9 @@ use crate::{
};
#[cfg(feature = "cloud-sync")]
use crate::host::HostBridge;
use crate::remote::PushUpdate;
impl WorkspaceSession {
#[cfg(feature = "cloud-sync")]
pub(crate) fn flush_outbound_to_host(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
now_ms: i64,
) -> ClientResult<()> {
let Some(sync) = &mut self.sync else {
return Ok(());
};
while let Some(item) = sync.peek_outbound() {
match item {
SpaceSyncOutbound::Transport(EngineIoOutput::OpenWebsocket { .. }) => {
let ctx = self.auth.api_context();
let mut headers =
vec![("x-affine-version".to_string(), ctx.client_version.clone())];
if let Some(token) = ctx.bearer_token {
headers.push(("authorization".to_string(), format!("Bearer {token}")));
}
match host.ws_connect(ws_url, &headers) {
Ok(handle) => {
let _ = sync.pop_outbound();
self.ws_handle = Some(handle);
}
Err(err) => {
let _ = sync.pop_outbound();
self.handle_outbound_ws_error(host, &err.to_string(), now_ms);
return Err(err);
}
}
}
SpaceSyncOutbound::Transport(EngineIoOutput::SendWsText(text)) => {
if let Some(handle) = self.ws_handle
&& let Err(err) = host.ws_send(handle, text)
{
self.handle_outbound_ws_error(host, &err.to_string(), now_ms);
return Err(err);
}
let _ = sync.pop_outbound();
}
SpaceSyncOutbound::Transport(EngineIoOutput::CloseTransport) => {
let _ = sync.pop_outbound();
if let Some(handle) = self.ws_handle.take() {
host.ws_close(handle)?;
}
}
_ => {
let _ = sync.pop_outbound();
}
}
}
Ok(())
}
#[cfg(feature = "cloud-sync")]
fn handle_outbound_ws_error(&mut self, host: &mut dyn HostBridge, reason: &str, now_ms: i64) {
let Some(sync) = &mut self.sync else {
return;
};
sync.on_ws_error(reason, now_ms);
let _ = self.process_sync_events(now_ms);
let Some(sync) = &mut self.sync else {
return;
};
while let Some(post) = sync.peek_outbound() {
match post {
SpaceSyncOutbound::Transport(EngineIoOutput::CloseTransport) => {
let _ = sync.pop_outbound();
if let Some(handle) = self.ws_handle.take() {
let _ = host.ws_close(handle);
}
}
SpaceSyncOutbound::ScheduleTimerAtMs(_)
| SpaceSyncOutbound::Transport(
EngineIoOutput::SendWsText(_) | EngineIoOutput::SendWsBinary(_),
) => {
let _ = sync.pop_outbound();
}
_ => break,
}
}
if let Some(handle) = self.ws_handle.take() {
let _ = host.ws_close(handle);
}
}
/// Resend existing local state of `doc_id` for cold-start reconciliation. The push writes no
/// new SQLite row.
#[cfg(feature = "cloud-sync")]
@@ -122,11 +36,22 @@ impl WorkspaceSession {
&mut self,
doc_id: &str,
update: Vec<u8>,
intent: PushDocIntent,
intent: PushIntent,
now_ms: i64,
) -> ClientResult<()> {
if let Some(sync) = &mut self.sync {
sync.push_doc_update(doc_id.to_string(), update, intent, now_ms)?;
if let Some(address) = self.doc_address(doc_id)
&& let Some(peer) = &mut self.sync
{
let seq = self.doc_sync.next_push_sequence();
peer.push(
PushUpdate {
address,
seq: LocalSeq(seq),
update_v1: update,
intent,
},
now_ms,
)?;
self.doc_sync.record_reconcile_push_dispatched(doc_id);
}
Ok(())
@@ -134,7 +59,7 @@ impl WorkspaceSession {
/// Merge authoritative local Yjs V1 CRDT update bytes (for example produced by an embedded
/// `PlaygroundView`) into this session's `PageDocSession`, updating the directory snapshot,
/// `SpaceSyncEngine`, and `pending_persist_updates` whenever the encoded CRDT state
/// `peer`, and `pending_persist_updates` whenever the encoded CRDT state
/// (`StructStore` or `DeleteSet`) advances.
pub fn merge_local_doc_update(
&mut self,
@@ -157,8 +82,7 @@ impl WorkspaceSession {
let Some(page) = page_opt else {
// Document is not yet hydrated from SQLite; stage the delta without inserting an
// empty PageDocSession into `open_docs` so later hydration merges with the disk base.
let push =
self.push_local_doc_update(doc_id, update_v1, PushDocIntent::Update, now_ms)?;
let push = self.push_local_doc_update(doc_id, update_v1, PushIntent::Update, now_ms)?;
self.unhydrated_pending_deltas
.entry(doc_id.to_string())
.or_default()
@@ -226,7 +150,7 @@ impl WorkspaceSession {
let root_push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(root_push);
@@ -239,7 +163,7 @@ impl WorkspaceSession {
);
}
let push =
self.push_local_doc_update(doc_id, diff.as_slice(), PushDocIntent::Update, now_ms)?;
self.push_local_doc_update(doc_id, diff.as_slice(), PushIntent::Update, now_ms)?;
self.push_stamped_persist_update(
PendingDocUpdate {
doc_id: doc_id.to_string(),
@@ -252,7 +176,7 @@ impl WorkspaceSession {
/// Rename `doc_id` authoritatively in both `WorkspaceRootDoc` (`meta.pages`) and its open
/// `PageDocSession` (`affine:page` `prop:title`), queuing root and page CRDT updates for
/// `SpaceSyncEngine` and SQLite WAL persistence.
/// `peer` and SQLite WAL persistence.
pub fn rename_document(
&mut self,
doc_id: &str,
@@ -270,7 +194,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(push);
@@ -324,7 +248,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
doc_id,
diff.as_slice(),
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.push_stamped_persist_update(
@@ -353,7 +277,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(push);
@@ -374,7 +298,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(push);
@@ -403,8 +327,12 @@ impl WorkspaceSession {
#[cfg(not(target_family = "wasm"))]
self.clock_receipts.forget(doc_id);
#[cfg(feature = "cloud-sync")]
if let Some(sync) = &mut self.sync {
sync.discard_offline_writes_for_doc(doc_id);
let address = self.doc_address(doc_id);
#[cfg(feature = "cloud-sync")]
if let Some(address) = &address
&& let Some(peer) = &mut self.sync
{
peer.discard(address);
}
self.doc_sync.mark_permanently_deleted(doc_id);
if self.active_doc_id.as_deref() == Some(doc_id) {
@@ -416,9 +344,10 @@ impl WorkspaceSession {
self.pending_deleted_docs.push(doc_id.to_string());
}
#[cfg(feature = "cloud-sync")]
if let Some(sync) = &mut self.sync
&& sync.state() == SpaceSyncState::Ready
&& sync.delete_doc(doc_id, now_ms).is_ok()
if let Some(address) = address
&& let Some(peer) = &mut self.sync
&& peer.state() == PeerSyncState::Ready
&& peer.delete(address, now_ms).is_ok()
{
self.doc_sync.mark_delete_in_flight(doc_id);
}
@@ -426,7 +355,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(push);
@@ -506,16 +435,9 @@ impl WorkspaceSession {
}
}
#[cfg(test)]
#[cfg(all(test, feature = "cloud-sync"))]
mod tests {
#![cfg(feature = "cloud-sync")]
use std::collections::BTreeMap;
use affine_store::sync::{
SPACE_JOIN_BATCH, SPACE_LOAD_DOC, SPACE_PUSH_DOC_UPDATE, SpaceSyncEvent, SpaceSyncState,
};
use blocksuite_editor::EditorDocMode;
use affine_store::{DocDiff, PeerSyncEvent};
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
@@ -524,275 +446,13 @@ mod tests {
use super::*;
use crate::{
doc_sync::{DocSyncPhase, MAX_LOADING_STAGED_DELTAS},
host::{HostKind, MemoryHostBridge, WsHandle},
host::{HostKind, MemoryHostBridge},
test_peer::MemoryDocumentPeer,
};
const TEST_WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
fn encode_base64_std(input: &[u8]) -> String {
const TABLE: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = u32::from(chunk[0]);
let b1 = chunk.get(1).copied().map(u32::from).unwrap_or(0);
let b2 = chunk.get(2).copied().map(u32::from).unwrap_or(0);
let triple = (b0 << 16) | (b1 << 8) | b2;
out.push(TABLE[((triple >> 18) & 0x3F) as usize] as char);
out.push(TABLE[((triple >> 12) & 0x3F) as usize] as char);
out.push(if chunk.len() > 1 {
TABLE[((triple >> 6) & 0x3F) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
TABLE[(triple & 0x3F) as usize] as char
} else {
'='
});
}
out
}
struct FailingWsHost {
next_ws: u64,
fail_on_send_call: Option<usize>,
send_calls: usize,
sent_by_handle: BTreeMap<WsHandle, Vec<String>>,
closed_handles: Vec<WsHandle>,
}
impl FailingWsHost {
fn new() -> Self {
Self {
next_ws: 1,
fail_on_send_call: None,
send_calls: 0,
sent_by_handle: BTreeMap::new(),
closed_handles: Vec::new(),
}
}
}
impl HostBridge for FailingWsHost {
fn host_kind(&self) -> HostKind {
HostKind::Native
}
fn ws_connect(
&mut self,
_url: &str,
_headers: &[(String, String)],
) -> ClientResult<WsHandle> {
let h = WsHandle(self.next_ws);
self.next_ws += 1;
self.sent_by_handle.insert(h, Vec::new());
Ok(h)
}
fn ws_send(&mut self, handle: WsHandle, text: &str) -> ClientResult<()> {
self.send_calls += 1;
if self.fail_on_send_call == Some(self.send_calls) {
return Err(ClientError::Host("simulated ws_send failure".into()));
}
self.sent_by_handle
.entry(handle)
.or_default()
.push(text.to_string());
Ok(())
}
fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()> {
self.closed_handles.push(handle);
Ok(())
}
fn read_credential(&self, _key: &str) -> ClientResult<Option<String>> {
Ok(None)
}
fn installation_id(&self) -> String {
"inst-test".into()
}
fn kv_get(&self, _key: &str) -> Option<String> {
None
}
fn kv_set(&mut self, _key: &str, _value: &str) {}
fn kv_remove(&mut self, _key: &str) {}
fn announce_accessibility(&mut self, _message: &str) {}
}
fn extract_ack_id(frame: &str) -> Option<u64> {
frame.strip_prefix("42")?.split('[').next()?.parse().ok()
}
fn complete_handshake(
session: &mut WorkspaceSession,
host: &mut FailingWsHost,
handle: WsHandle,
t: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
session.on_ws_open(host, TEST_WS_URL, t + 10)?;
session.on_ws_text(
host,
TEST_WS_URL,
r#"0{"sid":"eio","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
t + 20,
)?;
session.on_ws_text(host, TEST_WS_URL, r#"40{"sid":"sio"}"#, t + 30)?;
let join_frame = host
.sent_by_handle
.get(&handle)
.and_then(|frames| frames.iter().rev().find(|f| f.contains(SPACE_JOIN_BATCH)))
.cloned()
.expect("join frame sent on handle");
let ack = extract_ack_id(&join_frame).expect("join ack id");
session.on_ws_text(
host,
TEST_WS_URL,
&format!(
r#"43{ack}[{{"data":{{"clientId":"c","success":true,"protocolVersion":1}}}}]"#
),
t + 40,
)
}
#[test]
fn outbound_ws_send_failure_first_and_mid_batch_reconnects_cleanly_without_stale_leak() {
// Test both failing on the 1st post-join outbound frame (fail_offset = 1) and failing on
// the 2nd post-join outbound frame (fail_offset = 2) inside a multi-frame batch.
for fail_offset in [1usize, 2usize] {
let mut host = FailingWsHost::new();
let mut session = WorkspaceSession::new(
"ws-out",
"u-1",
11,
HostKind::Native,
"affine-cloud",
"https://app.affine.pro",
1_000,
)
.unwrap();
let (doc, _) = session
.create_document("Sync Target", EditorDocMode::Page, None, 1_050)
.unwrap();
let doc_id = doc.id.as_str().to_string();
session.connect_sync(&mut host, TEST_WS_URL, 1_100).unwrap();
let h1 = WsHandle(1);
// Complete EIO/SIO handshake up to join ACK, then inject ws_send failure on the
// exact post-join frame offset where both offline pushes and load-doc frames flush.
session.on_ws_open(&mut host, TEST_WS_URL, 1_110).unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
r#"0{"sid":"e1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
1_120,
)
.unwrap();
session
.on_ws_text(&mut host, TEST_WS_URL, r#"40{"sid":"s1"}"#, 1_130)
.unwrap();
let join_ack = host.sent_by_handle[&h1]
.iter()
.rev()
.find(|f| f.contains(SPACE_JOIN_BATCH))
.and_then(|f| extract_ack_id(f))
.unwrap();
host.fail_on_send_call = Some(host.send_calls + fail_offset);
let err = session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{join_ack}[{{"data":{{"clientId":"c1","success":true,"protocolVersion":1}}}}]"#
),
1_140,
)
.unwrap_err();
assert!(err.to_string().contains("simulated ws_send failure"));
assert!(
matches!(
session.sync_engine().unwrap().state(),
SpaceSyncState::ReconnectScheduled { .. }
),
"ws_send failure at offset {fail_offset} must transition to ReconnectScheduled"
);
assert!(
host.closed_handles.contains(&h1),
"failed connection handle must be closed"
);
assert!(
session.sync_engine().unwrap().peek_outbound().is_none(),
"no stale outbound frames may remain after ws_send disconnect"
);
// Reconnect on connection #2 without further send errors.
host.fail_on_send_call = None;
let SpaceSyncState::ReconnectScheduled { next_attempt_at_ms } =
session.sync_engine().unwrap().state()
else {
panic!("expected ReconnectScheduled");
};
session
.on_tick(&mut host, TEST_WS_URL, next_attempt_at_ms)
.unwrap();
let h2 = WsHandle(2);
let h2_before_join = host.sent_by_handle[&h2].clone();
assert!(
!h2_before_join
.iter()
.any(|f| f.contains(SPACE_PUSH_DOC_UPDATE) || f.contains(SPACE_LOAD_DOC)),
"stale frames from connection #1 must never leak onto connection #2"
);
complete_handshake(&mut session, &mut host, h2, next_attempt_at_ms + 10).unwrap();
let h2_frames = host.sent_by_handle[&h2].clone();
assert!(
h2_frames
.iter()
.any(|f| f.contains(SPACE_PUSH_DOC_UPDATE) && f.contains(&doc_id)),
"reconnected session must replay push for {doc_id} (offset {fail_offset})"
);
assert!(
h2_frames
.iter()
.any(|f| f.contains(SPACE_LOAD_DOC) && f.contains("\"ws-out\"")),
"reconnected session must rebuild root load-doc (offset {fail_offset})"
);
let subdoc_join_ack = h2_frames
.iter()
.rev()
.find(|f| f.contains(SPACE_JOIN_BATCH) && f.contains(&doc_id))
.and_then(|f| extract_ack_id(f))
.expect("reconnected session must rebuild space:join-batch for subdoc");
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{subdoc_join_ack}[{{"data":{{"clientId":"c2","success":true,"protocolVersion":1}}}}]"#
),
next_attempt_at_ms + 60,
)
.unwrap();
assert!(
host.sent_by_handle[&h2]
.iter()
.any(|f| f.contains(SPACE_LOAD_DOC) && f.contains(&doc_id)),
"reconnected session must rebuild subdoc load-doc after join ACK for {doc_id} (offset {fail_offset})"
);
}
}
#[test]
fn passive_unknown_broadcasts_stay_zero_resident_and_active_load_doc_does_not_drop_deltas() {
const SYNC_URL: &str = "https://app.affine.pro";
let mut host = MemoryHostBridge::new(HostKind::Native, "inst-passive");
let mut session = WorkspaceSession::new(
"ws-passive",
@@ -800,43 +460,27 @@ mod tests {
21,
HostKind::Native,
"affine-cloud",
"https://app.affine.pro",
SYNC_URL,
1_000,
)
.unwrap();
session.connect_sync(&mut host, TEST_WS_URL, 1_010).unwrap();
session.on_ws_open(&mut host, TEST_WS_URL, 1_020).unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
r#"0{"sid":"e1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
1_030,
)
.unwrap();
session
.on_ws_text(&mut host, TEST_WS_URL, r#"40{"sid":"s1"}"#, 1_040)
.unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
r#"430[{"data":{"clientId":"c1","success":true,"protocolVersion":1}}]"#,
1_050,
)
.unwrap();
let peer = MemoryDocumentPeer::default();
session.bind_document_peer(Box::new(peer.clone())).unwrap();
session.on_ws_open(&mut host, SYNC_URL, 1_050).unwrap();
let entries_before = session.doc_sync().entry_count();
let payload_b64 = encode_base64_std(&vec![0xabu8; 4096]);
let payload = vec![0xab; 4096];
for i in 0..2_000usize {
let doc_id = format!("unknown-doc-{}", i % 200);
let frame = format!(
r#"42["space:broadcast-doc-updates",{{"spaceType":"workspace","spaceId":"ws-passive","docId":"{doc_id}","updates":["{payload_b64}"],"timestamp":{},"editor":"peer-2"}}]"#,
2_000 + i as i64
);
let address = session.doc_address(&doc_id).unwrap();
peer.set_event(PeerSyncEvent::Updated {
address,
updates_v1: vec![payload.clone()],
timestamp_ms: 2_000 + i as i64,
});
session
.on_ws_text(&mut host, TEST_WS_URL, &frame, 2_000 + i as i64)
.on_tick(&mut host, SYNC_URL, 2_000 + i as i64)
.unwrap();
}
assert_eq!(
@@ -859,16 +503,14 @@ mod tests {
// bounded and schedules a follow-up incremental load-doc after DocLoaded applies.
let active_doc = "remote-burst-doc";
assert_eq!(session.doc_sync.begin_remote_load(active_doc), Ok(true));
let address = session.doc_address(active_doc).unwrap();
session
.sync
.as_mut()
.unwrap()
.load_doc(active_doc, None, 5_000)
.load(address.clone(), 5_000)
.unwrap();
session.doc_sync.mark_load_in_flight(active_doc);
session
.flush_outbound_to_host(&mut host, TEST_WS_URL, 5_000)
.unwrap();
let mut server = PageDocSession::new(active_doc, 900).unwrap();
server
@@ -910,13 +552,13 @@ mod tests {
.unwrap();
let delta = server.encode_diff_v1(&last_sv).unwrap();
last_sv = server.encode_state_vector_v1().unwrap();
let bcast = format!(
r#"42["space:broadcast-doc-updates",{{"spaceType":"workspace","spaceId":"ws-passive","docId":"{active_doc}","updates":["{}"],"timestamp":{},"editor":"peer-2"}}]"#,
encode_base64_std(&delta),
5_100 + idx as i64
);
peer.set_event(PeerSyncEvent::Updated {
address: address.clone(),
updates_v1: vec![delta],
timestamp_ms: 5_100 + idx as i64,
});
session
.on_ws_text(&mut host, TEST_WS_URL, &bcast, 5_100 + idx as i64)
.on_tick(&mut host, SYNC_URL, 5_100 + idx as i64)
.unwrap();
}
let staged_len = match &session.doc_sync().entry(active_doc).unwrap().phase {
@@ -936,52 +578,27 @@ mod tests {
"overflowing staging cap must arm stale_reload_needed"
);
// Answer the initial join + load-doc with base_full (pre-burst snapshot).
let sent = host.ws_sent(WsHandle(1)).unwrap().to_vec();
let join_ack = sent
.iter()
.rev()
.find(|f| f.contains(SPACE_JOIN_BATCH) && f.contains(active_doc))
.and_then(|f| extract_ack_id(f))
.unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{join_ack}[{{"data":{{"clientId":"c1","success":true,"protocolVersion":1}}}}]"#
),
5_500,
)
.unwrap();
let sent = host.ws_sent(WsHandle(1)).unwrap().to_vec();
let load_ack = sent
.iter()
.rev()
.find(|f| f.contains(SPACE_LOAD_DOC) && f.contains(active_doc))
.and_then(|f| extract_ack_id(f))
.unwrap();
let loads_before = sent
.iter()
.filter(|f| f.contains(SPACE_LOAD_DOC) && f.contains(active_doc))
.count();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{load_ack}[{{"data":{{"missing":"{}","state":"{}","timestamp":5500}}}}]"#,
encode_base64_std(&base_full),
encode_base64_std(&base_sv)
),
5_510,
)
.unwrap();
let sent_after = host.ws_sent(WsHandle(1)).unwrap();
let loads_after = sent_after
.iter()
.filter(|f| f.contains(SPACE_LOAD_DOC) && f.contains(active_doc))
let loads_before = peer
.take_loads()
.into_iter()
.filter(|a| a == &address)
.count();
assert_eq!(loads_before, 1);
peer.set_event(PeerSyncEvent::Loaded {
address: address.clone(),
diff: DocDiff {
update_v1: base_full,
state_vector_v1: base_sv,
},
timestamp_ms: 5_500,
});
session.on_tick(&mut host, SYNC_URL, 5_500).unwrap();
let loads_after = loads_before
+ peer
.take_loads()
.into_iter()
.filter(|a| a == &address)
.count();
assert_eq!(
loads_after,
loads_before + 1,
@@ -990,30 +607,21 @@ mod tests {
assert!(session.doc_sync().is_load_in_flight(active_doc));
// Verify follow-up incremental load-doc delivers the tail deltas beyond MAX_LOADING_STAGED_DELTAS.
let followup_ack = sent_after
.iter()
.rev()
.find(|f| f.contains(SPACE_LOAD_DOC) && f.contains(active_doc))
.and_then(|f| extract_ack_id(f))
.unwrap();
let hydrated_sv = session
.open_document(active_doc)
.unwrap()
.encode_state_vector_v1()
.unwrap();
let tail_diff = server.encode_diff_v1(&hydrated_sv).unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{followup_ack}[{{"data":{{"missing":"{}","state":"{}","timestamp":5600}}}}]"#,
encode_base64_std(&tail_diff),
encode_base64_std(&last_sv)
),
5_600,
)
.unwrap();
peer.set_event(PeerSyncEvent::Loaded {
address,
diff: DocDiff {
update_v1: tail_diff,
state_vector_v1: last_sv,
},
timestamp_ms: 5_600,
});
session.on_tick(&mut host, SYNC_URL, 5_600).unwrap();
let final_snap = session.doc_snapshot(active_doc).unwrap();
let last_block_id = format!("p-{}", MAX_LOADING_STAGED_DELTAS + 4);
assert!(
@@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde_json::{Value, json};
use affine_store::{
sync::PushDocIntent,
PushIntent,
workspace_db::{
FavoriteKind, FavoritePosition, FavoriteRecord, FavoriteRef, FolderRow, UserdataTableName,
WorkspaceDbTableName,
@@ -34,7 +34,7 @@ impl WorkspaceSession {
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes.as_slice(),
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(push);
@@ -51,19 +51,15 @@ impl WorkspaceSession {
now_ms: i64,
) -> ClientResult<()> {
if is_non_empty_update(&diff) {
let wm = self.push_local_doc_update(
table.local_doc_id(),
diff,
PushDocIntent::Update,
now_ms,
)?;
let wm =
self.push_local_doc_update(table.local_doc_id(), diff, PushIntent::Update, now_ms)?;
self.drain_directory_updates_stamped(wm);
}
Ok(())
}
/// Set the tag set of `doc_id` in `meta.pages` and queue the root update for
/// `SpaceSyncEngine` and SQLite WAL. Returns `false` when the tags are unchanged.
/// the document peer and SQLite WAL. Returns `false` when the tags are unchanged.
pub fn set_document_tags(
&mut self,
doc_id: &str,
@@ -79,18 +75,14 @@ impl WorkspaceSession {
let Some(bytes) = root_update else {
return Ok(false);
};
let push = self.push_local_doc_update(
self.space_id.clone(),
bytes,
PushDocIntent::Update,
now_ms,
)?;
let push =
self.push_local_doc_update(self.space_id.clone(), bytes, PushIntent::Update, now_ms)?;
self.drain_directory_updates_stamped(push);
Ok(true)
}
/// Bind `doc_id` to a journal `date` in `db$docProperties` while preserving any existing
/// properties on that row, and queue the table update for `SpaceSyncEngine` and SQLite WAL.
/// properties on that row, and queue the table update for the document peer and SQLite WAL.
pub fn set_doc_journal_date<'a>(
&mut self,
doc_id: &str,
@@ -162,7 +154,7 @@ impl WorkspaceSession {
}
/// Upsert a folder placement row in `db$folders` and queue the table update for
/// `SpaceSyncEngine` and SQLite WAL persistence.
/// the document peer and SQLite WAL persistence.
pub fn upsert_folder_row(&mut self, row: &FolderRow, now_ms: i64) -> ClientResult<()> {
let diff = {
let mut dir = self.directory.lock_directory();
@@ -294,7 +286,7 @@ impl WorkspaceSession {
let wm = self.push_local_doc_update(
UserdataTableName::Favorite.local_doc_id(&self.user_id),
diff,
PushDocIntent::Update,
PushIntent::Update,
now_ms,
)?;
self.drain_directory_updates_stamped(wm);
@@ -384,20 +376,29 @@ mod tests {
use super::*;
#[cfg(feature = "cloud-sync")]
#[test]
fn document_display_properties_stamp_writes_and_skip_equal_values() {
use crate::{EditorDocMode, HostKind, session_ops::RowProof};
fn cloud_session(client_id: u64) -> WorkspaceSession {
let mut session = WorkspaceSession::new(
"workspace",
"user",
1,
HostKind::Native,
client_id,
crate::HostKind::Native,
"server",
"https://example.com",
1_000,
)
.unwrap();
session
.bind_document_peer(Box::new(crate::test_peer::MemoryDocumentPeer::default()))
.unwrap();
session
}
#[cfg(feature = "cloud-sync")]
#[test]
fn document_display_properties_stamp_writes_and_skip_equal_values() {
use crate::{EditorDocMode, session_ops::RowProof};
let mut session = cloud_session(1);
let (doc, _) = session
.create_document("Page", EditorDocMode::Page, None, 1_010)
.unwrap();
@@ -432,18 +433,9 @@ mod tests {
fn folder_drop_stamps_changes_skips_noops_and_restores_order_from_updates() {
use affine_store::workspace_db::WorkspaceDb;
use crate::{HostKind, organize::FolderDrop, session_ops::RowProof};
use crate::{organize::FolderDrop, session_ops::RowProof};
let mut session = WorkspaceSession::new(
"workspace",
"user",
42,
HostKind::Native,
"server",
"https://example.com",
1_000,
)
.unwrap();
let mut session = cloud_session(42);
let table = WorkspaceDbTableName::Folders;
for mut row in [
row("first", None, "folder"),
@@ -542,23 +534,13 @@ mod tests {
use blocksuite_playground_doc::fractional_index::generate_key_between;
use crate::{
HostKind,
organize::{FolderDrop, plan_folder_drop},
session_ops::RowProof,
};
let table = WorkspaceDbTableName::Folders;
for drop in [FolderDrop::After("A"), FolderDrop::Before("B")] {
let mut session = WorkspaceSession::new(
"workspace",
"user",
42,
HostKind::Native,
"server",
"https://example.com",
1_000,
)
.unwrap();
let mut session = cloud_session(42);
let update_for = |client, id| {
let mut db = WorkspaceDb::new("workspace", "user", client);
let mut folder = row(id, None, "folder");
@@ -630,19 +612,10 @@ mod tests {
fn tied_folder_drop_skips_in_place_writes_and_replays_an_insertion() {
use affine_store::workspace_db::WorkspaceDb;
use crate::{HostKind, organize::FolderDrop, session_ops::RowProof};
use crate::{organize::FolderDrop, session_ops::RowProof};
let table = WorkspaceDbTableName::Folders;
let mut session = WorkspaceSession::new(
"workspace",
"user",
42,
HostKind::Native,
"server",
"https://example.com",
1_000,
)
.unwrap();
let mut session = cloud_session(42);
for (id, parent, index) in [
("parent", None, "a0"),
("A", Some("parent"), "a1"),
@@ -6,7 +6,7 @@ use std::borrow::Cow;
#[cfg(feature = "cloud-sync")]
use std::hash::{DefaultHasher, Hash, Hasher};
use affine_store::{sync::PushDocIntent, workspace_db::PendingDocUpdate};
use affine_store::{PushIntent, workspace_db::PendingDocUpdate};
use crate::{ClientResult, session::WorkspaceSession};
@@ -92,19 +92,35 @@ impl WorkspaceSession {
&mut self,
doc_id: impl Into<String>,
update: impl Into<Cow<'a, [u8]>>,
intent: PushDocIntent,
intent: PushIntent,
now_ms: i64,
) -> ClientResult<LocalPush> {
#[cfg(feature = "cloud-sync")]
let (proof, digest) = if let Some(sync) = &mut self.sync {
let (proof, digest) = {
let doc_id = doc_id.into();
let update = update.into();
let digest = update_digest(&doc_id, &update);
sync.push_doc_update(doc_id.clone(), update.into_owned(), intent, now_ms)?;
let seq = self.doc_sync.mark_local_write(&doc_id);
(RowProof::Pushed(seq), Some(digest))
} else {
(RowProof::Unproven, None)
if let Some(address) = self.doc_address(&doc_id) {
if let Some(peer) = &mut self.sync {
let update = update.into();
let digest = update_digest(&doc_id, &update);
let seq = self.doc_sync.next_push_sequence();
peer.push(
crate::remote::PushUpdate {
address,
seq: affine_store::LocalSeq(seq),
update_v1: update.into_owned(),
intent,
},
now_ms,
)?;
let seq = self.doc_sync.mark_local_write(&doc_id);
(RowProof::Pushed(seq), Some(digest))
} else {
self.doc_sync.seed_unpushed_docs([doc_id]);
(RowProof::Unproven, None)
}
} else {
(RowProof::Unproven, None)
}
};
#[cfg(not(feature = "cloud-sync"))]
let proof = {
@@ -270,7 +286,7 @@ mod tests {
writes.extend(body_writes);
assert_eq!(session.pending_persist_count(), 0);
#[cfg(feature = "cloud-sync")]
assert!(session.sync_engine().is_none());
assert!(session.document_peer().is_none());
assert!(session.pending_push_doc_ids().is_empty());
assert_eq!(session.sync_status(), WorkspaceSyncStatus::Offline);
assert_eq!(session.sync_status().pending_count(), 0);
@@ -362,7 +378,7 @@ mod tests {
let mut host = MemoryHostBridge::new(HostKind::Web, "local");
let url = "wss://example.com";
session.connect_sync(&mut host, url, 1_010).unwrap();
assert!(session.ws_handle.is_none());
assert!(session.document_peer().is_none());
assert!(
session
.on_ws_open(&mut host, url, 1_020)
+173 -74
View File
@@ -1,143 +1,242 @@
//! Cloud transport and sync status for a workspace session.
//! Document peer binding for a workspace session.
use affine_store::sync::{SpaceSyncEngine, SpaceSyncEvent, SpaceSyncState};
use affine_store::{DocAddress, PeerSyncEvent, PeerSyncState};
use crate::{
ClientResult, HostBridge,
ClientError, ClientResult, HostBridge,
blob_ingest::BlobUploadState,
remote::{DocumentPeer, PeerInput, PeerTransportAction},
session::{WorkspaceSession, WorkspaceSyncStatus},
};
impl WorkspaceSession {
pub fn sync_engine(&self) -> Option<&SpaceSyncEngine> {
self.sync.as_ref()
pub fn document_peer(&self) -> Option<&dyn DocumentPeer> {
self.sync.as_deref()
}
pub fn doc_address(&self, local_id: &str) -> Option<DocAddress> {
DocAddress::from_workspace_storage_key(self.sync_scope.clone()?, &self.space_id, local_id)
}
pub(crate) fn local_peer_id(&self, address: &DocAddress) -> Option<String> {
address.workspace_storage_key(self.sync_scope.as_ref()?, &self.space_id)
}
pub(crate) fn is_sync_ready(&self) -> bool {
self.sync
.as_ref()
.is_some_and(|sync| sync.state() == SpaceSyncState::Ready)
.is_some_and(|peer| peer.state() == PeerSyncState::Ready)
}
/// Derive the current UI-ready [`WorkspaceSyncStatus`].
pub fn sync_status(&self) -> WorkspaceSyncStatus {
let Some(sync) = &self.sync else {
if self.sync_scope.is_none() {
return WorkspaceSyncStatus::Offline;
};
}
let pending_blobs = self
.blobs
.values()
.filter(|(rec, _)| rec.upload_state != BlobUploadState::Uploaded)
.filter(|(record, _)| record.upload_state != BlobUploadState::Uploaded)
.count();
let pending_updates = sync.offline_queue().len()
+ self.doc_sync.unqueued_pending_push_count()
let pending_updates = self.sync.as_ref().map_or(0, |peer| peer.pending_pushes())
+ self.doc_sync.pending_unqueued_operation_count()
+ pending_blobs;
match sync.state() {
SpaceSyncState::Offline => {
if pending_updates > 0 {
WorkspaceSyncStatus::Syncing { pending_updates }
} else {
WorkspaceSyncStatus::Offline
}
match self
.sync
.as_ref()
.map_or(PeerSyncState::Offline, |peer| peer.state())
{
PeerSyncState::Offline if pending_updates == 0 => WorkspaceSyncStatus::Offline,
PeerSyncState::Ready if pending_updates == 0 => WorkspaceSyncStatus::Synced,
PeerSyncState::Offline | PeerSyncState::Ready => {
WorkspaceSyncStatus::Syncing { pending_updates }
}
SpaceSyncState::Connecting | SpaceSyncState::Joining => WorkspaceSyncStatus::Connecting,
SpaceSyncState::Ready => {
if pending_updates > 0 {
WorkspaceSyncStatus::Syncing { pending_updates }
} else {
WorkspaceSyncStatus::Synced
}
}
SpaceSyncState::ReconnectScheduled { next_attempt_at_ms } => {
PeerSyncState::Connecting => WorkspaceSyncStatus::Connecting,
PeerSyncState::ReconnectScheduled { next_attempt_at_ms } => {
WorkspaceSyncStatus::ReconnectScheduled {
next_attempt_at_ms,
pending_updates,
}
}
SpaceSyncState::AuthRequired => WorkspaceSyncStatus::AuthRequired,
SpaceSyncState::PermissionRevoked => WorkspaceSyncStatus::PermissionRevoked,
PeerSyncState::AuthRequired => WorkspaceSyncStatus::AuthRequired,
PeerSyncState::PermissionRevoked => WorkspaceSyncStatus::PermissionRevoked,
}
}
/// Connect the `SpaceSync` room over `HostBridge` and flush initial outbound frames.
pub fn connect_sync(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
url: &str,
now_ms: i64,
) -> ClientResult<()> {
let Some(sync) = &mut self.sync else {
let Some(scope) = &self.sync_scope else {
return Ok(());
};
sync.set_auth_mode(self.auth.socket_auth_mode());
sync.connect(now_ms);
self.flush_outbound_to_host(host, ws_url, now_ms)
let peer = self.sync.as_mut().ok_or(ClientError::MissingDocumentPeer)?;
if !scope.origin.matches_transport_endpoint(url) {
return Err(ClientError::SyncOriginMismatch);
}
peer.on_input(PeerInput::Connect(self.auth.connection_auth()), now_ms)?;
self.flush_peer(host, url, now_ms)
}
/// Install credentials for this account and notify its peer before it can reconnect.
/// A browser uses its current cookie when `access_token` is `None`.
pub fn refresh_sync_credentials(
&mut self,
host: &mut dyn HostBridge,
url: &str,
access_token: Option<String>,
now_ms: i64,
) -> ClientResult<()> {
self.validate_sync_origin(url)?;
self.auth.set_access_token(access_token);
self.update_peer_credentials(host, url, now_ms)
}
/// Cancel sync for this account while retaining its pending writes.
pub fn sign_out_sync(
&mut self,
host: &mut dyn HostBridge,
url: &str,
now_ms: i64,
) -> ClientResult<()> {
self.validate_sync_origin(url)?;
self.auth.clear_session();
self.doc_sync.on_disconnected();
self.update_peer_credentials(host, url, now_ms)
}
fn update_peer_credentials(
&mut self,
host: &mut dyn HostBridge,
url: &str,
now_ms: i64,
) -> ClientResult<()> {
if let Some(peer) = &mut self.sync {
peer.on_input(
PeerInput::CredentialsChanged(self.auth.connection_auth()),
now_ms,
)?;
}
self.flush_peer(host, url, now_ms)
}
fn validate_sync_origin(&self, url: &str) -> ClientResult<()> {
if self
.sync_scope
.as_ref()
.is_some_and(|scope| scope.origin.matches_transport_endpoint(url))
{
Ok(())
} else {
Err(ClientError::SyncOriginMismatch)
}
}
/// Notify that the WebSocket connection opened and flush Engine.IO/Socket.IO handshakes.
pub fn on_ws_open(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
url: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
let Some(sync) = &mut self.sync else {
return Ok(Vec::new());
};
sync.on_ws_open(now_ms);
self.flush_outbound_to_host(host, ws_url, now_ms)?;
self.process_sync_events(now_ms)
) -> ClientResult<Vec<PeerSyncEvent>> {
self.on_peer_input(host, url, PeerInput::Opened, now_ms)
}
/// Feed an inbound WebSocket text frame into `SpaceSyncEngine`, apply remote CRDT updates,
/// and flush any automatic responses back to `HostBridge`.
pub fn on_ws_text(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
url: &str,
frame: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
let Some(sync) = &mut self.sync else {
return Ok(Vec::new());
};
sync.on_ws_text(frame, now_ms)?;
let events = self.process_sync_events(now_ms)?;
self.flush_outbound_to_host(host, ws_url, now_ms)?;
Ok(events)
) -> ClientResult<Vec<PeerSyncEvent>> {
self.on_peer_input(host, url, PeerInput::Text(frame), now_ms)
}
pub fn on_ws_binary(
&mut self,
host: &mut dyn HostBridge,
url: &str,
frame: &[u8],
now_ms: i64,
) -> ClientResult<Vec<PeerSyncEvent>> {
self.on_peer_input(host, url, PeerInput::Binary(frame), now_ms)
}
/// Notify that the WebSocket transport errored/dropped at `now_ms`.
pub fn on_ws_error(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
url: &str,
reason: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
let Some(sync) = &mut self.sync else {
return Ok(Vec::new());
};
sync.on_ws_error(reason, now_ms);
let events = self.process_sync_events(now_ms)?;
self.flush_outbound_to_host(host, ws_url, now_ms)?;
Ok(events)
) -> ClientResult<Vec<PeerSyncEvent>> {
self.on_peer_input(host, url, PeerInput::TransportLost(reason), now_ms)
}
/// Advance deterministic reconnect / ACK / retry / invalidation timers at `now_ms`.
pub fn on_tick(
&mut self,
host: &mut dyn HostBridge,
ws_url: &str,
url: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
let Some(sync) = &mut self.sync else {
) -> ClientResult<Vec<PeerSyncEvent>> {
self.on_peer_input(host, url, PeerInput::Tick, now_ms)
}
fn on_peer_input(
&mut self,
host: &mut dyn HostBridge,
url: &str,
input: PeerInput<'_>,
now_ms: i64,
) -> ClientResult<Vec<PeerSyncEvent>> {
if self.sync.is_none() {
return Ok(Vec::new());
};
sync.on_tick(now_ms)?;
self.poll_invalidation_repair(now_ms);
}
self.validate_sync_origin(url)?;
let peer = self.sync.as_mut().ok_or(ClientError::MissingDocumentPeer)?;
let tick = matches!(input, PeerInput::Tick);
peer.on_input(input, now_ms)?;
if tick {
self.poll_invalidation_repair(now_ms);
}
let events = self.process_sync_events(now_ms)?;
self.flush_outbound_to_host(host, ws_url, now_ms)?;
self.flush_peer(host, url, now_ms)?;
Ok(events)
}
fn flush_peer(
&mut self,
host: &mut dyn HostBridge,
url: &str,
now_ms: i64,
) -> ClientResult<()> {
let Some(peer) = &mut self.sync else {
return Ok(());
};
while let Some(action) = peer.next_transport_action() {
let result = match action {
PeerTransportAction::Open { headers } => host
.ws_connect(url, &headers)
.map(|handle| self.ws_handle = Some(handle)),
PeerTransportAction::SendText(frame) => self
.ws_handle
.map_or(Ok(()), |handle| host.ws_send(handle, &frame)),
PeerTransportAction::SendBinary(frame) => self
.ws_handle
.map_or(Ok(()), |handle| host.ws_send_binary(handle, &frame)),
PeerTransportAction::Close => self
.ws_handle
.take()
.map_or(Ok(()), |handle| host.ws_close(handle)),
};
if let Err(err) = result {
let _ = peer.on_input(PeerInput::TransportLost(&err.to_string()), now_ms);
if let Some(handle) = self.ws_handle.take() {
let _ = host.ws_close(handle);
}
let _ = self.process_sync_events(now_ms);
return Err(err);
}
}
Ok(())
}
}
+3 -393
View File
@@ -8,7 +8,7 @@ use std::path::Path;
#[cfg(feature = "cloud-sync")]
use crate::host::HostBridge;
#[cfg(feature = "cloud-sync")]
use affine_store::sync::SpaceSyncEvent;
use affine_store::PeerSyncEvent;
use affine_store::{
sqlite::{
BlobRecord, CheckedAdvance, PeerProof, PendingBlobUpload, SetBlob, SqliteDocStorage,
@@ -348,7 +348,7 @@ impl SqliteWorkspaceStore {
host: &mut dyn HostBridge,
ws_url: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
) -> ClientResult<Vec<PeerSyncEvent>> {
self.flush_session_mutations(session, None, now_ms).await?;
session.on_tick(host, ws_url, now_ms)
}
@@ -720,40 +720,15 @@ mod tests {
ShareIngestRequest, SharePayloadKind, ingest_share_item_into_sqlite,
};
use blocksuite_playground_doc::schema::BlockSpec;
use super::*;
use crate::{
blob_ingest::{PickedMediaInput, prepare_ingested_blob},
host::{MemoryHostBridge, WsHandle},
session::{
MAX_EVICTED_REMOTE_DOCS, MAX_UNVERIFIED_REMOTE_BYTES, MAX_UNVERIFIED_REMOTE_DOCS,
},
};
const WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
const SERVER: &str = "affine-cloud";
const DOC: &str = "page-p";
fn encode_base64(input: &[u8]) -> String {
const TABLE: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
for i in 0..4 {
out.push(if i <= chunk.len() {
TABLE[((n >> (18 - 6 * i)) & 0x3F) as usize] as char
} else {
'='
});
}
}
out
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
@@ -764,119 +739,6 @@ mod tests {
dir
}
fn sent_frames(host: &MemoryHostBridge) -> Vec<String> {
(0..16u64)
.filter_map(|h| host.ws_sent(WsHandle(h)))
.flatten()
.cloned()
.collect()
}
/// Ack ID of the newest frame sent after `from` that contains every needle.
fn ack_id_after(host: &MemoryHostBridge, from: usize, needles: &[&str]) -> Option<u64> {
sent_frames(host)[from..].iter().rev().find_map(|f| {
let digits: String = f
.strip_prefix("42")?
.chars()
.take_while(char::is_ascii_digit)
.collect();
needles
.iter()
.all(|n| f.contains(n))
.then(|| digits.parse().ok())
.flatten()
})
}
fn reply(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, frame: &str, t: i64) {
session.on_ws_text(host, WS_URL, frame, t).unwrap();
}
fn join(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, id: u64, t: i64) {
let ok = format!(
r#"43{id}[{{"data":{{"clientId":"c-1","success":true,"protocolVersion":1}}}}]"#
);
reply(session, host, &ok, t);
}
fn connect(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64) {
let from = sent_frames(host).len();
session.connect_sync(host, WS_URL, t).unwrap();
session.on_ws_open(host, WS_URL, t).unwrap();
let open = r#"0{"sid":"e-1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#;
reply(session, host, open, t);
reply(session, host, r#"40{"sid":"s-1"}"#, t);
let id = ack_id_after(host, from, &["space:join-batch"]).unwrap();
join(session, host, id, t);
}
/// Tick until `event` for `doc_id` goes out, answering a `space:join-batch` for it on the
/// way, and return the ack ID of the request.
fn next_request(
session: &mut WorkspaceSession,
host: &mut MemoryHostBridge,
event: &str,
doc_id: &str,
t: i64,
) -> u64 {
let from = sent_frames(host).len();
session.on_tick(host, WS_URL, t).unwrap();
if let Some(id) = ack_id_after(host, from, &["space:join-batch", doc_id]) {
join(session, host, id, t);
session.on_tick(host, WS_URL, t).unwrap();
}
ack_id_after(host, from, &[event, doc_id]).unwrap()
}
fn loaded(id: u64, missing: &[u8], state: &[u8], timestamp: i64) -> String {
format!(
r#"43{id}[{{"data":{{"missing":"{}","state":"{}","timestamp":{timestamp}}}}}]"#,
encode_base64(missing),
encode_base64(state)
)
}
fn broadcast(doc_id: &str, update: &[u8], timestamp: i64) -> String {
format!(
r#"42["space:broadcast-doc-updates",{{"spaceType":"workspace","spaceId":"ws","docId":"{doc_id}","updates":["{}"],"timestamp":{timestamp},"editor":"peer"}}]"#,
encode_base64(update)
)
}
async fn pushed_and_doc_clock(store: &SqliteWorkspaceStore, doc_id: &str) -> (i64, i64) {
let pushed = store
.storage()
.get_peer_pushed_clock(SERVER, doc_id)
.await
.unwrap()
.map_or(0, |c| naive_utc_to_millis(c.timestamp));
let clock = store
.storage()
.get_doc_clock(doc_id)
.await
.unwrap()
.unwrap();
(pushed, naive_utc_to_millis(clock.timestamp))
}
/// Write a page baseline of `DOC` that the server already holds.
async fn seed_pushed_page(store: &SqliteWorkspaceStore) -> PageDocSession {
let mut page = PageDocSession::new(DOC, 7).unwrap();
let spec = BlockSpec::Page { title: "P".into() };
page.add_block("root", spec, None, None, 1).unwrap();
let ts = store
.storage()
.push_update(DOC, page.encode_update_v1().unwrap(), 1_000)
.await
.unwrap();
store
.storage()
.set_peer_pushed_clock(SERVER, DOC, ts)
.await
.unwrap();
page
}
async fn open_session(store: &SqliteWorkspaceStore, client_id: u64) -> WorkspaceSession {
store
.load_workspace_session(
@@ -942,7 +804,7 @@ mod tests {
assert_eq!(keys(&reopened), ["doc:doc-a", "folder:f-1"]);
// Without a table of its own, the session reads the table of a local workspace.
let local = UserdataTableName::Favorite.local_doc_id("__local__");
let local = UserdataTableName::Favorite.local_doc_id(affine_store::LOCAL_USER_ID);
store.storage().delete_doc(&own).await.unwrap();
store
.storage()
@@ -1188,258 +1050,6 @@ mod tests {
store_c.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn evicted_broadcast_for_a_doc_of_another_writer_reloads_it_from_the_server() {
// (case, caption bytes of the peer edit, broadcasts for other documents after it)
let cases = [
("over-byte-limit", 1_048_600usize, 0usize),
("over-doc-limit", 9, MAX_UNVERIFIED_REMOTE_DOCS),
];
for (case, caption_len, other_docs) in cases {
let dir = temp_dir(case);
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut session = open_session(&store, 11).await;
let mut host = MemoryHostBridge::new(HostKind::Native, "inst");
connect(&mut session, &mut host, 10);
// The page is not on the server yet: the first load ends missing.
assert!(
store
.open_or_hydrate_document(&mut session, DOC, 300)
.await
.is_err()
);
let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 310);
let not_found = format!(
r#"43{load}[{{"error":{{"status":404,"code":"DOC_NOT_FOUND","name":"DOC_NOT_FOUND","message":"doc not found"}}}}]"#
);
reply(&mut session, &mut host, &not_found, 340);
assert!(session.is_remote_doc_missing(DOC), "{case}");
// A Share Extension writes the page into the same SQLite file, and a peer edits it.
let db = resolve_workspace_db_path(&dir, "workspace", "local", "ws").unwrap();
let share = ShareIngestRequest {
share_id: "share-p".into(),
import_attempt_id: "attempt-p".into(),
doc_id: DOC.into(),
kind: SharePayloadKind::Text,
title: "Shared".into(),
text_or_url: "baseline".into(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 22,
now_ms: 1_000,
};
ingest_share_item_into_sqlite(&db, "ws", &share, &[])
.await
.unwrap();
let mut peer = store.load_doc_session(DOC, 33).await.unwrap().unwrap();
let root_id = peer.read_page_snapshot().unwrap().root.unwrap().id;
let caption = "p".repeat(caption_len);
let delta = peer
.set_block_caption(&root_id, &caption, 1_002)
.unwrap()
.unwrap()
.update;
reply(
&mut session,
&mut host,
&broadcast(DOC, &delta, 1_004),
1_004,
);
for i in 0..other_docs {
let frame = broadcast(&format!("other-{i}"), &delta, 1_005);
reply(&mut session, &mut host, &frame, 1_005);
}
assert_eq!(session.evicted_remote_doc_count(), 1, "{case}");
assert!(session.unhydrated_pending_delta_doc_count() <= MAX_UNVERIFIED_REMOTE_DOCS);
assert!(session.unhydrated_pending_delta_bytes() <= MAX_UNVERIFIED_REMOTE_BYTES);
// The flush finds the page in SQLite, and the session loads it from the server.
store
.flush_session_mutations(&mut session, None, 1_100)
.await
.unwrap();
assert_eq!(session.evicted_remote_doc_count(), 0, "{case}");
let reload = next_request(&mut session, &mut host, "space:load-doc", DOC, 1_200);
let server_state = peer.encode_update_v1().unwrap();
let server_sv = peer.encode_state_vector_v1().unwrap();
let frame = loaded(reload, &server_state, &server_sv, 1_300);
reply(&mut session, &mut host, &frame, 1_300);
store
.flush_session_mutations(&mut session, None, 1_400)
.await
.unwrap();
let page = store.load_doc_session(DOC, 55).await.unwrap().unwrap();
let root = page.read_page_snapshot().unwrap().root.unwrap();
let read = root.props.get("prop:caption").and_then(|v| v.as_str());
assert_eq!(read, Some(caption.as_str()), "{case}");
for i in 0..other_docs {
let doc_id = format!("other-{i}");
assert!(
store
.storage()
.get_doc_clock(&doc_id)
.await
.unwrap()
.is_none()
);
}
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
}
#[tokio::test]
async fn remote_update_on_a_pushed_unopened_doc_moves_pushed_clock_without_a_load() {
let dir = temp_dir("pushed-unopened");
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut peer = seed_pushed_page(&store).await;
let mut session = open_session(&store, 11).await;
assert!(!session.has_pending_push(DOC));
let mut host = MemoryHostBridge::new(HostKind::Native, "inst");
connect(&mut session, &mut host, 10);
let delta = peer
.set_block_caption("root", "remote", 2_000)
.unwrap()
.unwrap()
.update;
reply(
&mut session,
&mut host,
&broadcast(DOC, &delta, 2_000),
2_000,
);
assert!(!session.is_doc_loaded(DOC));
store
.flush_session_mutations(&mut session, None, 2_100)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock);
// A cold start has nothing to load or push for the page.
let mut restarted = open_session(&store, 12).await;
assert!(!restarted.has_pending_push(DOC));
connect(&mut restarted, &mut host, 3_000);
store
.flush_session_mutations(&mut restarted, None, 3_100)
.await
.unwrap();
assert_eq!(restarted.unopened_loaded_doc_count(), 0);
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn acked_local_rows_move_pushed_clock_until_a_row_of_another_writer() {
let dir = temp_dir("acked-local");
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut editor = seed_pushed_page(&store).await;
let mut other = store.load_doc_session(DOC, 99).await.unwrap().unwrap();
let mut session = open_session(&store, 11).await;
let mut host = MemoryHostBridge::new(HostKind::Native, "inst");
connect(&mut session, &mut host, 10);
assert!(
store
.open_or_hydrate_document(&mut session, DOC, 100)
.await
.is_ok()
);
let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 110);
let sv = editor.encode_state_vector_v1().unwrap();
reply(
&mut session,
&mut host,
&loaded(load, &[0, 0], &sv, 120),
120,
);
// Each local edit is pushed, flushed, and acknowledged. The ack can come before or after
// the flush that writes its row.
let mut acked_row_clock = 0;
for (i, ack_before_flush) in [(0i64, false), (1, true)] {
let t = 1_000 + i * 1_000;
let edit = editor.set_block_caption("root", &format!("v{i}"), t as u64);
let update = edit.unwrap().unwrap().update;
assert!(session.merge_local_doc_update(DOC, &update, t).unwrap());
let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, t);
let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":{t}}}}}]"#);
if ack_before_flush {
reply(&mut session, &mut host, &ack, t + 10);
}
store
.flush_session_mutations(&mut session, None, t + 20)
.await
.unwrap();
if !ack_before_flush {
reply(&mut session, &mut host, &ack, t + 30);
store
.flush_session_mutations(&mut session, None, t + 40)
.await
.unwrap();
}
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock, "edit {i}");
acked_row_clock = clock;
}
// Another writer adds a row, then a local edit lands after it. The server holds the
// whole in-memory state, but the content check finds the other row outside it.
let foreign = other
.set_block_caption("root", "other", 5_000)
.unwrap()
.unwrap()
.update;
store
.storage()
.push_update(DOC, &foreign, 5_000)
.await
.unwrap();
let update = editor
.set_block_caption("root", "v2", 6_000)
.unwrap()
.unwrap()
.update;
assert!(session.merge_local_doc_update(DOC, &update, 6_000).unwrap());
let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, 6_000);
let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":6000}}}}]"#);
reply(&mut session, &mut host, &ack, 6_010);
store
.flush_session_mutations(&mut session, None, 6_020)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, acked_row_clock);
assert!(pushed < clock);
// Once the server sends the other row back, the in-memory state holds every row.
reply(
&mut session,
&mut host,
&broadcast(DOC, &foreign, 7_000),
7_000,
);
store
.flush_session_mutations(&mut session, None, 7_100)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock);
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
@@ -3,7 +3,7 @@
use std::sync::{Arc, Mutex};
use std::time::Duration;
use affine_store::sync::SpaceSyncEvent;
use affine_store::PeerSyncEvent;
use tokio::runtime::Handle;
use crate::{ClientError, ClientResult, HostBridge, SqliteWorkspaceStore, WorkspaceSession};
@@ -75,10 +75,10 @@ impl SqliteSyncHost {
&SqliteWorkspaceStore,
&mut dyn HostBridge,
&str,
) -> ClientResult<Vec<SpaceSyncEvent>>
) -> ClientResult<Vec<PeerSyncEvent>>
+ Send
+ 'static,
) -> ClientResult<Vec<SpaceSyncEvent>> {
) -> ClientResult<Vec<PeerSyncEvent>> {
let host = self.clone();
self.runtime
.spawn_blocking(move || {
@@ -0,0 +1,164 @@
use std::sync::{Arc, Mutex};
use affine_client::remote::{
DocumentPeer, PeerInput, PeerTransportAction, PushUpdate, RemoteResult,
};
use affine_store::{CommitReceipt, DocAddress, PeerSyncEvent, PeerSyncState};
#[derive(Clone)]
pub struct MemoryDocumentPeer(Arc<Mutex<MemoryState>>);
struct MemoryState {
state: PeerSyncState,
reply_missing: bool,
pushes: Vec<PushUpdate>,
loads: Vec<DocAddress>,
events: Vec<PeerSyncEvent>,
}
impl Default for MemoryDocumentPeer {
fn default() -> Self {
Self(Arc::new(Mutex::new(MemoryState {
state: PeerSyncState::Offline,
reply_missing: false,
pushes: Vec::new(),
loads: Vec::new(),
events: Vec::new(),
})))
}
}
#[allow(dead_code)]
impl MemoryDocumentPeer {
pub fn with_empty_server() -> Self {
let peer = Self::default();
peer.0.lock().unwrap().reply_missing = true;
peer
}
pub fn set_event(&self, event: PeerSyncEvent) {
self.0.lock().unwrap().events.push(event);
}
pub fn take_pushes(&self) -> Vec<PushUpdate> {
std::mem::take(&mut self.0.lock().unwrap().pushes)
}
pub fn take_loads(&self) -> Vec<DocAddress> {
std::mem::take(&mut self.0.lock().unwrap().loads)
}
}
impl DocumentPeer for MemoryDocumentPeer {
fn state(&self) -> PeerSyncState {
self.0.lock().unwrap().state
}
fn pending_pushes(&self) -> usize {
self.0.lock().unwrap().pushes.len()
}
fn load(&mut self, address: DocAddress, _now_ms: i64) -> RemoteResult<()> {
let mut state = self.0.lock().unwrap();
state.loads.push(address.clone());
if state.reply_missing {
state.events.push(PeerSyncEvent::Missing { address });
}
Ok(())
}
fn diff(&mut self, address: DocAddress, _vector: Vec<u8>, now_ms: i64) -> RemoteResult<()> {
self.load(address, now_ms)
}
fn push(&mut self, update: PushUpdate, now_ms: i64) -> RemoteResult<()> {
let mut state = self.0.lock().unwrap();
if state.reply_missing {
state.events.push(PeerSyncEvent::Committed {
receipt: CommitReceipt {
address: update.address.clone(),
seq: update.seq,
},
timestamp_ms: now_ms,
});
}
state.pushes.push(update);
Ok(())
}
fn subscribe(&mut self, _addresses: &[DocAddress], _now_ms: i64) -> RemoteResult<()> {
Ok(())
}
fn unsubscribe(&mut self, _addresses: &[DocAddress], _now_ms: i64) -> RemoteResult<()> {
Ok(())
}
fn delete(&mut self, address: DocAddress, _now_ms: i64) -> RemoteResult<()> {
self.set_event(PeerSyncEvent::Deleted {
addresses: vec![address],
});
Ok(())
}
fn discard(&mut self, address: &DocAddress) {
self.0
.lock()
.unwrap()
.pushes
.retain(|push| &push.address != address);
}
fn request_inventory(&mut self, _now_ms: i64) -> RemoteResult<()> {
self.set_event(PeerSyncEvent::Inventory {
timestamps: Default::default(),
});
Ok(())
}
fn request_awareness(&mut self, address: DocAddress, _now_ms: i64) -> RemoteResult<()> {
self.set_event(PeerSyncEvent::AwarenessRequested { address });
Ok(())
}
fn publish_awareness(
&mut self,
address: DocAddress,
update_v1: Vec<u8>,
_now_ms: i64,
) -> RemoteResult<()> {
self.set_event(PeerSyncEvent::Awareness { address, update_v1 });
Ok(())
}
fn drain_events(&mut self) -> Vec<PeerSyncEvent> {
std::mem::take(&mut self.0.lock().unwrap().events)
}
fn on_input(&mut self, input: PeerInput<'_>, _now_ms: i64) -> RemoteResult<()> {
let mut state = self.0.lock().unwrap();
match input {
PeerInput::Connect(_) => state.state = PeerSyncState::Connecting,
PeerInput::Opened => {
state.state = PeerSyncState::Ready;
state.events.push(PeerSyncEvent::Ready);
}
PeerInput::TransportLost(_) => {
state.state = PeerSyncState::Offline;
state.events.push(PeerSyncEvent::Disconnected);
}
PeerInput::CredentialsChanged(affine_client::auth::ConnectionAuth::SignedOut) => {
state.state = PeerSyncState::Offline;
}
PeerInput::Text(_)
| PeerInput::Binary(_)
| PeerInput::CredentialsChanged(_)
| PeerInput::Tick => {}
}
Ok(())
}
fn next_transport_action(&mut self) -> Option<PeerTransportAction> {
None
}
}
+9
View File
@@ -0,0 +1,9 @@
# Working in `packages/frontend/compat-v027/` (for agents)
This crate holds the codecs for the legacy AFFiNE cloud protocol.
Host composition roots select this crate. Core crates do not depend on it.
- Keep `#![forbid(unsafe_code)]` at the crate root.
- Pass time and transport input explicitly. Keep OS, network, and storage I/O in the host.
- Keep every Rust file at or below 800 non-test lines. Do not use `super::super::`.
- Run the crate tests from `packages/frontend/` with `CARGO_ENCODED_RUSTFLAGS=""`.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "affine-compat-v027"
workspace = ".."
version.workspace = true
edition.workspace = true
publish.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
affine-client = { path = "../client" }
affine-store = { path = "../../common/store" }
base64.workspace = true
chrono.workspace = true
serde.workspace = true
serde_json.workspace = true
url.workspace = true
[dev-dependencies]
blocksuite-playground-doc = { path = "../../../blocksuite/crates/doc", default-features = false }
[target.'cfg(not(target_family = "wasm"))'.dev-dependencies]
tokio.workspace = true
File renamed without changes.
@@ -1,96 +1,9 @@
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use affine_store::{IdConverter, StoreResult, blob::BlobSource};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::{error::StoreResult, id_converter::IdConverter};
/// Compute the canonical content-addressed blob key (base64url-no-pad SHA-256) for `bytes`.
pub fn compute_blob_key(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
URL_SAFE_NO_PAD.encode(digest)
}
/// Compute the 64-character lowercase hexadecimal SHA-256 digest of `bytes`.
pub fn compute_sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(64);
for b in digest {
use std::fmt::Write as _;
let _ = write!(&mut hex, "{b:02x}");
}
hex
}
/// Inspect raw image bytes (PNG, GIF, JPEG, or WebP) and return `(width, height)` in pixels.
///
/// Pure in-memory header parser with zero external dependencies and full `wasm32` compatibility.
pub fn detect_image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
// PNG: 8-byte signature + IHDR chunk (width at 16..20, height at 20..24, big-endian).
if bytes.len() >= 24 && bytes.starts_with(b"\x89PNG\r\n\x1a\n") && &bytes[12..16] == b"IHDR" {
let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
if w > 0 && h > 0 {
return Some((w, h));
}
}
// GIF87a / GIF89a: width at 6..8, height at 8..10 (little-endian).
if bytes.len() >= 10 && (bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")) {
let w = u32::from(u16::from_le_bytes([bytes[6], bytes[7]]));
let h = u32::from(u16::from_le_bytes([bytes[8], bytes[9]]));
if w > 0 && h > 0 {
return Some((w, h));
}
}
// WebP (RIFF....WEBP): VP8X extended header.
if bytes.len() >= 30
&& &bytes[0..4] == b"RIFF"
&& &bytes[8..12] == b"WEBP"
&& &bytes[12..16] == b"VP8X"
{
let w =
1 + (u32::from(bytes[24]) | (u32::from(bytes[25]) << 8) | (u32::from(bytes[26]) << 16));
let h =
1 + (u32::from(bytes[27]) | (u32::from(bytes[28]) << 8) | (u32::from(bytes[29]) << 16));
if w > 0 && h > 0 {
return Some((w, h));
}
}
// JPEG: scan SOF0..SOF2 markers (`0xFF 0xC0..=0xC2`).
if bytes.len() >= 4 && bytes[0] == 0xFF && bytes[1] == 0xD8 {
let mut i = 2usize;
while i + 4 <= bytes.len() {
if bytes[i] != 0xFF {
break;
}
let marker = bytes[i + 1];
i += 2;
if marker == 0xD9 || marker == 0xDA {
break;
}
if i + 2 > bytes.len() {
break;
}
let seg_len = usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]]));
if seg_len < 2 || i + seg_len > bytes.len() {
break;
}
if matches!(marker, 0xC0..=0xC2) && seg_len >= 7 {
let h = u32::from(u16::from_be_bytes([bytes[i + 3], bytes[i + 4]]));
let w = u32::from(u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]));
if w > 0 && h > 0 {
return Some((w, h));
}
}
i += seg_len;
}
}
None
}
/// Source context required by source-scoped Blob REST endpoints (`v0.27.5`).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum BlobSource {
enum WireBlobSource {
#[serde(rename_all = "camelCase")]
CurrentDoc {
workspace_id: String,
@@ -104,43 +17,62 @@ pub enum BlobSource {
},
}
impl BlobSource {
pub fn source_type_str(&self) -> &'static str {
match self {
Self::CurrentDoc { .. } => "currentDoc",
Self::History { .. } => "history",
}
fn source_doc_id(source: &BlobSource) -> &str {
match source {
BlobSource::CurrentDoc { doc_id, .. } | BlobSource::History { doc_id, .. } => doc_id,
}
}
pub fn doc_id(&self) -> &str {
match self {
Self::CurrentDoc { doc_id, .. } | Self::History { doc_id, .. } => doc_id,
}
}
mod source_wire {
use super::{BlobSource, WireBlobSource};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn timestamp_ms(&self) -> Option<i64> {
match self {
Self::CurrentDoc { .. } => None,
Self::History { timestamp_ms, .. } => Some(*timestamp_ms),
}
}
fn with_doc_id(&self, next_doc_id: String) -> Self {
match self {
Self::CurrentDoc { workspace_id, .. } => Self::CurrentDoc {
workspace_id: workspace_id.clone(),
doc_id: next_doc_id,
},
Self::History {
pub(super) fn serialize<S: Serializer>(
source: &BlobSource,
serializer: S,
) -> Result<S::Ok, S::Error> {
let source = match source.clone() {
BlobSource::CurrentDoc {
workspace_id,
timestamp_ms,
..
} => Self::History {
workspace_id: workspace_id.clone(),
doc_id: next_doc_id,
timestamp_ms: *timestamp_ms,
doc_id,
} => WireBlobSource::CurrentDoc {
workspace_id,
doc_id,
},
}
BlobSource::History {
workspace_id,
doc_id,
timestamp_ms,
} => WireBlobSource::History {
workspace_id,
doc_id,
timestamp_ms,
},
};
source.serialize(serializer)
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<BlobSource, D::Error> {
Ok(match WireBlobSource::deserialize(deserializer)? {
WireBlobSource::CurrentDoc {
workspace_id,
doc_id,
} => BlobSource::CurrentDoc {
workspace_id,
doc_id,
},
WireBlobSource::History {
workspace_id,
doc_id,
timestamp_ms,
} => BlobSource::History {
workspace_id,
doc_id,
timestamp_ms,
},
})
}
}
@@ -168,6 +100,7 @@ pub struct SourceBlobRecord {
pub size: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(with = "source_wire")]
pub source: BlobSource,
}
@@ -211,22 +144,22 @@ fn hex_upper(nibble: u8) -> char {
}
fn source_query_string(source: &BlobSource, id_converter: &IdConverter) -> String {
let wire_doc_id = id_converter.new_id_to_old_id(source.doc_id());
let mut query = format!(
"sourceType={}&docId={}",
encode_uri_component(source.source_type_str()),
encode_uri_component(&wire_doc_id)
);
if let Some(ts) = source.timestamp_ms() {
query.push_str(&format!("&timestampMs={ts}"));
let wire_doc_id = id_converter.legacy_storage_key(source_doc_id(source));
let doc_id = encode_uri_component(&wire_doc_id);
match source {
BlobSource::CurrentDoc { .. } => format!("sourceType=currentDoc&docId={doc_id}"),
BlobSource::History { timestamp_ms, .. } => {
format!("sourceType=history&docId={doc_id}&timestampMs={timestamp_ms}")
}
}
query
}
fn normalize_manifest_entries(entries: &mut [SourceBlobRecord], id_converter: &IdConverter) {
for entry in entries {
let local_doc_id = id_converter.old_id_to_new_id(entry.source.doc_id());
entry.source = entry.source.with_doc_id(local_doc_id);
let doc_id = match &mut entry.source {
BlobSource::CurrentDoc { doc_id, .. } | BlobSource::History { doc_id, .. } => doc_id,
};
*doc_id = id_converter.local_storage_key(doc_id);
}
}
@@ -379,11 +312,11 @@ mod tests {
let parsed = decode_readable_blob_manifest_v1(manifest_json, &converter).unwrap();
assert_eq!(parsed.version, 1);
assert_eq!(parsed.entries.len(), 1);
assert_eq!(parsed.entries[0].source.doc_id(), "page-local");
assert_eq!(source_doc_id(&parsed.entries[0].source), "page-local");
assert_eq!(parsed.next_cursor.as_deref(), Some("next-1"));
let single_json = br#"{"version":1,"entries":[{"key":"b2","mime":"text/plain","size":4,"source":{"type":"history","workspaceId":"ws-1","docId":"db$ws-1$folders","timestampMs":42}}]}"#;
let single = decode_blob_manifest_v1(single_json, &converter).unwrap();
assert_eq!(single.entries[0].source.doc_id(), "db$folders");
assert_eq!(source_doc_id(&single.entries[0].source), "db$folders");
}
}
@@ -0,0 +1,544 @@
//! Pure sans-I/O authentication state machine and `0.27.5` `StoredAuthTokenPair` codec.
//!
//! ## Single Refresh Owner Architecture
//! Native platform hosts (`hosts/ios` `LegacyAuthBridge` and `hosts/android` `AuthSessionStore`)
//! are the sole I/O owners for Keychain/Keystore persistence and single-flight network
//! `/api/auth/session/{exchange,refresh,revoke}` execution. [`AuthController`] performs zero
//! network I/O and zero credential writes; host coordinators feed outcomes into
//! [`AuthController::apply_native_tokens`], [`AuthController::clear_native_session`], and
//! [`AuthController::apply_session_response`].
use crate::sync::SocketAuthMode;
use crate::{
api_client::{
ApiHttpRequest, ApiRequestContext, AuthSessionMeta, AuthSessionUser, AuthTokenPairResponse,
build_get_auth_session_request, decode_auth_session_response,
},
auth::{
MAX_EXPIRES_IN_SECS, parse_and_validate_token_pair_response, validate_token_pair_fields,
},
};
use serde::{Deserialize, Serialize};
use affine_client::{ClientError, ClientResult, host::HostKind};
/// Seconds between Unix epoch (`1970-01-01T00:00:00Z`) and Apple CoreFoundation / `Date`
/// reference epoch (`2001-01-01T00:00:00Z`).
pub const APPLE_CF_EPOCH_OFFSET_SECS: f64 = 978_307_200.0;
/// Native host storage format selector preventing iOS CF-epoch integer-second ambiguity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NativeAuthPlatform {
/// iOS Keychain JSON (`accessExpiresAt` encoded as 2001 CoreFoundation epoch seconds).
Ios,
/// Android DataStore JSON (`accessExpiresAt` encoded as 1970 Unix milliseconds).
Android,
}
/// Canonical `0.27.5` persisted native token pair (`StoredAuthTokenPair`).
///
/// Stores `version = 1`, absolute `accessExpiresAt` (Unix ms in memory / Android DataStore,
/// convertible losslessly to/from iOS 2001 CF epoch seconds), and nested `session: { id, absoluteExpiresAt }`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredAuthTokenPair {
pub version: u32,
pub token_type: String,
pub access_token: String,
pub access_expires_at: i64,
pub refresh_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_expires_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session: Option<AuthSessionMeta>,
}
/// Alias preserving compatibility for callers referring to `NativeTokenPair`.
pub type NativeTokenPair = StoredAuthTokenPair;
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IosKeychainTokenPairWire {
version: u32,
token_type: String,
access_token: String,
access_expires_at: f64,
refresh_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
refresh_expires_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
session: Option<AuthSessionMeta>,
}
impl StoredAuthTokenPair {
/// Maximum `expires_in` accepted from a native token endpoint (`24h`, matching `0.27.5`
/// `AuthPlugin.swift` / `AuthPlugin.kt`).
pub const MAX_EXPIRES_IN_SECS: u64 = MAX_EXPIRES_IN_SECS;
fn validate_invariant_fields(&self) -> ClientResult<()> {
validate_token_pair_fields(
self.version,
&self.token_type,
&self.access_token,
&self.refresh_token,
self.refresh_expires_at.as_deref(),
self.session.as_ref(),
)
.map_err(|err| ClientError::InvalidAuthPayload(err.to_string()))
}
/// Validate and convert a server [`AuthTokenPairResponse`] into a [`StoredAuthTokenPair`]
/// using an explicit deterministic `now_ms`.
///
/// Rejects non-`Bearer` `token_type`, empty tokens, out-of-range `expires_in`
/// (`1..=86_400`), and malformed RFC 3339 timestamps.
pub fn from_wire(parsed: AuthTokenPairResponse, now_ms: i64) -> ClientResult<Self> {
let validated = parse_and_validate_token_pair_response(parsed, now_ms)
.map_err(|err| ClientError::InvalidAuthPayload(err.to_string()))?;
Ok(Self {
version: validated.version,
token_type: validated.token_type,
access_token: validated.access_token,
access_expires_at: validated.access_expires_at_ms,
refresh_token: validated.refresh_token,
refresh_expires_at: validated.refresh_expires_at,
session: validated.session,
})
}
pub fn session_id(&self) -> Option<&str> {
self.session.as_ref().map(|s| s.id.as_str())
}
pub fn access_expires_at_unix_ms(&self) -> i64 {
self.access_expires_at
}
/// Convert `access_expires_at` (Unix ms) to iOS `Date` / CF 2001 epoch seconds.
pub fn access_expires_at_ios_cf_secs(&self) -> f64 {
(self.access_expires_at as f64 / 1_000.0) - APPLE_CF_EPOCH_OFFSET_SECS
}
/// Convert iOS `Date` / CF 2001 epoch seconds back to Unix milliseconds.
pub fn unix_ms_from_ios_cf_secs(cf_secs: f64) -> i64 {
((cf_secs + APPLE_CF_EPOCH_OFFSET_SECS) * 1_000.0).round() as i64
}
/// Serialize to the exact `0.27.5` Android DataStore JSON format (Unix ms `accessExpiresAt`).
pub fn to_android_datastore_json(&self) -> ClientResult<String> {
Ok(serde_json::to_string(self)?)
}
/// Deserialize from the exact `0.27.5` Android DataStore JSON format.
pub fn from_android_datastore_json(raw: &str) -> ClientResult<Self> {
let pair: Self = serde_json::from_str(raw)?;
pair.validate_invariant_fields()?;
Ok(pair)
}
/// Serialize to the exact `0.27.5` iOS Keychain JSON format (2001 CF epoch seconds `accessExpiresAt`).
pub fn to_ios_keychain_json(&self) -> ClientResult<String> {
let wire = IosKeychainTokenPairWire {
version: self.version,
token_type: self.token_type.clone(),
access_token: self.access_token.clone(),
access_expires_at: self.access_expires_at_ios_cf_secs(),
refresh_token: self.refresh_token.clone(),
refresh_expires_at: self.refresh_expires_at.clone(),
session: self.session.clone(),
};
Ok(serde_json::to_string(&wire)?)
}
/// Deserialize from the exact `0.27.5` iOS Keychain JSON format.
pub fn from_ios_keychain_json(raw: &str) -> ClientResult<Self> {
let wire: IosKeychainTokenPairWire = serde_json::from_str(raw)?;
if !wire.access_expires_at.is_finite() {
return Err(ClientError::InvalidAuthPayload(
"iOS accessExpiresAt must be finite".into(),
));
}
let pair = Self {
version: wire.version,
token_type: wire.token_type,
access_token: wire.access_token,
access_expires_at: Self::unix_ms_from_ios_cf_secs(wire.access_expires_at),
refresh_token: wire.refresh_token,
refresh_expires_at: wire.refresh_expires_at,
session: wire.session,
};
pair.validate_invariant_fields()?;
Ok(pair)
}
}
/// Active session state for a single server.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthSessionState {
SignedOut,
Authenticated { user: AuthSessionUser },
}
/// Pure sans-I/O per-server authentication state machine.
#[derive(Clone, Debug)]
pub struct AuthController {
server_id: String,
base_url: String,
host_kind: HostKind,
state: AuthSessionState,
native_tokens: Option<StoredAuthTokenPair>,
mutation_epoch: u64,
}
impl AuthController {
pub fn new(
server_id: impl Into<String>,
base_url: impl Into<String>,
host_kind: HostKind,
) -> Self {
Self {
server_id: server_id.into(),
base_url: base_url.into().trim().trim_end_matches('/').to_string(),
host_kind,
state: AuthSessionState::SignedOut,
native_tokens: None,
mutation_epoch: 0,
}
}
pub fn server_id(&self) -> &str {
&self.server_id
}
pub fn base_url(&self) -> &str {
&self.base_url
}
/// Endpoint-scoped credential key (`auth:<canonical_base_url>`) isolating credentials by URL.
pub fn credential_key(&self) -> String {
format!("auth:{}", self.base_url)
}
pub fn mutation_epoch(&self) -> u64 {
self.mutation_epoch
}
pub fn state(&self) -> &AuthSessionState {
&self.state
}
pub fn native_tokens(&self) -> Option<&StoredAuthTokenPair> {
self.native_tokens.as_ref()
}
/// Hydrate offline cached user profile (for example from `global-state:<serverId>-auth`)
/// so transient `5xx`/`429`/network failures preserve the cached signed-in UI state.
pub fn set_cached_user(&mut self, user: AuthSessionUser) {
self.state = AuthSessionState::Authenticated { user };
}
/// Sync newly exchanged or refreshed tokens produced by the native host coordinator.
pub fn apply_native_tokens(&mut self, pair: StoredAuthTokenPair) {
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.native_tokens = Some(pair);
}
/// Clear in-memory tokens and transition to `SignedOut` after host-owned revoke/sign-out.
pub fn clear_native_session(&mut self) {
self.mutation_epoch = self.mutation_epoch.saturating_add(1);
self.native_tokens = None;
self.state = AuthSessionState::SignedOut;
}
/// Build the frozen [`ApiRequestContext`] for this host kind and current credential state.
pub fn api_context(&self) -> ApiRequestContext {
match self.host_kind {
HostKind::Web => ApiRequestContext::web(),
HostKind::Native => ApiRequestContext::native(
self.native_tokens.as_ref().map(|t| t.access_token.clone()),
),
}
}
/// Build the Socket.IO `40` CONNECT [`SocketAuthMode`] for `SpaceSyncEngine`.
///
/// Native hosts without stored tokens return [`SocketAuthMode::Unauthenticated`] and never
/// fall back to [`SocketAuthMode::WebCookie`].
pub fn socket_auth_mode(&self) -> SocketAuthMode {
match self.host_kind {
HostKind::Web => SocketAuthMode::WebCookie,
HostKind::Native => match &self.native_tokens {
Some(tokens) => SocketAuthMode::NativeJwt {
token: tokens.access_token.clone(),
},
None => SocketAuthMode::Unauthenticated,
},
}
}
/// Build a transport-agnostic `GET /api/auth/session` request for the host to execute.
pub fn build_session_request(&self) -> ApiHttpRequest {
build_get_auth_session_request(&self.api_context())
}
/// Build a `GET /api/auth/session` request paired with the current `mutation_epoch` so
/// late responses arriving after sign-out or token rotation can be discarded safely.
pub fn build_fenced_session_request(&self) -> (u64, ApiHttpRequest) {
(self.mutation_epoch, self.build_session_request())
}
/// Apply a fenced `GET /api/auth/session` response only when `request_epoch` still matches
/// [`Self::mutation_epoch`]. Returns `Ok(None)` without mutating state on stale epochs.
pub fn apply_fenced_session_response(
&mut self,
request_epoch: u64,
status: u16,
body: &[u8],
) -> ClientResult<Option<AuthSessionState>> {
if request_epoch != self.mutation_epoch {
return Ok(None);
}
self.apply_session_response(status, body).map(Some)
}
/// Apply a `GET /api/auth/session` HTTP response to [`AuthSessionState`].
///
/// Transitions to `SignedOut` ONLY on `401`/`403` or `200 { user: null }`. Any other error
/// status (`>= 400`, including `429` and `5xx`) returns `Err` and preserves `self.state`.
pub fn apply_session_response(
&mut self,
status: u16,
body: &[u8],
) -> ClientResult<AuthSessionState> {
if status == 401 || status == 403 {
self.state = AuthSessionState::SignedOut;
return Ok(self.state.clone());
}
if status >= 400 {
return Err(ClientError::Host(format!(
"fetch session failed with transient HTTP {status}"
)));
}
let decoded = decode_auth_session_response(body)?;
self.state = match decoded.user {
Some(user) => AuthSessionState::Authenticated { user },
None => AuthSessionState::SignedOut,
};
Ok(self.state.clone())
}
/// Read a credential payload that the host retrieved from its vault.
pub fn load_stored_credentials(
&mut self,
raw: Option<&str>,
platform: NativeAuthPlatform,
) -> bool {
if self.host_kind != HostKind::Native {
return false;
}
let Some(raw) = raw else {
self.clear_native_session();
return false;
};
let parsed = match platform {
NativeAuthPlatform::Ios => StoredAuthTokenPair::from_ios_keychain_json(raw),
NativeAuthPlatform::Android => StoredAuthTokenPair::from_android_datastore_json(raw),
};
match parsed {
Ok(pair) => {
self.apply_native_tokens(pair);
true
}
Err(_) => {
self.clear_native_session();
false
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use affine_client::host::{HostBridge, MemoryHostBridge};
#[test]
fn ios_integer_and_fractional_cf_epoch_seconds_decode_explicitly_without_android_ambiguity() {
let mut host = MemoryHostBridge::new(HostKind::Native, "inst-ios");
let mut auth =
AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native);
// Integer CF epoch seconds (Swift JSONEncoder emits `800000000` without `.0`).
let ios_int = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-int","accessExpiresAt":800000000,"refreshToken":"rt-int","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-int","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), ios_int);
assert!(
auth.load_stored_credentials(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
NativeAuthPlatform::Ios,
)
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_778_307_200_000
);
// Fractional CF epoch seconds `800000000.5` -> `1778307200500` ms.
let ios_frac = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-frac","accessExpiresAt":800000000.5,"refreshToken":"rt-frac","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-frac","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), ios_frac);
assert!(
auth.load_stored_credentials(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
NativeAuthPlatform::Ios,
)
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_778_307_200_500
);
// Android DataStore fixture (`1970` Unix ms) roundtrips cleanly with Android selector.
let android_json = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-and","accessExpiresAt":1795622400000,"refreshToken":"rt-and","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-and","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(auth.credential_key(), android_json);
assert!(
auth.load_stored_credentials(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
NativeAuthPlatform::Android,
)
);
assert_eq!(
auth.native_tokens().unwrap().access_expires_at_unix_ms(),
1_795_622_400_000
);
}
#[test]
fn deleted_host_credential_clears_stale_jwt_and_from_wire_validates_fields() {
let mut host = MemoryHostBridge::new(HostKind::Native, "inst-1");
let mut auth =
AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native);
let valid_wire = AuthTokenPairResponse {
token_type: Some("Bearer".into()),
access_token: "at-1".into(),
refresh_token: "rt-1".into(),
expires_in: Some(3600),
refresh_expires_at: Some("2026-12-01T00:00:00Z".into()),
session: Some(AuthSessionMeta {
id: "sess-1".into(),
absolute_expires_at: Some("2027-01-01T00:00:00Z".into()),
}),
session_id: None,
};
let pair = StoredAuthTokenPair::from_wire(valid_wire.clone(), 1_700_000_000_000).unwrap();
auth.apply_native_tokens(pair);
assert_eq!(
auth.socket_auth_mode(),
SocketAuthMode::NativeJwt {
token: "at-1".into()
}
);
// Host vault has no credential (deleted by host coordinator) -> clears in-memory JWT.
assert!(
!auth.load_stored_credentials(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
NativeAuthPlatform::Android,
)
);
assert_eq!(auth.socket_auth_mode(), SocketAuthMode::Unauthenticated);
assert_eq!(auth.state(), &AuthSessionState::SignedOut);
// `from_wire` rejects non-Bearer, zero expiresIn, and malformed RFC3339 timestamps.
let mut bad_type = valid_wire.clone();
bad_type.token_type = Some("Basic".into());
assert!(StoredAuthTokenPair::from_wire(bad_type, 1_000).is_err());
let mut zero_exp = valid_wire.clone();
zero_exp.expires_in = Some(0);
assert!(StoredAuthTokenPair::from_wire(zero_exp, 1_000).is_err());
let mut bad_refresh_ts = valid_wire.clone();
bad_refresh_ts.refresh_expires_at = Some("not-a-date".into());
assert!(StoredAuthTokenPair::from_wire(bad_refresh_ts, 1_000).is_err());
let mut bad_abs_ts = valid_wire.clone();
bad_abs_ts.session.as_mut().unwrap().absolute_expires_at = Some("2027-99-99".into());
assert!(StoredAuthTokenPair::from_wire(bad_abs_ts, 1_000).is_err());
// Non-ASCII UTF-8 boundary and impossible calendar dates never panic and return Err.
let mut non_ascii_ts = valid_wire.clone();
non_ascii_ts.refresh_expires_at = Some("2026-12-01T00:00:0é0Z".into());
assert!(StoredAuthTokenPair::from_wire(non_ascii_ts, 1_000).is_err());
let mut feb_31_ts = valid_wire.clone();
feb_31_ts.refresh_expires_at = Some("2026-02-31T00:00:00Z".into());
assert!(StoredAuthTokenPair::from_wire(feb_31_ts, 1_000).is_err());
// Excess `expiresIn` (> 86_400) and empty tokens are rejected.
let mut huge_exp = valid_wire.clone();
huge_exp.expires_in = Some(86_401);
assert!(StoredAuthTokenPair::from_wire(huge_exp, 1_000).is_err());
let mut empty_tok = valid_wire;
empty_tok.access_token = String::new();
assert!(StoredAuthTokenPair::from_wire(empty_tok, 1_000).is_err());
// Corrupt JSON in host vault leaves vault untouched while clearing in-memory state.
host.seed_credential(auth.credential_key(), "{corrupt");
assert!(
!auth.load_stored_credentials(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
NativeAuthPlatform::Android,
)
);
assert_eq!(
host.read_credential(&auth.credential_key())
.unwrap()
.as_deref(),
Some("{corrupt")
);
// Epoch-fenced session responses ignore stale in-flight completions after sign-out/rotation.
let (stale_epoch, _req) = auth.build_fenced_session_request();
auth.clear_native_session();
assert_eq!(
auth.apply_fenced_session_response(
stale_epoch,
200,
br#"{"user":{"id":"u-stale","name":"Stale"}}"#,
)
.unwrap(),
None
);
assert_eq!(auth.state(), &AuthSessionState::SignedOut);
// Sans-I/O session response: 503/429 preserves cached user; 401/403 signs out.
auth.set_cached_user(AuthSessionUser {
id: "u1".into(),
email: None,
name: Some("Alice".into()),
avatar_url: None,
});
let req = auth.build_session_request();
assert_eq!(req.path, "/api/auth/session");
assert!(auth.apply_session_response(503, b"unavailable").is_err());
assert!(matches!(
auth.state(),
AuthSessionState::Authenticated { .. }
));
assert_eq!(
auth.apply_session_response(401, b"{}").unwrap(),
AuthSessionState::SignedOut
);
}
}
+10
View File
@@ -0,0 +1,10 @@
#![forbid(unsafe_code)]
pub mod api_client;
pub mod auth;
pub mod blob_api;
pub mod client_auth;
pub mod peer;
pub mod sync;
use affine_store::{error, id_converter};
+869
View File
@@ -0,0 +1,869 @@
//! Translate typed document addresses and events at the transport boundary.
use affine_client::{
ClientResult, WorkspaceSession,
auth::ConnectionAuth,
remote::{DocumentPeer, PeerInput, PeerTransportAction, PushUpdate, RemoteError, RemoteResult},
};
use affine_store::{
AccountScope, CanonicalOrigin, CommitReceipt, DocAddress, DocDiff, DocRoute, IdConverter,
LocalSeq, PeerOperation, PeerSyncEvent, PeerSyncState, PushIntent, SpaceKind, StoreError,
UserspaceResource,
};
use crate::{
api_client::HEADER_AFFINE_VERSION,
sync::{
DEFAULT_CLIENT_VERSION, DocLifecycleAction, EngineIoOutput, PushDocIntent,
SPACE_DELETE_DOC, SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_LOAD_DOC,
SPACE_LOAD_DOC_TIMESTAMPS, SPACE_PUSH_DOC_UPDATE, SocketAuthMode, SpaceSyncConfig,
SpaceSyncEngine, SpaceSyncEvent, SpaceSyncOutbound, SpaceSyncState, SpaceType,
},
};
pub struct LegacyDocumentPeer {
scope: AccountScope,
space: SpaceKind,
engine: SpaceSyncEngine,
signed_out: bool,
}
impl LegacyDocumentPeer {
pub fn new(scope: AccountScope, space: SpaceKind, converter: IdConverter) -> Self {
let (space_type, id) = match &space {
SpaceKind::Workspace(id) => (SpaceType::Workspace, id),
SpaceKind::Userspace(id) => (SpaceType::Userspace, id),
};
let mut config = SpaceSyncConfig::workspace(id, false);
config.space_type = space_type;
config.account_id = Some(scope.user_id.clone());
Self {
scope,
space,
engine: SpaceSyncEngine::new(config, converter),
signed_out: false,
}
}
/// Attach the adapter to an existing workspace without changing its local documents.
pub fn bind_workspace(session: &mut WorkspaceSession) -> ClientResult<()> {
if session.document_peer().is_some() {
return Ok(());
}
let scope = AccountScope {
origin: CanonicalOrigin::parse(session.auth().base_url())?,
user_id: session
.directory()
.lock_directory()
.db()
.user_id()
.to_owned(),
};
let id = session.space_id().to_owned();
session.bind_document_peer(Box::new(Self::new(
scope,
SpaceKind::Workspace(id.clone()),
IdConverter::new(id),
)))
}
pub fn engine(&self) -> &SpaceSyncEngine {
&self.engine
}
fn local_id(&self, address: &DocAddress) -> RemoteResult<String> {
if address.scope != self.scope {
return Err(RemoteError::PermissionRevoked);
}
match (&self.space, &address.route) {
(SpaceKind::Workspace(id), DocRoute::Workspace { .. }) => address
.workspace_storage_key(&self.scope, id)
.ok_or(RemoteError::PermissionRevoked),
(
SpaceKind::Userspace(expected),
DocRoute::Userspace {
id,
resource: UserspaceResource::EditorSetting,
},
) if id == expected && id == &self.scope.user_id => Ok("editorSetting".into()),
_ => Err(RemoteError::PermissionRevoked),
}
}
fn address(&self, local_id: String) -> Option<DocAddress> {
let route = match &self.space {
SpaceKind::Workspace(id) => {
return DocAddress::from_workspace_storage_key(self.scope.clone(), id, &local_id);
}
SpaceKind::Userspace(id) => {
if local_id != "editorSetting" || id != &self.scope.user_id {
return None;
}
DocRoute::Userspace {
id: id.clone(),
resource: UserspaceResource::EditorSetting,
}
}
};
Some(DocAddress {
scope: self.scope.clone(),
route,
})
}
fn convert_event(&self, event: SpaceSyncEvent) -> Option<PeerSyncEvent> {
Some(match event {
SpaceSyncEvent::Joined { .. } => PeerSyncEvent::Ready,
SpaceSyncEvent::DocsJoined { doc_ids } => PeerSyncEvent::Subscribed {
addresses: doc_ids
.into_iter()
.filter_map(|id| self.address(id))
.collect(),
},
SpaceSyncEvent::DocLoaded {
doc_id,
missing,
state,
timestamp,
} => PeerSyncEvent::Loaded {
address: self.address(doc_id)?,
diff: DocDiff {
state_vector_v1: state,
update_v1: missing,
},
timestamp_ms: timestamp,
},
SpaceSyncEvent::DocNotFound { doc_id } => PeerSyncEvent::Missing {
address: self.address(doc_id)?,
},
SpaceSyncEvent::DocUpdatePushed {
doc_id,
local_seq,
timestamp,
..
} => PeerSyncEvent::Committed {
receipt: CommitReceipt {
address: self.address(doc_id)?,
seq: LocalSeq(local_seq?),
},
timestamp_ms: timestamp,
},
SpaceSyncEvent::DocTimestampsLoaded { timestamps } => PeerSyncEvent::Inventory {
timestamps: timestamps
.into_iter()
.filter_map(|(id, time)| self.address(id).map(|address| (address, time)))
.collect(),
},
SpaceSyncEvent::DocDeleted { doc_id } => PeerSyncEvent::Deleted {
addresses: vec![self.address(doc_id)?],
},
SpaceSyncEvent::DocLifecycleApplied {
doc_id,
lifecycle: DocLifecycleAction::Delete,
deleted_doc_ids,
..
} => PeerSyncEvent::Deleted {
addresses: std::iter::once(doc_id)
.chain(deleted_doc_ids.into_iter().flatten())
.filter_map(|id| self.address(id))
.collect(),
},
SpaceSyncEvent::DocLifecycleApplied { .. } => return None,
SpaceSyncEvent::RemoteDocUpdates {
doc_id,
updates,
timestamp,
..
} => PeerSyncEvent::Updated {
address: self.address(doc_id)?,
updates_v1: updates,
timestamp_ms: timestamp,
},
SpaceSyncEvent::DocInvalidated {
inventory_changed, ..
} => PeerSyncEvent::Invalidated { inventory_changed },
SpaceSyncEvent::AwarenessRequested { doc_id } => PeerSyncEvent::AwarenessRequested {
address: self.address(doc_id)?,
},
SpaceSyncEvent::Awareness { doc_id, update_v1 } => PeerSyncEvent::Awareness {
address: self.address(doc_id)?,
update_v1,
},
SpaceSyncEvent::AuthRequired { doc_id, .. } => PeerSyncEvent::AuthRequired {
address: doc_id.and_then(|id| self.address(id)),
},
SpaceSyncEvent::PermissionRevoked { doc_id, .. } => PeerSyncEvent::PermissionRevoked {
address: doc_id.and_then(|id| self.address(id)),
},
SpaceSyncEvent::RequestFailed {
op, doc_id, reason, ..
} => PeerSyncEvent::RequestFailed {
reason,
operation: match op {
SPACE_LOAD_DOC => PeerOperation::Load,
SPACE_JOIN_BATCH => PeerOperation::Subscribe,
SPACE_LOAD_DOC_TIMESTAMPS => PeerOperation::InspectInventory,
SPACE_DELETE_DOC | SPACE_DOC_LIFECYCLE => PeerOperation::Delete,
SPACE_PUSH_DOC_UPDATE => PeerOperation::Push,
_ => PeerOperation::Connect,
},
address: doc_id.and_then(|id| self.address(id)),
},
SpaceSyncEvent::Disconnected { .. } => PeerSyncEvent::Disconnected,
})
}
}
fn convert_error(err: StoreError) -> RemoteError {
match err {
StoreError::PermissionRevoked { .. } => RemoteError::PermissionRevoked,
other => RemoteError::Protocol(other.to_string()),
}
}
impl DocumentPeer for LegacyDocumentPeer {
fn state(&self) -> PeerSyncState {
match self.engine.state() {
SpaceSyncState::Offline => PeerSyncState::Offline,
SpaceSyncState::Connecting | SpaceSyncState::Joining => PeerSyncState::Connecting,
SpaceSyncState::Ready => PeerSyncState::Ready,
SpaceSyncState::ReconnectScheduled { next_attempt_at_ms } => {
PeerSyncState::ReconnectScheduled { next_attempt_at_ms }
}
SpaceSyncState::AuthRequired => PeerSyncState::AuthRequired,
SpaceSyncState::PermissionRevoked => PeerSyncState::PermissionRevoked,
}
}
fn pending_pushes(&self) -> usize {
self.engine.pending_pushes()
}
fn load(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()> {
let id = self.local_id(&address)?;
self.engine
.load_doc(&id, None, now_ms)
.map(|_| ())
.map_err(convert_error)
}
fn diff(
&mut self,
address: DocAddress,
state_vector_v1: Vec<u8>,
now_ms: i64,
) -> RemoteResult<()> {
let id = self.local_id(&address)?;
self.engine
.load_doc(&id, Some(&state_vector_v1), now_ms)
.map(|_| ())
.map_err(convert_error)
}
fn push(&mut self, update: PushUpdate, now_ms: i64) -> RemoteResult<()> {
let id = self.local_id(&update.address)?;
let intent = match update.intent {
PushIntent::Create => PushDocIntent::Create,
PushIntent::Update => PushDocIntent::Update,
};
self.engine
.push_doc_update_with_seq(id, update.update_v1, intent, Some(update.seq.0), now_ms)
.map_err(convert_error)
}
fn subscribe(&mut self, addresses: &[DocAddress], now_ms: i64) -> RemoteResult<()> {
let ids = addresses
.iter()
.map(|address| self.local_id(address))
.collect::<RemoteResult<Vec<_>>>()?;
let ids = ids.iter().map(String::as_str).collect::<Vec<_>>();
self.engine
.join_docs(&ids, now_ms)
.map(|_| ())
.map_err(convert_error)
}
fn unsubscribe(&mut self, addresses: &[DocAddress], now_ms: i64) -> RemoteResult<()> {
let ids = addresses
.iter()
.map(|address| self.local_id(address))
.collect::<RemoteResult<Vec<_>>>()?;
self.engine.leave_docs(&ids, now_ms).map_err(convert_error)
}
fn delete(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()> {
let id = self.local_id(&address)?;
self.engine
.delete_doc(&id, now_ms)
.map(|_| ())
.map_err(convert_error)
}
fn discard(&mut self, address: &DocAddress) {
if let Ok(id) = self.local_id(address) {
self.engine.discard_offline_writes_for_doc(&id);
}
}
fn request_inventory(&mut self, now_ms: i64) -> RemoteResult<()> {
self.engine
.load_doc_timestamps(None, now_ms)
.map(|_| ())
.map_err(convert_error)
}
fn request_awareness(&mut self, address: DocAddress, now_ms: i64) -> RemoteResult<()> {
let id = self.local_id(&address)?;
self.engine
.request_awareness(&id, now_ms)
.map_err(convert_error)
}
fn publish_awareness(
&mut self,
address: DocAddress,
update_v1: Vec<u8>,
now_ms: i64,
) -> RemoteResult<()> {
let id = self.local_id(&address)?;
self.engine
.publish_awareness(&id, &update_v1, now_ms)
.map_err(convert_error)
}
fn drain_events(&mut self) -> Vec<PeerSyncEvent> {
self.engine
.drain_events()
.into_iter()
.filter_map(|event| self.convert_event(event))
.collect()
}
fn on_input(&mut self, input: PeerInput<'_>, now_ms: i64) -> RemoteResult<()> {
match input {
PeerInput::Connect(auth) | PeerInput::CredentialsChanged(auth) => {
if matches!(auth, ConnectionAuth::SignedOut) {
self.signed_out = true;
self.engine.set_auth_mode(SocketAuthMode::Unauthenticated);
self.engine.drain_outbound();
self.engine.disconnect(now_ms);
if matches!(input, PeerInput::Connect(_)) {
return Err(RemoteError::SessionExpired);
}
return Ok(());
}
self.signed_out = false;
let mode = match auth {
ConnectionAuth::Browser => SocketAuthMode::WebCookie,
ConnectionAuth::Native(Some(token)) => SocketAuthMode::NativeJwt {
token: token.to_owned(),
},
ConnectionAuth::Native(None) | ConnectionAuth::SignedOut => {
SocketAuthMode::Unauthenticated
}
};
let state = self.engine.state();
if state == SpaceSyncState::AuthRequired
&& matches!(input, PeerInput::CredentialsChanged(_))
{
self.engine
.resume_with_auth(Some(self.scope.user_id.clone()), mode, now_ms);
} else {
self.engine.set_auth_mode(mode);
if matches!(input, PeerInput::Connect(_))
&& matches!(
state,
SpaceSyncState::Offline | SpaceSyncState::ReconnectScheduled { .. }
)
{
self.engine.connect(now_ms);
}
}
}
_ if self.signed_out => {}
PeerInput::Opened => self.engine.on_ws_open(now_ms),
PeerInput::Text(frame) => self
.engine
.on_ws_text(frame, now_ms)
.map_err(convert_error)?,
PeerInput::Binary(bytes) => self
.engine
.on_ws_binary(bytes.to_vec(), now_ms)
.map_err(convert_error)?,
PeerInput::TransportLost(reason) => {
// Frames from the old connection must not escape after a reconnect.
self.engine.drain_outbound();
self.engine.on_ws_error(reason, now_ms);
}
PeerInput::Tick => self.engine.on_tick(now_ms).map_err(convert_error)?,
}
Ok(())
}
fn next_transport_action(&mut self) -> Option<PeerTransportAction> {
while let Some(item) = self.engine.pop_outbound() {
if let SpaceSyncOutbound::Transport(output) = item
&& let Some(action) = self.transport_action(output)
{
return Some(action);
}
}
None
}
}
impl LegacyDocumentPeer {
fn transport_action(&self, output: EngineIoOutput) -> Option<PeerTransportAction> {
Some(match output {
EngineIoOutput::OpenWebsocket { .. } => {
let mut headers = vec![(
HEADER_AFFINE_VERSION.to_owned(),
DEFAULT_CLIENT_VERSION.to_owned(),
)];
if let SocketAuthMode::NativeJwt { token } = self.engine.auth_mode() {
headers.push(("authorization".into(), format!("Bearer {token}")));
}
PeerTransportAction::Open { headers }
}
EngineIoOutput::SendWsText(text) => PeerTransportAction::SendText(text),
EngineIoOutput::SendWsBinary(bytes) => PeerTransportAction::SendBinary(bytes),
EngineIoOutput::CloseTransport => PeerTransportAction::Close,
_ => return None,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use affine_store::{PeerFailureReason, WorkspaceResource, WorkspaceTableKind};
use serde_json::{Value, json};
#[test]
fn routes_favorites_to_workspace_and_editor_settings_to_own_userspace() {
let scope = AccountScope {
origin: CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "same".into(),
};
let favorite = DocAddress {
scope: scope.clone(),
route: DocRoute::Workspace {
id: "same".into(),
resource: WorkspaceResource::UserFavorite,
},
};
let setting = DocAddress {
scope: scope.clone(),
route: DocRoute::Userspace {
id: "same".into(),
resource: UserspaceResource::EditorSetting,
},
};
let workspace_settings = DocAddress {
scope: scope.clone(),
route: DocRoute::Workspace {
id: "same".into(),
resource: WorkspaceResource::Table(WorkspaceTableKind::UserSettings),
},
};
let workspace =
LegacyDocumentPeer::new(scope.clone(), favorite.space(), IdConverter::new("same"));
let userspace = LegacyDocumentPeer::new(scope, setting.space(), IdConverter::new("same"));
for (peer, address, id, wire) in [
(
&workspace,
&favorite,
"userdata$same$favorite",
"userdata$same$same$favorite",
),
(
&workspace,
&workspace_settings,
"userdata$same$settings",
"userdata$same$same$settings",
),
(&userspace, &setting, "editorSetting", "editorSetting"),
] {
assert_eq!(peer.local_id(address).as_deref(), Ok(id));
assert_eq!(peer.engine.id_converter().legacy_storage_key(id), wire);
assert_eq!(peer.address(id.into()).as_ref(), Some(address));
}
assert_eq!(
workspace.local_id(&setting),
Err(RemoteError::PermissionRevoked)
);
assert_eq!(
userspace.local_id(&favorite),
Err(RemoteError::PermissionRevoked)
);
let mut foreign_setting = setting;
foreign_setting.scope.user_id = "another".into();
assert_eq!(
userspace.local_id(&foreign_setting),
Err(RemoteError::PermissionRevoked)
);
}
fn start(peer: &mut LegacyDocumentPeer, time: i64) {
peer.on_input(PeerInput::Connect(ConnectionAuth::Browser), time)
.unwrap();
assert!(matches!(
peer.next_transport_action(),
Some(PeerTransportAction::Open { .. })
));
peer.on_input(PeerInput::Opened, time + 1).unwrap();
feed(
peer,
r#"0{"sid":"eio","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
time + 2,
);
assert!(
matches!(peer.next_transport_action(), Some(PeerTransportAction::SendText(frame)) if frame == "40{}")
);
feed(peer, r#"40{"sid":"socket"}"#, time + 3);
}
fn feed(peer: &mut LegacyDocumentPeer, frame: &str, time: i64) {
peer.on_input(PeerInput::Text(frame), time).unwrap();
}
fn next_request(peer: &mut LegacyDocumentPeer, event: &str) -> (u64, Value) {
while let Some(action) = peer.next_transport_action() {
if let PeerTransportAction::SendText(text) = action
&& let Some((prefix, body)) =
text.strip_prefix("42").and_then(|s| s.split_once('['))
{
let data: Value = serde_json::from_str(&format!("[{body}")).unwrap();
if data[0] == event {
return (prefix.parse().unwrap_or_default(), data[1].clone());
}
}
}
panic!("no {event} request");
}
fn ack(peer: &mut LegacyDocumentPeer, request: u64, body: Value, time: i64) {
feed(peer, &format!("43{request}[{body}]"), time);
}
fn joined(peer: &mut LegacyDocumentPeer, request: u64, time: i64) {
ack(
peer,
request,
json!({
"data": { "success": true, "clientId": "client", "protocolVersion": 1 }
}),
time,
);
}
fn scope() -> AccountScope {
AccountScope {
origin: CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "account".into(),
}
}
#[test]
fn userspace_joins_without_root_and_late_subscription_ack_cannot_revive_awareness() {
let id = "account";
let setting = DocAddress {
scope: scope(),
route: DocRoute::Userspace {
id: id.into(),
resource: UserspaceResource::EditorSetting,
},
};
let mut peer = LegacyDocumentPeer::new(scope(), setting.space(), IdConverter::new(id));
start(&mut peer, 100);
let (initial, join) = next_request(&mut peer, SPACE_JOIN_BATCH);
assert_eq!(
join["spaces"],
json!([{ "spaceType": "userspace", "spaceId": id }])
);
joined(&mut peer, initial, 110);
assert!(peer.engine.joined_wire_doc_ids().is_empty());
assert_eq!(peer.drain_events(), vec![PeerSyncEvent::Ready]);
peer.subscribe(std::slice::from_ref(&setting), 120).unwrap();
let (first, join) = next_request(&mut peer, SPACE_JOIN_BATCH);
assert_eq!(join["spaces"][0]["docId"], "editorSetting");
peer.unsubscribe(std::slice::from_ref(&setting), 121)
.unwrap();
joined(&mut peer, first, 122);
assert!(peer.engine.joined_wire_doc_ids().is_empty());
assert!(peer.drain_events().is_empty());
let (_, leave) = next_request(&mut peer, "space:leave-batch");
assert_eq!(leave["docIds"], json!(["editorSetting"]));
let binary_header = r#"451-["space:broadcast-awareness-update",{"spaceType":"userspace","spaceId":"account","docId":"editorSetting","awarenessUpdate":{"_placeholder":true,"num":0}}]"#;
let bytes = [0x11, 0xff, 0x00];
feed(&mut peer, binary_header, 123);
peer.on_input(PeerInput::Binary(&bytes), 124).unwrap();
assert!(peer.drain_events().is_empty());
assert!(
peer.publish_awareness(setting.clone(), bytes.to_vec(), 125)
.is_err()
);
peer.subscribe(std::slice::from_ref(&setting), 130).unwrap();
let (second, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, second, 131);
assert_eq!(
peer.drain_events(),
vec![PeerSyncEvent::Subscribed {
addresses: vec![setting.clone()]
}]
);
feed(&mut peer, binary_header, 132);
peer.on_input(PeerInput::Binary(&bytes), 133).unwrap();
assert_eq!(
peer.drain_events(),
vec![PeerSyncEvent::Awareness {
address: setting.clone(),
update_v1: bytes.to_vec()
}]
);
peer.publish_awareness(setting, bytes.to_vec(), 134)
.unwrap();
let (_, presence) = next_request(&mut peer, "space:update-awareness");
assert_eq!(presence["awarenessUpdate"], "Ef8A");
assert!(matches!(
peer.transport_action(EngineIoOutput::SendWsBinary(bytes.to_vec())),
Some(PeerTransportAction::SendBinary(frame)) if frame == bytes
));
}
#[test]
fn denied_join_retries_only_the_readable_document_on_this_connection_and_after_reconnect() {
let space = "workspace";
let page = |id: &str| DocAddress {
scope: scope(),
route: DocRoute::Workspace {
id: space.into(),
resource: WorkspaceResource::Page(id.into()),
},
};
let (a, b) = (page("page-a"), page("page-b"));
let mut converter = IdConverter::new(space);
converter.register_page_mapping("page-b", "guid-b");
let mut peer = LegacyDocumentPeer::new(scope(), a.space(), converter);
start(&mut peer, 10);
let (initial, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, initial, 20);
assert_eq!(peer.drain_events(), [PeerSyncEvent::Ready]);
peer.subscribe(&[a.clone(), b.clone()], 30).unwrap();
let (batch, request) = next_request(&mut peer, SPACE_JOIN_BATCH);
assert_eq!(
request["spaces"],
json!([
{ "spaceType": "workspace", "spaceId": space, "docId": "guid-b" },
{ "spaceType": "workspace", "spaceId": space, "docId": "page-a" }
])
);
ack(
&mut peer,
batch,
json!({
"error": { "name": "DOC_ACTION_DENIED", "status": 403, "message": "access revoked",
"data": { "action": "read", "spaceId": space, "docId": "guid-b" } }
}),
31,
);
assert_eq!(peer.state(), PeerSyncState::Ready);
assert_eq!(
peer.drain_events(),
[PeerSyncEvent::PermissionRevoked { address: Some(b) }]
);
let (retry, request) = next_request(&mut peer, SPACE_JOIN_BATCH);
let readable = json!([{ "spaceType": "workspace", "spaceId": space, "docId": "page-a" }]);
assert_eq!(request["spaces"], readable);
joined(&mut peer, retry, 32);
assert_eq!(
peer.drain_events(),
[PeerSyncEvent::Subscribed {
addresses: vec![a.clone()]
}]
);
peer.on_input(PeerInput::TransportLost("disconnected"), 50)
.unwrap();
assert!(matches!(
peer.next_transport_action(),
Some(PeerTransportAction::Close)
));
peer.drain_events();
start(&mut peer, 1_100);
let (initial, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, initial, 1_110);
let (rejoined, request) = next_request(&mut peer, SPACE_JOIN_BATCH);
assert_eq!(request["spaces"], readable);
assert!(peer.next_transport_action().is_none());
joined(&mut peer, rejoined, 1_111);
assert_eq!(
peer.drain_events(),
[
PeerSyncEvent::Ready,
PeerSyncEvent::Subscribed { addresses: vec![a] }
]
);
}
#[test]
fn rate_limited_push_preserves_the_server_deadline_and_sequence_across_reconnect() {
let space = "workspace";
let address = DocAddress {
scope: scope(),
route: DocRoute::Workspace {
id: space.into(),
resource: WorkspaceResource::Root,
},
};
for reconnect in [false, true] {
let mut peer =
LegacyDocumentPeer::new(scope(), address.space(), IdConverter::new(space));
start(&mut peer, 10);
let (initial, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, initial, 20);
peer.drain_events();
let seq = LocalSeq(25);
peer.push(
PushUpdate {
address: address.clone(),
seq,
update_v1: vec![0x00, 0xff],
intent: PushIntent::Update,
},
90,
)
.unwrap();
let (push, payload) = next_request(&mut peer, SPACE_PUSH_DOC_UPDATE);
ack(
&mut peer,
push,
json!({
"error": { "status": 429, "name": "TOO_MANY_REQUESTS", "message": "retry later",
"data": { "retryAfterMs": 60000 } }
}),
100,
);
assert!(matches!(
peer.drain_events().as_slice(),
[PeerSyncEvent::RequestFailed {
reason: PeerFailureReason::RateLimited {
retry_after_ms: Some(60000)
},
..
}]
));
assert_eq!(peer.pending_pushes(), 1);
if reconnect {
peer.on_input(PeerInput::TransportLost("disconnected"), 200)
.unwrap();
assert!(matches!(
peer.next_transport_action(),
Some(PeerTransportAction::Close)
));
start(&mut peer, 1_200);
let (initial, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, initial, 1_210);
assert!(peer.next_transport_action().is_none());
peer.drain_events();
} else {
peer.on_input(PeerInput::Tick, 1_100).unwrap();
assert!(peer.next_transport_action().is_none());
}
for now in [25_000, 50_000] {
feed(&mut peer, "2", now);
assert!(
matches!(peer.next_transport_action(), Some(PeerTransportAction::SendText(frame)) if frame == "3")
);
peer.on_input(PeerInput::Tick, now).unwrap();
assert!(peer.next_transport_action().is_none());
}
peer.on_input(PeerInput::Tick, 60_099).unwrap();
assert!(peer.next_transport_action().is_none());
peer.on_input(PeerInput::Tick, 60_100).unwrap();
let (retry, update) = next_request(&mut peer, SPACE_PUSH_DOC_UPDATE);
assert_ne!(push, retry);
assert_eq!(update, payload);
ack(
&mut peer,
retry,
json!({"data":{"accepted":true,"timestamp":60101}}),
60_101,
);
assert_eq!(
peer.drain_events(),
[PeerSyncEvent::Committed {
receipt: CommitReceipt {
address: address.clone(),
seq
},
timestamp_ms: 60_101,
}]
);
assert_eq!(peer.pending_pushes(), 0);
}
}
#[test]
fn rejected_push_ack_reports_typed_failure_without_a_durable_receipt() {
let space = "workspace";
let address = DocAddress {
scope: scope(),
route: DocRoute::Workspace {
id: space.into(),
resource: WorkspaceResource::Root,
},
};
for (code, status, reason) in [
("QUOTA_EXCEEDED", 403, PeerFailureReason::QuotaExceeded),
(
"TOO_MANY_REQUESTS",
429,
PeerFailureReason::RateLimited {
retry_after_ms: Some(800),
},
),
("BAD_REQUEST", 400, PeerFailureReason::Protocol),
("DOC_UPDATE_BLOCKED", 403, PeerFailureReason::ReadOnly),
] {
let mut peer =
LegacyDocumentPeer::new(scope(), address.space(), IdConverter::new(space));
start(&mut peer, 100);
let (initial, _) = next_request(&mut peer, SPACE_JOIN_BATCH);
joined(&mut peer, initial, 110);
peer.drain_events();
peer.push(
PushUpdate {
address: address.clone(),
seq: LocalSeq(1),
update_v1: vec![0, 0],
intent: PushIntent::Update,
},
120,
)
.unwrap();
let (push, _) = next_request(&mut peer, SPACE_PUSH_DOC_UPDATE);
assert_eq!(peer.pending_pushes(), 1);
ack(
&mut peer,
push,
json!({
"error": { "name": code, "status": status, "message": "write rejected", "data": { "retryAfterMs": 800 } }
}),
121,
);
assert_eq!(
peer.drain_events(),
vec![PeerSyncEvent::RequestFailed {
operation: PeerOperation::Push,
address: Some(address.clone()),
reason,
}]
);
}
}
}
@@ -24,23 +24,29 @@ impl SpaceSyncEngine {
if data.success
&& data.protocol_version == self.config.protocol_version =>
{
self.joined_doc_ids.insert(root_wire_id);
if let Some(id) = root_wire_id {
if self.left_doc_ids.contains(&id) {
let _ = self.leave_wire_docs(&[id], now_ms);
} else {
self.joined_doc_ids.insert(id);
}
}
self.state = SpaceSyncState::Ready;
self.reconnect_attempts = 0;
self.offline_retry_attempts = 0;
self.next_offline_retry_at_ms = None;
self.waiting_for_id_converter = self.config.defer_offline_replay_on_join;
self.events.push(SpaceSyncEvent::Joined {
client_id: data.client_id,
protocol_version: data.protocol_version,
client_version: data.client_version,
});
let _ = self.join_desired_docs(now_ms);
if !self.waiting_for_id_converter {
self.replay_offline_queue(now_ms);
}
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
self.handle_auth_or_permission_pause(
None,
&code,
@@ -64,15 +70,26 @@ impl SpaceSyncEngine {
&& data.protocol_version == self.config.protocol_version =>
{
let mut local_ids = Vec::with_capacity(wire_doc_ids.len());
let mut left = Vec::new();
for wire_id in wire_doc_ids {
local_ids.push(self.id_converter.old_id_to_new_id(&wire_id));
if self.left_doc_ids.contains(&wire_id) {
left.push(wire_id.clone());
} else {
local_ids.push(self.id_converter.local_storage_key(&wire_id));
}
self.joined_doc_ids.insert(wire_id);
}
self.events
.push(SpaceSyncEvent::DocsJoined { doc_ids: local_ids });
if !local_ids.is_empty() {
self.events
.push(SpaceSyncEvent::DocsJoined { doc_ids: local_ids });
}
if let Some(next_op) = deferred {
self.run_deferred_after_join(next_op, now_ms);
}
for id in &left {
self.joined_doc_ids.remove(id);
}
let _ = self.leave_wire_docs(&left, now_ms);
if self.state == SpaceSyncState::Ready
&& !self.waiting_for_id_converter
&& self.next_offline_retry_at_ms.is_none()
@@ -81,38 +98,25 @@ impl SpaceSyncEngine {
}
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let doc_id = deferred_doc_id(deferred.as_ref());
let code = error.canonical_code().to_string();
let failed = match deferred {
Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) => {
Some((ack_id, entry))
}
_ => None,
};
self.handle_auth_or_permission_pause(
doc_id,
&code,
error.message,
failed,
self.handle_join_permission_error(
ack_id,
&wire_doc_ids,
deferred,
error,
now_ms,
);
}
Ok(WebsocketResponse::Err { error }) => {
let doc_id = deferred_doc_id(deferred.as_ref());
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
self.shelve_push_for_retry(entry, now_ms);
self.shelve_push_for_retry(entry, error.rate_limit_delay_ms(), now_ms);
}
self.emit_request_failed(
SPACE_JOIN_BATCH,
doc_id,
error.canonical_code().to_string(),
error.message,
);
self.emit_server_request_failed(SPACE_JOIN_BATCH, doc_id, error);
}
_ => {
let doc_id = deferred_doc_id(deferred.as_ref());
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
self.shelve_push_for_retry(entry, now_ms);
self.shelve_push_for_retry(entry, None, now_ms);
}
self.emit_request_failed(
SPACE_JOIN_BATCH,
@@ -157,7 +161,7 @@ impl SpaceSyncEngine {
let _ = self.dispatch_load_doc(doc_id, state_vector, true, now_ms);
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
self.handle_auth_or_permission_pause(
Some(doc_id),
&code,
@@ -166,12 +170,9 @@ impl SpaceSyncEngine {
now_ms,
);
}
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
SPACE_LOAD_DOC,
Some(doc_id),
error.canonical_code().to_string(),
error.message,
),
Ok(WebsocketResponse::Err { error }) => {
self.emit_server_request_failed(SPACE_LOAD_DOC, Some(doc_id), error)
}
Err(err) => self.emit_request_failed(
SPACE_LOAD_DOC,
Some(doc_id),
@@ -185,14 +186,25 @@ impl SpaceSyncEngine {
retried_not_in_space,
} => {
match serde_json::from_value::<WebsocketResponse<PushDocUpdateResponse>>(payload) {
Ok(WebsocketResponse::Ok { data }) => {
Ok(WebsocketResponse::Ok { data }) if data.accepted => {
self.offline_retry_attempts = 0;
self.events.push(SpaceSyncEvent::DocUpdatePushed {
doc_id: entry.doc_id,
local_seq: entry.local_seq,
timestamp: data.timestamp,
created: data.created,
});
}
Ok(WebsocketResponse::Ok { .. }) => {
let doc_id = entry.doc_id.clone();
self.shelve_push_for_retry(entry, None, now_ms);
self.emit_request_failed(
SPACE_PUSH_DOC_UPDATE,
Some(doc_id),
"PUSH_REJECTED".into(),
"the server did not accept the update".into(),
);
}
Ok(WebsocketResponse::Err { error })
if error.is_not_in_space() && !retried_not_in_space =>
{
@@ -200,7 +212,7 @@ impl SpaceSyncEngine {
let _ = self.dispatch_push_doc_update(entry, true, now_ms);
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
let doc_id = entry.doc_id.clone();
self.handle_auth_or_permission_pause(
Some(doc_id),
@@ -212,17 +224,12 @@ impl SpaceSyncEngine {
}
Ok(WebsocketResponse::Err { error }) => {
let doc_id = entry.doc_id.clone();
self.shelve_push_for_retry(entry, now_ms);
self.emit_request_failed(
SPACE_PUSH_DOC_UPDATE,
Some(doc_id),
error.canonical_code().to_string(),
error.message,
);
self.shelve_push_for_retry(entry, error.rate_limit_delay_ms(), now_ms);
self.emit_server_request_failed(SPACE_PUSH_DOC_UPDATE, Some(doc_id), error);
}
Err(err) => {
let doc_id = entry.doc_id.clone();
self.shelve_push_for_retry(entry, now_ms);
self.shelve_push_for_retry(entry, None, now_ms);
self.emit_request_failed(
SPACE_PUSH_DOC_UPDATE,
Some(doc_id),
@@ -237,8 +244,8 @@ impl SpaceSyncEngine {
Ok(WebsocketResponse::Ok { data }) => {
let mut normalized = BTreeMap::new();
for (wire_id, ts) in data {
let local_id = self.id_converter.old_id_to_new_id(&wire_id);
if self.id_converter.new_id_to_old_id(&local_id) == wire_id {
let local_id = self.id_converter.local_storage_key(&wire_id);
if self.id_converter.legacy_storage_key(&local_id) == wire_id {
normalized.insert(local_id, ts);
}
}
@@ -247,7 +254,7 @@ impl SpaceSyncEngine {
});
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
self.handle_auth_or_permission_pause(
None,
&code,
@@ -256,12 +263,9 @@ impl SpaceSyncEngine {
now_ms,
);
}
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
SPACE_LOAD_DOC_TIMESTAMPS,
None,
error.canonical_code().to_string(),
error.message,
),
Ok(WebsocketResponse::Err { error }) => {
self.emit_server_request_failed(SPACE_LOAD_DOC_TIMESTAMPS, None, error)
}
Err(err) => self.emit_request_failed(
SPACE_LOAD_DOC_TIMESTAMPS,
None,
@@ -276,7 +280,7 @@ impl SpaceSyncEngine {
self.events.push(SpaceSyncEvent::DocDeleted { doc_id });
}
Ok(WebsocketResponse::Err { error }) if error.is_permission_revoked() => {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
self.handle_auth_or_permission_pause(
Some(doc_id),
&code,
@@ -285,12 +289,9 @@ impl SpaceSyncEngine {
now_ms,
);
}
Ok(WebsocketResponse::Err { error }) => self.emit_request_failed(
SPACE_DELETE_DOC,
Some(doc_id),
error.canonical_code().to_string(),
error.message,
),
Ok(WebsocketResponse::Err { error }) => {
self.emit_server_request_failed(SPACE_DELETE_DOC, Some(doc_id), error)
}
Err(err) => self.emit_request_failed(
SPACE_DELETE_DOC,
Some(doc_id),
@@ -319,7 +320,7 @@ impl SpaceSyncEngine {
self.pending_deletes.remove(&doc_id);
}
if error.is_permission_revoked() {
let code = error.canonical_code().to_string();
let code = error.auth_or_permission_code().to_owned();
self.handle_auth_or_permission_pause(
Some(doc_id),
&code,
@@ -328,11 +329,10 @@ impl SpaceSyncEngine {
now_ms,
);
} else {
self.emit_request_failed(
self.emit_server_request_failed(
SPACE_DOC_LIFECYCLE,
Some(doc_id),
error.canonical_code().to_string(),
error.message,
error,
);
}
}
@@ -0,0 +1,93 @@
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde::Deserialize;
use serde_json::{Value, json};
use super::{SpaceSyncEngine, SpaceSyncEvent, SpaceType, StoreError, StoreResult};
pub(super) const COLLECT_AWARENESS: &str = "space:collect-awareness";
pub(super) const BROADCAST_AWARENESS: &str = "space:broadcast-awareness-update";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AwarenessMessage {
space_type: SpaceType,
space_id: String,
doc_id: String,
awareness_update: Option<String>,
}
impl SpaceSyncEngine {
/// Ask subscribed peers to report their current presence.
pub fn request_awareness(&mut self, doc_id: &str, now_ms: i64) -> StoreResult<()> {
self.send_awareness(doc_id, None, now_ms)
}
/// Publish presence to an active room. Presence is never queued for replay.
pub fn publish_awareness(
&mut self,
doc_id: &str,
update_v1: &[u8],
now_ms: i64,
) -> StoreResult<()> {
self.send_awareness(doc_id, Some(update_v1), now_ms)
}
fn send_awareness(
&mut self,
doc_id: &str,
update: Option<&[u8]>,
now_ms: i64,
) -> StoreResult<()> {
self.ensure_ready()?;
let wire_id = self.id_converter.legacy_storage_key(doc_id);
if !self.joined_doc_ids.contains(&wire_id) {
return Err(StoreError::InvalidProtocol(
"presence requires a document subscription".into(),
));
}
let mut payload = json!({
"spaceType": self.config.space_type,
"spaceId": self.config.space_id,
"docId": wire_id,
});
let event = match update {
Some(bytes) => {
payload["awarenessUpdate"] = Value::String(BASE64.encode(bytes));
"space:update-awareness"
}
None => "space:load-awarenesses",
};
let packet = self.socket_io.encode_event(event, payload)?;
self.engine_io.send_message(&packet)?;
self.flush_engine_io_outputs(now_ms);
Ok(())
}
pub(super) fn receive_awareness(&mut self, event: &str, payload: Value) {
let Ok(msg) = serde_json::from_value::<AwarenessMessage>(payload) else {
return;
};
if msg.space_id != self.config.space_id
|| msg.space_type != self.config.space_type
|| !self.joined_doc_ids.contains(&msg.doc_id)
{
return;
}
let doc_id = self.id_converter.local_storage_key(&msg.doc_id);
if self.id_converter.legacy_storage_key(&doc_id) != msg.doc_id {
return;
}
if event == COLLECT_AWARENESS {
self.events
.push(SpaceSyncEvent::AwarenessRequested { doc_id });
} else if let Some(bin) = msg
.awareness_update
.and_then(|encoded| BASE64.decode(encoded).ok())
{
self.events.push(SpaceSyncEvent::Awareness {
doc_id,
update_v1: bin,
});
}
}
}
@@ -1,6 +1,7 @@
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde_json::Value;
use super::awareness::{BROADCAST_AWARENESS, COLLECT_AWARENESS};
use super::{
BroadcastDocInvalidationMessage, BroadcastDocUpdatesMessage, DeferredAfterJoin, EngineIoOutput,
InFlightRequest, JoinSpaceBatchEntry, JoinSpaceBatchMessage, LoadDocMessage,
@@ -8,7 +9,7 @@ use super::{
SPACE_BROADCAST_DOC_INVALIDATION, SPACE_BROADCAST_DOC_UPDATES, SPACE_DELETE_DOC,
SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS,
SPACE_PUSH_DOC_UPDATE, SocketIoEvent, SpaceSyncEngine, SpaceSyncEvent, SpaceSyncOutbound,
SpaceSyncState,
SpaceSyncState, SpaceType,
};
use crate::error::StoreResult;
@@ -57,7 +58,7 @@ impl SpaceSyncEngine {
retried_not_in_space: bool,
now_ms: i64,
) -> StoreResult<u64> {
let wire_doc_id = self.id_converter.new_id_to_old_id(&doc_id);
let wire_doc_id = self.id_converter.legacy_storage_key(&doc_id);
if !self.joined_doc_ids.contains(&wire_doc_id) {
return self.send_join_docs_batch(
vec![wire_doc_id],
@@ -101,7 +102,14 @@ impl SpaceSyncEngine {
retried_not_in_space: bool,
now_ms: i64,
) -> StoreResult<()> {
let wire_doc_id = self.id_converter.new_id_to_old_id(&entry.doc_id);
if self
.next_offline_retry_at_ms
.is_some_and(|retry_at| now_ms < retry_at)
{
self.offline_queue.push_back(entry);
return Ok(());
}
let wire_doc_id = self.id_converter.legacy_storage_key(&entry.doc_id);
let needs_join = (retried_not_in_space
|| (self.config.protocol_version != 1 && entry.intent == PushDocIntent::Update))
&& !self.joined_doc_ids.contains(&wire_doc_id);
@@ -160,6 +168,7 @@ impl SpaceSyncEngine {
self.outbound.push_back(SpaceSyncOutbound::Transport(
EngineIoOutput::Connected { sid, upgraded_ws },
));
self.socket_io.clear_pending_binary();
let auth_payload = self.config.auth_mode.to_connect_payload();
if let Ok(connect_pkt) = self.socket_io.encode_connect(Some(auth_payload)) {
let _ = self.engine_io.send_message(&connect_pkt);
@@ -195,12 +204,13 @@ impl SpaceSyncEngine {
match event {
SocketIoEvent::Connected { .. } => {
self.state = SpaceSyncState::Joining;
let root_wire_id = self.id_converter.new_id_to_old_id(&self.config.space_id);
let root_wire_id = (self.config.space_type == SpaceType::Workspace)
.then(|| self.id_converter.legacy_storage_key(&self.config.space_id));
let join = JoinSpaceBatchMessage {
spaces: vec![JoinSpaceBatchEntry {
space_type: self.config.space_type,
space_id: self.config.space_id.clone(),
doc_id: Some(root_wire_id.clone()),
doc_id: root_wire_id.clone(),
}],
client_version: self.config.client_version.clone(),
protocol_version: self.config.protocol_version,
@@ -225,7 +235,6 @@ impl SpaceSyncEngine {
self.clear_stale_ws_outbound();
self.requeue_in_flight_pushes(None);
self.joined_doc_ids.clear();
self.next_offline_retry_at_ms = None;
self.waiting_for_id_converter = false;
self.state = SpaceSyncState::AuthRequired;
self.engine_io.disconnect();
@@ -261,8 +270,8 @@ impl SpaceSyncEngine {
{
return;
}
let doc_id = self.id_converter.old_id_to_new_id(&msg.doc_id);
if self.id_converter.new_id_to_old_id(&doc_id) != msg.doc_id {
let doc_id = self.id_converter.local_storage_key(&msg.doc_id);
if self.id_converter.legacy_storage_key(&doc_id) != msg.doc_id {
return;
}
let mut decoded = Vec::with_capacity(msg.updates.len());
@@ -293,6 +302,7 @@ impl SpaceSyncEngine {
});
}
}
BROADCAST_AWARENESS | COLLECT_AWARENESS => self.receive_awareness(name, payload),
_ => {}
}
}
@@ -316,7 +326,7 @@ impl SpaceSyncEngine {
InFlightRequest::JoinDocs { deferred, .. } => {
let doc_id = deferred_doc_id(deferred.as_ref());
if let Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) = deferred {
self.shelve_push_for_retry(entry, now_ms);
self.shelve_push_for_retry(entry, None, now_ms);
}
self.emit_request_failed(
SPACE_JOIN_BATCH,
@@ -378,15 +388,41 @@ impl SpaceSyncEngine {
code: String,
message: String,
) {
let reason = match code.as_str() {
"ACK_TIMEOUT" => affine_store::PeerFailureReason::TransientNetwork,
_ => affine_store::PeerFailureReason::Protocol,
};
self.events.push(SpaceSyncEvent::RequestFailed {
op,
doc_id,
code,
message,
reason,
});
}
pub(super) fn shelve_push_for_retry(&mut self, entry: OfflinePendingUpdate, now_ms: i64) {
pub(super) fn emit_server_request_failed(
&mut self,
op: &'static str,
doc_id: Option<String>,
error: super::WebsocketErrorBody,
) {
let reason = error.failure_reason();
self.events.push(SpaceSyncEvent::RequestFailed {
op,
doc_id,
code: error.canonical_code().to_owned(),
message: error.message,
reason,
});
}
pub(super) fn shelve_push_for_retry(
&mut self,
entry: OfflinePendingUpdate,
retry_after_ms: Option<u64>,
now_ms: i64,
) {
self.offline_queue.push_front(entry);
if self.state == SpaceSyncState::Ready {
let delay = self
@@ -394,7 +430,12 @@ impl SpaceSyncEngine {
.reconnect
.backoff_ms(self.offline_retry_attempts);
self.offline_retry_attempts = self.offline_retry_attempts.saturating_add(1);
let retry_at = now_ms.saturating_add(delay);
let server_delay =
i64::try_from(retry_after_ms.unwrap_or_default()).unwrap_or(i64::MAX);
let retry_at = now_ms.saturating_add(delay.max(server_delay));
let retry_at = self
.next_offline_retry_at_ms
.map_or(retry_at, |scheduled| scheduled.max(retry_at));
self.next_offline_retry_at_ms = Some(retry_at);
self.outbound
.push_back(SpaceSyncOutbound::ScheduleTimerAtMs(retry_at));
@@ -452,7 +493,6 @@ impl SpaceSyncEngine {
self.clear_stale_ws_outbound();
self.requeue_in_flight_pushes(failed_push);
self.joined_doc_ids.clear();
self.next_offline_retry_at_ms = None;
self.waiting_for_id_converter = false;
self.state = if code == "AUTHENTICATION_REQUIRED" {
SpaceSyncState::AuthRequired
@@ -485,6 +525,13 @@ impl SpaceSyncEngine {
/// Replay only queued writes belonging to the active `account_id`, keeping other accounts'
/// writes isolated and frozen in `offline_queue`.
pub(super) fn replay_offline_queue(&mut self, now_ms: i64) {
if self
.next_offline_retry_at_ms
.is_some_and(|retry_at| now_ms < retry_at)
{
return;
}
self.next_offline_retry_at_ms = None;
let active_account = self.config.account_id.clone();
let existing = std::mem::take(&mut self.offline_queue);
let mut frozen_or_remaining = std::collections::VecDeque::new();
@@ -532,7 +579,6 @@ impl SpaceSyncEngine {
return;
}
self.joined_doc_ids.clear();
self.next_offline_retry_at_ms = None;
self.waiting_for_id_converter = false;
self.requeue_in_flight_pushes(None);
self.engine_io.disconnect();
@@ -1,5 +1,7 @@
mod acks;
mod awareness;
mod handlers;
mod subscriptions;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
@@ -15,12 +17,11 @@ use super::{
SPACE_BROADCAST_DOC_INVALIDATION, SPACE_BROADCAST_DOC_UPDATES, SPACE_DELETE_DOC,
SPACE_DOC_LIFECYCLE, SPACE_JOIN_BATCH, SPACE_JOIN_BATCH_LIMIT, SPACE_LEAVE_BATCH,
SPACE_LOAD_DOC, SPACE_LOAD_DOC_TIMESTAMPS, SPACE_PUSH_DOC_UPDATE, SocketIoClient,
SocketIoEvent, SpaceType, TransportMode, WebsocketResponse,
SocketIoEvent, SpaceType, TransportMode, WebsocketErrorBody, WebsocketResponse,
};
use crate::{
error::{StoreError, StoreResult},
id_converter::IdConverter,
workspace_db::WORKSPACE_SYNC_PROTOCOL_VERSION,
};
/// Socket.IO `40` CONNECT authentication mode.
@@ -96,7 +97,7 @@ impl SpaceSyncConfig {
space_id: space_id.into(),
account_id: None,
client_version: DEFAULT_CLIENT_VERSION.to_string(),
protocol_version: WORKSPACE_SYNC_PROTOCOL_VERSION,
protocol_version: 1,
transport_mode: if is_self_hosted {
TransportMode::PollingThenWebsocket
} else {
@@ -120,6 +121,8 @@ pub struct OfflinePendingUpdate {
pub intent: PushDocIntent,
#[serde(default)]
pub account_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub local_seq: Option<u64>,
}
/// Serializable snapshot of unsynced state persisted across restarts.
@@ -169,6 +172,7 @@ pub enum SpaceSyncEvent {
},
DocUpdatePushed {
doc_id: String,
local_seq: Option<u64>,
timestamp: i64,
created: bool,
},
@@ -194,6 +198,13 @@ pub enum SpaceSyncEvent {
timestamp: Option<i64>,
inventory_changed: bool,
},
AwarenessRequested {
doc_id: String,
},
Awareness {
doc_id: String,
update_v1: Vec<u8>,
},
AuthRequired {
doc_id: Option<String>,
code: String,
@@ -209,6 +220,7 @@ pub enum SpaceSyncEvent {
doc_id: Option<String>,
code: String,
message: String,
reason: affine_store::PeerFailureReason,
},
Disconnected {
reason: String,
@@ -230,7 +242,7 @@ pub(super) enum DeferredAfterJoin {
pub(super) enum InFlightRequest {
InitialJoin {
root_wire_id: String,
root_wire_id: Option<String>,
},
JoinDocs {
wire_doc_ids: Vec<String>,
@@ -270,6 +282,8 @@ pub struct SpaceSyncEngine {
pub(super) socket_io: SocketIoClient,
pub(super) id_converter: IdConverter,
pub(super) joined_doc_ids: BTreeSet<String>,
pub(super) desired_doc_ids: BTreeSet<String>,
pub(super) left_doc_ids: BTreeSet<String>,
pub(super) pending_deletes: BTreeMap<String, String>,
pub(super) offline_queue: VecDeque<OfflinePendingUpdate>,
pub(super) rejected_updates: Vec<OfflinePendingUpdate>,
@@ -296,6 +310,8 @@ impl SpaceSyncEngine {
socket_io: SocketIoClient::new(),
id_converter,
joined_doc_ids: BTreeSet::new(),
desired_doc_ids: BTreeSet::new(),
left_doc_ids: BTreeSet::new(),
pending_deletes: BTreeMap::new(),
offline_queue: VecDeque::new(),
rejected_updates: Vec::new(),
@@ -324,6 +340,10 @@ impl SpaceSyncEngine {
self.config.auth_mode = auth_mode;
}
pub(crate) fn auth_mode(&self) -> &SocketAuthMode {
&self.config.auth_mode
}
pub fn id_converter(&self) -> &IdConverter {
&self.id_converter
}
@@ -356,6 +376,24 @@ impl SpaceSyncEngine {
&self.joined_doc_ids
}
pub(crate) fn pending_pushes(&self) -> usize {
self.offline_queue.len()
+ self
.in_flight
.values()
.filter(|pending| {
matches!(
pending.request,
InFlightRequest::PushDocUpdate { .. }
| InFlightRequest::JoinDocs {
deferred: Some(DeferredAfterJoin::PushDocUpdate { .. }),
..
}
)
})
.count()
}
/// Snapshot the offline queue for persistence across restarts.
pub fn offline_queue(&self) -> &VecDeque<OfflinePendingUpdate> {
&self.offline_queue
@@ -415,10 +453,12 @@ impl SpaceSyncEngine {
/// Writes queued under the same `account_id` are automatically replayed once joined; writes
/// belonging to a different `account_id` remain isolated and frozen.
pub fn resume_with_account(&mut self, account_id: Option<String>, now_ms: i64) {
if self.config.account_id != account_id {
self.next_offline_retry_at_ms = None;
}
self.config.account_id = account_id;
self.reconnect_attempts = 0;
self.offline_retry_attempts = 0;
self.next_offline_retry_at_ms = None;
self.waiting_for_id_converter = false;
self.state = SpaceSyncState::Connecting;
self.engine_io.connect(now_ms);
@@ -459,35 +499,16 @@ impl SpaceSyncEngine {
self.clear_stale_ws_outbound();
self.requeue_in_flight_pushes(None);
self.joined_doc_ids.clear();
self.next_offline_retry_at_ms = None;
self.state = SpaceSyncState::Offline;
self.engine_io.disconnect();
self.flush_engine_io_outputs(now_ms);
}
/// Explicitly subscribe to a deduplicated list of local document IDs in batches of
/// `SPACE_JOIN_BATCH_LIMIT`.
pub fn join_docs(&mut self, local_doc_ids: &[&str], now_ms: i64) -> StoreResult<Vec<u64>> {
self.ensure_ready()?;
let mut seen = BTreeSet::new();
let mut wire_ids = Vec::new();
for id in local_doc_ids {
let wire = self.id_converter.new_id_to_old_id(id);
if !self.joined_doc_ids.contains(&wire) && seen.insert(wire.clone()) {
wire_ids.push(wire);
}
}
let mut ack_ids = Vec::new();
for chunk in wire_ids.chunks(SPACE_JOIN_BATCH_LIMIT) {
let ack = self.send_join_docs_batch(chunk.to_vec(), None, now_ms)?;
ack_ids.push(ack);
}
Ok(ack_ids)
}
/// Emit `space:leave-batch` in batches of `SPACE_JOIN_BATCH_LIMIT` followed by an empty
/// `docIds: []` leave packet, then reset `EngineIoClient` and close the underlying transport.
pub fn leave_space(&mut self, now_ms: i64) -> StoreResult<()> {
self.desired_doc_ids.clear();
self.left_doc_ids.clear();
let doc_ids: Vec<String> = std::mem::take(&mut self.joined_doc_ids)
.into_iter()
.collect();
@@ -514,7 +535,6 @@ impl SpaceSyncEngine {
self.flush_engine_io_outputs(now_ms);
self.requeue_in_flight_pushes(None);
self.next_offline_retry_at_ms = None;
self.state = SpaceSyncState::Offline;
self.engine_io.disconnect();
self.flush_engine_io_outputs(now_ms);
@@ -522,27 +542,6 @@ impl SpaceSyncEngine {
}
/// Queue or immediately push a local document update tagged with the active `account_id`.
pub fn push_doc_update(
&mut self,
doc_id: impl Into<String>,
update: Vec<u8>,
intent: PushDocIntent,
now_ms: i64,
) -> StoreResult<()> {
let entry = OfflinePendingUpdate {
doc_id: doc_id.into(),
update,
intent,
account_id: self.config.account_id.clone(),
};
if self.state == SpaceSyncState::Ready && !self.waiting_for_id_converter {
self.dispatch_push_doc_update(entry, false, now_ms)
} else {
self.offline_queue.push_back(entry);
Ok(())
}
}
/// Request a document snapshot/diff via `space:load-doc`.
pub fn load_doc(
&mut self,
@@ -588,7 +587,7 @@ impl SpaceSyncEngine {
let msg = DeleteDocMessage {
space_type: self.config.space_type,
space_id: self.config.space_id.clone(),
doc_id: self.id_converter.new_id_to_old_id(doc_id),
doc_id: self.id_converter.legacy_storage_key(doc_id),
};
let (ack_id, packet) = self
.socket_io
@@ -620,12 +619,12 @@ impl SpaceSyncEngine {
let phys = self
.pending_deletes
.entry(doc_id.to_string())
.or_insert_with(|| self.id_converter.new_id_to_old_id(doc_id))
.or_insert_with(|| self.id_converter.legacy_storage_key(doc_id))
.clone();
(doc_id.to_string(), Some(phys))
}
DocLifecycleAction::Trash | DocLifecycleAction::Restore => {
(self.id_converter.new_id_to_old_id(doc_id), None)
(self.id_converter.legacy_storage_key(doc_id), None)
}
};
let msg = DocLifecycleMessage {
@@ -725,7 +724,6 @@ impl SpaceSyncEngine {
.next_offline_retry_at_ms
.is_some_and(|retry_at| now_ms >= retry_at)
{
self.next_offline_retry_at_ms = None;
self.replay_offline_queue(now_ms);
}
@@ -802,6 +800,90 @@ mod tests {
let _ = engine.drain_outbound();
}
#[test]
fn reports_live_awareness_for_joined_documents_in_the_bound_space() {
let mut engine = SpaceSyncEngine::new(
SpaceSyncConfig::workspace("ws-1", true),
IdConverter::new("ws-1"),
);
assert!(engine.publish_awareness("ws-1", &[1, 2, 3], 100).is_err());
assert!(engine.offline_queue().is_empty());
connect_and_join_ws(&mut engine);
assert!(engine.request_awareness("other-doc", 1_400).is_err());
engine.request_awareness("ws-1", 1_440).unwrap();
engine.publish_awareness("ws-1", &[1, 2, 3], 1_450).unwrap();
let out = engine.drain_outbound();
assert!(out.iter().any(|event| matches!(
event, SpaceSyncOutbound::Transport(EngineIoOutput::SendWsText(frame))
if frame.contains("space:load-awarenesses") && frame.contains(r#""docId":"ws-1""#)
)));
assert!(out.iter().any(|event| matches!(
event, SpaceSyncOutbound::Transport(EngineIoOutput::SendWsText(frame))
if frame.contains("space:update-awareness") && frame.contains(r#""awarenessUpdate":"AQID""#)
)));
for (space_type, space_id, doc_id, data, expected) in [
("workspace", "ws-1", "ws-1", "AQID", true),
("userspace", "ws-1", "ws-1", "AQID", false),
("workspace", "ws-2", "ws-1", "AQID", false),
("workspace", "ws-1", "other-doc", "AQID", false),
("workspace", "ws-1", "ws-1", "%", false),
] {
let frame = format!(
r#"42["space:broadcast-awareness-update",{{"spaceType":"{space_type}","spaceId":"{space_id}","docId":"{doc_id}","awarenessUpdate":"{data}"}}]"#
);
engine.on_ws_text(&frame, 1_500).unwrap();
let events = engine.drain_events();
if expected {
assert_eq!(
events,
[SpaceSyncEvent::Awareness {
doc_id: "ws-1".into(),
update_v1: vec![1, 2, 3]
}]
);
} else {
assert!(events.is_empty(), "{frame}");
}
}
engine.on_ws_text(r#"42["space:collect-awareness",{"spaceType":"workspace","spaceId":"ws-1","docId":"ws-1"}]"#, 1_550).unwrap();
assert_eq!(
engine.drain_events(),
[SpaceSyncEvent::AwarenessRequested {
doc_id: "ws-1".into()
}]
);
}
#[test]
fn rejected_push_keeps_the_exact_sequence_pending() {
let config = SpaceSyncConfig::workspace("ws-1", true);
let mut engine = SpaceSyncEngine::new(config, IdConverter::new("ws-1"));
connect_and_join_ws(&mut engine);
engine
.push_doc_update_with_seq(
"ws-1",
vec![1, 2, 3],
PushDocIntent::Update,
Some(42),
1_500,
)
.unwrap();
engine
.on_ws_text(
r#"431[{"data":{"accepted":false,"timestamp":2000}}]"#,
2_000,
)
.unwrap();
assert!(matches!(
engine.drain_events().as_slice(),
[SpaceSyncEvent::RequestFailed {
op: SPACE_PUSH_DOC_UPDATE,
..
}]
));
assert_eq!(engine.offline_queue()[0].local_seq, Some(42));
}
#[test]
fn offline_queue_replay_ack_timeout_retry_and_permission_revocation() {
let config = SpaceSyncConfig::workspace("ws-1", true);
@@ -860,6 +942,7 @@ mod tests {
.drain_events()
.contains(&SpaceSyncEvent::DocUpdatePushed {
doc_id: "doc-1".into(),
local_seq: None,
timestamp: 9_999,
created: true,
})
@@ -934,6 +1017,7 @@ mod tests {
.push_doc_update("doc-inflight", vec![1, 1], PushDocIntent::Update, 2_000)
.unwrap();
engine.offline_queue.push_back(OfflinePendingUpdate {
local_seq: None,
doc_id: "doc-queued".into(),
update: vec![2, 2],
intent: PushDocIntent::Update,
@@ -1083,6 +1167,7 @@ mod tests {
.drain_events()
.contains(&SpaceSyncEvent::DocUpdatePushed {
doc_id: "doc-new".into(),
local_seq: None,
timestamp: 4_444,
created: false,
})
@@ -0,0 +1,174 @@
use std::collections::BTreeSet;
use super::{
DeferredAfterJoin, InFlightRequest, LeaveSpaceBatchMessage, OfflinePendingUpdate,
PushDocIntent, SPACE_JOIN_BATCH_LIMIT, SPACE_LEAVE_BATCH, SpaceSyncEngine, SpaceSyncEvent,
SpaceSyncState, SpaceType, StoreResult, WebsocketErrorBody, handlers::deferred_doc_id,
};
impl SpaceSyncEngine {
/// Remember subscriptions across reconnects and join each room at most once per batch.
pub fn join_docs(&mut self, local_doc_ids: &[&str], now_ms: i64) -> StoreResult<Vec<u64>> {
for id in local_doc_ids {
let wire_id = self.id_converter.legacy_storage_key(id);
self.left_doc_ids.remove(&wire_id);
self.desired_doc_ids.insert(wire_id);
}
self.join_desired_docs(now_ms)
}
pub(super) fn join_desired_docs(&mut self, now_ms: i64) -> StoreResult<Vec<u64>> {
if self.state != SpaceSyncState::Ready {
return Ok(Vec::new());
}
let joining: BTreeSet<_> = self
.in_flight
.values()
.filter_map(|pending| match &pending.request {
InFlightRequest::JoinDocs { wire_doc_ids, .. } => Some(wire_doc_ids),
_ => None,
})
.flatten()
.collect();
let docs: Vec<_> = self
.desired_doc_ids
.difference(&self.joined_doc_ids)
.filter(|id| !joining.contains(id))
.cloned()
.collect();
docs.chunks(SPACE_JOIN_BATCH_LIMIT)
.map(|ids| self.send_join_docs_batch(ids.to_vec(), None, now_ms))
.collect()
}
pub(super) fn handle_join_permission_error(
&mut self,
ack_id: u64,
wire_doc_ids: &[String],
deferred: Option<DeferredAfterJoin>,
error: WebsocketErrorBody,
now_ms: i64,
) {
let code = error.auth_or_permission_code().to_owned();
let deferred_doc = deferred_doc_id(deferred.as_ref());
let denied_wire = error
.data
.as_ref()
.and_then(|data| data.get("docId"))
.and_then(serde_json::Value::as_str)
.map(str::to_owned)
.or_else(|| {
deferred_doc
.as_ref()
.map(|id| self.id_converter.legacy_storage_key(id))
});
if let Some(wire_id) = denied_wire
&& wire_doc_ids.contains(&wire_id)
&& !matches!(
code.as_str(),
"AUTHENTICATION_REQUIRED" | "SPACE_ACCESS_DENIED" | "UNSUPPORTED_CLIENT_VERSION"
)
&& (self.config.space_type != SpaceType::Workspace
|| wire_id != self.id_converter.legacy_storage_key(&self.config.space_id))
{
let doc_id = self.id_converter.local_storage_key(&wire_id);
let _ = self.leave_docs(std::slice::from_ref(&doc_id), now_ms);
self.events.push(SpaceSyncEvent::PermissionRevoked {
doc_id: Some(doc_id.clone()),
code,
message: error.message,
});
let (rejected, remaining): (Vec<_>, Vec<_>) = std::mem::take(&mut self.offline_queue)
.into_iter()
.partition(|entry| {
entry.doc_id == doc_id && entry.account_id == self.config.account_id
});
self.offline_queue = remaining.into();
self.rejected_updates.extend(rejected);
match deferred {
Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) if entry.doc_id == doc_id => {
self.rejected_updates.push(entry);
}
Some(op) if deferred_doc.as_deref() != Some(&doc_id) => {
self.run_deferred_after_join(op, now_ms);
}
_ => {}
}
let _ = self.join_desired_docs(now_ms);
} else {
let failed = match deferred {
Some(DeferredAfterJoin::PushDocUpdate { entry, .. }) => Some((ack_id, entry)),
_ => None,
};
self.handle_auth_or_permission_pause(
deferred_doc,
&code,
error.message,
failed,
now_ms,
);
}
}
pub fn leave_docs(&mut self, local_ids: &[String], now_ms: i64) -> StoreResult<()> {
let mut joined = Vec::new();
for id in local_ids {
let wire_id = self.id_converter.legacy_storage_key(id);
self.desired_doc_ids.remove(&wire_id);
self.left_doc_ids.insert(wire_id.clone());
if self.joined_doc_ids.remove(&wire_id) {
joined.push(wire_id);
}
}
self.leave_wire_docs(&joined, now_ms)
}
pub(super) fn leave_wire_docs(&mut self, ids: &[String], now_ms: i64) -> StoreResult<()> {
for chunk in ids.chunks(SPACE_JOIN_BATCH_LIMIT) {
let message = LeaveSpaceBatchMessage {
space_type: self.config.space_type,
space_id: self.config.space_id.clone(),
doc_ids: chunk.to_vec(),
};
let packet = self
.socket_io
.encode_event(SPACE_LEAVE_BATCH, serde_json::to_value(message)?)?;
self.engine_io.send_message(&packet)?;
}
self.flush_engine_io_outputs(now_ms);
Ok(())
}
pub fn push_doc_update(
&mut self,
doc_id: impl Into<String>,
update: Vec<u8>,
intent: PushDocIntent,
now_ms: i64,
) -> StoreResult<()> {
self.push_doc_update_with_seq(doc_id, update, intent, None, now_ms)
}
pub fn push_doc_update_with_seq(
&mut self,
doc_id: impl Into<String>,
update: Vec<u8>,
intent: PushDocIntent,
local_seq: Option<u64>,
now_ms: i64,
) -> StoreResult<()> {
let entry = OfflinePendingUpdate {
doc_id: doc_id.into(),
update,
intent,
account_id: self.config.account_id.clone(),
local_seq,
};
if self.state == SpaceSyncState::Ready && !self.waiting_for_id_converter {
self.dispatch_push_doc_update(entry, false, now_ms)
} else {
self.offline_queue.push_back(entry);
Ok(())
}
}
}
@@ -20,21 +20,7 @@ pub const SPACE_DOC_LIFECYCLE: &str = "space:doc-lifecycle";
pub const SPACE_BROADCAST_DOC_UPDATES: &str = "space:broadcast-doc-updates";
pub const SPACE_BROADCAST_DOC_INVALIDATION: &str = "space:broadcast-doc-invalidation";
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpaceType {
Workspace,
Userspace,
}
impl SpaceType {
pub const fn as_str(self) -> &'static str {
match self {
Self::Workspace => "workspace",
Self::Userspace => "userspace",
}
}
}
pub use affine_store::SpaceType;
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -207,19 +193,58 @@ impl WebsocketErrorBody {
}
pub fn is_auth_required(&self) -> bool {
self.canonical_code() == "AUTHENTICATION_REQUIRED"
self.status == Some(401) || self.canonical_code() == "AUTHENTICATION_REQUIRED"
}
pub(super) fn failure_reason(&self) -> affine_store::PeerFailureReason {
use affine_store::PeerFailureReason::*;
match self.canonical_code() {
"QUOTA_EXCEEDED" | "BLOB_QUOTA_EXCEEDED" | "STORAGE_QUOTA_EXCEEDED" => QuotaExceeded,
"READ_ONLY" | "DOC_UPDATE_BLOCKED" => ReadOnly,
"RATE_LIMITED" | "TOO_MANY_REQUESTS" | "TOO_MANY_CONCURRENT_WRITINGS" => RateLimited {
retry_after_ms: self.retry_after_ms(),
},
_ => match self.status {
Some(429) => RateLimited {
retry_after_ms: self.retry_after_ms(),
},
Some(500..=599) => TransientNetwork,
_ => Protocol,
},
}
}
pub(super) fn rate_limit_delay_ms(&self) -> Option<u64> {
match self.failure_reason() {
affine_store::PeerFailureReason::RateLimited { retry_after_ms } => retry_after_ms,
_ => None,
}
}
fn retry_after_ms(&self) -> Option<u64> {
self.data.as_ref()?.get("retryAfterMs")?.as_u64()
}
pub(super) fn auth_or_permission_code(&self) -> &str {
if self.is_auth_required() {
"AUTHENTICATION_REQUIRED"
} else {
self.canonical_code()
}
}
pub fn is_permission_revoked(&self) -> bool {
matches!(
self.canonical_code(),
"SPACE_ACCESS_DENIED"
| "DOC_ACTION_DENIED"
| "ACCESS_DENIED"
| "FORBIDDEN"
| "AUTHENTICATION_REQUIRED"
| "UNSUPPORTED_CLIENT_VERSION"
)
self.is_auth_required()
|| matches!(
self.canonical_code(),
"SPACE_ACCESS_DENIED"
| "DOC_ACTION_DENIED"
| "ACCESS_DENIED"
| "FORBIDDEN"
| "AUTHENTICATION_REQUIRED"
| "UNSUPPORTED_CLIENT_VERSION"
)
}
pub fn is_doc_not_found(&self) -> bool {
@@ -234,6 +234,10 @@ impl SocketIoClient {
Self::default()
}
pub(crate) fn clear_pending_binary(&mut self) {
self.pending_binary = None;
}
/// Allocate the next monotonic ACK identifier.
pub fn allocate_ack_id(&mut self) -> u64 {
let id = self.next_ack_id;
@@ -11,7 +11,8 @@ use affine_client::{
ClientError, EditorDocMode, HostKind, MemoryHostBridge, SqliteWorkspaceStore, WorkspaceSession,
WorkspaceSyncStatus, WsHandle,
};
use affine_store::sync::SpaceSyncEvent;
use affine_compat_v027::peer::LegacyDocumentPeer;
use affine_store::PeerSyncEvent;
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
@@ -65,7 +66,7 @@ async fn open_store(dir: &std::path::Path, space_id: &str) -> SqliteWorkspaceSto
}
async fn open_session(store: &SqliteWorkspaceStore, client_id: u64, t: i64) -> WorkspaceSession {
store
let mut session = store
.load_workspace_session(
"u-sync-proto",
client_id,
@@ -75,7 +76,9 @@ async fn open_session(store: &SqliteWorkspaceStore, client_id: u64, t: i64) -> W
t,
)
.await
.unwrap()
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
session
}
fn sent_frames(host: &MemoryHostBridge) -> Vec<String> {
@@ -160,9 +163,7 @@ fn join_room(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64
let events = session
.on_ws_text(&mut *host, WS_URL, &join_ok(join_id), t + 200)
.unwrap();
events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::Joined { .. }))
events.iter().any(|e| matches!(e, PeerSyncEvent::Ready))
}
/// Join the room, then run the periodic flush of a host, which also starts pushing the unopened
@@ -473,7 +474,7 @@ async fn load_doc_server_error_clears_in_flight_and_allows_retry() {
assert!(
events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::RequestFailed { .. }))
.any(|e| matches!(e, PeerSyncEvent::RequestFailed { .. }))
);
let n0 = count_naming(&sent_frames(&stage.host), "space:load-doc", REMOTE_DOC);
@@ -1895,8 +1896,8 @@ async fn doc_level_permission_revoked_and_empty_remote_load_do_not_disrupt_space
}
});
assert_eq!(
session.sync_engine().unwrap().state(),
affine_store::sync::SpaceSyncState::Ready
session.document_peer().unwrap().state(),
affine_store::PeerSyncState::Ready
);
assert!(
session.doc_sync().is_synced("ws-iso"),
@@ -8,7 +8,8 @@
use affine_client::{
ClientError, EditorDocMode, HostKind, MemoryHostBridge, SqliteWorkspaceStore, WorkspaceSession,
};
use affine_store::{sqlite::resolve_workspace_db_path, sync::SpaceSyncEvent};
use affine_compat_v027::peer::LegacyDocumentPeer;
use affine_store::{PeerSyncEvent, sqlite::resolve_workspace_db_path};
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
@@ -62,13 +63,11 @@ fn join_room(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64
t + 200,
)
.unwrap();
events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::Joined { .. }))
events.iter().any(|e| matches!(e, PeerSyncEvent::Ready))
}
async fn open_session(store: &SqliteWorkspaceStore, client: u64, t: i64) -> WorkspaceSession {
store
let mut session = store
.load_workspace_session(
"u-sync",
client,
@@ -78,7 +77,9 @@ async fn open_session(store: &SqliteWorkspaceStore, client: u64, t: i64) -> Work
t,
)
.await
.unwrap()
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
session
}
#[tokio::test]
@@ -15,9 +15,10 @@ use affine_client::{
ClientError, EditorDocMode, HostKind, MemoryHostBridge, SqliteWorkspaceStore, WorkspaceSession,
WsHandle,
};
use affine_compat_v027::peer::LegacyDocumentPeer;
use affine_store::{
PeerSyncEvent,
sqlite::{SqliteDocStorage, resolve_workspace_db_path},
sync::SpaceSyncEvent,
workspace_db::{PageIdSource, WorkspaceRootDoc},
};
use blocksuite_playground_doc::{
@@ -96,13 +97,11 @@ fn join_room_on(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t:
let events = session
.on_ws_text(&mut *host, WS_URL, &ack, t + 200)
.unwrap();
events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::Joined { .. }))
events.iter().any(|e| matches!(e, PeerSyncEvent::Ready))
}
async fn open_session(store: &SqliteWorkspaceStore, client: u64, t: i64) -> WorkspaceSession {
store
let mut session = store
.load_workspace_session(
"u-sync",
client,
@@ -112,7 +111,9 @@ async fn open_session(store: &SqliteWorkspaceStore, client: u64, t: i64) -> Work
t,
)
.await
.unwrap()
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
session
}
#[test]
@@ -1083,14 +1084,7 @@ async fn online_delete_acked_before_flush_leaves_no_orphan_pending_remote_delete
.unwrap();
let doc_id = created.id.as_str().to_string();
assert!(
session
.sync_engine()
.unwrap()
.offline_queue()
.iter()
.any(|e| e.doc_id == doc_id)
);
assert!(session.has_pending_push(&doc_id));
let mut host = affine_client::MemoryHostBridge::new(HostKind::Native, "inst-del-ack");
let ws_url = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
session.connect_sync(&mut host, ws_url, 1_200).unwrap();
@@ -1117,12 +1111,7 @@ async fn online_delete_acked_before_flush_leaves_no_orphan_pending_remote_delete
assert!(session.delete_document_permanently(&doc_id, 1_500).unwrap());
assert!(
!session
.sync_engine()
.unwrap()
.offline_queue()
.iter()
.any(|e| e.doc_id == doc_id),
!session.has_pending_push(&doc_id),
"permanent deletion must clear residual offline_queue entries for the deleted doc"
);
let _ = session.on_tick(&mut host, ws_url, 1_520);
@@ -1153,7 +1142,7 @@ async fn online_delete_acked_before_flush_leaves_no_orphan_pending_remote_delete
assert!(
events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::DocDeleted { doc_id: id } if id == &doc_id)),
.any(|e| matches!(e, PeerSyncEvent::Deleted { addresses } if addresses.iter().any(|address| Some(address) == session.doc_address(&doc_id).as_ref()))),
"space:delete-doc ACK must emit DocDeleted"
);
@@ -0,0 +1,489 @@
#![cfg(not(target_family = "wasm"))]
use affine_client::{
ClientError, ClientResult, EditorDocMode, HostBridge, HostKind, WorkspaceSession, WsHandle,
};
use affine_compat_v027::{
peer::LegacyDocumentPeer,
sync::{SPACE_JOIN_BATCH, SPACE_LOAD_DOC, SPACE_PUSH_DOC_UPDATE},
};
use affine_store::{LocalSeq, PeerSyncEvent, PeerSyncState};
use std::collections::BTreeMap;
const TEST_WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
struct FailingWsHost {
next_ws: u64,
fail_on_send_call: Option<usize>,
send_calls: usize,
sent_by_handle: BTreeMap<WsHandle, Vec<String>>,
closed_handles: Vec<WsHandle>,
opened_tokens: Vec<Option<String>>,
}
impl FailingWsHost {
fn new() -> Self {
Self {
next_ws: 1,
fail_on_send_call: None,
send_calls: 0,
sent_by_handle: BTreeMap::new(),
closed_handles: Vec::new(),
opened_tokens: Vec::new(),
}
}
}
impl HostBridge for FailingWsHost {
fn host_kind(&self) -> HostKind {
HostKind::Native
}
fn ws_connect(&mut self, _url: &str, headers: &[(String, String)]) -> ClientResult<WsHandle> {
self.opened_tokens.push(
headers
.iter()
.find(|(name, _)| name == "authorization")
.map(|(_, value)| value.clone()),
);
let h = WsHandle(self.next_ws);
self.next_ws += 1;
self.sent_by_handle.insert(h, Vec::new());
Ok(h)
}
fn ws_send(&mut self, handle: WsHandle, text: &str) -> ClientResult<()> {
self.send_calls += 1;
if self.fail_on_send_call == Some(self.send_calls) {
return Err(ClientError::Host("simulated ws_send failure".into()));
}
self.sent_by_handle
.entry(handle)
.or_default()
.push(text.to_string());
Ok(())
}
fn ws_send_binary(&mut self, _handle: WsHandle, _bytes: &[u8]) -> ClientResult<()> {
Err(ClientError::Host("unexpected binary frame".into()))
}
fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()> {
self.closed_handles.push(handle);
Ok(())
}
fn read_credential(&self, _key: &str) -> ClientResult<Option<String>> {
Ok(None)
}
fn installation_id(&self) -> String {
"inst-test".into()
}
fn kv_get(&self, _key: &str) -> Option<String> {
None
}
fn kv_set(&mut self, _key: &str, _value: &str) {}
fn kv_remove(&mut self, _key: &str) {}
fn announce_accessibility(&mut self, _message: &str) {}
}
fn extract_ack_id(frame: &str) -> Option<u64> {
frame.strip_prefix("42")?.split('[').next()?.parse().ok()
}
fn complete_handshake(
session: &mut WorkspaceSession,
host: &mut FailingWsHost,
handle: WsHandle,
t: i64,
) -> ClientResult<Vec<PeerSyncEvent>> {
session.on_ws_open(host, TEST_WS_URL, t + 10)?;
session.on_ws_text(
host,
TEST_WS_URL,
r#"0{"sid":"eio","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
t + 20,
)?;
session.on_ws_text(host, TEST_WS_URL, r#"40{"sid":"sio"}"#, t + 30)?;
let join_frame = host
.sent_by_handle
.get(&handle)
.and_then(|frames| frames.iter().rev().find(|f| f.contains(SPACE_JOIN_BATCH)))
.cloned()
.expect("join frame sent on handle");
let ack = extract_ack_id(&join_frame).expect("join ack id");
session.on_ws_text(
host,
TEST_WS_URL,
&format!(r#"43{ack}[{{"data":{{"clientId":"c","success":true,"protocolVersion":1}}}}]"#),
t + 40,
)
}
#[test]
fn outbound_ws_send_failure_first_and_mid_batch_reconnects_cleanly_without_stale_leak() {
// Test both failing on the 1st post-join outbound frame (fail_offset = 1) and failing on
// the 2nd post-join outbound frame (fail_offset = 2) inside a multi-frame batch.
for fail_offset in [1usize, 2usize] {
let mut host = FailingWsHost::new();
let mut session = WorkspaceSession::new(
"ws-out",
"u-1",
11,
HostKind::Native,
"affine-cloud",
"https://app.affine.pro",
1_000,
)
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
let (doc, _) = session
.create_document("Sync Target", EditorDocMode::Page, None, 1_050)
.unwrap();
let doc_id = doc.id.as_str().to_string();
session.connect_sync(&mut host, TEST_WS_URL, 1_100).unwrap();
let h1 = WsHandle(1);
// Complete EIO/SIO handshake up to join ACK, then inject ws_send failure on the
// exact post-join frame offset where both offline pushes and load-doc frames flush.
session.on_ws_open(&mut host, TEST_WS_URL, 1_110).unwrap();
session
.on_ws_text(
&mut host,
TEST_WS_URL,
r#"0{"sid":"e1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
1_120,
)
.unwrap();
session
.on_ws_text(&mut host, TEST_WS_URL, r#"40{"sid":"s1"}"#, 1_130)
.unwrap();
let join_ack = host.sent_by_handle[&h1]
.iter()
.rev()
.find(|f| f.contains(SPACE_JOIN_BATCH))
.and_then(|f| extract_ack_id(f))
.unwrap();
host.fail_on_send_call = Some(host.send_calls + fail_offset);
let err = session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{join_ack}[{{"data":{{"clientId":"c1","success":true,"protocolVersion":1}}}}]"#
),
1_140,
)
.unwrap_err();
assert!(err.to_string().contains("simulated ws_send failure"));
assert!(
matches!(
session.document_peer().unwrap().state(),
PeerSyncState::ReconnectScheduled { .. }
),
"ws_send failure at offset {fail_offset} must transition to ReconnectScheduled"
);
assert!(
host.closed_handles.contains(&h1),
"failed connection handle must be closed"
);
let sends = host.send_calls;
session.on_tick(&mut host, TEST_WS_URL, 1_141).unwrap();
assert_eq!(
host.send_calls, sends,
"no stale outbound frames may remain"
);
// Reconnect on connection #2 without further send errors.
host.fail_on_send_call = None;
let PeerSyncState::ReconnectScheduled { next_attempt_at_ms } =
session.document_peer().unwrap().state()
else {
panic!("expected ReconnectScheduled");
};
session
.on_tick(&mut host, TEST_WS_URL, next_attempt_at_ms)
.unwrap();
let h2 = WsHandle(2);
let h2_before_join = host.sent_by_handle[&h2].clone();
assert!(
!h2_before_join
.iter()
.any(|f| f.contains(SPACE_PUSH_DOC_UPDATE) || f.contains(SPACE_LOAD_DOC)),
"stale frames from connection #1 must never leak onto connection #2"
);
complete_handshake(&mut session, &mut host, h2, next_attempt_at_ms + 10).unwrap();
let h2_frames = host.sent_by_handle[&h2].clone();
assert!(
h2_frames
.iter()
.any(|f| f.contains(SPACE_PUSH_DOC_UPDATE) && f.contains(&doc_id)),
"reconnected session must replay push for {doc_id} (offset {fail_offset})"
);
assert!(
h2_frames
.iter()
.any(|f| f.contains(SPACE_LOAD_DOC) && f.contains("\"ws-out\"")),
"reconnected session must rebuild root load-doc (offset {fail_offset})"
);
let subdoc_join_ack = h2_frames
.iter()
.rev()
.find(|f| f.contains(SPACE_JOIN_BATCH) && f.contains(&doc_id))
.and_then(|f| extract_ack_id(f))
.expect("reconnected session must rebuild space:join-batch for subdoc");
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(
r#"43{subdoc_join_ack}[{{"data":{{"clientId":"c2","success":true,"protocolVersion":1}}}}]"#
),
next_attempt_at_ms + 60,
)
.unwrap();
assert!(
host.sent_by_handle[&h2]
.iter()
.any(|f| f.contains(SPACE_LOAD_DOC) && f.contains(&doc_id)),
"reconnected session must rebuild subdoc load-doc after join ACK for {doc_id} (offset {fail_offset})"
);
}
}
fn native_cloud_session() -> WorkspaceSession {
let mut session = WorkspaceSession::new(
"ws-auth-lifecycle",
"account",
7,
HostKind::Native,
"affine-cloud",
"https://app.affine.pro",
100,
)
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
session
}
fn retry_at(session: &WorkspaceSession) -> i64 {
match session.document_peer().unwrap().state() {
PeerSyncState::ReconnectScheduled { next_attempt_at_ms } => next_attempt_at_ms,
state => panic!("expected reconnect timer, got {state:?}"),
}
}
#[test]
fn reconnect_uses_new_credentials_and_signout_cancels_backoff() {
let mut host = FailingWsHost::new();
let mut session = native_cloud_session();
session
.refresh_sync_credentials(&mut host, TEST_WS_URL, Some("old".into()), 100)
.unwrap();
session.connect_sync(&mut host, TEST_WS_URL, 101).unwrap();
complete_handshake(&mut session, &mut host, WsHandle(1), 102).unwrap();
session
.on_ws_error(&mut host, TEST_WS_URL, "transport gone", 150)
.unwrap();
let retry = retry_at(&session);
session
.refresh_sync_credentials(&mut host, TEST_WS_URL, Some("new".into()), 151)
.unwrap();
let foreign = "wss://other.example/socket.io/";
assert_eq!(
session.on_tick(&mut host, foreign, retry),
Err(ClientError::SyncOriginMismatch)
);
assert_eq!(host.next_ws, 2);
session.on_tick(&mut host, TEST_WS_URL, retry).unwrap();
assert_eq!(
host.opened_tokens,
[Some("Bearer old".into()), Some("Bearer new".into())]
);
complete_handshake(&mut session, &mut host, WsHandle(2), retry + 1).unwrap();
session
.on_ws_error(&mut host, TEST_WS_URL, "transport gone", retry + 100)
.unwrap();
let retry = retry_at(&session);
session
.sign_out_sync(&mut host, TEST_WS_URL, retry - 1)
.unwrap();
session
.on_ws_error(&mut host, TEST_WS_URL, "late close", retry)
.unwrap();
session.on_tick(&mut host, TEST_WS_URL, retry + 1).unwrap();
assert_eq!(host.next_ws, 3);
assert_eq!(
session.document_peer().unwrap().state(),
PeerSyncState::Offline
);
assert!(matches!(
session.connect_sync(&mut host, TEST_WS_URL, retry + 2),
Err(ClientError::Remote(
affine_client::remote::RemoteError::SessionExpired
))
));
assert_eq!(host.next_ws, 3);
}
#[test]
fn same_account_reauth_resumes_after_401_and_acks_the_pending_write() {
let mut host = FailingWsHost::new();
let mut session = native_cloud_session();
session
.refresh_sync_credentials(&mut host, TEST_WS_URL, Some("expired".into()), 100)
.unwrap();
session.connect_sync(&mut host, TEST_WS_URL, 101).unwrap();
complete_handshake(&mut session, &mut host, WsHandle(1), 102).unwrap();
session
.create_document("Queued", EditorDocMode::Page, None, 150)
.unwrap();
session.on_tick(&mut host, TEST_WS_URL, 151).unwrap();
let find_push = |host: &FailingWsHost, handle| {
host.sent_by_handle[&handle]
.iter()
.find(|frame| {
frame.contains(SPACE_PUSH_DOC_UPDATE)
&& frame.contains(r#""docId":"ws-auth-lifecycle""#)
})
.and_then(|frame| extract_ack_id(frame))
.unwrap()
};
let seq = LocalSeq(
session
.doc_sync()
.entry("ws-auth-lifecycle")
.unwrap()
.last_push_seq
.unwrap(),
);
let push = find_push(&host, WsHandle(1));
let events = session.on_ws_text(&mut host, TEST_WS_URL,
&format!(r#"43{push}[{{"error":{{"status":401,"name":"UNAUTHORIZED","message":"expired"}}}}]"#),
152,
).unwrap();
assert!(
events
.iter()
.any(|event| matches!(event, PeerSyncEvent::AuthRequired { .. }))
);
assert!(
events
.iter()
.all(|event| !matches!(event, PeerSyncEvent::Committed { .. }))
);
assert!(session.has_pending_push("ws-auth-lifecycle"));
assert_eq!(
session.document_peer().unwrap().state(),
PeerSyncState::AuthRequired
);
session
.refresh_sync_credentials(&mut host, TEST_WS_URL, Some("fresh".into()), 153)
.unwrap();
assert_eq!(
host.opened_tokens.last(),
Some(&Some("Bearer fresh".into()))
);
complete_handshake(&mut session, &mut host, WsHandle(2), 154).unwrap();
let retried = find_push(&host, WsHandle(2));
assert_ne!(retried, push);
let events = session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(r#"43{retried}[{{"data":{{"accepted":true,"timestamp":200}}}}]"#),
200,
)
.unwrap();
let address = session.doc_address("ws-auth-lifecycle").unwrap();
assert!(events.iter().any(|event| matches!(event,
PeerSyncEvent::Committed { receipt, .. } if receipt.address == address && receipt.seq == seq
)));
assert!(!session.has_pending_push("ws-auth-lifecycle"));
}
#[test]
fn sync_status_counts_one_delete_until_the_replayed_ack() {
use affine_client::WorkspaceSyncStatus;
let mut host = FailingWsHost::new();
let mut session = native_cloud_session();
session.connect_sync(&mut host, TEST_WS_URL, 101).unwrap();
complete_handshake(&mut session, &mut host, WsHandle(1), 102).unwrap();
let (doc, _) = session
.create_document("To delete", EditorDocMode::Page, None, 150)
.unwrap();
session.on_tick(&mut host, TEST_WS_URL, 151).unwrap();
let complete_pushes = |session: &mut WorkspaceSession, host: &mut FailingWsHost, time| {
let pushes: Vec<_> = std::mem::take(host.sent_by_handle.get_mut(&WsHandle(1)).unwrap())
.iter()
.filter(|frame| frame.contains(SPACE_PUSH_DOC_UPDATE))
.filter_map(|frame| extract_ack_id(frame))
.collect();
assert!(!pushes.is_empty());
for id in pushes {
session
.on_ws_text(
host,
TEST_WS_URL,
&format!(r#"43{id}[{{"data":{{"accepted":true,"timestamp":{time}}}}}]"#),
time,
)
.unwrap();
}
};
complete_pushes(&mut session, &mut host, 152);
assert_eq!(session.sync_status(), WorkspaceSyncStatus::Synced);
let doc_id = doc.id.as_str();
assert!(session.delete_document_permanently(doc_id, 160).unwrap());
session.on_tick(&mut host, TEST_WS_URL, 161).unwrap();
let pending_delete = |host: &FailingWsHost, handle| {
host.sent_by_handle[&handle]
.iter()
.find(|frame| frame.contains("space:delete-doc") && frame.contains(doc_id))
.and_then(|frame| extract_ack_id(frame))
.unwrap()
};
let first = pending_delete(&host, WsHandle(1));
complete_pushes(&mut session, &mut host, 162);
assert_eq!(
session.sync_status(),
WorkspaceSyncStatus::Syncing { pending_updates: 1 }
);
session
.on_ws_error(&mut host, TEST_WS_URL, "disconnected", 170)
.unwrap();
let retry = retry_at(&session);
assert_eq!(
session.sync_status(),
WorkspaceSyncStatus::ReconnectScheduled {
next_attempt_at_ms: retry,
pending_updates: 1,
}
);
session.on_tick(&mut host, TEST_WS_URL, retry).unwrap();
complete_handshake(&mut session, &mut host, WsHandle(2), retry + 1).unwrap();
let replayed = pending_delete(&host, WsHandle(2));
assert_ne!(first, replayed);
assert_eq!(
session.sync_status(),
WorkspaceSyncStatus::Syncing { pending_updates: 1 }
);
session
.on_ws_text(
&mut host,
TEST_WS_URL,
&format!(r#"43{replayed}[{{"data":{{"success":true}}}}]"#),
retry + 50,
)
.unwrap();
assert_eq!(session.sync_status(), WorkspaceSyncStatus::Synced);
}
@@ -0,0 +1,464 @@
#![cfg(not(target_family = "wasm"))]
use affine_client::session::{MAX_UNVERIFIED_REMOTE_BYTES, MAX_UNVERIFIED_REMOTE_DOCS};
use std::sync::{Arc, Mutex};
use affine_client::{
ClientError, HostKind, MemoryHostBridge, SqliteSyncHost, SqliteWorkspaceStore,
WorkspaceSession, WorkspaceSyncStatus, WsHandle,
};
use affine_compat_v027::peer::LegacyDocumentPeer;
use affine_store::{
share_ingest::{ShareIngestRequest, SharePayloadKind, ingest_share_item_into_sqlite},
sqlite::{naive_utc_to_millis, resolve_workspace_db_path},
};
use blocksuite_playground_doc::{schema::BlockSpec, session::PageDocSession};
const WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
const SERVER: &str = "affine-cloud";
const DOC: &str = "page-p";
fn encode_base64(input: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
for i in 0..4 {
out.push(if i <= chunk.len() {
TABLE[((n >> (18 - 6 * i)) & 0x3F) as usize] as char
} else {
'='
});
}
}
out
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"affine-sqlite-session-{}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn sent_frames(host: &MemoryHostBridge) -> Vec<String> {
(0..16u64)
.filter_map(|h| host.ws_sent(WsHandle(h)))
.flatten()
.cloned()
.collect()
}
/// Ack ID of the newest frame sent after `from` that contains every needle.
fn ack_id_after(host: &MemoryHostBridge, from: usize, needles: &[&str]) -> Option<u64> {
sent_frames(host)[from..].iter().rev().find_map(|f| {
let digits: String = f
.strip_prefix("42")?
.chars()
.take_while(char::is_ascii_digit)
.collect();
needles
.iter()
.all(|n| f.contains(n))
.then(|| digits.parse().ok())
.flatten()
})
}
fn reply(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, frame: &str, t: i64) {
session.on_ws_text(host, WS_URL, frame, t).unwrap();
}
fn join(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, id: u64, t: i64) {
let ok =
format!(r#"43{id}[{{"data":{{"clientId":"c-1","success":true,"protocolVersion":1}}}}]"#);
reply(session, host, &ok, t);
}
fn connect(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64) {
session.connect_sync(host, WS_URL, t).unwrap();
finish_handshake(session, host, t);
}
fn finish_handshake(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64) {
let from = sent_frames(host).len();
session.on_ws_open(host, WS_URL, t).unwrap();
let open = r#"0{"sid":"e-1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#;
reply(session, host, open, t);
reply(session, host, r#"40{"sid":"s-1"}"#, t);
let id = ack_id_after(host, from, &["space:join-batch"]).unwrap();
join(session, host, id, t);
}
/// Tick until `event` for `doc_id` goes out, answering a `space:join-batch` for it on the
/// way, and return the ack ID of the request.
fn next_request(
session: &mut WorkspaceSession,
host: &mut MemoryHostBridge,
event: &str,
doc_id: &str,
t: i64,
) -> u64 {
let from = sent_frames(host).len();
session.on_tick(host, WS_URL, t).unwrap();
if let Some(id) = ack_id_after(host, from, &["space:join-batch", doc_id]) {
join(session, host, id, t);
session.on_tick(host, WS_URL, t).unwrap();
}
ack_id_after(host, from, &[event, doc_id]).unwrap()
}
fn loaded(id: u64, missing: &[u8], state: &[u8], timestamp: i64) -> String {
format!(
r#"43{id}[{{"data":{{"missing":"{}","state":"{}","timestamp":{timestamp}}}}}]"#,
encode_base64(missing),
encode_base64(state)
)
}
fn broadcast(doc_id: &str, update: &[u8], timestamp: i64) -> String {
format!(
r#"42["space:broadcast-doc-updates",{{"spaceType":"workspace","spaceId":"ws","docId":"{doc_id}","updates":["{}"],"timestamp":{timestamp},"editor":"peer"}}]"#,
encode_base64(update)
)
}
async fn pushed_and_doc_clock(store: &SqliteWorkspaceStore, doc_id: &str) -> (i64, i64) {
let pushed = store
.storage()
.get_peer_pushed_clock(SERVER, doc_id)
.await
.unwrap()
.map_or(0, |c| naive_utc_to_millis(c.timestamp));
let clock = store
.storage()
.get_doc_clock(doc_id)
.await
.unwrap()
.unwrap();
(pushed, naive_utc_to_millis(clock.timestamp))
}
/// Write a page baseline of `DOC` that the server already holds.
async fn seed_pushed_page(store: &SqliteWorkspaceStore) -> PageDocSession {
let mut page = PageDocSession::new(DOC, 7).unwrap();
let spec = BlockSpec::Page { title: "P".into() };
page.add_block("root", spec, None, None, 1).unwrap();
let ts = store
.storage()
.push_update(DOC, page.encode_update_v1().unwrap(), 1_000)
.await
.unwrap();
store
.storage()
.set_peer_pushed_clock(SERVER, DOC, ts)
.await
.unwrap();
page
}
async fn open_session(store: &SqliteWorkspaceStore, client_id: u64) -> WorkspaceSession {
let mut session = store
.load_workspace_session(
"u-1",
client_id,
HostKind::Native,
SERVER,
"https://app.affine.pro",
1_000,
)
.await
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
session
}
#[tokio::test]
async fn evicted_broadcast_for_a_doc_of_another_writer_reloads_it_from_the_server() {
// (case, caption bytes of the peer edit, broadcasts for other documents after it)
let cases = [
("over-byte-limit", 1_048_600usize, 0usize),
("over-doc-limit", 9, MAX_UNVERIFIED_REMOTE_DOCS),
];
for (case, caption_len, other_docs) in cases {
let dir = temp_dir(case);
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut session = open_session(&store, 11).await;
let mut host = MemoryHostBridge::new(HostKind::Native, "inst");
connect(&mut session, &mut host, 10);
// The page is not on the server yet: the first load ends missing.
assert!(
store
.open_or_hydrate_document(&mut session, DOC, 300)
.await
.is_err()
);
let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 310);
let not_found = format!(
r#"43{load}[{{"error":{{"status":404,"code":"DOC_NOT_FOUND","name":"DOC_NOT_FOUND","message":"doc not found"}}}}]"#
);
reply(&mut session, &mut host, &not_found, 340);
assert!(session.is_remote_doc_missing(DOC), "{case}");
// A Share Extension writes the page into the same SQLite file, and a peer edits it.
let db = resolve_workspace_db_path(&dir, "workspace", "local", "ws").unwrap();
let share = ShareIngestRequest {
share_id: "share-p".into(),
import_attempt_id: "attempt-p".into(),
doc_id: DOC.into(),
kind: SharePayloadKind::Text,
title: "Shared".into(),
text_or_url: "baseline".into(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 22,
now_ms: 1_000,
};
ingest_share_item_into_sqlite(&db, "ws", &share, &[])
.await
.unwrap();
let mut peer = store.load_doc_session(DOC, 33).await.unwrap().unwrap();
let root_id = peer.read_page_snapshot().unwrap().root.unwrap().id;
let caption = "p".repeat(caption_len);
let delta = peer
.set_block_caption(&root_id, &caption, 1_002)
.unwrap()
.unwrap()
.update;
reply(
&mut session,
&mut host,
&broadcast(DOC, &delta, 1_004),
1_004,
);
for i in 0..other_docs {
let frame = broadcast(&format!("other-{i}"), &delta, 1_005);
reply(&mut session, &mut host, &frame, 1_005);
}
assert_eq!(session.evicted_remote_doc_count(), 1, "{case}");
assert!(session.unhydrated_pending_delta_doc_count() <= MAX_UNVERIFIED_REMOTE_DOCS);
assert!(session.unhydrated_pending_delta_bytes() <= MAX_UNVERIFIED_REMOTE_BYTES);
// The flush finds the page in SQLite, and the session loads it from the server.
store
.flush_session_mutations(&mut session, None, 1_100)
.await
.unwrap();
assert_eq!(session.evicted_remote_doc_count(), 0, "{case}");
let reload = next_request(&mut session, &mut host, "space:load-doc", DOC, 1_200);
let server_state = peer.encode_update_v1().unwrap();
let server_sv = peer.encode_state_vector_v1().unwrap();
let frame = loaded(reload, &server_state, &server_sv, 1_300);
reply(&mut session, &mut host, &frame, 1_300);
store
.flush_session_mutations(&mut session, None, 1_400)
.await
.unwrap();
let page = store.load_doc_session(DOC, 55).await.unwrap().unwrap();
let root = page.read_page_snapshot().unwrap().root.unwrap();
let read = root.props.get("prop:caption").and_then(|v| v.as_str());
assert_eq!(read, Some(caption.as_str()), "{case}");
for i in 0..other_docs {
let doc_id = format!("other-{i}");
assert!(
store
.storage()
.get_doc_clock(&doc_id)
.await
.unwrap()
.is_none()
);
}
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
}
#[tokio::test]
async fn remote_update_on_a_pushed_unopened_doc_moves_pushed_clock_without_a_load() {
let dir = temp_dir("pushed-unopened");
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut peer = seed_pushed_page(&store).await;
let mut session = open_session(&store, 11).await;
assert!(!session.has_pending_push(DOC));
let mut host = MemoryHostBridge::new(HostKind::Native, "inst");
connect(&mut session, &mut host, 10);
let delta = peer
.set_block_caption("root", "remote", 2_000)
.unwrap()
.unwrap()
.update;
reply(
&mut session,
&mut host,
&broadcast(DOC, &delta, 2_000),
2_000,
);
assert!(!session.is_doc_loaded(DOC));
store
.flush_session_mutations(&mut session, None, 2_100)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock);
// A cold start has nothing to load or push for the page.
let mut restarted = open_session(&store, 12).await;
assert!(!restarted.has_pending_push(DOC));
connect(&mut restarted, &mut host, 3_000);
store
.flush_session_mutations(&mut restarted, None, 3_100)
.await
.unwrap();
assert_eq!(restarted.unopened_loaded_doc_count(), 0);
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn sqlite_connect_requires_a_peer_and_exact_acks_advance_only_covered_rows() {
let dir = temp_dir("acked-local");
let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws")
.await
.unwrap();
let mut editor = seed_pushed_page(&store).await;
let mut other = store.load_doc_session(DOC, 99).await.unwrap().unwrap();
let store = Arc::new(store);
let mut session = store
.load_workspace_session(
"user",
11,
HostKind::Native,
SERVER,
"https://app.affine.pro",
10,
)
.await
.unwrap();
let transport = Arc::new(Mutex::new(MemoryHostBridge::new(HostKind::Native, "inst")));
let sync_host = SqliteSyncHost::new(
store.clone(),
transport.clone(),
WS_URL.into(),
tokio::runtime::Handle::current(),
);
assert_eq!(
sync_host.connect(&mut session, 10),
Err(ClientError::MissingDocumentPeer)
);
assert!(transport.lock().unwrap().ws_sent(WsHandle(1)).is_none());
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
sync_host.connect(&mut session, 10).unwrap();
drop(sync_host);
let mut host = Arc::try_unwrap(transport).unwrap().into_inner().unwrap();
assert!(host.ws_sent(WsHandle(1)).is_some());
finish_handshake(&mut session, &mut host, 10);
assert_eq!(session.sync_status(), WorkspaceSyncStatus::Synced);
assert!(
store
.open_or_hydrate_document(&mut session, DOC, 100)
.await
.is_ok()
);
let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 110);
let sv = editor.encode_state_vector_v1().unwrap();
reply(
&mut session,
&mut host,
&loaded(load, &[0, 0], &sv, 120),
120,
);
// Each local edit is pushed, flushed, and acknowledged. The ack can come before or after
// the flush that writes its row.
let mut acked_row_clock = 0;
for (i, ack_before_flush) in [(0i64, false), (1, true)] {
let t = 1_000 + i * 1_000;
let edit = editor.set_block_caption("root", &format!("v{i}"), t as u64);
let update = edit.unwrap().unwrap().update;
assert!(session.merge_local_doc_update(DOC, &update, t).unwrap());
let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, t);
assert_eq!(
session.sync_status(),
WorkspaceSyncStatus::Syncing { pending_updates: 1 }
);
let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":{t}}}}}]"#);
if ack_before_flush {
reply(&mut session, &mut host, &ack, t + 10);
}
store
.flush_session_mutations(&mut session, None, t + 20)
.await
.unwrap();
if !ack_before_flush {
reply(&mut session, &mut host, &ack, t + 30);
store
.flush_session_mutations(&mut session, None, t + 40)
.await
.unwrap();
}
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock, "edit {i}");
assert_eq!(session.sync_status(), WorkspaceSyncStatus::Synced);
acked_row_clock = clock;
}
// Another writer adds a row, then a local edit lands after it. The server holds the
// whole in-memory state, but the content check finds the other row outside it.
let foreign = other
.set_block_caption("root", "other", 5_000)
.unwrap()
.unwrap()
.update;
store
.storage()
.push_update(DOC, &foreign, 5_000)
.await
.unwrap();
let update = editor
.set_block_caption("root", "v2", 6_000)
.unwrap()
.unwrap()
.update;
assert!(session.merge_local_doc_update(DOC, &update, 6_000).unwrap());
let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, 6_000);
let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":6000}}}}]"#);
reply(&mut session, &mut host, &ack, 6_010);
store
.flush_session_mutations(&mut session, None, 6_020)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, acked_row_clock);
assert!(pushed < clock);
// Once the server sends the other row back, the in-memory state holds every row.
reply(
&mut session,
&mut host,
&broadcast(DOC, &foreign, 7_000),
7_000,
);
store
.flush_session_mutations(&mut session, None, 7_100)
.await
.unwrap();
let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await;
assert_eq!(pushed, clock);
store.close().await;
let _ = std::fs::remove_dir_all(&dir);
}
@@ -4,11 +4,12 @@
//! ingestion with single-step Undo.
use affine_client::{
BlobUploadState, DocQueryCancelToken, DocQueryRequest, EditorDocMode, HostKind,
MemoryHostBridge, NativeAuthPlatform, PickedMediaInput, PickedMediaKind, WorkspaceSession,
WorkspaceSyncStatus,
BlobUploadState, DocQueryCancelToken, DocQueryRequest, EditorDocMode, HostBridge, HostKind,
MemoryHostBridge, PickedMediaInput, PickedMediaKind, WorkspaceSession, WorkspaceSyncStatus,
};
use affine_store::sync::SpaceSyncEvent;
use affine_compat_v027::client_auth::{AuthController, NativeAuthPlatform};
use affine_compat_v027::peer::LegacyDocumentPeer;
use affine_store::PeerSyncEvent;
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ParagraphType},
@@ -71,18 +72,24 @@ fn multi_doc_switching_at_directory_auth_spacesync_and_blob_undo_pipeline() {
)
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
// 1. Hydrate native Android DataStore JWT credentials via HostBridge.
let android_json = r#"{"version":1,"tokenType":"Bearer","accessToken":"jwt-mobile-live","accessExpiresAt":1795622400000,"refreshToken":"rt-mobile","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"sess-mobile","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#;
host.seed_credential(session.auth().credential_key(), android_json);
assert!(
session
.hydrate_auth(&host, NativeAuthPlatform::Android)
.unwrap()
);
assert_eq!(
session.auth().native_tokens().unwrap().access_token,
"jwt-mobile-live"
);
let mut auth = AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native);
host.seed_credential(auth.credential_key(), android_json);
let credentials = host.read_credential(&auth.credential_key()).unwrap();
assert!(auth.load_stored_credentials(credentials.as_deref(), NativeAuthPlatform::Android));
let token = &auth.native_tokens().unwrap().access_token;
assert_eq!(token, "jwt-mobile-live");
session
.refresh_sync_credentials(
&mut host,
"wss://app.affine.pro/socket.io/",
Some(token.clone()),
1_000,
)
.unwrap();
// 2. Create two documents while offline -> queued in SpaceSync offline queue.
let (doc_a, _) = session
@@ -97,7 +104,7 @@ fn multi_doc_switching_at_directory_auth_spacesync_and_blob_undo_pipeline() {
.create_document("Sync Protocol", EditorDocMode::Page, Some("op-b"), 2_100)
.unwrap();
assert_ne!(doc_a.id, doc_b.id);
assert!(session.sync_engine().unwrap().offline_queue().len() >= 2);
assert!(session.document_peer().unwrap().pending_pushes() >= 2);
assert!(matches!(
session.sync_status(),
WorkspaceSyncStatus::Syncing { pending_updates } if pending_updates >= 2
@@ -218,7 +225,7 @@ fn multi_doc_switching_at_directory_auth_spacesync_and_blob_undo_pipeline() {
assert!(
join_events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::Joined { .. }))
.any(|e| matches!(e, PeerSyncEvent::Ready))
);
// Simulate a remote collaborator editing `doc_b` and broadcasting via `space:broadcast-doc-updates`.
@@ -253,7 +260,7 @@ fn multi_doc_switching_at_directory_auth_spacesync_and_blob_undo_pipeline() {
assert!(
remote_events
.iter()
.any(|e| matches!(e, SpaceSyncEvent::RemoteDocUpdates { .. }))
.any(|e| matches!(e, PeerSyncEvent::Updated { .. }))
);
let synced_b = session.doc_snapshot(doc_b.id.as_str()).unwrap();
assert!(synced_b.block("remote-p-1").is_some());
@@ -394,6 +401,7 @@ async fn sqlite_lazy_doc_hydration_uncached_remote_load_and_permanent_delete() {
)
.await
.unwrap();
LegacyDocumentPeer::bind_workspace(&mut session).unwrap();
assert_eq!(
session.loaded_doc_count(),
0,
@@ -901,14 +901,19 @@ pub(crate) mod tests {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mounted_typing_survives_sidebar_switch_and_reaches_transport_on_tick() {
use affine_client::{
HostKind, MemoryHostBridge, SqliteSyncHost, SqliteWorkspaceStore, WsHandle,
};
use affine_store::sync::EngineIoPacket;
use affine_client::{HostKind, MemoryHostBridge, SqliteSyncHost, SqliteWorkspaceStore};
use affine_store::{DocRoute, WorkspaceResource};
mod memory_peer {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../client/tests/support/document_peer.rs"
));
}
use blocksuite_playground_doc::{read::BlockContent, session::PageDocSession};
use memory_peer::MemoryDocumentPeer;
use playground::overlays::{ActiveSelection, OverlayEvent};
use std::sync::{Arc, Mutex};
const URL: &str = "wss://example.com/socket.io/?EIO=4&transport=websocket";
const URL: &str = "https://example.com";
const DOC: &str = "doc-arch";
const SPACE: &str = "ws-affine-desktop";
const BODY: &str = "Typed in the mounted editor. ";
@@ -921,19 +926,22 @@ pub(crate) mod tests {
.await
.unwrap(),
);
let session = Arc::new(Mutex::new(
store
.load_workspace_session(
"test",
41,
HostKind::Native,
"local",
"https://example.com",
1000,
)
.await
.unwrap(),
));
let mut session = store
.load_workspace_session(
"test",
41,
HostKind::Native,
"local",
"https://example.com",
1000,
)
.await
.unwrap();
let remote = MemoryDocumentPeer::default();
session
.bind_document_peer(Box::new(remote.clone()))
.unwrap();
let session = Arc::new(Mutex::new(session));
let bridge = Arc::new(Mutex::new(MemoryHostBridge::new(HostKind::Native, "test")));
let host = SqliteSyncHost::new(
store.clone(),
@@ -1000,28 +1008,11 @@ pub(crate) mod tests {
text.plain.clone()
};
if tick {
{
let mut ws = session.lock().unwrap();
let mut transport = bridge.lock().unwrap();
ws.on_ws_open(&mut *transport, URL, 1000).unwrap();
for frame in [
r#"0{"sid":"engine","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#,
r#"40{"sid":"socket"}"#,
] {
ws.on_ws_text(&mut *transport, URL, frame, 1000).unwrap();
}
let join = transport
.ws_sent(WsHandle(1))
.unwrap()
.iter()
.find(|f| f.contains("space:join-batch"))
.unwrap();
let ack = join.strip_prefix("42").unwrap().split_once('[').unwrap().0;
let frame = format!(
r#"43{ack}[{{"data":{{"clientId":"test","success":true,"protocolVersion":1}}}}]"#
);
ws.on_ws_text(&mut *transport, URL, &frame, 1000).unwrap();
}
session
.lock()
.unwrap()
.on_ws_open(&mut *bridge.lock().unwrap(), URL, 1000)
.unwrap();
platform.advance_clock(SqliteSyncHost::INTERVAL);
platform.run_until_parked();
platform.scheduler().allow_parking();
@@ -1035,19 +1026,10 @@ pub(crate) mod tests {
None
));
let mut peer = PageDocSession::new(DOC, 42).unwrap();
for frame in bridge.lock().unwrap().ws_sent(WsHandle(1)).unwrap() {
if let Some((_, body)) = frame.split_once('[') {
let data: serde_json::Value =
serde_json::from_str(&format!("[{body}")).unwrap();
if data[0] == "space:push-doc-update" && data[1]["docId"] == DOC {
let payload = data[1]["update"].as_str().unwrap();
let EngineIoPacket::Binary(bytes) =
EngineIoPacket::decode_text(&format!("b{payload}")).unwrap()
else {
panic!("expected binary update")
};
peer.apply_remote_update_v1(&bytes).unwrap();
}
for push in remote.take_pushes() {
if matches!(&push.address.route, DocRoute::Workspace { resource: WorkspaceResource::Page(id), .. } if id == DOC)
{
peer.apply_remote_update_v1(&push.update_v1).unwrap();
}
}
assert!(read_body(&peer).starts_with(BODY));
+19 -10
View File
@@ -801,10 +801,17 @@ mod tests {
use std::sync::{Arc, Mutex};
use affine_client::{HostKind, SqliteWorkspaceStore};
use affine_store::directory::DocId;
use affine_store::{DocRoute, WorkspaceResource, directory::DocId};
use blocksuite_playground_doc::read::BlockContent;
use crate::doc_store::SessionWriter;
mod memory_peer {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../client/tests/support/document_peer.rs"
));
}
let peer = memory_peer::MemoryDocumentPeer::default();
const SERVER: &str = "test-server";
const ORIGIN: &str = "https://example.com";
@@ -812,12 +819,12 @@ mod tests {
let space = state.store.active_workspace().id.clone();
let now = state.logical_clock_ms;
let sqlite = SqliteWorkspaceStore::open_in_memory(&space).await.unwrap();
let session = Arc::new(Mutex::new(
sqlite
.load_workspace_session("desktop", 41, HostKind::Native, SERVER, ORIGIN, now)
.await
.unwrap(),
));
let mut session = sqlite
.load_workspace_session("desktop", 41, HostKind::Native, SERVER, ORIGIN, now)
.await
.unwrap();
session.bind_document_peer(Box::new(peer.clone())).unwrap();
let session = Arc::new(Mutex::new(session));
state.store.bind_writer(SessionWriter::new(
space.clone(),
session.clone(),
@@ -829,9 +836,11 @@ mod tests {
let title = "Copy of AFFiNE Desktop Shell Architecture";
state.store.unbind_writer();
let mut session = Arc::into_inner(session).unwrap().into_inner().unwrap();
let queued = session.sync_engine().unwrap().offline_queue();
assert!(queued.iter().any(|update| update.doc_id == space));
assert!(queued.iter().any(|update| update.doc_id == copy));
let queued = peer.take_pushes();
assert!(queued.iter().any(|push| matches!(&push.address.route,
DocRoute::Workspace { id, resource: WorkspaceResource::Root } if id == &space)));
assert!(queued.iter().any(|push| matches!(&push.address.route,
DocRoute::Workspace { id, resource: WorkspaceResource::Page(page) } if id == &space && page == &copy)));
sqlite
.flush_session_mutations(&mut session, Some(SERVER), state.logical_clock_ms)
.await
@@ -3,7 +3,7 @@
use super::DesktopShellView;
use crate::doc_store::{PendingUpdates, SessionWriter, merge_pending_updates};
use affine_client::{ClientError, ClientResult, SqliteSyncHost, WorkspaceSession};
use affine_store::sync::SpaceSyncEvent;
use affine_store::PeerSyncEvent;
use std::{
cell::RefCell,
fs::{self, OpenOptions},
@@ -98,7 +98,7 @@ impl DesktopShellView {
session: Arc<Mutex<WorkspaceSession>>,
host: SqliteSyncHost,
now_ms: i64,
mut completed: impl FnMut(ClientResult<Vec<SpaceSyncEvent>>) + 'static,
mut completed: impl FnMut(ClientResult<Vec<PeerSyncEvent>>) + 'static,
cx: &mut Context<Self>,
) -> ClientResult<()> {
let workspace_id = self.state.store.active_workspace().id.clone();
+5 -2
View File
@@ -16,6 +16,7 @@ preview-typst = ["playground/preview-typst"]
[dependencies]
affine-client = { path = "../../client" }
affine-compat-v027 = { path = "../../compat-v027" }
affine-legacy-import = { path = "../../legacy-import" }
affine-mobile = { path = "../../mobile" }
affine-store = { path = "../../../common/store" }
@@ -30,13 +31,15 @@ serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
smallvec.workspace = true
sqlx.workspace = true
tokio.workspace = true
ui = { path = "../../../ui/ui" }
ui-tokens = { path = "../../../ui/tokens" }
url.workspace = true
uuid.workspace = true
y-octo.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
sqlx.workspace = true
tokio.workspace = true
[lints]
workspace = true
@@ -12,11 +12,11 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
pub use affine_store::auth::{
pub use affine_compat_v027::auth::{
PERMANENT_AUTH_ERROR_CODES, canonical_endpoint, is_permanent_auth_error_code,
legacy_storage_endpoint_key,
};
use affine_store::{
use affine_compat_v027::{
api_client::{
ApiClientKind, ApiHttpRequest, ApiRequestContext, AuthSessionExchangeRequest,
HEADER_AFFINE_VERSION, HEADER_CLIENT_KIND, build_auth_session_exchange_request,
+57 -1
View File
@@ -9,13 +9,51 @@
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
pub use affine_store::SpaceType;
use affine_store::sqlite::{
DocDiff, SqliteDocStorage, resolve_workspace_db_path, sanitize_peer_name,
};
pub use affine_store::sync::SpaceType;
use affine_store::workspace_db::PendingDocUpdate;
use tokio::runtime::{Builder, Runtime};
/// Open a cloud workspace with the native host's selected document peer.
pub async fn open_cloud_workspace(
base_dir: &Path,
server_id: &str,
space_id: &str,
account: &affine_store::AccountScope,
now_ms: i64,
) -> affine_client::ClientResult<(
affine_client::SqliteWorkspaceStore,
affine_client::WorkspaceSession,
)> {
use affine_client::{ClientError, HostKind, SqliteWorkspaceStore};
if matches!(server_id, "" | "local")
|| account.user_id.is_empty()
|| account.user_id == affine_store::LOCAL_USER_ID
{
return Err(ClientError::InvalidAuthPayload(
"cloud workspace requires a server and account".into(),
));
}
let client_id = blocksuite_playground_doc::try_random_client_id()
.map_err(|e| ClientError::Store(format!("making a client ID: {e}")))?;
let store = SqliteWorkspaceStore::open(base_dir, "workspace", server_id, space_id).await?;
let mut session = store
.load_workspace_session(
&account.user_id,
client_id,
HostKind::Native,
server_id,
account.origin.as_str(),
now_ms,
)
.await?;
affine_compat_v027::peer::LegacyDocumentPeer::bind_workspace(&mut session)?;
Ok((store, session))
}
/// Explicit SQLite busy timeout (milliseconds) applied to maintenance connections.
pub const SQLITE_BUSY_TIMEOUT_MS: u64 = 5_000;
@@ -552,6 +590,24 @@ impl AndroidSqliteBridge {
#[cfg(test)]
mod tests {
#[tokio::test]
async fn opens_cloud_sqlite_with_a_bound_document_peer() {
let path = unique_temp_dir("cloud-peer");
let account = affine_store::AccountScope {
origin: affine_store::CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "account".into(),
};
let (store, session) =
super::open_cloud_workspace(&path, "remote", "workspace", &account, 100)
.await
.unwrap();
assert!(session.document_peer().is_some());
assert_eq!(session.doc_address("workspace").unwrap().scope, account);
store.close().await;
std::fs::remove_dir_all(path).unwrap();
}
use std::borrow::Cow;
use std::time::Duration;
+5 -2
View File
@@ -15,6 +15,7 @@ preview-typst = ["playground/preview-typst"]
[dependencies]
affine-client = { path = "../../client" }
affine-compat-v027 = { path = "../../compat-v027" }
affine-legacy-import = { path = "../../legacy-import" }
affine-mobile = { path = "../../mobile" }
affine-store = { path = "../../../common/store" }
@@ -28,12 +29,14 @@ raw-window-handle.workspace = true
serde.workspace = true
serde_json.workspace = true
smallvec.workspace = true
sqlx.workspace = true
thiserror.workspace = true
tokio.workspace = true
ui = { path = "../../../ui/ui" }
ui-tokens = { path = "../../../ui/tokens" }
uuid.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
sqlx.workspace = true
tokio.workspace = true
[lints]
workspace = true
+2 -2
View File
@@ -1,8 +1,8 @@
pub use affine_store::auth::{
pub use affine_compat_v027::auth::{
auth_error_json_permanently_invalidates_session as auth_error_permanently_invalidates_session,
canonical_endpoint, legacy_storage_endpoint_key,
};
use affine_store::{
use affine_compat_v027::{
api_client::{
ApiClientKind, ApiHttpRequest, ApiRequestContext, AuthSessionExchangeRequest,
HEADER_AFFINE_VERSION, HEADER_CLIENT_KIND, build_auth_session_exchange_request,
@@ -17,6 +17,44 @@ use serde::Serialize;
use thiserror::Error;
use tokio::runtime::{Builder, Runtime};
/// Open a cloud workspace with the native host's selected document peer.
pub async fn open_cloud_workspace(
base_dir: &Path,
server_id: &str,
space_id: &str,
account: &affine_store::AccountScope,
now_ms: i64,
) -> affine_client::ClientResult<(
affine_client::SqliteWorkspaceStore,
affine_client::WorkspaceSession,
)> {
use affine_client::{ClientError, HostKind, SqliteWorkspaceStore};
if matches!(server_id, "" | "local")
|| account.user_id.is_empty()
|| account.user_id == affine_store::LOCAL_USER_ID
{
return Err(ClientError::InvalidAuthPayload(
"cloud workspace requires a server and account".into(),
));
}
let client_id = blocksuite_playground_doc::try_random_client_id()
.map_err(|e| ClientError::Store(format!("making a client ID: {e}")))?;
let store = SqliteWorkspaceStore::open(base_dir, "workspace", server_id, space_id).await?;
let mut session = store
.load_workspace_session(
&account.user_id,
client_id,
HostKind::Native,
server_id,
account.origin.as_str(),
now_ms,
)
.await?;
affine_compat_v027::peer::LegacyDocumentPeer::bind_workspace(&mut session)?;
Ok((store, session))
}
/// Explicit SQLite busy timeout (milliseconds) configured on every opened iOS host connection.
pub const SQLITE_BUSY_TIMEOUT_MS: u64 = 5_000;
@@ -369,6 +407,24 @@ impl IosWorkspaceHandle {
#[cfg(test)]
mod tests {
#[tokio::test]
async fn opens_cloud_sqlite_with_a_bound_document_peer() {
let path = unique_temp_dir("cloud-peer");
let account = affine_store::AccountScope {
origin: affine_store::CanonicalOrigin::parse("https://example.com").unwrap(),
user_id: "account".into(),
};
let (store, session) =
super::open_cloud_workspace(&path, "remote", "workspace", &account, 100)
.await
.unwrap();
assert!(session.document_peer().is_some());
assert_eq!(session.doc_address("workspace").unwrap().scope, account);
store.close().await;
std::fs::remove_dir_all(path).unwrap();
}
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
use sqlx::{Connection, sqlite::SqliteConnectOptions};
@@ -2,7 +2,7 @@
use crate::{MobileShellView, MobileWorkspaceBridge};
use affine_client::{ClientError, ClientResult, SqliteSyncHost};
use affine_store::sync::SpaceSyncEvent;
use affine_store::PeerSyncEvent;
use std::sync::Arc;
use ui::Context;
@@ -19,7 +19,7 @@ impl MobileShellView {
mut bridge: MobileWorkspaceBridge,
host: SqliteSyncHost,
now_ms: i64,
mut completed: impl FnMut(ClientResult<Vec<SpaceSyncEvent>>) + 'static,
mut completed: impl FnMut(ClientResult<Vec<PeerSyncEvent>>) + 'static,
cx: &mut Context<Self>,
) -> ClientResult<()> {
let workspace_id = self.state.active_workspace_id().to_owned();
@@ -11,7 +11,7 @@ use affine_client::{
#[cfg(not(target_family = "wasm"))]
use affine_client::{HostBridge, SqliteWorkspaceStore};
#[cfg(not(target_family = "wasm"))]
use affine_store::sync::SpaceSyncEvent;
use affine_store::PeerSyncEvent;
use affine_store::workspace_db::{
DocPropertiesRow, FavoriteKind, FolderRow, PendingDocUpdate, UserdataTableName,
WorkspaceDbTableName,
@@ -293,7 +293,7 @@ impl MobileWorkspaceBridge {
host: &mut dyn HostBridge,
ws_url: &str,
now_ms: i64,
) -> ClientResult<Vec<SpaceSyncEvent>> {
) -> ClientResult<Vec<PeerSyncEvent>> {
store
.on_sync_tick(&mut self.session, host, ws_url, now_ms)
.await
@@ -5,7 +5,6 @@
use std::{
cell::{Cell, RefCell},
collections::BTreeSet,
rc::Rc,
sync::{Arc, Mutex},
time::Duration,
@@ -14,62 +13,30 @@ use ui::{
Application, ApplicationHandle, HeadlessPlatform, WindowHandle, WindowOptions, prelude::*,
};
use affine_client::{HostKind, MemoryHostBridge, SqliteSyncHost, SqliteWorkspaceStore, WsHandle};
use affine_client::{
ClientError, HostKind, MemoryHostBridge, SqliteSyncHost, SqliteWorkspaceStore,
};
use affine_mobile::{
MobileAppState, MobileLocale, MobileShellView, MobileWorkspaceBridge, seed_showcase_state,
};
use affine_store::{DocRoute, WorkspaceResource};
use ui_tokens::ThemeMode;
const WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket";
mod memory_peer {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../client/tests/support/document_peer.rs"
));
}
const WS_URL: &str = "https://app.affine.pro";
const SERVER: &str = "affine-cloud";
const WS_ID: &str = "ws-mobile-rust";
fn sent_frames(host: &MemoryHostBridge) -> Vec<String> {
(0..16u64)
.filter_map(|h| host.ws_sent(WsHandle(h)))
.flat_map(|frames| frames.iter().cloned())
.collect()
}
fn ack_id(frame: &str) -> Option<u64> {
let rest = frame.strip_prefix("42")?;
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
digits.parse().ok()
}
/// Server reply to the request `frame` with ack ID `id`: every document is new to the server,
/// and the server accepts every push.
fn server_reply(frame: &str, id: u64) -> Option<String> {
if frame.contains("space:join-batch") {
Some(format!(
r#"43{id}[{{"data":{{"clientId":"c-1","success":true,"protocolVersion":1}}}}]"#
))
} else if frame.contains("space:load-doc-timestamps") {
Some(format!(r#"43{id}[{{"data":{{}}}}]"#))
} else if frame.contains("\"space:load-doc\"") {
Some(format!(
r#"43{id}[{{"error":{{"status":404,"code":"DOC_NOT_FOUND","name":"DOC_NOT_FOUND","message":"doc not found"}}}}]"#
))
} else if frame.contains("space:push-doc-update") {
Some(format!(
r#"43{id}[{{"data":{{"accepted":true,"timestamp":20000}}}}]"#
))
} else {
None
}
}
fn push_count(frames: &[String], doc_id: &str) -> usize {
let doc = format!("\"docId\":\"{doc_id}\"");
frames
.iter()
.filter(|f| f.contains("\"space:push-doc-update\"") && f.contains(&doc))
.count()
}
fn mount_connected_shell(
state: MobileAppState,
bridge: MobileWorkspaceBridge,
unbound: Option<MobileWorkspaceBridge>,
host: SqliteSyncHost,
) -> (
ApplicationHandle,
@@ -88,6 +55,13 @@ fn mount_connected_shell(
.open_window(WindowOptions::default(), |_, cx| {
cx.new(|cx| {
let mut shell = MobileShellView::new(state, cx);
if let Some(unbound) = unbound {
assert_eq!(
shell.connect_workspace(unbound, host.clone(), 2_000, |_| {}, cx),
Err(ClientError::MissingDocumentPeer)
);
assert!(shell.workspace_bridge().is_none());
}
shell
.connect_workspace(
bridge,
@@ -112,7 +86,7 @@ fn mount_connected_shell(
}
#[tokio::test]
async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
async fn mobile_cloud_connect_requires_peer_and_ticks_advance_unopened_docs() {
const DOCS: usize = 20;
let base_dir =
std::env::temp_dir().join(format!("affine-mobile-sync-tick-{}", std::process::id()));
@@ -175,7 +149,7 @@ async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
let store = SqliteWorkspaceStore::open(&base_dir, "workspace", SERVER, WS_ID)
.await
.unwrap();
let session = store
let mut session = store
.load_workspace_session(
"u-tick",
9902,
@@ -186,6 +160,12 @@ async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
)
.await
.unwrap();
let unbound = store
.load_workspace_session("u-tick", 9903, HostKind::Native, SERVER, WS_URL, 2_000)
.await
.unwrap();
let peer = memory_peer::MemoryDocumentPeer::with_empty_server();
session.bind_document_peer(Box::new(peer.clone())).unwrap();
let pending = session.pending_push_doc_ids();
assert!(doc_ids.iter().all(|id| pending.contains(id)));
let store = Arc::new(store);
@@ -200,34 +180,26 @@ async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
tokio::runtime::Handle::current(),
);
let state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-12-01");
let (app, platform, window, completed) =
mount_connected_shell(state, MobileWorkspaceBridge::new(session), host);
let deliver = |frame: Option<&str>, time| {
app.update(|cx| {
window
.update(cx, |view, _, _| {
let mut mounted = view.workspace_bridge_mut().unwrap();
let session = mounted.session_mut();
let mut host = transport.lock().unwrap();
match frame {
None => session.on_ws_open(&mut *host, WS_URL, time),
Some(text) => session.on_ws_text(&mut *host, WS_URL, text, time),
}
.unwrap();
})
.unwrap()
})
};
deliver(None, 2_000);
deliver(
Some(r#"0{"sid":"eio-1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#),
2_000,
let (app, platform, window, completed) = mount_connected_shell(
state,
MobileWorkspaceBridge::new(session),
Some(MobileWorkspaceBridge::new(unbound)),
host,
);
deliver(Some(r#"40{"sid":"sio-1"}"#), 2_000);
app.update(|cx| {
window
.update(cx, |view, _, _| {
let mut mounted = view.workspace_bridge_mut().unwrap();
mounted
.session_mut()
.on_ws_open(&mut *transport.lock().unwrap(), WS_URL, 2_000)
.unwrap();
})
.unwrap();
});
platform.advance_clock(Duration::from_millis(999));
platform.run_until_parked();
assert_eq!(completed.get(), 0);
let mut answered = BTreeSet::new();
let mut high_water = 0;
for tick in 1..=12 {
let delta = if tick == 1 { 1 } else { 1_000 };
@@ -237,15 +209,6 @@ async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
platform.run_until_parked();
tokio::task::yield_now().await;
}
let frames = sent_frames(&transport.lock().unwrap());
for frame in frames {
if let Some(id) = ack_id(&frame)
&& answered.insert(id)
&& let Some(reply) = server_reply(&frame, id)
{
deliver(Some(&reply), 2_000 + tick * 1_000);
}
}
let (unopened, loaded) = app.update(|cx| {
window
.update(cx, |view, _, _| {
@@ -281,9 +244,11 @@ async fn host_sync_tick_pushes_unopened_offline_docs_and_releases_them() {
})
.unwrap()
});
let frames = sent_frames(&transport.lock().unwrap());
let pushes = peer.take_pushes();
for id in &doc_ids {
assert_eq!(push_count(&frames, id), 1, "{id}");
assert_eq!(pushes.iter().filter(|push| matches!(&push.address.route,
DocRoute::Workspace { resource: WorkspaceResource::Page(page), .. } if page == id
)).count(), 1, "{id}");
let pushed = store
.storage()
.get_peer_pushed_clock(SERVER, id)
@@ -357,6 +322,10 @@ async fn tick_projects_interleaved_peer_and_shell_edits_to_the_same_page() {
};
let local = edit(22, "local-A");
let peer = edit(23, "peer-B");
bridge
.session_mut()
.bind_document_peer(Box::new(memory_peer::MemoryDocumentPeer::default()))
.unwrap();
// Keep the shell's first tick awaiting its worker while the two replicas receive edits.
let runtime = Builder::new_multi_thread()
@@ -376,7 +345,7 @@ async fn tick_projects_interleaved_peer_and_shell_edits_to_the_same_page() {
WS_URL.into(),
runtime.handle().clone(),
);
let (app, platform, window, completed) = mount_connected_shell(state, bridge, host);
let (app, platform, window, completed) = mount_connected_shell(state, bridge, None, host);
platform.advance_clock(Duration::from_secs(1));
platform.run_until_parked();
assert_eq!(completed.get(), 0);
@@ -448,7 +417,7 @@ async fn switching_before_the_first_tick_saves_the_new_page_and_title() {
.await
.unwrap(),
);
let session = store
let mut session = store
.load_workspace_session(
"mobile",
31,
@@ -459,6 +428,8 @@ async fn switching_before_the_first_tick_saves_the_new_page_and_title() {
)
.await
.unwrap();
let peer = memory_peer::MemoryDocumentPeer::default();
session.bind_document_peer(Box::new(peer.clone())).unwrap();
let transport = Arc::new(Mutex::new(MemoryHostBridge::new(
HostKind::Native,
"mobile",
@@ -471,7 +442,7 @@ async fn switching_before_the_first_tick_saves_the_new_page_and_title() {
);
let state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-12-01");
let (app, platform, window, ticks) =
mount_connected_shell(state, MobileWorkspaceBridge::new(session), host);
mount_connected_shell(state, MobileWorkspaceBridge::new(session), None, host);
let id = app.update(|cx| {
window
.update(cx, |view, _, cx| {
@@ -495,7 +466,14 @@ async fn switching_before_the_first_tick_saves_the_new_page_and_title() {
.unwrap()
});
assert_eq!(ticks.get(), 0);
assert_eq!(push_count(&sent_frames(&transport.lock().unwrap()), &id), 0);
assert!(!peer.take_pushes().is_empty());
assert!((0..16).all(|handle| {
transport
.lock()
.unwrap()
.ws_sent(affine_client::WsHandle(handle))
.is_none()
}));
store.close().await;
let reopened = SqliteWorkspaceStore::open(&dir, "workspace", SERVER, WS_ID)
.await
+35 -2
View File
@@ -52,6 +52,20 @@ PY
echo "Client workspace members:"
echo "$MEMBER_LINES"
echo "==> Checking normal dependency graphs and client wire isolation"
(
export CARGO_ENCODED_RUSTFLAGS=""
graph=$(mktemp)
trap 'rm -f "$graph"' EXIT
native_target=$(rustc -vV | sed -n 's/^host: //p')
for target in "$native_target" wasm32-unknown-unknown; do
cargo metadata --locked --format-version 1 --filter-platform "$target" >"$graph"
node "$REPO_ROOT/scripts/ci/client-compat.mjs" "$graph" "$target"
done
node --test "$REPO_ROOT/scripts/ci/client-compat.test.mjs"
node "$REPO_ROOT/scripts/ci/check-l0-tier-a.mjs"
)
echo "==> Checking test targets that require the harness feature"
WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY'
import json
@@ -197,6 +211,10 @@ ALLOWED_DEPS = {
"packages/common/store",
"packages/frontend/legacy-import",
},
"packages/frontend/compat-v027": {
"packages/common/store",
"packages/frontend/client",
},
"packages/frontend/mobile": UI_ALL | BS_LOWER | {
"blocksuite/crates/playground",
"packages/common/store",
@@ -227,7 +245,9 @@ def is_allowed_edge(src_rel: str, dep_rel: str) -> bool:
if src_rel.startswith("packages/frontend/hosts/"):
parts = src_rel.split("/")
if len(parts) == 4 and parts[3]:
return dep_rel in HOST_ALLOWED
return dep_rel in HOST_ALLOWED or (
parts[3] in {"ios", "android"} and dep_rel == "packages/frontend/compat-v027"
)
return False
allowed = ALLOWED_DEPS.get(src_rel)
if allowed is None:
@@ -242,6 +262,8 @@ POSITIVE_FIXTURES = [
("packages/common/store", "blocksuite/crates/doc"),
("packages/frontend/mobile", "packages/frontend/client"),
("packages/frontend/hosts/ios", "packages/frontend/mobile"),
("packages/frontend/hosts/android", "packages/frontend/compat-v027"),
("packages/frontend/compat-v027", "packages/frontend/client"),
]
NEGATIVE_FIXTURES = [
("packages/ui/ui", "packages/ui/kit"),
@@ -255,6 +277,9 @@ NEGATIVE_FIXTURES = [
("packages/frontend/mobile", "packages/frontend/desktop"),
("packages/frontend/hosts/ios", "packages/frontend/hosts/android"),
("packages/frontend/unregistered", "packages/ui/ui"),
("packages/frontend/client", "packages/frontend/compat-v027"),
("packages/frontend/desktop", "packages/frontend/compat-v027"),
("packages/frontend/hosts/web", "packages/frontend/compat-v027"),
]
for s_rel, d_rel in POSITIVE_FIXTURES:
@@ -292,6 +317,10 @@ for pkg in meta["packages"]:
if dep_name not in pkg_rel:
continue
dep_rel = pkg_rel[dep_name]
if (src_rel == "packages/frontend/compat-v027"
and dep_rel == "blocksuite/crates/doc"
and dep.get("kind") == "dev"):
continue
if not is_allowed_edge(src_rel, dep_rel):
errors.append(f"{src_name} ({src_rel}) must not depend on {dep_name} ({dep_rel})")
@@ -773,4 +802,8 @@ fi
echo "==> Checking snapshot prefix liveness"
node "$SCRIPT_DIR/check-snapshot-prefixes.mjs" --source-only
echo "All static invariants passed."
echo "==> Checking core builds without the compatibility adapter"
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-store -p affine-client -p affine-desktop -p affine-mobile
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-store -p affine-client -p affine-desktop -p affine-mobile --target wasm32-unknown-unknown
echo "All invariants passed."
+19 -2
View File
@@ -20,6 +20,7 @@
// 7. compat-backlog: every `// compat(<kind>): <slug> -- <reason>` marker in
// packages/backend/ production Rust has a `### <slug>` entry in
// docs/post-cutover-ablation-backlog.md, and every entry has a marker.
// Rust client core sources also reject legacy wire syntax without a tracked marker.
// 8. Directory classification: every first-level subdirectory under
// packages/frontend/, packages/common/, and blocksuite/ belongs to a known
// legacy Web set or a known Rust/client set, and native-playground.yml's
@@ -36,6 +37,8 @@ import {
import { join, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { checkClientWireBoundary } from './client-compat.mjs';
const started = performance.now();
const ROOT = fileURLToPath(new URL('../..', import.meta.url));
const BASELINE_PATH = join(ROOT, 'scripts/ci/l0-ratchet.json');
@@ -736,8 +739,21 @@ for (const abs of walk(CRATES)) {
if (!existsSync(COMPAT_BACKLOG_PATH)) {
fail('compat-backlog', 'missing docs/post-cutover-ablation-backlog.md');
} else {
const backlog = read(COMPAT_BACKLOG_PATH);
const clientWire = checkClientWireBoundary(ROOT, backlog);
for (const err of clientWire.errors) fail('client-compat', err);
for (const [slug, at] of clientWire.markers) {
if (markerSlugs.has(slug)) {
fail(
'compat-backlog',
`${at}: slug ${slug} is already used at ${markerSlugs.get(slug)}`
);
} else {
markerSlugs.set(slug, at);
}
}
const docSlugs = new Set();
for (const m of read(COMPAT_BACKLOG_PATH).matchAll(/^### (.+)$/gm)) {
for (const m of backlog.matchAll(/^### (.+)$/gm)) {
const slug = m[1].trim();
if (docSlugs.has(slug)) {
fail(
@@ -759,7 +775,7 @@ if (!existsSync(COMPAT_BACKLOG_PATH)) {
if (!markerSlugs.has(slug)) {
fail(
'compat-backlog',
`docs/post-cutover-ablation-backlog.md: ${slug} has no compat marker in packages/backend/`
`docs/post-cutover-ablation-backlog.md: ${slug} has no compat marker`
);
}
}
@@ -789,6 +805,7 @@ const DOMAIN_CLASSIFICATION = {
]),
newRust: new Set([
'client',
'compat-v027',
'desktop',
'hosts',
'legacy-import',
+147
View File
@@ -0,0 +1,147 @@
import { readdirSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
const marker =
/\/\/ compat\(client-0275\): ([a-z0-9]+(?:-[a-z0-9]+)*)(?:\s*--\s*\S.*)?$/;
const forbiddenWire =
/"space:|\b\w*(?:SocketIo|EngineIo)\w*\b|"\/graphql|"affine_session"|"x-affine-version"|"\/api\/(?:auth|oauth)\/|"affine_csrf_token"|"x-affine-(?:client-kind|refresh-attempt)"/;
const guardedRoots = [
'packages/common/store/src',
'packages/frontend/client/src',
'packages/frontend/desktop/src',
'packages/frontend/mobile/src',
'blocksuite/crates',
];
function* rustFiles(root) {
for (const entry of readdirSync(root, { withFileTypes: true })) {
const path = join(root, entry.name);
if (
entry.isDirectory() &&
!['target', 'node_modules', '.git'].includes(entry.name)
) {
yield* rustFiles(path);
} else if (entry.isFile() && entry.name.endsWith('.rs')) {
yield path;
}
}
}
export function checkWireSources(sources, backlog) {
const errors = [];
const markers = new Map();
const headings = new Set();
for (const match of backlog.matchAll(/^### (.+)\s*$/gm)) {
headings.add(match[1].trim());
}
for (const [path, source] of sources) {
source.split('\n').forEach((line, index) => {
const location = `${path}:${index + 1}`;
const slug = marker.exec(line)?.[1];
if (slug && markers.has(slug)) {
errors.push(
`${location}: marker ${slug} already occurs at ${markers.get(slug)}`
);
} else if (slug) {
markers.set(slug, location);
}
if (forbiddenWire.test(line) && !slug) {
errors.push(
`${location}: legacy wire syntax requires a compatibility marker`
);
}
});
}
for (const [slug, location] of markers) {
if (!headings.has(slug)) {
errors.push(`${location}: no ablation backlog entry for ${slug}`);
}
}
return { errors, markers };
}
export function checkClientWireBoundary(root, backlog) {
const sources = guardedRoots.flatMap(dir =>
[...rustFiles(join(root, dir))].map(path => [
relative(root, path),
readFileSync(path, 'utf8'),
])
);
return checkWireSources(sources, backlog);
}
const corePackages = [
'affine-store',
'affine-client',
'affine-desktop',
'affine-mobile',
'blocksuite-playground-doc',
'blocksuite-editor',
'playground',
'blocksuite-preview',
];
const forbiddenWasm = new Set([
'reqwest',
'hyper',
'rustls',
'tokio',
'graphql_client',
'tokio-tungstenite',
'openssl',
'native-tls',
]);
export function checkNormalDependencies(metadata, wasm) {
const packages = new Map(metadata.packages.map(pkg => [pkg.id, pkg.name]));
const nodes = new Map(
metadata.resolve.nodes.map(node => [node.id, node.deps])
);
const members = new Map(
metadata.workspace_members.map(id => [packages.get(id), id])
);
const errors = [];
function visit(from, forbidden) {
const visited = new Set();
const pending = [from];
while (pending.length) {
const id = pending.pop();
if (visited.has(id)) continue;
visited.add(id);
const name = packages.get(id);
if (forbidden.has(name)) {
errors.push(
`${packages.get(from)} can reach ${name} through normal dependencies`
);
}
for (const dep of nodes.get(id) ?? []) {
if (dep.dep_kinds.some(edge => edge.kind === null))
pending.push(dep.pkg);
}
}
}
for (const name of corePackages) {
if (!members.has(name)) {
errors.push(`missing core workspace package ${name}`);
continue;
}
visit(members.get(name), new Set(['affine-compat-v027']));
}
if (wasm) {
for (const id of members.values()) visit(id, forbiddenWasm);
}
return errors;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [path, target] = process.argv.slice(2);
const errors = checkNormalDependencies(
JSON.parse(readFileSync(path, 'utf8')),
target === 'wasm32-unknown-unknown'
);
for (const error of errors) console.error(error);
if (errors.length) process.exitCode = 1;
}
+83
View File
@@ -0,0 +1,83 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { checkNormalDependencies, checkWireSources } from './client-compat.mjs';
void test('the source gate rejects protocol syntax and untracked or duplicate markers', () => {
for (const source of [
'"space:load-doc"',
'SocketIoPacket',
'EngineIoOutput',
'"/graphql"',
'"affine_session"',
'"x-affine-version"',
'"/api/auth/sign-in"',
'"/api/oauth/start"',
'"affine_csrf_token"',
'"x-affine-client-kind"',
'"x-affine-refresh-attempt"',
]) {
for (const [suffix, docs, errors] of [
['', '', 1],
[' // compat(client-0275): old-wire', '', 1],
[' // compat(client-0275): old-wire', '### old-wire', 0],
]) {
const result = checkWireSources([['core.rs', source + suffix]], docs);
assert.equal(result.errors.length, errors, source + suffix);
}
}
const source = '"space:x" // compat(client-0275): duplicate';
assert.equal(
checkWireSources([['core.rs', `${source}\n${source}`]], '### duplicate')
.errors.length,
1
);
});
void test('the graph gate follows transitive normal edges for each platform', () => {
const members = [
'affine-store',
'affine-client',
'affine-desktop',
'affine-mobile',
'blocksuite-playground-doc',
'blocksuite-editor',
'playground',
'blocksuite-preview',
'affine-compat-v027',
];
for (const [name, kind, wasm, errors] of [
['affine-compat-v027', null, false, 1],
['affine-compat-v027', null, true, 1],
['affine-compat-v027', 'dev', false, 0],
['affine-compat-v027', 'build', true, 0],
['tokio', null, false, 0],
['tokio', null, true, 1],
['reqwest', null, true, 1],
['hyper', null, true, 1],
['rustls', null, true, 1],
...['graphql_client', 'tokio-tungstenite', 'openssl', 'native-tls'].map(
name => [name, null, true, 1]
),
]) {
const edge = (pkg, kind) => ({ pkg, dep_kinds: [{ kind }] });
const packages = [...new Set([...members, 'indirect', name])].map(id => ({
id,
name: id,
}));
const nodes = packages.map(({ id }) => ({
id,
deps:
id === 'affine-store'
? [edge('indirect', null)]
: id === 'indirect'
? [edge(name, kind)]
: [],
}));
const actual = checkNormalDependencies(
{ packages, workspace_members: members, resolve: { nodes } },
wasm
);
assert.equal(actual.length, errors, [name, kind, wasm].join(','));
}
});