chore: replace uuid with nanoid

This commit is contained in:
appflowy
2022-04-11 15:27:03 +08:00
parent f438898831
commit 82840e1201
33 changed files with 133 additions and 120 deletions

View File

@ -73,7 +73,7 @@ class FlowyGrid extends StatefulWidget {
class _FlowyGridState extends State<FlowyGrid> { class _FlowyGridState extends State<FlowyGrid> {
final _scrollController = GridScrollController(); final _scrollController = GridScrollController();
// final _key = GlobalKey<SliverAnimatedListState>(); final _key = GlobalKey<SliverAnimatedListState>();
@override @override
void dispose() { void dispose() {

View File

@ -919,6 +919,7 @@ dependencies = [
"flowy-error-code", "flowy-error-code",
"lib-infra", "lib-infra",
"log", "log",
"nanoid",
"protobuf", "protobuf",
"serde", "serde",
"serde_json", "serde_json",
@ -926,7 +927,6 @@ dependencies = [
"strum", "strum",
"strum_macros", "strum_macros",
"unicode-segmentation", "unicode-segmentation",
"uuid",
] ]
[[package]] [[package]]
@ -951,6 +951,7 @@ dependencies = [
"lib-dispatch", "lib-dispatch",
"lib-infra", "lib-infra",
"lib-ot", "lib-ot",
"nanoid",
"protobuf", "protobuf",
"rayon", "rayon",
"rust_decimal", "rust_decimal",
@ -962,7 +963,6 @@ dependencies = [
"strum_macros", "strum_macros",
"tokio", "tokio",
"tracing", "tracing",
"uuid",
] ]
[[package]] [[package]]
@ -974,13 +974,13 @@ dependencies = [
"flowy-error-code", "flowy-error-code",
"indexmap", "indexmap",
"lib-infra", "lib-infra",
"nanoid",
"protobuf", "protobuf",
"serde", "serde",
"serde_json", "serde_json",
"serde_repr", "serde_repr",
"strum", "strum",
"strum_macros", "strum_macros",
"uuid",
] ]
[[package]] [[package]]
@ -1008,6 +1008,7 @@ dependencies = [
"lib-infra", "lib-infra",
"lib-ws", "lib-ws",
"log", "log",
"nanoid",
"parking_lot", "parking_lot",
"protobuf", "protobuf",
"reqwest", "reqwest",
@ -1122,6 +1123,7 @@ dependencies = [
"lib-infra", "lib-infra",
"lib-ot", "lib-ot",
"log", "log",
"nanoid",
"protobuf", "protobuf",
"quickcheck", "quickcheck",
"quickcheck_macros", "quickcheck_macros",
@ -1190,6 +1192,7 @@ dependencies = [
"lib-dispatch", "lib-dispatch",
"lib-infra", "lib-infra",
"log", "log",
"nanoid",
"once_cell", "once_cell",
"parking_lot", "parking_lot",
"protobuf", "protobuf",
@ -1702,6 +1705,7 @@ dependencies = [
"futures-util", "futures-util",
"lazy_static", "lazy_static",
"log", "log",
"nanoid",
"paste", "paste",
"pin-project", "pin-project",
"protobuf", "protobuf",
@ -1711,7 +1715,6 @@ dependencies = [
"thread-id", "thread-id",
"tokio", "tokio",
"tracing", "tracing",
"uuid",
] ]
[[package]] [[package]]
@ -1740,7 +1743,6 @@ dependencies = [
"tera", "tera",
"tokio", "tokio",
"toml", "toml",
"uuid",
"walkdir", "walkdir",
] ]
@ -1965,6 +1967,15 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "nanoid"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
dependencies = [
"rand 0.8.4",
]
[[package]] [[package]]
name = "native-tls" name = "native-tls"
version = "0.2.8" version = "0.2.8"
@ -3587,7 +3598,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [ dependencies = [
"getrandom 0.2.3", "getrandom 0.2.3",
"serde",
] ]
[[package]] [[package]]

View File

@ -14,10 +14,9 @@ use crate::{
}; };
use bytes::Bytes; use bytes::Bytes;
use flowy_database::kv::KV; use flowy_database::kv::KV;
use flowy_folder_data_model::entities::view::ViewDataType; use flowy_folder_data_model::entities::view::{gen_view_id, ViewDataType};
use flowy_sync::entities::text_block_info::TextBlockId; use flowy_sync::entities::text_block_info::TextBlockId;
use futures::{FutureExt, StreamExt}; use futures::{FutureExt, StreamExt};
use lib_infra::uuid;
use std::{collections::HashSet, sync::Arc}; use std::{collections::HashSet, sync::Arc};
const LATEST_VIEW_ID: &str = "latest_view_id"; const LATEST_VIEW_ID: &str = "latest_view_id";
@ -171,7 +170,7 @@ impl ViewController {
thumbnail: view.thumbnail, thumbnail: view.thumbnail,
data_type: view.data_type, data_type: view.data_type,
data: delta_bytes.to_vec(), data: delta_bytes.to_vec(),
view_id: uuid(), view_id: gen_view_id(),
plugin_type: view.plugin_type, plugin_type: view.plugin_type,
}; };

View File

@ -25,7 +25,7 @@ rust_decimal = "1.8.1"
rusty-money = {version = "0.4.0", features = ["iso"]} rusty-money = {version = "0.4.0", features = ["iso"]}
lazy_static = "1.4.0" lazy_static = "1.4.0"
chrono = "0.4.19" chrono = "0.4.19"
uuid = { version = "0.8", features = ["serde", "v4"] } nanoid = "0.4.0"
bytes = { version = "1.0" } bytes = { version = "1.0" }
diesel = {version = "1.4.8", features = ["sqlite"]} diesel = {version = "1.4.8", features = ["sqlite"]}
dashmap = "4.0" dashmap = "4.0"

View File

@ -1,6 +1,6 @@
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::{NotEmptyStr, NotEmptyUuid}; use flowy_grid_data_model::parser::NotEmptyStr;
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct CreateSelectOptionPayload { pub struct CreateSelectOptionPayload {
@ -51,9 +51,9 @@ impl TryInto<CellIdentifier> for CellIdentifierPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CellIdentifier, Self::Error> { fn try_into(self) -> Result<CellIdentifier, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyUuid::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
let row_id = NotEmptyUuid::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?; let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
Ok(CellIdentifier { Ok(CellIdentifier {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,

View File

@ -1,6 +1,6 @@
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyUuid; use flowy_grid_data_model::parser::NotEmptyStr;
#[derive(Debug, Clone, Default, ProtoBuf)] #[derive(Debug, Clone, Default, ProtoBuf)]
pub struct FieldIdentifierPayload { pub struct FieldIdentifierPayload {
@ -20,8 +20,8 @@ impl TryInto<FieldIdentifier> for FieldIdentifierPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<FieldIdentifier, Self::Error> { fn try_into(self) -> Result<FieldIdentifier, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyUuid::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
Ok(FieldIdentifier { Ok(FieldIdentifier {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,

View File

@ -2,14 +2,14 @@ use crate::impl_type_option;
use crate::services::cell::{CellIdentifier, CellIdentifierPayload}; use crate::services::cell::{CellIdentifier, CellIdentifierPayload};
use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder}; use crate::services::field::{BoxTypeOptionBuilder, TypeOptionBuilder};
use crate::services::row::{CellDataChangeset, CellDataOperation, TypeOptionCellData}; use crate::services::row::{CellDataChangeset, CellDataOperation, TypeOptionCellData};
use crate::services::util::*;
use bytes::Bytes; use bytes::Bytes;
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::{ErrorCode, FlowyError}; use flowy_error::{ErrorCode, FlowyError};
use flowy_grid_data_model::entities::{ use flowy_grid_data_model::entities::{
CellChangeset, CellMeta, FieldMeta, FieldType, TypeOptionDataDeserializer, TypeOptionDataEntry, CellChangeset, CellMeta, FieldMeta, FieldType, TypeOptionDataDeserializer, TypeOptionDataEntry,
}; };
use flowy_grid_data_model::parser::NotEmptyUuid; use flowy_grid_data_model::parser::NotEmptyStr;
use nanoid::nanoid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
@ -260,7 +260,7 @@ pub struct SelectOption {
impl SelectOption { impl SelectOption {
pub fn new(name: &str) -> Self { pub fn new(name: &str) -> Self {
SelectOption { SelectOption {
id: uuid(), id: nanoid!(4),
name: name.to_owned(), name: name.to_owned(),
color: SelectOptionColor::default(), color: SelectOptionColor::default(),
} }
@ -376,13 +376,13 @@ impl TryInto<SelectOptionCellChangesetParams> for SelectOptionCellChangesetPaylo
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<SelectOptionCellChangesetParams, Self::Error> { fn try_into(self) -> Result<SelectOptionCellChangesetParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let row_id = NotEmptyUuid::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?; let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
let field_id = NotEmptyUuid::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
let insert_option_id = match self.insert_option_id { let insert_option_id = match self.insert_option_id {
None => None, None => None,
Some(insert_option_id) => Some( Some(insert_option_id) => Some(
NotEmptyUuid::parse(insert_option_id) NotEmptyStr::parse(insert_option_id)
.map_err(|_| ErrorCode::OptionIdIsEmpty)? .map_err(|_| ErrorCode::OptionIdIsEmpty)?
.0, .0,
), ),
@ -391,7 +391,7 @@ impl TryInto<SelectOptionCellChangesetParams> for SelectOptionCellChangesetPaylo
let delete_option_id = match self.delete_option_id { let delete_option_id = match self.delete_option_id {
None => None, None => None,
Some(delete_option_id) => Some( Some(delete_option_id) => Some(
NotEmptyUuid::parse(delete_option_id) NotEmptyStr::parse(delete_option_id)
.map_err(|_| ErrorCode::OptionIdIsEmpty)? .map_err(|_| ErrorCode::OptionIdIsEmpty)?
.0, .0,
), ),

View File

@ -1,8 +1,7 @@
use crate::services::row::apply_cell_data_changeset;
use crate::services::field::SelectOptionCellChangeset; use crate::services::field::SelectOptionCellChangeset;
use crate::services::row::apply_cell_data_changeset;
use flowy_error::{FlowyError, FlowyResult}; use flowy_error::{FlowyError, FlowyResult};
use flowy_grid_data_model::entities::{CellMeta, FieldMeta, RowMeta, DEFAULT_ROW_HEIGHT}; use flowy_grid_data_model::entities::{gen_row_id, CellMeta, FieldMeta, RowMeta, DEFAULT_ROW_HEIGHT};
use indexmap::IndexMap; use indexmap::IndexMap;
use std::collections::HashMap; use std::collections::HashMap;
@ -19,7 +18,7 @@ impl<'a> CreateRowMetaBuilder<'a> {
.collect::<HashMap<&String, &FieldMeta>>(); .collect::<HashMap<&String, &FieldMeta>>();
let payload = CreateRowMetaPayload { let payload = CreateRowMetaPayload {
row_id: uuid::Uuid::new_v4().to_string(), row_id: gen_row_id(),
cell_by_field_id: Default::default(), cell_by_field_id: Default::default(),
height: DEFAULT_ROW_HEIGHT, height: DEFAULT_ROW_HEIGHT,
visibility: true, visibility: true,

View File

@ -1,6 +1,6 @@
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use flowy_error::ErrorCode; use flowy_error::ErrorCode;
use flowy_grid_data_model::parser::NotEmptyUuid; use flowy_grid_data_model::parser::NotEmptyStr;
#[derive(ProtoBuf, Default)] #[derive(ProtoBuf, Default)]
pub struct RowIdentifierPayload { pub struct RowIdentifierPayload {
@ -20,8 +20,8 @@ impl TryInto<RowIdentifier> for RowIdentifierPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<RowIdentifier, Self::Error> { fn try_into(self) -> Result<RowIdentifier, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let row_id = NotEmptyUuid::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?; let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;
Ok(RowIdentifier { Ok(RowIdentifier {
grid_id: grid_id.0, grid_id: grid_id.0,

View File

@ -1,3 +1 @@
pub fn uuid() -> String {
uuid::Uuid::new_v4().to_string()
}

View File

@ -37,6 +37,7 @@ config = { version = "0.10.1", default-features = false, features = ["yaml"] }
log = "0.4.14" log = "0.4.14"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
nanoid = "0.4.0"
[features] [features]
http_server = [] http_server = []

View File

@ -17,6 +17,7 @@ use flowy_sync::{
}; };
use futures_util::stream::StreamExt; use futures_util::stream::StreamExt;
use lib_ws::{WSChannel, WebSocketRawMessage}; use lib_ws::{WSChannel, WebSocketRawMessage};
use nanoid::nanoid;
use parking_lot::RwLock; use parking_lot::RwLock;
use std::{ use std::{
convert::{TryFrom, TryInto}, convert::{TryFrom, TryInto},
@ -251,6 +252,8 @@ impl RevisionUser for LocalRevisionUser {
} }
} }
use flowy_folder_data_model::entities::app::gen_app_id;
use flowy_folder_data_model::entities::workspace::gen_workspace_id;
use flowy_folder_data_model::entities::{ use flowy_folder_data_model::entities::{
app::{App, AppId, CreateAppParams, RepeatedApp, UpdateAppParams}, app::{App, AppId, CreateAppParams, RepeatedApp, UpdateAppParams},
trash::{RepeatedTrash, RepeatedTrashId}, trash::{RepeatedTrash, RepeatedTrashId},
@ -262,7 +265,7 @@ use flowy_user::event_map::UserCloudService;
use flowy_user_data_model::entities::{ use flowy_user_data_model::entities::{
SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile, SignInParams, SignInResponse, SignUpParams, SignUpResponse, UpdateUserParams, UserProfile,
}; };
use lib_infra::{future::FutureResult, timestamp, uuid}; use lib_infra::{future::FutureResult, timestamp};
impl FolderCouldServiceV1 for LocalServer { impl FolderCouldServiceV1 for LocalServer {
fn init(&self) {} fn init(&self) {}
@ -270,7 +273,7 @@ impl FolderCouldServiceV1 for LocalServer {
fn create_workspace(&self, _token: &str, params: CreateWorkspaceParams) -> FutureResult<Workspace, FlowyError> { fn create_workspace(&self, _token: &str, params: CreateWorkspaceParams) -> FutureResult<Workspace, FlowyError> {
let time = timestamp(); let time = timestamp();
let workspace = Workspace { let workspace = Workspace {
id: uuid(), id: gen_workspace_id(),
name: params.name, name: params.name,
desc: params.desc, desc: params.desc,
apps: RepeatedApp::default(), apps: RepeatedApp::default(),
@ -330,7 +333,7 @@ impl FolderCouldServiceV1 for LocalServer {
fn create_app(&self, _token: &str, params: CreateAppParams) -> FutureResult<App, FlowyError> { fn create_app(&self, _token: &str, params: CreateAppParams) -> FutureResult<App, FlowyError> {
let time = timestamp(); let time = timestamp();
let app = App { let app = App {
id: uuid(), id: gen_app_id(),
workspace_id: params.workspace_id, workspace_id: params.workspace_id,
name: params.name, name: params.name,
desc: params.desc, desc: params.desc,
@ -372,7 +375,7 @@ impl FolderCouldServiceV1 for LocalServer {
impl UserCloudService for LocalServer { impl UserCloudService for LocalServer {
fn sign_up(&self, params: SignUpParams) -> FutureResult<SignUpResponse, FlowyError> { fn sign_up(&self, params: SignUpParams) -> FutureResult<SignUpResponse, FlowyError> {
let uid = uuid(); let uid = nanoid!(10);
FutureResult::new(async move { FutureResult::new(async move {
Ok(SignUpResponse { Ok(SignUpResponse {
user_id: uid.clone(), user_id: uid.clone(),
@ -384,7 +387,7 @@ impl UserCloudService for LocalServer {
} }
fn sign_in(&self, params: SignInParams) -> FutureResult<SignInResponse, FlowyError> { fn sign_in(&self, params: SignInParams) -> FutureResult<SignInResponse, FlowyError> {
let user_id = uuid(); let user_id = nanoid!(10);
FutureResult::new(async { FutureResult::new(async {
Ok(SignInResponse { Ok(SignInResponse {
user_id: user_id.clone(), user_id: user_id.clone(),

View File

@ -26,6 +26,7 @@ futures-util = "0.3.15"
thread-id = "3.3.0" thread-id = "3.3.0"
log = "0.4" log = "0.4"
bytes = "1.0" bytes = "1.0"
nanoid = "0.4.0"
[dev-dependencies] [dev-dependencies]
quickcheck = "0.9.2" quickcheck = "0.9.2"

View File

@ -14,7 +14,6 @@ use flowy_user::{
event_map::UserEvent::{InitUser, SignIn, SignOut, SignUp}, event_map::UserEvent::{InitUser, SignIn, SignOut, SignUp},
}; };
use lib_dispatch::prelude::{EventDispatcher, ModuleRequest, ToBytes}; use lib_dispatch::prelude::{EventDispatcher, ModuleRequest, ToBytes};
use lib_infra::uuid;
use std::{fs, path::PathBuf, sync::Arc}; use std::{fs, path::PathBuf, sync::Arc};
pub struct ViewTest { pub struct ViewTest {
@ -127,7 +126,7 @@ pub fn root_dir() -> String {
} }
pub fn random_email() -> String { pub fn random_email() -> String {
format!("{}@appflowy.io", uuid()) format!("{}@appflowy.io", nanoid!(10))
} }
pub fn login_email() -> String { pub fn login_email() -> String {

View File

@ -5,7 +5,7 @@ use crate::helper::*;
use flowy_net::{get_client_server_configuration, ClientServerConfiguration}; use flowy_net::{get_client_server_configuration, ClientServerConfiguration};
use flowy_sdk::{FlowySDK, FlowySDKConfig}; use flowy_sdk::{FlowySDK, FlowySDKConfig};
use flowy_user::entities::UserProfile; use flowy_user::entities::UserProfile;
use lib_infra::uuid; use nanoid::nanoid;
pub mod prelude { pub mod prelude {
pub use crate::{event_builder::*, helper::*, *}; pub use crate::{event_builder::*, helper::*, *};
@ -36,7 +36,7 @@ impl std::default::Default for FlowySDKTest {
impl FlowySDKTest { impl FlowySDKTest {
pub fn new(server_config: ClientServerConfiguration) -> Self { pub fn new(server_config: ClientServerConfiguration) -> Self {
let config = FlowySDKConfig::new(&root_dir(), server_config, &uuid()).log_filter("trace"); let config = FlowySDKConfig::new(&root_dir(), server_config, &nanoid!(6)).log_filter("trace");
let sdk = std::thread::spawn(|| FlowySDK::new(config)).join().unwrap(); let sdk = std::thread::spawn(|| FlowySDK::new(config)).join().unwrap();
std::mem::forget(sdk.dispatcher()); std::mem::forget(sdk.dispatcher());
Self { inner: sdk } Self { inner: sdk }

View File

@ -34,6 +34,7 @@ tokio = { version = "1", features = ["rt"] }
[dev-dependencies] [dev-dependencies]
flowy-test = { path = "../flowy-test" } flowy-test = { path = "../flowy-test" }
futures = "0.3.15" futures = "0.3.15"
nanoid = "0.4.0"
[features] [features]
http_server = [] http_server = []

View File

@ -2,7 +2,8 @@ use crate::helper::*;
use flowy_test::{event_builder::UserModuleEventBuilder, FlowySDKTest}; use flowy_test::{event_builder::UserModuleEventBuilder, FlowySDKTest};
use flowy_user::{errors::ErrorCode, event_map::UserEvent::*}; use flowy_user::{errors::ErrorCode, event_map::UserEvent::*};
use flowy_user_data_model::entities::{UpdateUserPayload, UserProfile}; use flowy_user_data_model::entities::{UpdateUserPayload, UserProfile};
use lib_infra::uuid; use nanoid::nanoid;
// use serial_test::*; // use serial_test::*;
#[tokio::test] #[tokio::test]
@ -51,7 +52,7 @@ async fn user_update_with_name() {
async fn user_update_with_email() { async fn user_update_with_email() {
let sdk = FlowySDKTest::default(); let sdk = FlowySDKTest::default();
let user = sdk.init_user().await; let user = sdk.init_user().await;
let new_email = format!("{}@gmail.com", uuid()); let new_email = format!("{}@gmail.com", nanoid!(6));
let request = UpdateUserPayload::new(&user.id).email(&new_email); let request = UpdateUserPayload::new(&user.id).email(&new_email);
let _ = UserModuleEventBuilder::new(sdk.clone()) let _ = UserModuleEventBuilder::new(sdk.clone())
.event(UpdateUser) .event(UpdateUser)

View File

@ -14,7 +14,7 @@ futures = "0.3.15"
futures-util = "0.3.15" futures-util = "0.3.15"
bytes = {version = "1.0", features = ["serde"]} bytes = {version = "1.0", features = ["serde"]}
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
uuid = { version = "0.8", features = ["serde", "v4"] } nanoid = "0.4.0"
log = "0.4.14" log = "0.4.14"
env_logger = "0.8" env_logger = "0.8"
serde_with = "1.9.4" serde_with = "1.9.4"

View File

@ -22,6 +22,7 @@ use crate::{
}, },
}; };
use futures_core::future::BoxFuture; use futures_core::future::BoxFuture;
use nanoid::nanoid;
use std::sync::Arc; use std::sync::Arc;
pub type ModuleMap = Arc<HashMap<Event, Arc<Module>>>; pub type ModuleMap = Arc<HashMap<Event, Arc<Module>>>;
@ -118,7 +119,7 @@ impl ModuleRequest {
E: Into<Event>, E: Into<Event>,
{ {
Self { Self {
id: uuid::Uuid::new_v4().to_string(), id: nanoid!(6),
event: event.into(), event: event.into(),
payload: Payload::None, payload: Payload::None,
} }

24
shared-lib/Cargo.lock generated
View File

@ -441,6 +441,7 @@ dependencies = [
"flowy-error-code", "flowy-error-code",
"lib-infra", "lib-infra",
"log", "log",
"nanoid",
"protobuf", "protobuf",
"serde", "serde",
"serde_json", "serde_json",
@ -448,7 +449,6 @@ dependencies = [
"strum", "strum",
"strum_macros", "strum_macros",
"unicode-segmentation", "unicode-segmentation",
"uuid",
] ]
[[package]] [[package]]
@ -460,13 +460,13 @@ dependencies = [
"flowy-error-code", "flowy-error-code",
"indexmap", "indexmap",
"lib-infra", "lib-infra",
"nanoid",
"protobuf", "protobuf",
"serde", "serde",
"serde_json", "serde_json",
"serde_repr", "serde_repr",
"strum", "strum",
"strum_macros", "strum_macros",
"uuid",
] ]
[[package]] [[package]]
@ -851,7 +851,6 @@ dependencies = [
"tera", "tera",
"tokio", "tokio",
"toml", "toml",
"uuid",
"walkdir", "walkdir",
] ]
@ -972,6 +971,15 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "nanoid"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
dependencies = [
"rand 0.8.4",
]
[[package]] [[package]]
name = "ntapi" name = "ntapi"
version = "0.3.6" version = "0.3.6"
@ -2097,16 +2105,6 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [
"getrandom 0.2.3",
"serde",
]
[[package]] [[package]]
name = "validator" name = "validator"
version = "0.12.0" version = "0.12.0"

View File

@ -14,7 +14,7 @@ strum = "0.21"
strum_macros = "0.21" strum_macros = "0.21"
derive_more = {version = "0.99", features = ["display"]} derive_more = {version = "0.99", features = ["display"]}
log = "0.4.14" log = "0.4.14"
uuid = { version = "0.8", features = ["serde", "v4"] } nanoid = "0.4.0"
chrono = { version = "0.4" } chrono = { version = "0.4" }
flowy-error-code = { path = "../flowy-error-code"} flowy-error-code = { path = "../flowy-error-code"}
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }

View File

@ -8,9 +8,13 @@ use crate::{
}, },
}; };
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use nanoid::nanoid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::convert::TryInto; use std::convert::TryInto;
pub fn gen_app_id() -> String {
nanoid!(10)
}
#[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)] #[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)]
pub struct App { pub struct App {
#[pb(index = 1)] #[pb(index = 1)]

View File

@ -8,10 +8,15 @@ use crate::{
}, },
}; };
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use nanoid::nanoid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_repr::*; use serde_repr::*;
use std::convert::TryInto; use std::convert::TryInto;
pub fn gen_view_id() -> String {
nanoid!(10)
}
#[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)] #[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)]
pub struct View { pub struct View {
#[pb(index = 1)] #[pb(index = 1)]
@ -163,7 +168,7 @@ impl TryInto<CreateViewParams> for CreateViewPayload {
fn try_into(self) -> Result<CreateViewParams, Self::Error> { fn try_into(self) -> Result<CreateViewParams, Self::Error> {
let name = ViewName::parse(self.name)?.0; let name = ViewName::parse(self.name)?.0;
let belong_to_id = AppIdentify::parse(self.belong_to_id)?.0; let belong_to_id = AppIdentify::parse(self.belong_to_id)?.0;
let view_id = uuid::Uuid::new_v4().to_string(); let view_id = gen_view_id();
let thumbnail = match self.thumbnail { let thumbnail = match self.thumbnail {
None => "".to_string(), None => "".to_string(),
Some(thumbnail) => ViewThumbnail::parse(thumbnail)?.0, Some(thumbnail) => ViewThumbnail::parse(thumbnail)?.0,

View File

@ -5,9 +5,13 @@ use crate::{
parser::workspace::{WorkspaceDesc, WorkspaceIdentify, WorkspaceName}, parser::workspace::{WorkspaceDesc, WorkspaceIdentify, WorkspaceName},
}; };
use flowy_derive::ProtoBuf; use flowy_derive::ProtoBuf;
use nanoid::nanoid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::convert::TryInto; use std::convert::TryInto;
pub fn gen_workspace_id() -> String {
nanoid!(10)
}
#[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)] #[derive(Eq, PartialEq, ProtoBuf, Default, Debug, Clone, Serialize, Deserialize)]
pub struct Workspace { pub struct Workspace {
#[pb(index = 1)] #[pb(index = 1)]

View File

@ -1,3 +1,6 @@
use crate::entities::app::gen_app_id;
use crate::entities::view::gen_view_id;
use crate::entities::workspace::gen_workspace_id;
use crate::entities::{ use crate::entities::{
app::{App, RepeatedApp}, app::{App, RepeatedApp},
view::{RepeatedView, View, ViewDataType}, view::{RepeatedView, View, ViewDataType},
@ -7,7 +10,7 @@ use chrono::Utc;
pub fn create_default_workspace() -> Workspace { pub fn create_default_workspace() -> Workspace {
let time = Utc::now(); let time = Utc::now();
let workspace_id = uuid::Uuid::new_v4(); let workspace_id = gen_workspace_id();
let name = "Workspace".to_string(); let name = "Workspace".to_string();
let desc = "".to_string(); let desc = "".to_string();
@ -26,7 +29,7 @@ pub fn create_default_workspace() -> Workspace {
} }
fn create_default_app(workspace_id: String, time: chrono::DateTime<Utc>) -> App { fn create_default_app(workspace_id: String, time: chrono::DateTime<Utc>) -> App {
let app_id = uuid::Uuid::new_v4(); let app_id = gen_app_id();
let name = "⭐️ Getting started".to_string(); let name = "⭐️ Getting started".to_string();
let desc = "".to_string(); let desc = "".to_string();
@ -47,7 +50,7 @@ fn create_default_app(workspace_id: String, time: chrono::DateTime<Utc>) -> App
} }
fn create_default_view(app_id: String, time: chrono::DateTime<Utc>) -> View { fn create_default_view(app_id: String, time: chrono::DateTime<Utc>) -> View {
let view_id = uuid::Uuid::new_v4(); let view_id = gen_view_id();
let name = "Read me".to_string(); let name = "Read me".to_string();
let desc = "".to_string(); let desc = "".to_string();
let data_type = ViewDataType::TextBlock; let data_type = ViewDataType::TextBlock;

View File

@ -14,7 +14,7 @@ strum_macros = "0.21"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = {version = "1.0"} serde_json = {version = "1.0"}
serde_repr = "0.1" serde_repr = "0.1"
uuid = { version = "0.8", features = ["serde", "v4"] } nanoid = "0.4.0"
flowy-error-code = { path = "../flowy-error-code"} flowy-error-code = { path = "../flowy-error-code"}
indexmap = {version = "1.8.1", features = ["serde"]} indexmap = {version = "1.8.1", features = ["serde"]}
[build-dependencies] [build-dependencies]

View File

@ -1,5 +1,5 @@
use crate::entities::{CellMeta, FieldMeta, RowMeta, RowMetaChangeset}; use crate::entities::{CellMeta, FieldMeta, RowMeta, RowMetaChangeset};
use crate::parser::NotEmptyUuid; use crate::parser::NotEmptyStr;
use flowy_derive::{ProtoBuf, ProtoBuf_Enum}; use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error_code::ErrorCode; use flowy_error_code::ErrorCode;
@ -118,8 +118,8 @@ impl TryInto<EditFieldParams> for EditFieldPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<EditFieldParams, Self::Error> { fn try_into(self) -> Result<EditFieldParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyUuid::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
Ok(EditFieldParams { Ok(EditFieldParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_id: field_id.0, field_id: field_id.0,
@ -474,7 +474,7 @@ impl TryInto<CreateRowParams> for CreateRowPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateRowParams, Self::Error> { fn try_into(self) -> Result<CreateRowParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
Ok(CreateRowParams { Ok(CreateRowParams {
grid_id: grid_id.0, grid_id: grid_id.0,
start_row_id: self.start_row_id, start_row_id: self.start_row_id,
@ -509,12 +509,12 @@ impl TryInto<CreateFieldParams> for CreateFieldPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<CreateFieldParams, Self::Error> { fn try_into(self) -> Result<CreateFieldParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let _ = NotEmptyUuid::parse(self.field.id.clone()).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let _ = NotEmptyStr::parse(self.field.id.clone()).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
let start_field_id = match self.start_field_id { let start_field_id = match self.start_field_id {
None => None, None => None,
Some(id) => Some(NotEmptyUuid::parse(id).map_err(|_| ErrorCode::FieldIdIsEmpty)?.0), Some(id) => Some(NotEmptyStr::parse(id).map_err(|_| ErrorCode::FieldIdIsEmpty)?.0),
}; };
Ok(CreateFieldParams { Ok(CreateFieldParams {
@ -544,7 +544,7 @@ impl TryInto<QueryFieldParams> for QueryFieldPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<QueryFieldParams, Self::Error> { fn try_into(self) -> Result<QueryFieldParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
Ok(QueryFieldParams { Ok(QueryFieldParams {
grid_id: grid_id.0, grid_id: grid_id.0,
field_orders: self.field_orders, field_orders: self.field_orders,
@ -570,7 +570,7 @@ impl TryInto<QueryGridBlocksParams> for QueryGridBlocksPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> { fn try_into(self) -> Result<QueryGridBlocksParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
Ok(QueryGridBlocksParams { Ok(QueryGridBlocksParams {
grid_id: grid_id.0, grid_id: grid_id.0,
block_orders: self.block_orders, block_orders: self.block_orders,
@ -633,8 +633,8 @@ impl TryInto<FieldChangesetParams> for FieldChangesetPayload {
type Error = ErrorCode; type Error = ErrorCode;
fn try_into(self) -> Result<FieldChangesetParams, Self::Error> { fn try_into(self) -> Result<FieldChangesetParams, Self::Error> {
let grid_id = NotEmptyUuid::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?; let grid_id = NotEmptyStr::parse(self.grid_id).map_err(|_| ErrorCode::GridIdIsEmpty)?;
let field_id = NotEmptyUuid::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?; let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;
if let Some(type_option_data) = self.type_option_data.as_ref() { if let Some(type_option_data) = self.type_option_data.as_ref() {
if type_option_data.is_empty() { if type_option_data.is_empty() {

View File

@ -1,13 +1,29 @@
use crate::entities::FieldType; use crate::entities::FieldType;
use bytes::Bytes; use bytes::Bytes;
use indexmap::IndexMap; use indexmap::IndexMap;
use nanoid::nanoid;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
pub const DEFAULT_ROW_HEIGHT: i32 = 42; pub const DEFAULT_ROW_HEIGHT: i32 = 42;
pub fn gen_grid_id() -> String {
// nanoid calculator https://zelark.github.io/nano-id-cc/
nanoid!(10)
}
pub fn gen_block_id() -> String {
nanoid!(10)
}
pub fn gen_row_id() -> String {
nanoid!(6)
}
pub fn gen_field_id() -> String {
nanoid!(6)
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GridMeta { pub struct GridMeta {
pub grid_id: String, pub grid_id: String,
@ -35,7 +51,7 @@ impl GridBlockMeta {
impl GridBlockMeta { impl GridBlockMeta {
pub fn new() -> Self { pub fn new() -> Self {
GridBlockMeta { GridBlockMeta {
block_id: uuid::Uuid::new_v4().to_string(), block_id: gen_block_id(),
..Default::default() ..Default::default()
} }
} }
@ -91,7 +107,7 @@ impl FieldMeta {
pub fn new(name: &str, desc: &str, field_type: FieldType) -> Self { pub fn new(name: &str, desc: &str, field_type: FieldType) -> Self {
let width = field_type.default_cell_width(); let width = field_type.default_cell_width();
Self { Self {
id: uuid::Uuid::new_v4().to_string(), id: gen_field_id(),
name: name.to_string(), name: name.to_string(),
desc: desc.to_string(), desc: desc.to_string(),
field_type, field_type,
@ -152,7 +168,7 @@ pub struct RowMeta {
impl RowMeta { impl RowMeta {
pub fn new(block_id: &str) -> Self { pub fn new(block_id: &str) -> Self {
Self { Self {
id: uuid::Uuid::new_v4().to_string(), id: gen_row_id(),
block_id: block_id.to_owned(), block_id: block_id.to_owned(),
cells: Default::default(), cells: Default::default(),
height: DEFAULT_ROW_HEIGHT, height: DEFAULT_ROW_HEIGHT,

View File

@ -1,25 +1,3 @@
use uuid::Uuid;
#[derive(Debug)]
pub struct NotEmptyUuid(pub String);
impl NotEmptyUuid {
pub fn parse(s: String) -> Result<Self, String> {
if s.trim().is_empty() {
return Err("Input string is empty".to_owned());
}
debug_assert!(Uuid::parse_str(&s).is_ok());
Ok(Self(s))
}
}
impl AsRef<str> for NotEmptyUuid {
fn as_ref(&self) -> &str {
&self.0
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct NotEmptyStr(pub String); pub struct NotEmptyStr(pub String);

View File

@ -1,8 +1,7 @@
use crate::entities::revision::{md5, RepeatedRevision, Revision}; use crate::entities::revision::{md5, RepeatedRevision, Revision};
use crate::errors::{CollaborateError, CollaborateResult}; use crate::errors::{CollaborateError, CollaborateResult};
use crate::util::{cal_diff, make_delta_from_revisions}; use crate::util::{cal_diff, make_delta_from_revisions};
use flowy_grid_data_model::entities::{CellMeta, GridBlockMetaData, RowMeta, RowMetaChangeset}; use flowy_grid_data_model::entities::{gen_block_id, CellMeta, GridBlockMetaData, RowMeta, RowMetaChangeset};
use lib_infra::uuid;
use lib_ot::core::{OperationTransformable, PlainTextAttributes, PlainTextDelta, PlainTextDeltaBuilder}; use lib_ot::core::{OperationTransformable, PlainTextAttributes, PlainTextDelta, PlainTextDeltaBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::borrow::Cow; use std::borrow::Cow;
@ -225,7 +224,7 @@ pub fn make_block_meta_revisions(user_id: &str, grid_block_meta_data: &GridBlock
impl std::default::Default for GridBlockMetaPad { impl std::default::Default for GridBlockMetaPad {
fn default() -> Self { fn default() -> Self {
let block_meta_data = GridBlockMetaData { let block_meta_data = GridBlockMetaData {
block_id: uuid(), block_id: gen_block_id(),
rows: vec![], rows: vec![],
}; };

View File

@ -3,10 +3,9 @@ use crate::errors::{internal_error, CollaborateError, CollaborateResult};
use crate::util::{cal_diff, make_delta_from_revisions}; use crate::util::{cal_diff, make_delta_from_revisions};
use bytes::Bytes; use bytes::Bytes;
use flowy_grid_data_model::entities::{ use flowy_grid_data_model::entities::{
FieldChangesetParams, FieldMeta, FieldOrder, FieldType, GridBlockMeta, GridBlockMetaChangeset, GridMeta, gen_field_id, gen_grid_id, FieldChangesetParams, FieldMeta, FieldOrder, FieldType, GridBlockMeta,
GridBlockMetaChangeset, GridMeta,
}; };
use lib_infra::uuid;
use lib_ot::core::{OperationTransformable, PlainTextAttributes, PlainTextDelta, PlainTextDeltaBuilder}; use lib_ot::core::{OperationTransformable, PlainTextAttributes, PlainTextDelta, PlainTextDeltaBuilder};
use std::collections::HashMap; use std::collections::HashMap;
@ -89,7 +88,7 @@ impl GridMetaPad {
None => Ok(None), None => Ok(None),
Some(index) => { Some(index) => {
let mut duplicate_field_meta = grid_meta.fields[index].clone(); let mut duplicate_field_meta = grid_meta.fields[index].clone();
duplicate_field_meta.id = uuid(); duplicate_field_meta.id = gen_field_id();
duplicate_field_meta.name = format!("{} (copy)", duplicate_field_meta.name); duplicate_field_meta.name = format!("{} (copy)", duplicate_field_meta.name);
grid_meta.fields.insert(index + 1, duplicate_field_meta); grid_meta.fields.insert(index + 1, duplicate_field_meta);
Ok(Some(())) Ok(Some(()))
@ -374,7 +373,7 @@ pub fn make_grid_revisions(user_id: &str, grid_meta: &GridMeta) -> RepeatedRevis
impl std::default::Default for GridMetaPad { impl std::default::Default for GridMetaPad {
fn default() -> Self { fn default() -> Self {
let grid = GridMeta { let grid = GridMeta {
grid_id: uuid(), grid_id: gen_grid_id(),
fields: vec![], fields: vec![],
blocks: vec![], blocks: vec![],
}; };

View File

@ -6,7 +6,6 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
uuid = { version = "0.8", features = ["serde", "v4"] }
log = "0.4.14" log = "0.4.14"
chrono = "0.4.19" chrono = "0.4.19"
bytes = { version = "1.0" } bytes = { version = "1.0" }

View File

@ -2,11 +2,6 @@ pub mod code_gen;
pub mod future; pub mod future;
pub mod retry; pub mod retry;
#[allow(dead_code)]
pub fn uuid() -> String {
uuid::Uuid::new_v4().to_string()
}
#[allow(dead_code)] #[allow(dead_code)]
pub fn timestamp() -> i64 { pub fn timestamp() -> i64 {
chrono::Utc::now().timestamp() chrono::Utc::now().timestamp()