Skip to content

Conversation

@ItzNotABug
Copy link
Member

@ItzNotABug ItzNotABug commented Jul 19, 2025

This PR does the following in order to optimize the reports fetching from Appwrite source -

  1. Use appropriate queries to get only the data we want - Query.limit(1) when we just need the total.
  2. Use pagination in order to not miss any data counts for reports because by default there's info about 25 only.
  3. Use data from top level if the inner level needs some info which can already be available at the parent level. Example - Vars from functions, or attributes, indexes from collections, etc.

Benchmark Datasets

Dataset Users Databases Tables Rows Columns Functions Deployments
Prodn Small Dataset 625 1 1 46 2 1 1
Local Large Dataset 7,000+ 10 250 62,492 1,250 1 1

Benchmark Results

image

Summary by CodeRabbit

  • Refactor
    • Improved efficiency and consistency of resource counting by introducing consistent pagination and reducing redundant API calls when fetching users, teams, memberships, storage buckets, files, functions, and related data.
    • Optimized table, column, and index counting by utilizing paginated fetches and direct data access, minimizing unnecessary API requests.
  • Bug Fixes
    • Prevented potential errors when accessing deployment IDs in function exports by adding a safe fallback.

@ItzNotABug ItzNotABug self-assigned this Jul 19, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 19, 2025

Walkthrough

The changes refactor internal methods for resource counting and reporting in Appwrite migration and API reader classes. Pagination is standardized with a fixed page limit and cursor-based approach, and redundant API calls are reduced by leveraging batch responses. Resource counts are now computed more efficiently and accurately using data already present in API responses.

Changes

File(s) Change Summary
src/Migration/Sources/Appwrite.php Refactored private methods (reportAuth, reportStorage, reportFunctions, exportFunctions) to use consistent pagination, reduce redundant API calls, and improve resource counting logic.
src/Migration/Sources/Appwrite/Reader/API.php Updated table (collection) fetching to use paginated, cursor-based loops; now counts columns and indexes directly from fetched table data instead of separate API calls.

Poem

In the warren of code, we hop with delight,
Chasing paginated carrots through the night.
Fewer calls, more counts, the data flows free,
A hop, a skip, in efficiency!
With paws on the keys and a twitch of the nose,
This rabbit refactors—see how it grows!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@ItzNotABug ItzNotABug requested a review from abnegate July 19, 2025 08:23
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: 3

🔭 Outside diff range comments (1)
src/Migration/Sources/Appwrite.php (1)

286-334: Fix query construction in nested pagination loops

The bucket and file pagination loops have the same query construction issue where limit is missing when using cursorAfter.

Apply these diffs:

For bucket pagination:

                 $currentBuckets = $this->storage->listBuckets(
                     $lastBucket
-                        ? [Query::cursorAfter($lastBucket)]
-                        : [Query::limit($pageLimit)]
+                        ? [Query::limit($pageLimit), Query::cursorAfter($lastBucket)]
+                        : [Query::limit($pageLimit)]
                 )['buckets'];

For file pagination:

                     $files = $this->storage->listFiles(
                         $bucket['$id'],
                         $lastFile
-                            ? [Query::cursorAfter($lastFile)]
-                            : [Query::limit($pageLimit)]
+                            ? [Query::limit($pageLimit), Query::cursorAfter($lastFile)]
+                            : [Query::limit($pageLimit)]
                     )['files'];
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 973a4da and 817d477.

📒 Files selected for processing (2)
  • src/Migration/Sources/Appwrite.php (5 hunks)
  • src/Migration/Sources/Appwrite/Reader/API.php (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite/Reader/API.php:8-8
Timestamp: 2025-06-28T09:47:11.436Z
Learning: In the Appwrite migration codebase, commented-out Tables service references (import statements and constructor parameters) are intentionally kept for future implementation when the Tables service becomes available in the Appwrite SDK, rather than being dead code that should be removed.
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Supabase.php:300-308
Timestamp: 2025-06-28T09:47:58.757Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the user ItzNotABug prefers to keep the existing query logic unchanged even if it becomes semantically incorrect with the new naming. The focus is purely on resource type renaming, not on fixing logical issues that become apparent after the terminology change.
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite.php:843-851
Timestamp: 2025-06-28T09:47:08.333Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the class constructors and method parameters use the new terminology (like "relatedTable"), but the underlying data structures and API responses still use the legacy keys (like "relatedCollection"). This is an intentional design pattern to allow gradual migration while maintaining compatibility with existing data sources.
src/Migration/Sources/Appwrite/Reader/API.php (4)
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite.php:843-851
Timestamp: 2025-06-28T09:47:08.333Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the class constructors and method parameters use the new terminology (like "relatedTable"), but the underlying data structures and API responses still use the legacy keys (like "relatedCollection"). This is an intentional design pattern to allow gradual migration while maintaining compatibility with existing data sources.
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Supabase.php:300-308
Timestamp: 2025-06-28T09:47:58.757Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the user ItzNotABug prefers to keep the existing query logic unchanged even if it becomes semantically incorrect with the new naming. The focus is purely on resource type renaming, not on fixing logical issues that become apparent after the terminology change.
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite/Reader/API.php:8-8
Timestamp: 2025-06-28T09:47:11.436Z
Learning: In the Appwrite migration codebase, commented-out Tables service references (import statements and constructor parameters) are intentionally kept for future implementation when the Tables service becomes available in the Appwrite SDK, rather than being dead code that should be removed.
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Resources/Database/Columns/Relationship.php:86-89
Timestamp: 2025-06-28T09:45:57.650Z
Learning: In the utopia-php/migration codebase Relationship column class, the `getRelatedTable()` method intentionally returns `$this->options['relatedCollection']` (not `relatedTable`) because the underlying API still uses "collection" terminology, even though the internal codebase has been refactored to use "table" terminology.
🔇 Additional comments (8)
src/Migration/Sources/Appwrite/Reader/API.php (3)

93-96: Efficient column counting implementation

Good optimization! Leveraging the attributes/columns already present in the table response eliminates unnecessary API calls.


98-101: Efficient index counting implementation

Excellent optimization! Using the indexes already available in the table response avoids redundant API calls.


103-113: Optimal row counting given API constraints

Good use of Query::limit(1) to minimize data transfer when only the total count is needed. The comment appropriately acknowledges the performance impact for many tables.

src/Migration/Sources/Appwrite.php (5)

202-216: Smart conditional fetching of teams

Good optimization to only fetch teams when necessary based on the requested resources. The user count fetching correctly uses Query::limit(1).


279-284: Efficient bucket counting

Good optimization using Query::limit(1) to fetch only the total count.


337-354: Excellent optimization for function counting

Great implementation of short-circuit logic when only function count is needed, avoiding unnecessary data fetching.


388-394: Efficient environment variable counting

Excellent optimization using the vars array already present in the function model instead of making separate API calls.


1377-1377: Good defensive programming

Adding null coalescing for deploymentId prevents potential errors when the field is missing.

Comment on lines +64 to 84
$tables = [];
$pageLimit = 25;
$lastTable = null;

while (true) {
/* $currentTables = $this->tables->list(...); */
$currentTables = $this->database->listCollections(
$databaseId,
$lastTable
? [Query::cursorAfter($lastTable)]
: [Query::limit($pageLimit)]
)['collections']; /* ['tables'] */

$tables = array_merge($tables, $currentTables);
$lastTable = $tables[count($tables) - 1]['$id'] ?? null;

if (count($currentTables) < $pageLimit) {
break;
}
}

Copy link
Contributor

@coderabbitai coderabbitai bot Jul 19, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential array access issue and query construction

There are two issues in the pagination implementation:

  1. Line 78 could fail if no tables are returned in the response. You should check if the array is not empty before accessing the last element.
  2. The query construction is incorrect. When using cursorAfter, you still need to include the limit parameter.

Apply this diff to fix both issues:

-                $lastTable = $tables[count($tables) - 1]['$id'] ?? null;
+                $lastTable = !empty($tables) ? $tables[count($tables) - 1]['$id'] : null;
                 $currentTables = $this->database->listCollections(
                     $databaseId,
                     $lastTable
-                        ? [Query::cursorAfter($lastTable)]
-                        : [Query::limit($pageLimit)]
+                        ? [Query::limit($pageLimit), Query::cursorAfter($lastTable)]
+                        : [Query::limit($pageLimit)]
                 )['collections']; /* ['tables'] */
📝 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
$tables = [];
$pageLimit = 25;
$lastTable = null;
while (true) {
/* $currentTables = $this->tables->list(...); */
$currentTables = $this->database->listCollections(
$databaseId,
$lastTable
? [Query::cursorAfter($lastTable)]
: [Query::limit($pageLimit)]
)['collections']; /* ['tables'] */
$tables = array_merge($tables, $currentTables);
$lastTable = $tables[count($tables) - 1]['$id'] ?? null;
if (count($currentTables) < $pageLimit) {
break;
}
}
$tables = [];
$pageLimit = 25;
$lastTable = null;
while (true) {
/* $currentTables = $this->tables->list(...); */
$currentTables = $this->database->listCollections(
$databaseId,
$lastTable
? [Query::limit($pageLimit), Query::cursorAfter($lastTable)]
: [Query::limit($pageLimit)]
)['collections']; /* ['tables'] */
$tables = array_merge($tables, $currentTables);
- $lastTable = $tables[count($tables) - 1]['$id'] ?? null;
+ $lastTable = !empty($tables) ? $tables[count($tables) - 1]['$id'] : null;
if (count($currentTables) < $pageLimit) {
break;
}
}
🤖 Prompt for AI Agents
In src/Migration/Sources/Appwrite/Reader/API.php around lines 64 to 84, fix the
pagination logic by first checking if $currentTables is not empty before
accessing the last element to avoid potential errors. Also, modify the query
construction to always include the limit parameter along with cursorAfter when
$lastTable is set, ensuring correct pagination behavior.

Copy link
Member Author

Choose a reason for hiding this comment

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

its fine because the $pageLimit is 25 which is the same as the default number of records returned by the API as well. We don't need - Query::limit($pageLimit), Query::cursorAfter($lastTable).

Copy link
Contributor

Choose a reason for hiding this comment

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

@ItzNotABug Thank you for the clarification about the API's default behavior with 25 records. You're absolutely right that the query construction is fine as-is since the API defaults to returning 25 records.

However, there's still a potential issue with the array access on line 78. If the first API call returns an empty $currentTables array (which could happen if there are no tables in the database), then $tables would remain empty, but we'd still try to access $tables[count($tables) - 1]['$id'] where count($tables) - 1 would be -1, leading to an undefined index error.

The fix for just the array access issue would be:

$lastTable = !empty($tables) ? $tables[count($tables) - 1]['$id'] : null;

But if you're confident this scenario won't occur in practice or is handled elsewhere, feel free to keep it as-is.


✏️ Learnings added
Learnt from: ItzNotABug
PR: utopia-php/migration#89
File: src/Migration/Sources/Appwrite/Reader/API.php:64-84
Timestamp: 2025-07-19T08:29:22.280Z
Learning: In the Appwrite API, the default page limit for listing collections is 25 records, so when using cursor-based pagination with Query::cursorAfter(), there's no need to explicitly specify Query::limit(25) as the API will default to this limit.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Supabase.php:300-308
Timestamp: 2025-06-28T09:47:58.757Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the user ItzNotABug prefers to keep the existing query logic unchanged even if it becomes semantically incorrect with the new naming. The focus is purely on resource type renaming, not on fixing logical issues that become apparent after the terminology change.

Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite.php:843-851
Timestamp: 2025-06-28T09:47:08.333Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the class constructors and method parameters use the new terminology (like "relatedTable"), but the underlying data structures and API responses still use the legacy keys (like "relatedCollection"). This is an intentional design pattern to allow gradual migration while maintaining compatibility with existing data sources.

Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite/Reader/API.php:8-8
Timestamp: 2025-06-28T09:47:11.436Z
Learning: In the Appwrite migration codebase, commented-out Tables service references (import statements and constructor parameters) are intentionally kept for future implementation when the Tables service becomes available in the Appwrite SDK, rather than being dead code that should be removed.

Copy link
Member Author

Choose a reason for hiding this comment

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

kinda makes sense.
But I wonder how this never led to any issues with similar logic where pagination is used in the codebase 🤔

Changing this here would mean, changing the check everywhere we use pagination. I'll wait for @abnegate's insight on this.

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@abnegate abnegate merged commit 626aa1f into main Jul 21, 2025
4 checks passed
@abnegate abnegate deleted the optimize-appwrite-reports branch July 21, 2025 07:10
@coderabbitai coderabbitai bot mentioned this pull request Jul 23, 2025
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.

3 participants