Skip to content

Commit bea0fd8

Browse files
committed
[refactor] 0.2.0
1. unused and remove `bytes::Bytes` 2. add Error types
1 parent 91c6d9b commit bea0fd8

File tree

7 files changed

+38
-44
lines changed

7 files changed

+38
-44
lines changed

Cargo.lock

Lines changed: 2 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

yrs-postgres/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "yrs-postgres"
3-
version = "0.1.0"
3+
version = "0.2.0"
44
edition = "2024"
55
description = "Simple store layer over Yrs documents"
66
license = "MIT"
@@ -11,7 +11,6 @@ repository = "https://github.com/icode/yrs-store"
1111
readme = "./README.md"
1212

1313
[dependencies]
14-
bytes = "1.10.1"
1514
chrono = { version = "0.4", features = ["serde"] }
1615
futures-util = "0.3.31"
1716
sqlx = { version = "0.8", default-features = false, features = ["postgres", "chrono", "runtime-tokio"] }
@@ -20,7 +19,7 @@ tokio = { version = "1.44", features = ["macros", "rt-multi-thread"] }
2019
yrs = { version = "0.23", features = ["sync", "weak"] }
2120
async-trait = "0.1.88"
2221

23-
yrs-store = { version = "0.1", path = "../yrs-store" }
22+
yrs-store = { version = "0.2", path = "../yrs-store" }
2423

2524
[dev-dependencies]
2625
sqlx = { version = "0.8", default-features = false, features = ["macros", "postgres"] }

yrs-postgres/src/lib.rs

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use async_stream;
22
use async_trait::async_trait;
3-
use bytes::Bytes;
43
use chrono::NaiveDateTime;
54
use futures_util::stream::BoxStream;
65
use futures_util::TryStreamExt;
@@ -33,6 +32,10 @@ impl PostgresStorage {
3332
}
3433
}
3534

35+
fn map_sqlx_err(error: sqlx::Error) -> StoreError {
36+
StoreError::StorageError(Box::new(error))
37+
}
38+
3639
#[async_trait]
3740
impl Store for PostgresStorage {
3841
async fn delete(&self) -> Result<(), StoreError> {
@@ -44,22 +47,22 @@ impl Store for PostgresStorage {
4447
.execute(&self.pool)
4548
.await
4649
.map(|_| ())
47-
.map_err(StoreError::SqlxError)
50+
.map_err(map_sqlx_err)
4851
}
4952

50-
async fn write(&self, update: &Bytes) -> Result<(), StoreError> {
53+
async fn write(&self, update: &Vec<u8>) -> Result<(), StoreError> {
5154
let document_id = self.document_id.clone();
5255
let now = chrono::Utc::now().naive_utc();
5356
let query_result = sqlx::query(&format!(
5457
"INSERT INTO {} (document_id, payload, timestamp) VALUES ($1, $2, $3)",
5558
self.table_name
5659
))
5760
.bind(document_id)
58-
.bind(update.as_ref())
61+
.bind(update)
5962
.bind(now)
6063
.execute(&self.pool)
6164
.await
62-
.map_err(StoreError::SqlxError)?;
65+
.map_err(map_sqlx_err)?;
6366

6467
let rows_affected = query_result.rows_affected();
6568

@@ -74,7 +77,7 @@ impl Store for PostgresStorage {
7477
Ok(())
7578
}
7679

77-
async fn read(&self) -> Result<BoxStream<Result<(Bytes, i64), StoreError>>, StoreError> {
80+
async fn read(&self) -> Result<BoxStream<Result<(Vec<u8>, i64), StoreError>>, StoreError> {
7881
let document_id = self.document_id;
7982
let table_name = self.table_name.clone();
8083
let pool = self.pool.clone();
@@ -89,9 +92,8 @@ impl Store for PostgresStorage {
8992
.bind(document_id)
9093
.fetch(&pool);
9194

92-
while let Some(row) = rows.try_next().await.map_err(StoreError::SqlxError)? {
93-
let payload_vec: Vec<u8> = row.get("payload");
94-
let payload = payload_vec.into();
95+
while let Some(row) = rows.try_next().await.map_err(map_sqlx_err)? {
96+
let payload: Vec<u8> = row.get("payload");
9597
let timestamp_ndt: NaiveDateTime = row.get("timestamp");
9698
let timestamp_ms = timestamp_ndt.and_utc().timestamp_millis();
9799
yield Ok((payload, timestamp_ms));
@@ -101,7 +103,7 @@ impl Store for PostgresStorage {
101103
Ok(Box::pin(stream))
102104
}
103105

104-
async fn read_payloads(&self) -> Result<BoxStream<Result<Bytes, StoreError>>, StoreError> {
106+
async fn read_payloads(&self) -> Result<BoxStream<Result<Vec<u8>, StoreError>>, StoreError> {
105107
let document_id = self.document_id;
106108
let table_name = self.table_name.clone();
107109
let pool = self.pool.clone();
@@ -116,9 +118,8 @@ impl Store for PostgresStorage {
116118
.bind(document_id)
117119
.fetch(&pool);
118120

119-
while let Some(row) = rows.try_next().await.map_err(StoreError::SqlxError)? {
120-
let payload_vec: Vec<u8> = row.get("payload");
121-
let payload = payload_vec.into();
121+
while let Some(row) = rows.try_next().await.map_err(map_sqlx_err)? {
122+
let payload: Vec<u8> = row.get("payload");
122123
yield Ok(payload);
123124
}
124125
};
@@ -129,28 +130,28 @@ impl Store for PostgresStorage {
129130
async fn squash(&self) -> Result<(), StoreError> {
130131
let doc = Doc::new();
131132
self.load(&doc).await?;
132-
let tx = self.pool.begin().await.map_err(StoreError::SqlxError)?;
133+
let tx = self.pool.begin().await.map_err(map_sqlx_err)?;
133134
sqlx::query(&format!(
134135
"DELETE FROM {} WHERE document_id = $1",
135136
self.table_name
136137
))
137138
.bind(self.document_id)
138139
.execute(&self.pool)
139140
.await
140-
.map_err(StoreError::SqlxError)?;
141+
.map_err(map_sqlx_err)?;
141142

142143
let squashed_update = doc.get_update();
143144
self.write(&squashed_update).await?;
144145

145146
// 如果在事务超出范围之前都未调用,rollback则自动调用
146-
tx.commit().await.map_err(StoreError::SqlxError)?;
147+
tx.commit().await.map_err(map_sqlx_err)?;
147148

148149
if self.run_vacuum {
149150
// 回收死行占据的存储空间
150151
sqlx::query(&format!("VACUUM {}", self.table_name))
151152
.execute(&self.pool)
152153
.await
153-
.map_err(StoreError::SqlxError)?;
154+
.map_err(map_sqlx_err)?;
154155
}
155156
Ok(())
156157
}

yrs-store/Cargo.toml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "yrs-store"
3-
version = "0.1.0"
3+
version = "0.2.0"
44
edition = "2024"
55
description = "Simple store layer over Yrs documents"
66
license = "MIT"
@@ -11,8 +11,6 @@ repository = "https://github.com/icode/yrs-store"
1111
readme = "./README.md"
1212

1313
[dependencies]
14-
bytes = "1.10.1"
1514
futures-util = "0.3.31"
16-
sqlx = { version = "0.8", default-features = false }
1715
yrs = { version = "0.23", features = ["sync", "weak"] }
1816
async-trait = "0.1.88"

yrs-store/src/doc.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use bytes::Bytes;
21
use std::collections::HashMap;
32
use yrs::error::{Error, UpdateError};
43
use yrs::updates::decoder::Decode;
@@ -8,29 +7,29 @@ use yrs::{
87
};
98

109
pub trait ForStore {
11-
fn get_update(&self) -> Bytes;
12-
fn diff_state_update(&self, state: &Bytes) -> Result<Bytes, Error>;
13-
fn apply_update(&self, txn: &mut TransactionMut, update: &Bytes) -> Result<(), UpdateError>;
10+
fn get_update(&self) -> Vec<u8>;
11+
fn diff_state_update(&self, state: &Vec<u8>) -> Result<Vec<u8>, Error>;
12+
fn apply_update(&self, txn: &mut TransactionMut, update: &Vec<u8>) -> Result<(), UpdateError>;
1413
fn roots(&self, txn: &Transaction<'static>) -> HashMap<String, Out>;
1514
fn observe<F>(&self, f: F) -> Result<Subscription, TransactionAcqError>
1615
where
1716
F: Fn(&TransactionMut, &TransactionCleanupEvent) + Send + Sync + 'static;
1817
}
1918

2019
impl ForStore for Doc {
21-
fn get_update(&self) -> Bytes {
20+
fn get_update(&self) -> Vec<u8> {
2221
self.transact()
2322
.encode_state_as_update_v1(&StateVector::default())
2423
.into()
2524
}
2625

27-
fn diff_state_update(&self, state: &Bytes) -> Result<Bytes, Error> {
26+
fn diff_state_update(&self, state: &Vec<u8>) -> Result<Vec<u8>, Error> {
2827
let state_vector = StateVector::decode_v1(&state.as_ref())?;
2928
let update = self.transact().encode_state_as_update_v1(&state_vector);
3029
Ok(update.into())
3130
}
3231

33-
fn apply_update(&self, txn: &mut TransactionMut, update: &Bytes) -> Result<(), UpdateError> {
32+
fn apply_update(&self, txn: &mut TransactionMut, update: &Vec<u8>) -> Result<(), UpdateError> {
3433
let u = Update::decode_v1(update.as_ref()).unwrap();
3534
txn.apply_update(u)
3635
}

yrs-store/src/errors.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::error::Error;
12
use std::fmt;
23
use yrs::error::UpdateError;
34

@@ -6,18 +7,20 @@ pub enum StoreError {
67
UpdateError(UpdateError),
78
YrsError(yrs::error::Error),
89
WriteError(String),
9-
SqlxError(sqlx::Error),
10+
Error(Box<dyn Error + Send + Sync + 'static>),
11+
StorageError(Box<dyn Error + Send + Sync + 'static>),
1012
}
1113

1214
impl fmt::Display for StoreError {
1315
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1416
match self {
1517
StoreError::UpdateError(e) => e.fmt(f),
16-
StoreError::SqlxError(e) => e.fmt(f),
18+
StoreError::Error(e) => e.fmt(f),
19+
StoreError::StorageError(e) => e.fmt(f),
1720
StoreError::YrsError(e) => e.fmt(f),
1821
StoreError::WriteError(msg) => write!(f, "Write error: {}", msg),
1922
}
2023
}
2124
}
2225

23-
impl std::error::Error for StoreError {}
26+
impl Error for StoreError {}

yrs-store/src/lib.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@ pub mod errors;
44
use crate::doc::ForStore;
55
use crate::errors::StoreError;
66
use async_trait::async_trait;
7-
use bytes::Bytes;
87
use futures_util::stream::BoxStream;
98
use futures_util::{StreamExt};
10-
use std::pin::pin;
119
use yrs::{Doc, Transact};
1210

1311
#[async_trait]
@@ -19,9 +17,9 @@ pub trait Store: Send + Sync {
1917
Ok(())
2018
}
2119
async fn delete(&self) -> Result<(), StoreError>;
22-
async fn write(&self, update: &Bytes) -> Result<(), StoreError>;
23-
async fn read(&self) -> Result<BoxStream<Result<(Bytes, i64), StoreError>>, StoreError>;
24-
async fn read_payloads(&self) -> Result<BoxStream<Result<Bytes, StoreError>>, StoreError>;
20+
async fn write(&self, update: &Vec<u8>) -> Result<(), StoreError>;
21+
async fn read(&self) -> Result<BoxStream<Result<(Vec<u8>, i64), StoreError>>, StoreError>;
22+
async fn read_payloads(&self) -> Result<BoxStream<Result<Vec<u8>, StoreError>>, StoreError>;
2523
async fn squash(&self) -> Result<(), StoreError>;
2624
/// save a YDoc updates
2725
/// # Arguments
@@ -36,7 +34,6 @@ pub trait Store: Send + Sync {
3634
async fn load(&self, doc: &Doc) -> Result<(), StoreError> {
3735
let mut txn = doc.transact_mut();
3836
let mut streams = self.read_payloads().await?;
39-
let mut streams = pin!(streams);
4037
while let Some(result) = streams.next().await {
4138
let update = result?;
4239
doc.apply_update(&mut txn, &update)

0 commit comments

Comments
 (0)