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

feat: switch analytics to posthog #508

Merged
merged 10 commits into from
Sep 18, 2024
Merged

feat: switch analytics to posthog #508

merged 10 commits into from
Sep 18, 2024

Conversation

morgante
Copy link
Contributor

@morgante morgante commented Sep 18, 2024

Cut costs / complexity by skipping Segment

Summary by CodeRabbit

  • New Features

    • Introduced a new analytics tracking structure for improved data handling and accessibility.
    • Added integration with PostHog for enhanced user interaction tracking and analytics capabilities.
  • Bug Fixes

    • Improved error handling for analytics event capturing, ensuring better reliability.
  • Documentation

    • Updated documentation to reflect the new analytics structure and PostHog integration.

@morgante morgante marked this pull request as ready for review September 18, 2024 02:18
@morgante morgante requested a review from a team as a code owner September 18, 2024 02:18
Copy link
Contributor

coderabbitai bot commented Sep 18, 2024

Warning

Rate limit exceeded

@morgante has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 27 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between ce93abe and 90e47a2.

Walkthrough

Walkthrough

The changes involve restructuring the analytics functionality within a CLI application. A new AnalyticsPayload struct replaces the previous SegmentPayload, improving field accessibility. The track_event function has been updated to utilize this new struct. Additionally, a new posthog module has been introduced, which includes a PostHogClient for capturing analytics events. This client employs reqwest for HTTP requests and serde for JSON serialization, enhancing error handling and integrating with the PostHog analytics tool.

Changes

Files Change Summary
crates/cli/src/analytics.rs Introduced AnalyticsPayload struct, modified track_event to use it, and updated event sending logic to utilize PostHogClient with improved error handling.
crates/cli/src/lib.rs Added a new module posthog, indicating expanded functionality related to PostHog analytics.
crates/cli/src/posthog.rs Implemented PostHogClient for capturing events, including methods for capturing analytics events and handling conversions from AnalyticsPayload to PostHogEvent.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant PostHogClient
    participant PostHogAPI

    User->>CLI: Trigger event
    CLI->>PostHogClient: Capture event with AnalyticsPayload
    PostHogClient->>PostHogAPI: Send PostHogEvent
    PostHogAPI-->>PostHogClient: Response
    PostHogClient-->>CLI: Acknowledge event capture
Loading

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>, please review it.
    -- 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 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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.
Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI o1 for code reviews: OpenAI's new o1 model is being tested for code reviews. This model has advanced reasoning capabilities and can provide more detailed feedback on your code.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

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: 4

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 23e88a5 and eb9b62a.

Files selected for processing (3)
  • crates/cli/src/analytics.rs (3 hunks)
  • crates/cli/src/lib.rs (1 hunks)
  • crates/cli/src/posthog.rs (1 hunks)
Additional comments not posted (2)
crates/cli/src/lib.rs (1)

12-12: Module inclusion is correct

The addition of the posthog module integrates the new analytics functionality properly into the CLI application.

crates/cli/src/analytics.rs (1)

206-212: Ensure compatibility with Rust version when using let else syntax

The usage of the let Ok(client) = ... else { ... } syntax requires Rust 1.65 or newer. It's important to confirm that the project's minimum supported Rust version (MSRV) is set accordingly to avoid build failures for users on older Rust versions.

Run the following script to check the project's specified Rust version:

Ensure that the Rust version is set to 1.65 or higher in your project's configuration.

Comment on lines +15 to +16
static ref POSTHOG_WRITE_KEY: String =
String::from("phc_ksrztn1ogPbqUSUf1qRjhoC6GMzpmBm7iqSNhVzvor5");
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid hard-coding API keys

The PostHog API key is hard-coded into the source code:

static ref POSTHOG_WRITE_KEY: String =
    String::from("phc_ksrztn1ogPbqUSUf1qRjhoC6GMzpmBm7iqSNhVzvor5");

This practice poses a security risk, as it can lead to unauthorized access if the code is exposed publicly. It's recommended to retrieve the API key from environment variables or a secure configuration.

Consider modifying the code to read the API key from an environment variable:

-static ref POSTHOG_WRITE_KEY: String =
-    String::from("phc_ksrztn1ogPbqUSUf1qRjhoC6GMzpmBm7iqSNhVzvor5");
+static ref POSTHOG_WRITE_KEY: String =
+    env::var("POSTHOG_WRITE_KEY").expect("POSTHOG_WRITE_KEY must be set");

Ensure that the environment variable POSTHOG_WRITE_KEY is securely provided in the deployment environment.

.client
.post(POSTHOG_HOST.to_string())
.header(CONTENT_TYPE, "application/json")
.body(serde_json::to_string(&event).expect("unwrap here is safe"))
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle serialization errors without panicking

Using expect("unwrap here is safe") on serde_json::to_string(&event) may cause a panic if serialization fails unexpectedly, which could crash the application.

Modify the code to properly handle serialization errors:

             .header(CONTENT_TYPE, "application/json")
-            .body(serde_json::to_string(&event).expect("unwrap here is safe"))
+            .body(serde_json::to_string(&event)?)
             .send()

By using the ? operator, any serialization errors will be propagated as part of the Result, allowing for graceful error handling.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.body(serde_json::to_string(&event).expect("unwrap here is safe"))
.body(serde_json::to_string(&event)?)

crates/cli/src/posthog.rs Outdated Show resolved Hide resolved
Comment on lines +206 to +212
let Ok(client) = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.send()
.await
{
Ok(response) => {
if !response.status().is_success() {
log::error!(
"Failed to send event {}: {}",
analytics_event_name,
response.status()
);
}
}
Err(e) => {
log::error!("Failed to send event {}: {:#}", analytics_event_name, e);
}
.build()
else {
log::error!("Failed to create client");
return;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Log error details when client creation fails

Currently, if the reqwest::Client fails to build, the error details are not logged, making it difficult to diagnose the issue.

Modify the error handling to capture and log the specific error:

 let client = match reqwest::Client::builder()
     .timeout(Duration::from_secs(5))
     .build() {
-    Ok(client) => client,
-    else {
-        log::error!("Failed to create client");
+    Ok(client) => client,
+    Err(e) => {
+        log::error!("Failed to create client: {:#}", e);
         return;
-    }
+    }
 };

This will provide more insight into why the client creation failed.

Committable suggestion was skipped due to low confidence.

morgante and others added 4 commits September 17, 2024 21:32
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

grit-app bot commented Sep 18, 2024

On commit ce93abe, Grit tried to heal these tests:

Job Original Status Final Status
code quality / clippy_check ❌ Failed ❗ Failed on attempt #2 after trying strategies ai, rerun

Tip

You can view and edit CI healing settings on the Grit App.

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between eb9b62a and ce93abe.

Files selected for processing (1)
  • crates/cli/src/posthog.rs (1 hunks)
Additional context used
GitHub Check: clippy
crates/cli/src/posthog.rs

[failure] 39-39: borrow of moved value: res
error[E0382]: borrow of moved value: res
--> crates/cli/src/posthog.rs:39:82
|
30 | let res = self
| --- move occurs because res has type reqwest::Response, which does not implement the Copy trait
...
38 | let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
| ------ res moved due to this method call
39 | bail!("Failed to send event {}: {}\nResponse body: {}", event.event, res.status(), body);
| ^^^ value borrowed here after move
|
note: reqwest::Response::text takes ownership of the receiver self, which moves res
--> /home/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/reqwest-0.11.24/src/async_impl/response.rs:147:23
|
147 | pub async fn text(self) -> crate::Result {
| ^^^^

Additional comments not posted (2)
crates/cli/src/posthog.rs (2)

15-16: Avoid hardcoding API keys


34-34: Handle serialization errors without panicking

Comment on lines 38 to 39
let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
bail!("Failed to send event {}: {}\nResponse body: {}", event.event, res.status(), body);
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the use-after-move error

res is moved when calling res.text().await, so it cannot be used afterward. This causes a compilation error due to the use of a moved value.

Apply this diff to fix the error by capturing the status before consuming res:

     if !res.status().is_success() {
+        let status = res.status();
         let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
-        bail!("Failed to send event {}: {}\nResponse body: {}", event.event, res.status(), body);
+        bail!("Failed to send event {}: {}\nResponse body: {}", event.event, status, body);
     }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
bail!("Failed to send event {}: {}\nResponse body: {}", event.event, res.status(), body);
if !res.status().is_success() {
let status = res.status();
let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
bail!("Failed to send event {}: {}\nResponse body: {}", event.event, status, body);
}
Tools
GitHub Check: clippy

[failure] 39-39: borrow of moved value: res
error[E0382]: borrow of moved value: res
--> crates/cli/src/posthog.rs:39:82
|
30 | let res = self
| --- move occurs because res has type reqwest::Response, which does not implement the Copy trait
...
38 | let body = res.text().await.unwrap_or_else(|_| "Unable to read response body".to_string());
| ------ res moved due to this method call
39 | bail!("Failed to send event {}: {}\nResponse body: {}", event.event, res.status(), body);
| ^^^ value borrowed here after move
|
note: reqwest::Response::text takes ownership of the receiver self, which moves res
--> /home/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/reqwest-0.11.24/src/async_impl/response.rs:147:23
|
147 | pub async fn text(self) -> crate::Result {
| ^^^^

@morgante morgante merged commit 9184797 into main Sep 18, 2024
9 checks passed
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