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

Improve resources loading #692

Merged
merged 3 commits into from
Feb 11, 2025
Merged

Improve resources loading #692

merged 3 commits into from
Feb 11, 2025

Conversation

chiragchhatrala
Copy link
Collaborator

@chiragchhatrala chiragchhatrala commented Feb 5, 2025

Summary by CodeRabbit

  • Refactor
    • Improved how form data is loaded by retrieving multiple pages in parallel, resulting in faster, more consistent load times.
    • Streamlined error handling and loading indicators for a smoother, more reliable experience when viewing and submitting forms.

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

The pull request revises the pagination logic in both the form submissions component and the forms store. In the FormSubmissions.vue component, the recursive page-fetching approach has been replaced with a method that fetches the first page and then concurrently retrieves subsequent pages using Promise.all. Similarly, the useFormsStore module now manages concurrent requests via a new promise variable (loadAllRequest) instead of using a currentPage counter. Both files now update the loading state only after all pages have been successfully fetched and feature streamlined error handling.

Changes

Files Change Summary
client/components/.../FormSubmissions.vue Replaced recursive pagination with parallel fetching using Promise.all. Removed the currentPage variable. Loading state is now updated only after all requests complete, and error handling has been simplified.
client/stores/forms.js Removed the currentPage counter and introduced loadAllRequest to track the loading state. Modified the loadAll function to fetch the first page and, if needed, concurrently request additional pages with streamlined error handling.

Sequence Diagram(s)

sequenceDiagram
    participant UI
    participant FormSubmissions
    participant API

    UI->>FormSubmissions: Call getSubmissionsData
    FormSubmissions->>API: Fetch page 1
    API-->>FormSubmissions: Return page 1 data (includes lastPage info)
    alt More pages exist
        FormSubmissions->>API: Concurrently fetch pages 2...lastPage using Promise.all
        API-->>FormSubmissions: Return additional pages data
    end
    FormSubmissions->>UI: Update UI with combined submissions data
Loading
sequenceDiagram
    participant User
    participant FormsStore
    participant API

    User->>FormsStore: Invoke loadAll
    FormsStore->>API: Fetch first page of forms
    API-->>FormsStore: Return first page data (includes total pages)
    alt Additional pages exist
        FormsStore->>API: Concurrently request pages 2...lastPage using Promise.all
        API-->>FormsStore: Return additional pages data
    end
    FormsStore->>User: Update store with all forms data and finish loading
Loading

Poem

I hopped through the code with a curious gaze,
Leaping over loops in parallel arrays,
From recursive trails I did bid adieu,
Promise.all now makes my data dreams come true,
In fields of code I dance with glee—
A bunny’s beat in the tech spree!
🐇✨

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

🧹 Nitpick comments (2)
client/stores/forms.js (1)

12-60: Consider adding request cancellation and timeout handling.

While the parallel fetching implementation is good, there are a few improvements that could enhance reliability:

  1. Request cancellation for cleanup during component unmount
  2. Timeout handling for long-running requests
  3. Rate limiting to prevent overwhelming the server

Here's how you could enhance the implementation:

 const loadAll = (workspaceId) => {
   if (loadAllRequest.value) {
     return loadAllRequest.value
   }
   if (!workspaceId) {
     return
   }
   contentStore.startLoading()
   
+  const controller = new AbortController()
+  const signal = controller.signal
+  const timeout = 30000 // 30 seconds
   
   loadAllRequest.value = new Promise((resolve, reject) => {
-    opnFetch(formsEndpoint.replace('{workspaceId}', workspaceId), { query: { page: 1 } })
+    opnFetch(formsEndpoint.replace('{workspaceId}', workspaceId), { 
+      query: { page: 1 },
+      signal,
+      timeout
+    })
       .then(firstResponse => {
         contentStore.resetState()
         contentStore.save(firstResponse.data)
         
         const lastPage = firstResponse.meta.last_page
         
         if (lastPage > 1) {
           // Create an array of promises for remaining pages
           const remainingPages = Array.from({ length: lastPage - 1 }, (_, i) => {
             const page = i + 2 // Start from page 2
-            return opnFetch(formsEndpoint.replace('{workspaceId}', workspaceId), { query: { page } })
+            return opnFetch(formsEndpoint.replace('{workspaceId}', workspaceId), { 
+              query: { page },
+              signal,
+              timeout
+            })
           })
           
           // Fetch all remaining pages in parallel
           return Promise.all(remainingPages)
         }
         return []
       })
       .then(responses => {
         // Save all responses data
         responses.forEach(response => {
           contentStore.save(response.data)
         })
         
         allLoaded.value = true
         contentStore.stopLoading()
         loadAllRequest.value = null
         resolve()
       })
       .catch(err => {
+        if (err.name === 'AbortError') {
+          console.log('Request was cancelled')
+        } else if (err.name === 'TimeoutError') {
+          console.error('Request timed out')
+        }
         contentStore.stopLoading()
         loadAllRequest.value = null
         reject(err)
       })
   })

+  // Cleanup function
+  const cleanup = () => {
+    controller.abort()
+    loadAllRequest.value = null
+    contentStore.stopLoading()
+  }
+
+  // Add cleanup to the promise
+  loadAllRequest.value.cleanup = cleanup

   return loadAllRequest.value
 }
client/components/open/forms/components/FormSubmissions.vue (1)

287-321: Consider implementing error retry and user feedback.

While the parallel fetching implementation is good, there are opportunities to enhance the user experience:

  1. Error retry mechanism for failed requests
  2. Progress indicator for large datasets
  3. Detailed error feedback

Here's how you could enhance the implementation:

 getSubmissionsData() {
   if (this.fullyLoaded) {
     return
   }
   this.recordStore.startLoading()
+  const maxRetries = 3
+  let progress = 0
+  
+  const fetchWithRetry = (url, retries = 0) => {
+    return opnFetch(url).catch(error => {
+      if (retries < maxRetries) {
+        return new Promise(resolve => setTimeout(resolve, 1000 * (retries + 1)))
+          .then(() => fetchWithRetry(url, retries + 1))
+      }
+      throw error
+    })
+  }
   
-  opnFetch('/open/forms/' + this.form.id + '/submissions?page=1')
+  fetchWithRetry('/open/forms/' + this.form.id + '/submissions?page=1')
     .then((firstResponse) => {
       this.recordStore.save(firstResponse.data.map((record) => record.data))
       
       const lastPage = firstResponse.meta.last_page
+      progress = Math.round((1 / lastPage) * 100)
+      this.$emit('loading-progress', progress)
       
       if (lastPage > 1) {
         // Create an array of promises for remaining pages
         const remainingPages = Array.from({ length: lastPage - 1 }, (_, i) => {
           const page = i + 2 // Start from page 2
-          return opnFetch('/open/forms/' + this.form.id + '/submissions?page=' + page)
+          return fetchWithRetry('/open/forms/' + this.form.id + '/submissions?page=' + page)
+            .then(response => {
+              progress = Math.round(((i + 2) / lastPage) * 100)
+              this.$emit('loading-progress', progress)
+              return response
+            })
         })
         
         // Fetch all remaining pages in parallel
         return Promise.all(remainingPages)
       }
       return []
     }).then(responses => {
       // Save all responses data
       responses.forEach(response => {
         this.recordStore.save(response.data.map((record) => record.data))
       })
       
       this.fullyLoaded = true
       this.recordStore.stopLoading()
       this.dataChanged()
-    }).catch(() => {
+    }).catch((error) => {
+      console.error('Failed to fetch submissions:', error)
+      this.$emit('fetch-error', error.message || 'Failed to load submissions')
       this.recordStore.stopLoading()
     })
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 29640fc and 52772b0.

📒 Files selected for processing (2)
  • client/components/open/forms/components/FormSubmissions.vue (1 hunks)
  • client/stores/forms.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build the Nuxt app
🔇 Additional comments (1)
client/stores/forms.js (1)

10-10: LGTM! Good practice using ref for tracking request state.

The loadAllRequest ref is well-suited for managing asynchronous state in Vue/Pinia stores.

@JhumanJ JhumanJ merged commit 1f9a1f8 into main Feb 11, 2025
7 checks passed
@JhumanJ JhumanJ deleted the 17ca6-improve-resources-loading branch February 11, 2025 16:14
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.

2 participants