Skip to content

Conversation

@nikhilsaikethe
Copy link
Contributor

@nikhilsaikethe nikhilsaikethe commented Sep 11, 2024

  1. Some times the pagination partition bug occurred so this PR fixes that part

Summary by CodeRabbit

  • New Features
    • Improved calculation of totals for partition details, enhancing accuracy and performance.
    • Streamlined logic for processing query results, making it clearer and more efficient.
  • Bug Fixes
    • Resolved issues related to total calculations by directly linking them to query results.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 11, 2024

Walkthrough

The pull request introduces modifications to the useLogs function, specifically in how query results and partition totals are processed. The previous method of calculating totals from aggregated results has been removed, with totals now computed directly within a mapping function that iterates over partition details. This change simplifies the logic and enhances the clarity of the code by directly linking total hits to specific partitions based on the current query results.

Changes

File Change Summary
web/src/composables/useLogs.ts Refactored useLogs function to calculate partition totals directly from query results, removing previous aggregation logic and unnecessary variables.

Possibly related PRs

  • fix: Pagination partition fix #4494: This PR also modifies the logic for calculating partition totals within the useLogs function, indicating a direct connection to the main PR's updates on how totals are computed for partitions.

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.
    • @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.

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.

@github-actions github-actions bot added the ☢️ Bug Something isn't working label Sep 11, 2024
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

Outside diff range and nitpick comments (2)
web/src/composables/useLogs.ts (2)

1705-1714: Approved with nitpicks

The code changes look good functionally. A couple of suggestions:

  1. Add a comment explaining the purpose of the setTimeout when handling multiple partitions.
  2. The await inside setTimeout looks unusual. Consider refactoring it or add a comment if this pattern is needed for some reason.

2372-2389: Approved with a minor refactoring suggestion

The code changes look good. One small suggestion:
Consider changing the map to a for...of loop for better performance. Something like:

for (const [index, item] of searchObj.data.queryResults.partitionDetail.partitions.entries()) {
  if (item[0] == currentStartTime && item[1] == currentEndTime) {
    totalHits = res.data.hits.reduce(
      (accumulator, currentValue) => accumulator + Math.max(parseInt(currentValue.zo_sql_num, 10), 0),
      0
    );
    searchObj.data.queryResults.partitionDetail.partitionTotal[index] = totalHits;
    break;
  }
}

This avoids creating a new function on each iteration. But it's a minor nitpick, the current code is fine too.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2296ede and eb3ed73.

Files selected for processing (1)
  • web/src/composables/useLogs.ts (4 hunks)
Additional comments not posted (1)
web/src/composables/useLogs.ts (1)

Line range hint 1376-1389: LGTM!

The code changes are approved.

Tools
Biome

[error] 1373-1373: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

@bjp232004 bjp232004 force-pushed the test_pagination branch 2 times, most recently from 22f2f6a to 9b86cf3 Compare September 11, 2024 14:49
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

Outside diff range and nitpick comments (3)
web/src/composables/useLogs.ts (3)

Line range hint 1-2500: Consider decomposing useLogs into smaller focused functions

The useLogs function is quite large with many responsibilities. Consider breaking it down further into smaller focused functions based on logical areas of responsibility. This will improve readability, maintainability and testability of the code.

For example, you could have separate composable functions like:

  • useSearchState - manages the reactive searchObj and related state
  • useStreamData - handles retrieving and updating stream data
  • useQueryData - responsible for running queries and updating results
  • useHistogramData - handles histogram data generation and updates
  • useURLParams - manages syncing state with URL query params

And so on. The useLogs function can then compose these together.

Recommend adding types for searchObj and other variables/functions

To improve readability and catch potential bugs, consider adding TypeScript types for the key objects like searchObj, searchAggData, fieldValues etc.

You can define interfaces like:

interface SearchObj {
  organizationIdentifier: string;
  runQuery: boolean;
  loading: boolean;
  // ...
}

And use it to type the searchObj:

const searchObj: SearchObj = reactive({
  // ...
});

Also add types for function parameters and return values.

Propose moving SQL parser import logic outside

To declutter the useLogs function, consider moving the SQL parser import logic to a separate composable or service.

For example:

// useSqlParser.ts
import { sqlParser } from "@/composables/useParser";

export default function useSqlParser() {  
  const parser = ref();

  async function initSqlParser() {
    parser.value = await sqlParser();
  }

  return {
    parser,
    initSqlParser,
  }
}

And in useLogs:

import useSqlParser from "./useSqlParser";

export default function useLogs() {
  const { parser, initSqlParser } = useSqlParser();

  onBeforeMount(() => {
    initSqlParser();
    // ...
  });

  // ...
}

This keeps the SQL parser logic separate and makes the code more modular.


Line range hint 1800-2000: Consider decomposing getQueryData into smaller focused functions

The getQueryData function is quite long and has multiple responsibilities. Consider breaking it down into smaller focused functions to improve readability and maintainability.

For example, you could extract the logic for resetting query data, getting partitions, fetching paginated data, updating histogram data, etc into separate functions.

Something like:

async function getQueryData(isPagination = false) {
  try {
    if (!isPagination) {
      resetQueryData();
      await getQueryPartitions(queryReq);
    }

    await fetchPaginatedData(queryReq);
    await updateHistogramData();
    await updateTotalCounts();

    // ...
  }
  // ...
}

This makes the main function more readable and the individual steps more reusable and testable.

Refactor the duplicated partition update logic

There is some duplicated logic for updating the partition totals in the getQueryData function:

for (const [index, item] of searchObj.data.queryResults.partitionDetail.partitions.entries()) {
  if (searchObj.data.queryResults.partitionDetail.partitionTotal[index] == -1 && 
      queryReq.query.start_time == item[0]) {
    searchObj.data.queryResults.partitionDetail.partitionTotal[index] = res.data.total;
  }
}

This block appears multiple times. Consider refactoring it into a separate function for reuse:

function updatePartitionTotals(partitions, totals, startTime, total) {
  for (const [index, item] of partitions.entries()) {
    if (totals[index] == -1 && startTime == item[0]) {
      totals[index] = total;
    }
  }
}

And then use it like:

updatePartitionTotals(
  searchObj.data.queryResults.partitionDetail.partitions,
  searchObj.data.queryResults.partitionDetail.partitionTotal, 
  queryReq.query.start_time,
  res.data.total
);

Improve error handling with more specific messages

The getQueryData function has a generic catch block that logs the error and shows a generic "Something went wrong" notification:

} catch (e: any) {
  searchObj.loading = false;
  showErrorNotification("Error occurred during the search operation.");
  notificationMsg.value = "";
}

Consider providing more specific error messages based on the type of error. For example:

} catch (e: any) {
  searchObj.loading = false;
  
  if (e instanceof QueryPartitionError) {
    showErrorNotification("Error retrieving query partitions: " + e.message);
  } else if (e instanceof PaginationError) {
    showErrorNotification("Error retrieving paginated data: " + e.message);
  } else {
    showErrorNotification("An unexpected error occurred during the search operation");
  }

  notificationMsg.value = "";
}

This will make it easier to diagnose and fix issues.

Tools
Biome

[error] 1373-1373: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)


Line range hint 2900-3000: Add types for variables

Consider adding types for the variables in the generateHistogramData function to improve type safety and readability.

For example:

let num_records: number = 0;
const unparsed_x_data: (string | number)[] = [];
const xData: number[] = [];
const yData: number[] = [];

This makes it clear what type of data each variable holds.

Improve error handling with more specific messages

The generateHistogramData function has a generic catch block that logs the error and shows a generic "Error while generating histogram data" notification:

} catch (e: any) {
  console.log("Error while generating histogram data", e);
  notificationMsg.value = "Error while generating histogram data.";
}

Consider providing more specific error messages based on the type of error. For example:

} catch (e: any) {
  if (e instanceof DataMappingError) {
    console.log("Error mapping histogram data:", e);
    notificationMsg.value = "Error mapping histogram data. Please try again.";
  } else {
    console.log("Unexpected error generating histogram data:", e);
    notificationMsg.value = "An unexpected error occurred while generating the histogram. Please try again.";
  }
}

This will make it easier to diagnose and fix issues.

Tools
Biome

[error] 1373-1373: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 22f2f6a and 9b86cf3.

Files selected for processing (1)
  • web/src/composables/useLogs.ts (4 hunks)

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

Outside diff range and nitpick comments (1)
web/src/composables/useLogs.ts (1)

1710-1714: Asynchronous histogram regeneration looks good, but consider a dynamic delay.

Calling generateHistogramData and refreshPartitionPagination asynchronously after processing the partitions is a good approach to regenerate the histogram. The 100ms delay provides a small buffer for the processing to complete.

However, consider calculating the delay dynamically based on the number of partitions and query complexity. This will ensure the histogram is regenerated after processing is fully complete, even for a large number of partitions or complex queries.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9b86cf3 and a326b7e.

Files selected for processing (1)
  • web/src/composables/useLogs.ts (4 hunks)
Additional comments not posted (2)
web/src/composables/useLogs.ts (2)

2375-2388: LGTM!

The code segment correctly calculates the total hits for the partition that matches the current query's start and end times. It efficiently uses reduce to sum up the parsed zo_sql_num values, ensuring the total is never negative by taking the Math.max with 0.


Line range hint 1743-1752: LGTM!

Fetching the total page count asynchronously using setTimeout with a 0ms delay is a good approach. It ensures the main thread isn't blocked while allowing the page count to be retrieved.

The conditions to trigger the getPageCount call are also appropriate. It's only fetched for the first page of results in non-aggregation queries that returned hits.

Wrapping the call with performance timers is a nice touch for measuring and debugging the performance of this operation.

@bjp232004 bjp232004 merged commit b9df5a3 into main Sep 12, 2024
@bjp232004 bjp232004 deleted the test_pagination branch September 12, 2024 03:52
This was referenced Sep 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

☢️ Bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants