Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: Use UUID instead of using String #7699

Merged
merged 4 commits into from
Apr 7, 2025
Merged

Chore: Use UUID instead of using String #7699

merged 4 commits into from
Apr 7, 2025

Conversation

appflowy
Copy link
Contributor

@appflowy appflowy commented Apr 7, 2025

Feature Preview


PR Checklist

  • My code adheres to AppFlowy's Conventions
  • I've listed at least one issue that this PR fixes in the description above.
  • I've added a test(s) to validate changes in this PR, or this PR only contains semantic changes.
  • All existing tests are passing.

Summary by Sourcery

Migrate workspace and view identifiers from string to UUID across the AppFlowy codebase

Enhancements:

  • Replaced string-based workspace and view identifiers with UUID throughout the project
  • Updated type signatures to use Uuid instead of String for improved type safety
  • Refactored code to handle UUID conversions and parsing

Chores:

  • Updated multiple Cargo.toml files to include uuid dependency
  • Removed unnecessary dependencies
  • Standardized UUID handling across different modules

Copy link

sourcery-ai bot commented Apr 7, 2025

Reviewer's Guide by Sourcery

This pull request migrates the codebase to use UUIDs instead of strings for identifying key entities like workspaces, views, and chats. This change improves data integrity and consistency across the application.

Updated class diagram for FolderManager

classDiagram
  class FolderManager {
    -user: FolderUser
    -collab_builder: CollabBuilder
    -cloud_service: dyn FolderCloudService
    -operation_handlers: HashMap<ViewLayout, FolderOperationHandler>
    -mutex_folder: Arc<Mutex<Folder>>
    -folder_indexer: FolderIndexer
    -store_preferences: KVStorePreferences
  }
  class FolderUser {
    <<interface>>
    +user_id() i64
    +workspace_id() Uuid
    +collab_db(uid: i64) Weak<CollabKVDB>
    +is_folder_exist_on_disk(uid: i64, workspace_id: Uuid) FlowyResult<bool>
  }

  FolderManager -- FolderUser : depends on

  note for FolderUser "workspace_id() now returns Uuid instead of String"
  note for FolderUser "is_folder_exist_on_disk() now takes Uuid instead of String"
Loading

Updated class diagram for DatabaseManager

classDiagram
  class DatabaseManager {
    -user: DatabaseUser
    -cloud_service: dyn DatabaseCloudService
    -ai_service: dyn DatabaseAIService
    -workspace_database: Arc<RwLock<WorkspaceDatabaseCollabServiceImpl>>
    -database_editors: DatabaseEditorMap
    -store_preferences: KVStorePreferences
  }
  class DatabaseUser {
    <<interface>>
    +user_id() i64
    +collab_db(uid: i64) Weak<CollabKVDB>
    +workspace_id() Uuid
    +workspace_database_object_id() Uuid
  }

  DatabaseManager -- DatabaseUser : depends on

  note for DatabaseUser "workspace_id() now returns Uuid instead of String"
  note for DatabaseUser "workspace_database_object_id() now returns Uuid instead of String"
Loading

Updated class diagram for AIUserService

classDiagram
  class AIUserService {
    <<interface>>
    +user_id() i64
    +device_id() String
    +workspace_id() Uuid
    +sqlite_connection(uid: i64) DBConnection
    +application_root_dir() PathBuf
  }

  note for AIUserService "workspace_id() now returns Uuid instead of String"
Loading

Updated class diagram for AIExternalService

classDiagram
  class AIExternalService {
    <<interface>>
    +query_chat_rag_ids(parent_view_id: Uuid, chat_id: Uuid) Result<Vec<Uuid>, FlowyError>
    +sync_rag_documents(workspace_id: Uuid, rag_ids: Vec<Uuid>, rag_metadata_map: HashMap<Uuid, AFCollabMetadata>) Result<Vec<AFCollabMetadata>, FlowyError>
    +notify_did_send_message(chat_id: Uuid, message: String) Result<(), FlowyError>
  }
Loading

File-Level Changes

Change Details Files
Replaced string-based IDs with UUIDs for various entities like workspaces, views, and chats.
  • Changed function signatures to accept Uuid instead of String for workspace and object IDs.
  • Updated data structures to store UUIDs instead of strings.
  • Modified database queries to use UUIDs.
  • Added UUID parsing where string IDs were previously used.
  • Updated collab object creation to use UUIDs.
frontend/rust-lib/flowy-core/src/deps_resolve/cloud_service_impl.rs
frontend/rust-lib/flowy-folder/src/manager.rs
frontend/rust-lib/flowy-database2/src/manager.rs
frontend/rust-lib/flowy-ai/src/completion.rs
frontend/rust-lib/flowy-server/src/af_cloud/impls/chat.rs
frontend/rust-lib/flowy-server/src/af_cloud/impls/folder.rs
frontend/rust-lib/flowy-server/src/af_cloud/impls/user/cloud_service_impl.rs
frontend/rust-lib/flowy-ai/src/ai_manager.rs
frontend/rust-lib/flowy-ai/src/middleware/chat_service_mw.rs
frontend/rust-lib/flowy-core/src/deps_resolve/folder_deps/folder_deps_database_impl.rs
frontend/rust-lib/flowy-server/src/default_impl.rs
frontend/rust-lib/flowy-document/src/manager.rs
frontend/rust-lib/flowy-server/src/af_cloud/impls/database.rs
frontend/rust-lib/flowy-ai-pub/src/cloud.rs
frontend/rust-lib/flowy-server/src/local_server/impls/folder.rs
frontend/rust-lib/flowy-folder/src/manager_observer.rs
frontend/rust-lib/flowy-document/tests/document/util.rs
frontend/rust-lib/flowy-core/src/deps_resolve/folder_deps/mod.rs
frontend/rust-lib/flowy-storage/src/manager.rs
frontend/rust-lib/flowy-user/src/user_manager/manager_user_workspace.rs
frontend/rust-lib/flowy-folder-pub/src/cloud.rs
frontend/rust-lib/flowy-folder/src/entities/view.rs
frontend/rust-lib/flowy-document/src/entities.rs
frontend/rust-lib/flowy-ai/src/chat.rs
frontend/rust-lib/flowy-ai/src/event_handler.rs
frontend/rust-lib/flowy-search/src/folder/indexer.rs
frontend/rust-lib/flowy-server/src/af_cloud/impls/document.rs
frontend/rust-lib/flowy-server/src/local_server/impls/database.rs
frontend/rust-lib/flowy-user-pub/src/cloud.rs
frontend/rust-lib/flowy-core/src/deps_resolve/chat_deps.rs
frontend/rust-lib/flowy-database-pub/src/cloud.rs
frontend/rust-lib/flowy-storage-pub/src/cloud.rs
frontend/rust-lib/flowy-user/src/user_manager/manager_user_awareness.rs
frontend/rust-lib/flowy-folder/src/manager_init.rs
frontend/rust-lib/flowy-document/tests/document/document_test.rs
frontend/rust-lib/flowy-core/src/deps_resolve/document_deps.rs
frontend/rust-lib/flowy-core/src/lib.rs
frontend/rust-lib/flowy-database2/src/event_handler.rs
frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
frontend/rust-lib/flowy-document/tests/document/document_redo_undo_test.rs
frontend/rust-lib/flowy-storage/src/manager.rs
frontend/rust-lib/flowy-user/src/event_handler.rs
frontend/rust-lib/flowy-folder-pub/src/query.rs
frontend/rust-lib/flowy-folder/src/view_operation.rs
frontend/rust-lib/flowy-server/src/local_server/impls/document.rs
frontend/rust-lib/event-integration-test/tests/chat/chat_message_test.rs
frontend/rust-lib/flowy-core/src/user_state_callback.rs
frontend/rust-lib/flowy-database2/src/services/database/database_observe.rs
frontend/rust-lib/flowy-document/src/document.rs
frontend/rust-lib/flowy-ai/src/notification.rs
frontend/rust-lib/flowy-folder/src/notification.rs
frontend/rust-lib/flowy-user/src/services/authenticate_user.rs
frontend/rust-lib/event-integration-test/tests/document/local_test/edit_test.rs
frontend/rust-lib/flowy-core/src/deps_resolve/file_storage_deps.rs
frontend/rust-lib/flowy-core/src/deps_resolve/user_deps.rs
frontend/rust-lib/flowy-document/src/parser/parser_entities.rs
frontend/rust-lib/collab-integrate/src/collab_builder.rs
frontend/rust-lib/flowy-ai/src/local_ai/controller.rs
frontend/rust-lib/flowy-ai/src/entities.rs
frontend/rust-lib/flowy-search/src/document/handler.rs
frontend/rust-lib/flowy-search/Cargo.toml
frontend/rust-lib/event-integration-test/src/folder_event.rs
frontend/rust-lib/flowy-document/src/event_handler.rs
frontend/rust-lib/flowy-error/src/errors.rs
frontend/rust-lib/flowy-user/src/services/billing_check.rs
frontend/rust-lib/flowy-core/src/deps_resolve/collab_deps.rs
frontend/rust-lib/flowy-document/src/parser/parser_entities.rs
frontend/rust-lib/flowy-user-pub/src/entities.rs
frontend/rust-lib/flowy-ai/src/chat.rs
frontend/rust-lib/collab-integrate/src/persistence/collab_metadata_sql.rs
frontend/rust-lib/flowy-ai-pub/Cargo.toml
frontend/rust-lib/flowy-core/Cargo.toml
frontend/rust-lib/flowy-database2/Cargo.toml
frontend/rust-lib/flowy-error/Cargo.toml
frontend/rust-lib/flowy-document-pub/Cargo.toml
frontend/rust-lib/flowy-folder/src/util.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @appflowy - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The change from String to UUID is good, but you should also validate the UUIDs when they come from external sources, like deserialization or user input.
  • Consider adding a migration strategy for existing data that uses strings for IDs.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 3 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

.load::<AFCollabMetadata>(&mut conn)?
.into_iter()
.map(|m| (m.object_id.clone(), m))
.flat_map(|m| Uuid::from_str(&m.object_id).map(|v| (v, m)))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Consider explicit handling of Uuid conversion failures.

Using flat_map with .ok() silently drops conversion failures. If a failure indicates data inconsistency, logging or handling the error explicitly might help with debugging.

Suggested implementation:

    .into_iter()
    .map(|m| {
        Uuid::from_str(&m.object_id)
            .map(|v| (v, m))
            .map_err(|e| {
                log::error!("Failed to convert object_id '{}' to Uuid: {}", m.object_id, e);
                e
            })
    })
    .collect::<Result<_, _>>()?;

Ensure that the log crate is imported and initialized in your project if it is not already. You may also need to adjust the error handling to integrate with your application's error type.

@@ -44,16 +44,18 @@ use flowy_sqlite::kv::KVStorePreferences;
use futures::future;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider updating APIs to use Uuid directly for workspace IDs instead of converting to and from String to reduce conversion overhead and simplify code flow, especially in methods like get_workspace_info and related callsites, including notifications, index removals, and view movements, to improve code clarity and efficiency..

Consider updating the APIs for workspace IDs so they use `Uuid` directly, rather than relying on converting to and from `String`. For example, instead of writing:

    folder.get_workspace_info(&workspace_id.to_string())

update both the API and its callers so that the signature becomes:

    fn get_workspace_info(&self, workspace_id: &Uuid) -> Option<Workspace>

Then adjust call sites accordingly:

    folder.get_workspace_info(workspace_id)

This removes repeated `.to_string()` and `Uuid::from_str(...)` invocations. Audit similar cases (e.g., in notifications, index removals, view movements) and update them to work directly with `Uuid`. This will reduce conversion clutter and simplify the control flow.

@@ -24,15 +24,17 @@ use lib_infra::box_any::BoxAny;
use lib_infra::isolate_stream::{IsolateSink, SinkExt};
use lib_infra::util::timestamp;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider updating lower-layer functions to accept Uuid directly for workspace_id instead of converting it to a string, to improve consistency and reduce conversion overhead throughout the codebase.

It looks like the change now brings workspace_id into domain type Uuid, but then many higher‐layer callers continue to convert it to and from strings. Instead of sprinkling conversions, consider updating the lower layer (e.g. database and cloud APIs) to work with Uuid directly. This minimizes conversion overhead and makes the intent clearer.

For example, if you have a function like:

fn delete_upload_file_by_file_id(conn: DBConnection, workspace_id: &String, parent_dir: &str, file_id: &str) -> Result<Option<File>, FlowyError> { ... }

change its signature to:

fn delete_upload_file_by_file_id(conn: DBConnection, workspace_id: &Uuid, parent_dir: &str, file_id: &str) -> Result<Option<File>, FlowyError> { ... }

Then in the caller, you won’t need to call

&workspace_id.to_string()

—you can pass &workspace_id directly. Similarly update all functions that expect a string workspace id. This makes the API consistent and reduces cognitive load.

@@ -46,9 +48,10 @@ pub(crate) fn subscribe_folder_view_changed(
ChildViewChangeReason::Create,
);
let folder = lock.read().await;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider refactoring the domain to use Uuid for the parent_view_id field to avoid repeated conversions and error handling in the observer logic, reducing nesting and complexity while keeping all functionality intact.

Consider refactoring the domain to use Uuid for the parent_view_id field instead of a String. This would eliminate the repeated inline calls to Uuid::from_str and the associated error handling. For example, update the view struct so the conversion happens once, at creation time:

// Before
pub struct View {
    pub parent_view_id: String,
    // ...
}

// After
use uuid::Uuid;
pub struct View {
    pub parent_view_id: Uuid,
    // ...
}

Then ensure that when you create or deserialize a View, the conversion occurs right there:

let view = View {
    parent_view_id: Uuid::parse_str(&raw_parent_view_id).expect("Invalid UUID format"),
    // ...
};

With the field stored as a Uuid, you can remove the additional error handling in your observer logic, thus reducing nesting and complexity while keeping all functionality intact.

@appflowy appflowy changed the title Use UUID Chore: Use UUID instead of using String Apr 7, 2025
@appflowy appflowy merged commit b06a233 into main Apr 7, 2025
8 checks passed
@appflowy appflowy deleted the use_uuid branch April 7, 2025 13:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant