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

refactor(sozo): fetch writes from events and calculate diff for that + some refactor #2203

Merged
merged 18 commits into from
Jul 31, 2024

Conversation

lambda-0x
Copy link
Contributor

@lambda-0x lambda-0x commented Jul 23, 2024

fix: #2079

Summary by CodeRabbit

  • New Features

    • Introduced a new function for extracting tags from filenames, enhancing filename parsing capabilities.
    • Added a new authorization function that consolidates granting and revoking permissions.
    • Updated migration functions to include additional context and improve clarity during the migration process.
    • Introduced a new function to find authorization differences during migrations, improving resource access management.
  • Bug Fixes

    • Improved error handling in migration processes to ensure proper validation of changes.
  • Refactor

    • Streamlined functions to reduce mutability and improve performance by passing parameters by reference.
    • Simplified logic in various asynchronous functions to enhance code clarity and efficiency.
  • Documentation

    • Enhanced documentation for several functions, clarifying parameters and return types to improve user understanding.
  • Style

    • Made formatting adjustments across multiple files for consistency and readability.

Copy link

codecov bot commented Jul 24, 2024

Codecov Report

Attention: Patch coverage is 78.03618% with 85 lines in your changes missing coverage. Please review.

Project coverage is 70.20%. Comparing base (f14c445) to head (0aa5d3e).

Files Patch % Lines
crates/sozo/ops/src/migration/migrate.rs 68.29% 39 Missing ⚠️
crates/sozo/ops/src/migration/mod.rs 61.22% 19 Missing ⚠️
bin/sozo/src/commands/auth.rs 0.00% 11 Missing ⚠️
crates/dojo-world/src/contracts/naming.rs 0.00% 11 Missing ⚠️
crates/dojo-world/src/manifest/mod.rs 97.33% 2 Missing ⚠️
crates/sozo/ops/src/auth.rs 86.66% 2 Missing ⚠️
crates/sozo/ops/src/migration/utils.rs 97.82% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2203      +/-   ##
==========================================
+ Coverage   70.15%   70.20%   +0.05%     
==========================================
  Files         343      343              
  Lines       44981    45185     +204     
==========================================
+ Hits        31556    31722     +166     
- Misses      13425    13463      +38     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Nice work mate and good addition of the selector on the auth part. Some changes have been merged on main related to auth, you may have conflict there.

About the writers, it looks good on the logic, and make the flow easy for the user to simply use migrate apply and everything is computed.

The only downside of the current implementation is that when revoking, only the selectors are displayed. And fetching each one of the selector info to display the name might be worthy for easier debugging / understanding of the operations, wdyt?

crates/dojo-world/src/manifest/mod.rs Show resolved Hide resolved
crates/dojo-world/src/manifest/types.rs Outdated Show resolved Hide resolved
crates/dojo-world/src/migration/strategy.rs Outdated Show resolved Hide resolved
crates/sozo/ops/src/auth.rs Show resolved Hide resolved
crates/sozo/ops/src/auth.rs Outdated Show resolved Hide resolved
crates/sozo/ops/src/auth.rs Outdated Show resolved Hide resolved
crates/sozo/ops/src/auth.rs Outdated Show resolved Hide resolved
crates/sozo/ops/src/migration/migrate.rs Show resolved Hide resolved
crates/sozo/ops/src/migration/migrate.rs Outdated Show resolved Hide resolved
crates/sozo/ops/src/migration/mod.rs Outdated Show resolved Hide resolved
@lambda-0x lambda-0x changed the title refactor(sozo): add metadata.toml to track state during migration failure + some refactor refactor(sozo): fetch writes from events and calculate diff for that + some refactor Jul 31, 2024
@lambda-0x lambda-0x marked this pull request as ready for review July 31, 2024 09:11
Copy link

coderabbitai bot commented Jul 31, 2024

Walkthrough

Ohayo, sensei! The recent changes enhance the codebase's performance and clarity by optimizing parameter handling, improving resource management, and refining the migration process. Key modifications include passing parameters by reference for better efficiency, simplifying function signatures, and adding new functionalities such as tracking authorization changes during migrations. Overall, these adjustments contribute to a more robust and efficient system.

Changes

Files Change Summary
bin/sozo/src/commands/auth.rs, crates/sozo/ops/src/auth.rs Modified function signatures to pass parameters by reference for efficiency; added a new variant to ResourceType.
crates/dojo-world/src/migration.rs, crates/dojo-world/src/migration/world.rs Updated migration functions to improve logic and return types, enhancing error handling and functionality for migration strategies.
crates/sozo/ops/src/migration/mod.rs, crates/sozo/ops/src/migration/migrate.rs Introduced find_authorization_diff to streamline authorization during migration; updated migration logic for clarity and performance enhancements.
crates/sozo/ops/src/tests/auth.rs, crates/sozo/ops/src/tests/migration.rs Adjusted test cases to use slice syntax for collections, improving performance; updated function signatures to align with new changes in logic.
examples/spawn-and-move/Scarb.toml, examples/spawn-and-move/overlays/dev/actions.toml Minor formatting changes for improved clarity without altering functionality.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MigrationService
    participant AuthService

    User->>MigrationService: Start Migration
    MigrationService->>AuthService: Request Authorization
    AuthService->>MigrationService: Return Authorization Result
    MigrationService-->>User: Migrate Complete
Loading

Assessment against linked issues

Objective Addressed Explanation
Authorizations using overlays seem to fail (#2079)
Improve authorization tracking in migration processes
World metadatas not uploaded after failure (#2096) The changes do not address the issue of metadata upload failure during migration restarts.

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ccd9a59 and 0aa5d3e.

Files selected for processing (1)
  • crates/sozo/ops/src/migration/migrate.rs (13 hunks)
Additional comments not posted (8)
crates/sozo/ops/src/migration/migrate.rs (8)

258-264: Ohayo, sensei! The parameter and return type updates improve clarity.

The function now includes a ResourceMetadata object, providing a more precise definition of the resources being handled.


698-727: Ohayo, sensei! Simplifying the function signature enhances reliability.

Changing the world_address parameter from Option<Felt> to Felt ensures that a valid address is always provided, reducing potential errors.


728-728: Ohayo, sensei! The update ensures compatibility with the new function signature.

The print_strategy function now calls get_contract_operation_name with the updated world_address parameter type, ensuring compatibility.


Line range hint 824-836:
Ohayo, sensei! The update ensures compatibility with the new MigrationOutput structure.

The update_manifests_and_abis function now correctly processes the updated MigrationOutput structure, enhancing maintainability and future-proofing the code.


878-878: Ohayo, sensei! The update ensures compatibility with the new MigrationOutput structure.

The register_dojo_models function now correctly processes the updated MigrationOutput structure, enhancing maintainability and future-proofing the code.


878-878: Ohayo, sensei! The update ensures compatibility with the new MigrationOutput structure.

The register_dojo_contracts function now correctly processes the updated MigrationOutput structure, enhancing maintainability and future-proofing the code.


78-78: LGTM! But verify the function usage in the codebase.

The code changes are approved. The shift towards a more functional style by using an immutable reference for strategy reduces potential side effects and improves readability.

However, ensure that all function calls to apply_diff match the new signature.

Verification successful

Ohayo, sensei! The function usage for apply_diff has been verified and matches the new signature with an immutable reference for strategy.

  • crates/sozo/ops/src/migration/mod.rs: The function call to apply_diff correctly uses an immutable reference for strategy.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `apply_diff` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type rust -A 5 $'apply_diff'

Length of output: 2506


878-1003: Ohayo, sensei! The new function enhances access management accuracy.

The find_authorization_diff function processes migration outputs to determine resource access rights, using a HashSet to track recently migrated contracts and generating a map of resource selectors.

Ensure that the function is used correctly throughout the codebase.

Verification successful

Ohayo, sensei! The new function find_authorization_diff enhances access management accuracy.

The function is correctly utilized in both the test file crates/sozo/ops/src/tests/migration.rs and the module file crates/sozo/ops/src/migration/mod.rs, ensuring it is both tested and integrated into the migration process.

  • Files and lines:
    • crates/sozo/ops/src/tests/migration.rs: Lines where the function is imported and called.
    • crates/sozo/ops/src/migration/mod.rs: Lines where the function is imported and called.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new `find_authorization_diff` function in the codebase.

# Test: Search for the function usage. Expect: Correct usage of the new function.
rg --type rust -A 5 $'find_authorization_diff'

Length of output: 2239


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (2)
crates/sozo/ops/src/migration/mod.rs (1)

127-129: Dry run enhancement.

The TODO comment suggests that the dry run can also show the diffs for things apart from the world state. This is a good enhancement for future implementation.

crates/sozo/ops/src/migration/migrate.rs (1)

877-878: Ohayo, sensei! Add a comment for future handling of owners.

Adding a comment to note that handling of owners might be added in the future will help avoid forgetting this enhancement.

+ // For now we just handle writers, handling of owners might be added in the future

@lambda-0x
Copy link
Contributor Author

And fetching each one of the selector info to display the name might be worthy for easier debugging / understanding of the operations

good point, updated it to show more appropriate resource type instead of selector where possible.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Outside diff range, codebase verification and nitpick comments (3)
crates/sozo/ops/src/migration/migrate.rs (3)

Line range hint 78-113:
Ohayo, sensei! Simplify the check for migration_output.full.

The function is well-structured, but the check for migration_output.full can be simplified by combining the if-else blocks.

if let Some(block_number) = migration_output.world_block_number {
    ui.print(format!(
        "\n🎉 Successfully migrated World on block #{} at address {}\n",
        block_number,
        bold_message(format!("{:#x}", strategy.world_address))
    ));
} else {
    ui.print(format!(
        "\n🎉 Successfully migrated World at address {}\n",
        bold_message(format!("{:#x}", strategy.world_address))
    ));
}

Line range hint 115-204:
Ohayo, sensei! Simplify the match statements for readability.

The function is well-structured, but the match statements can be simplified to improve readability.

match &strategy.base {
    Some(base) => {
        ui.print_header("# Base Contract");
        match base.declare(&migrator, &txn_config).await {
            Ok(res) => ui.print_sub(format!("Class Hash: {:#x}", res.class_hash)),
            Err(MigrationError::ClassAlreadyDeclared) => ui.print_sub(format!("Already declared: {:#x}", base.diff.local_class_hash)),
            Err(MigrationError::ArtifactError(e)) => return Err(handle_artifact_error(&ui, base.artifact_path(), e)),
            Err(e) => {
                ui.verbose(format!("{e:?}"));
                return Err(e.into());
            }
        };
    }
    None => {}
};

match &strategy.world {
    Some(world) => {
        ui.print_header("# World");
        if let Some(_) = world.diff.remote_class_hash {
            let _deploy_result = upgrade_contract(
                world,
                "world",
                world.diff.original_class_hash,
                strategy.base.as_ref().unwrap().diff.original_class_hash,
                &migrator,
                &ui,
                &txn_config,
            ).await.map_err(|e| {
                ui.verbose(format!("{e:?}"));
                anyhow!("Failed to upgrade world: {e}")
            })?;
            ui.print_sub(format!("Upgraded Contract at address: {:#x}", world.contract_address));
        } else {
            let calldata = vec![strategy.base.as_ref().unwrap().diff.local_class_hash];
            let deploy_result = deploy_contract(world, "world", calldata.clone(), &migrator, &ui, &txn_config).await.map_err(|e| {
                ui.verbose(format!("{e:?}"));
                anyhow!("Failed to deploy world: {e}")
            })?;
            (world_tx_hash, world_block_number) = if let ContractDeploymentOutput::Output(deploy_result) = deploy_result {
                (Some(deploy_result.transaction_hash), deploy_result.block_number)
            } else {
                (None, None)
            };
            ui.print_sub(format!("Contract address: {:#x}", world.contract_address));
        }
    }
    None => {}
};

Line range hint 277-350:
Ohayo, sensei! Improve error handling for IPFS uploads.

The function is well-structured, but the error handling for the IPFS uploads can be improved by consolidating error messages.

// world
if migration_output.world_tx_hash.is_some() {
    match dojo_metadata.world.upload().await {
        Ok(hash) => {
            let resource = create_resource_metadata(Felt::ZERO, hash.clone())?;
            ui.print_sub(format!("world: ipfs://{}", hash));
            resources.push(resource);
        }
        Err(err) => ui.print_sub(format!("Failed to upload World metadata:\n{err}")),
    }
}

// models
if !migration_output.models.is_empty() {
    for model_tag in migration_output.models {
        if let Some(m) = dojo_metadata.resources_artifacts.get(&model_tag) {
            ipfs.push(upload_on_ipfs_and_create_resource(
                &ui,
                compute_selector_from_tag(&model_tag),
                m.clone(),
            ));
        }
    }
}

// contracts
let migrated_contracts = migration_output.contracts.into_iter().flatten().collect::<Vec<_>>();

if !migrated_contracts.is_empty() {
    for contract in migrated_contracts {
        if let Some(m) = dojo_metadata.resources_artifacts.get(&contract.tag) {
            ipfs.push(upload_on_ipfs_and_create_resource(
                &ui,
                naming::compute_selector_from_tag(&contract.tag),
                m.clone(),
            ));
        }
    }
}

// upload IPFS
resources.extend(
    future::try_join_all(ipfs)
        .await
        .map_err(|_| anyhow!("Unable to upload IPFS artifacts."))?,
);

ui.print("> All IPFS artifacts have been successfully uploaded.".to_string());

crates/sozo/ops/src/migration/utils.rs Show resolved Hide resolved
crates/sozo/ops/src/migration/migrate.rs Outdated Show resolved Hide resolved
@lambda-0x lambda-0x merged commit 86c554c into main Jul 31, 2024
15 checks passed
@lambda-0x lambda-0x deleted the refactor-things branch July 31, 2024 19:52
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.

Authorizations using overlays seem to fail
2 participants