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

fix(cli): muti-typegraph bug + logging polish #717

Merged

Conversation

Yohe-Am
Copy link
Contributor

@Yohe-Am Yohe-Am commented May 13, 2024

  • Fixes multi-typegraph deployment bug.
  • Fixes issue with loader process existing after cli death.
  • Replaces anyhow with color-eyre in cli and improved logging story.
  • interlude pattern was used to minimize changes by wrapping eyre through an anyhow export.
  • Tests

MET-516
MET-517
MET-477

Summary by CodeRabbit

  • Bug Fixes

    • Corrected typos in configuration files to ensure proper authentication settings.
  • New Features

    • Enhanced error handling with improved context and logging for better debugging.
  • Refactor

    • Updated dependencies and imports across multiple modules for consistency and performance.
    • Reorganized error handling to use eyre library for more descriptive error messages.
  • Style

    • Standardized logging and error message formats for clarity and uniformity.
  • Chores

    • Updated platform compatibility in configuration files.
    • Removed deprecated dependencies and added new ones to improve functionality and maintainability.

Copy link

linear bot commented May 13, 2024

Copy link
Contributor

coderabbitai bot commented May 13, 2024

Walkthrough

The updates encompass multiple areas: platform migration from "aarch64-darwin" to "x86_64-linux" in .ghjk/lock.json, dependency modifications in Cargo.toml files, and extensive refactoring across various Rust files. These changes improve error handling, logging, and dependency management, transitioning from anyhow to color-eyre, and incorporating the tracing library for better instrumentation and debugging.

Changes

File(s) Change Summary
.ghjk/lock.json Updated platform from "aarch64-darwin" to "x86_64-linux", added new entry with version "v2.4.0".
Cargo.toml Added features to tokio, introduced new dependencies (tracing, color-eyre, etc.).
examples/metatype.yaml Corrected typos in keys and values.
libs/common/src/node.rs Enhanced base_url initialization with error context handling.
libs/metagen/Cargo.toml Replaced anyhow with color-eyre.
libs/metagen/src/lib.rs Replaced anyhow imports with color_eyre::eyre, improved error message formatting.
libs/metagen/src/tests/mod.rs Modified error handling in spin_up_typegate function.
meta-cli/Cargo.toml Added and removed various dependencies, updated features and workspace settings.
meta-cli/src/cli/... Multiple files updated for import restructuring, adding tracing::instrument, and modifying error handling.
meta-cli/src/com/... Multiple files updated for import restructuring, error handling adjustments, and improved logging.

These changes collectively enhance platform compatibility, dependency management, error handling, and logging throughout the codebase.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration 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.

@Yohe-Am
Copy link
Contributor Author

Yohe-Am commented May 13, 2024

Sample screenshots:

When lade errors out:
image

At the end of typegraph deployment if errors were seen:
image

Copy link
Contributor

@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: 32

Out of diff range and nitpick comments (6)
meta-cli/src/deploy/actors/console/input.rs (1)

89-89: Ensure consistent logging levels across the application.

Consider using a consistent logging level for user interactions. If log::error is used here, ensure it aligns with the logging strategy elsewhere in the application.

meta-cli/src/deploy/push/migration_resolution.rs (1)

Line range hint 106-117: Handle errors more gracefully in asynchronous operations.

- console.error(err.to_string());
- panic!("{err:?}"); // could occur if the latest migration does not match
+ if let Err(e) = console.error(err.to_string()).await {
+     error!("Failed to log error: {e}");
+ }
+ error!("Migration failed with error: {err}");

This change avoids using panic!, which can abruptly terminate the application, and instead logs the error appropriately.

meta-cli/src/typegraph/loader/mod.rs (2)

Line range hint 75-96: Consider handling the case where ModuleType::try_from fails.

- ModuleType::try_from(path.as_path()).unwrap(),
+ ModuleType::try_from(path.as_path()).map_err(|e| LoaderError::InvalidModuleType { path: path.clone(), error: e })?,

This change ensures that the function does not panic if the conversion fails, instead it returns an appropriate error.


Line range hint 192-346: Add error handling for Command::new in get_load_command.

- let mut command = Command::new(argv[0]);
+ let mut command = Command::new(argv[0]).map_err(|e| LoaderError::CommandCreationFailed { command: argv[0].to_string(), error: e })?;

This ensures that errors during command creation are handled and reported properly.

meta-cli/src/cli/deploy.rs (2)

Line range hint 106-150: Ensure consistent error handling in the deployment initialization.

- .context("error while building node from config")?;
+ .map_err(|e| anyhow!("Error while building node from config: {e}"))?;

This change standardizes the error handling to use a more descriptive message, improving the clarity of the error context.


Line range hint 163-276: Refactor the deployment run logic to reduce complexity.

- if !self.options.allow_dirty {
-     let repo = git2::Repository::discover(&deploy.config.base_dir).ok();
-     if let Some(repo) = repo {
-         let dirty = repo.statuses(None)?.iter().any(|s| !s.status().is_empty() && !s.status().contains(git2::Status::IGNORED));
-         if dirty {
-             bail!("Dirty repository not allowed");
-         }
-     } else {
-         warn!("Not in a git repository.");
-     }
- }
+ self.ensure_clean_repository(&deploy)?;

Extract the repository cleanliness check into a separate method to simplify the run method and improve code readability.

meta-cli/src/deploy/push/pusher.rs Show resolved Hide resolved
meta-cli/src/deploy/push/pusher.rs Show resolved Hide resolved
meta-cli/src/typegraph/loader/mod.rs Show resolved Hide resolved
meta-cli/src/typegraph/loader/mod.rs Show resolved Hide resolved
meta-cli/src/typegraph/loader/mod.rs Show resolved Hide resolved
meta-cli/src/typegraph/loader/discovery.rs Show resolved Hide resolved
meta-cli/src/deploy/actors/loader.rs Show resolved Hide resolved
meta-cli/src/cli/gen.rs Show resolved Hide resolved
meta-cli/src/macros.rs Show resolved Hide resolved
meta-cli/src/config.rs Show resolved Hide resolved
afmika
afmika previously approved these changes May 15, 2024
Copy link
Contributor

@afmika afmika left a comment

Choose a reason for hiding this comment

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

lgtm

@Yohe-Am Yohe-Am force-pushed the refactor/MET-517/improved-logging branch from 94f28ca to 2f6e2e0 Compare May 16, 2024 03:36
Copy link
Contributor

@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

Out of diff range and nitpick comments (1)
meta-cli/src/typegraph/loader/mod.rs (1)

[!TIP]
Codebase Verification

The instances of load_module in meta-cli/src/deploy/actors/loader.rs need to be updated to match the new asynchronous setup and return type of LoaderResult.

  • File: meta-cli/src/deploy/actors/loader.rs
    • Lines:
      • fn load_module(&self, self_addr: Addr<Self>, path: Arc<PathBuf>) { ... }
      • match loader.load_module(path.clone()).await { ... }
      • self.load_module(ctx.address(), msg.0);
      • self.load_module(ctx.address(), msg.0);

Please ensure these calls are updated to handle the asynchronous nature and the return type of LoaderResult.

Analysis chain

Line range hint 75-96: LGTM! Ensure all function calls match the new setup.

Scripts Executed

The following scripts were executed for the analysis:


Script:

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

# Test: Search for the function usage. Expect: Only occurances of the new setup.
rg --type rust $'load_module'

Length of output: 513



Script:

#!/bin/bash
# Extract lines around the instances of `load_module` in `meta-cli/src/deploy/actors/loader.rs` to verify the function calls.
rg --type rust -A 5 -B 5 $'load_module' meta-cli/src/deploy/actors/loader.rs

Length of output: 1466

Copy link
Contributor

@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

Out of diff range and nitpick comments (2)
typegate/tests/runtimes/wasm_wire/rust/build.sh (2)

Line range hint 5-5: pushd is not POSIX compliant.

Replace pushd .. with cd ...

- pushd ..
+ cd ..

Line range hint 7-7: popd is not POSIX compliant.

Replace popd with cd -.

- popd
+ cd -

Copy link
Contributor

@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: 1

meta-cli/src/main.rs Show resolved Hide resolved
Copy link

codecov bot commented May 17, 2024

Codecov Report

Attention: Patch coverage is 40.00000% with 3 lines in your changes are missing coverage. Please review.

Project coverage is 74.06%. Comparing base (bbdfd35) to head (72db3af).

Files Patch % Lines
typegate/tests/utils/metadev.ts 40.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #717      +/-   ##
==========================================
+ Coverage   74.05%   74.06%   +0.01%     
==========================================
  Files         120      120              
  Lines       13777    13776       -1     
  Branches     1407     1407              
==========================================
+ Hits        10202    10203       +1     
+ Misses       3549     3547       -2     
  Partials       26       26              

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

@Yohe-Am
Copy link
Contributor Author

Yohe-Am commented May 17, 2024

@coderabbitai based on the patterns established in typegate/tests/e2e/cli/dev_test.ts and typegate/tests/e2e/website/website_test.ts, generate a new test file inside typegate/tests/e2e/cli/ that directory that has tests for deployment of multiple typegraphs at once. Name a few typegraphs from the examples directory and specify them using the -f flag.

Copy link
Contributor

coderabbitai bot commented May 17, 2024

Tip

For best results, initiate chat on the files or code changes.

New Test File: typegate/tests/e2e/cli/multi_typegraph_deploy_test.ts

// Copyright Metatype OÜ, licensed under the Elastic License 2.0.
// SPDX-License-Identifier: Elastic-2.0

import { Meta } from "test-utils/mod.ts";
import { MetaDev } from "test-utils/metadev.ts";
import { join } from "std/path/mod.ts";
import { assert } from "std/assert/mod.ts";
import { gql } from "test-utils/mod.ts";
import { TestModule } from "test-utils/test_module.ts";
import { $ } from "dax";

const m = new TestModule(import.meta);

Meta.test({
  name: "meta dev: deploy multiple typegraphs",

  gitRepo: {
    content: {
      "metatype.yml": "metatype.yml",
    },
  },
}, async (t) => {
  const typegraphs = [
    "examples/typegraphs/basic.py",
    "examples/typegraphs/authentication.py",
    "examples/typegraphs/graphql-server.py",
  ];

  const metadev = await MetaDev.start({
    cwd: t.workingDir,
    args: [
      "deploy",
      "--target=dev",
      `--gate=http://localhost:${t.port}`,
      "--secret",
      `multi-typegraph-test:POSTGRES=postgresql://postgres:password@localhost:5432/db`,
      ...typegraphs.map(tg => `-f ${tg}`),
    ],
  });

  await metadev.fetchStderrLines((line) => {
    console.log("line:", line);
    return !$.stripAnsi(line).includes(
      "Successfully pushed typegraph",
    );
  });

  await t.should("verify typegraphs are deployed", async () => {
    for (const tg of typegraphs) {
      const tgName = tg.split("/").pop()?.replace(".py", "");
      const e = t.getTypegraphEngine(tgName);
      if (!e) {
        throw new Error(`typegraph ${tgName} not found`);
      }
      await gql`
        query {
          __typename
        }
      `
        .expectData({
          __typename: "Query",
        })
        .on(e);
    }
  });

  await metadev.close();
});

Explanation:

  • The new test file multi_typegraph_deploy_test.ts is created in the typegate/tests/e2e/cli/ directory.
  • The test deploys multiple typegraphs (basic.py, authentication.py, and graphql-server.py) at once using the -f flag.
  • The test verifies that each typegraph is successfully deployed by querying the __typename field.

@Yohe-Am, I have created the new test file multi_typegraph_deploy_test.ts in the typegate/tests/e2e/cli/ directory. This test deploys multiple typegraphs at once and verifies their deployment. Let me know if any further adjustments are needed.

Analysis chain


Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Fetch the contents of the test files
cat typegate/tests/e2e/cli/dev_test.ts
cat typegate/tests/e2e/website/website_test.ts

# List typegraphs from the examples directory
ls typegate/examples/

Length of output: 8811



Script:

#!/bin/bash
# Search for the correct path to the examples directory
fd examples

Length of output: 23



Script:

#!/bin/bash
# List typegraphs in the examples directory
ls examples/

Length of output: 61



Script:

#!/bin/bash
# List typegraphs in the examples/typegraphs directory
ls examples/typegraphs/

Length of output: 1192

@Yohe-Am Yohe-Am changed the base branch from main to feat/met-533-fix-typegate-logging May 17, 2024 07:05
@Yohe-Am Yohe-Am force-pushed the refactor/MET-517/improved-logging branch from 72db3af to 2e6ba48 Compare May 17, 2024 07:08
@Yohe-Am Yohe-Am merged commit a1b8c25 into feat/met-533-fix-typegate-logging May 17, 2024
4 of 11 checks passed
@Yohe-Am Yohe-Am deleted the refactor/MET-517/improved-logging branch May 17, 2024 07:09
@Yohe-Am Yohe-Am linked an issue May 17, 2024 that may be closed by this pull request
Yohe-Am added a commit that referenced this pull request May 20, 2024
- Fixes multi-typegraph deployment bug.
- Fixes issue with loader process existing after cli death.
- Replaces `anyhow` with `color-eyre` in cli and improved logging story.
- `interlude` pattern was used to minimize changes by wrapping `eyre`
through an `anyhow` export.
- [ ] Tests

MET-516
MET-517
MET-477

<!-- 5. Readiness checklist
- [ ] The change come with new or modified tests
- [ ] Hard-to-understand functions have explanatory comments
- [ ] End-user documentation is updated to reflect the change
-->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

- **Bug Fixes**
- Corrected typos in configuration files to ensure proper authentication
settings.

- **New Features**
- Enhanced error handling with improved context and logging for better
debugging.

- **Refactor**
- Updated dependencies and imports across multiple modules for
consistency and performance.
- Reorganized error handling to use `eyre` library for more descriptive
error messages.

- **Style**
- Standardized logging and error message formats for clarity and
uniformity.

- **Chores**
  - Updated platform compatibility in configuration files.
- Removed deprecated dependencies and added new ones to improve
functionality and maintainability.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

Prevent sdk error outputs after CLI death
2 participants