Skip to content

Improved Gitlab All in case of many repositories #372

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

abraverm
Copy link

@abraverm abraverm commented Jul 2, 2025

When there are many repositories on Giltab, doing actions in one hit would fail to API timeout.
This is a quick workaround/hack by using batches.

Also when there a lot of repositories, just getting the list of them might be too much.

Ideally, I would like Sourcebot to add a repository as it finds it instead of handling the entire connection sync. Otherwise this process blocks other connections from syncing, and if it fails/breaks, then it has to start over.

Note: prisma also failing when there are too many connections, not sure what is the magical number is (sometimes 1000 resulted with errors too):

Invalid `prisma.userToOrg.findUnique()` invocation: Too many database connections opened: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute Prisma Accelerate has built-in connection pooling to prevent such errors: https:/ / pris. ly/ client/ error-accelerate
( https://pris.ly/client/error-accelerate ) at Vn.handleRequestError
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:7339) at Vn.handleAndLogRequestError
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:6663) at Vn.request
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:6370) at async l
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:130:9617) at async el (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ chunks/ 616. js:1:39994 (
http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/chunks/616.js:1:39994
) ) at async ei (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ chunks/ 616. js:1:38467 ( http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/chunks/616.js:1:38467
) ) at async j (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ app/ [domain]/ page. js:1:4267 ( http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/app/[domain]/page.js:1:4267
) ) { code: 'P2037',
clientVersion: '6.2.1',
meta: {
modelName: 'UserToOrg',
message: 'FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute'
}
}

Summary by CodeRabbit

  • Refactor
    • Improved efficiency and reliability of repository processing by introducing batching for GitLab repository fetches, repository indexing scheduling, and updating repository indexing status.
    • Enhanced logging for better visibility into batch processing progress and outcomes.
  • Bug Fixes
    • Improved error handling for group and user project fetches, ensuring graceful handling of not found errors.
  • Chores
    • Minor code cleanup and improved control flow for repository operations.
  • New Features
    • Added comprehensive NixOS module and deployment configurations for SourceBot, including systemd services, firewall, Redis, and PostgreSQL integration.
    • Introduced Nix flake configurations, overlays, and microVM environment setup to streamline development and deployment.
    • Added detailed deployment guide section for NixOS with flakes.
    • Included automated NixOS test to verify SourceBot service startup and responsiveness.

Copy link

coderabbitai bot commented Jul 2, 2025

Walkthrough

The changes introduce batching to various operations that previously processed large arrays all at once. GitLab repository fetching, scheduling of repository indexing, and database updates for repository indexing status are now performed in sequential or chunked batches. These modifications affect internal control flow but do not alter any exported function or class signatures. Additionally, new NixOS deployment configurations, modules, overlays, and tests for SourceBot are added, along with documentation updates and a new JSON file listing package hashes.

Changes

File(s) Change Summary
packages/backend/src/gitlab.ts Refactored repository fetching to process groups and users in sequential batches of 10; replaced direct all-projects fetch with separate group/user enumeration; added debug logging and adjusted error handling.
packages/backend/src/repoManager.ts Modified scheduling of repo indexing to process repositories in batches of 100 instead of all at once.
packages/web/src/actions.ts Updated flagReposForIndex to batch update repo indexing status in chunks of 1000 IDs per call.
packages/web/src/initialize.ts Changed retry logic for failed indexing to batch updates in chunks of 100 IDs per call.
docs/docs/deployment-guide.mdx Added "NixOS deployment" section with instructions for deploying SourceBot using flakes; reorganized headings and added "Container deployment" section.
flake.nix Added new Nix flake configuration defining NixOS modules, packages, devShells, and tests for SourceBot.
nix/microvm.nix Added microVM Nix configuration with network, port forwarding, volumes, services, and SourceBot setup.
nix/missing-hashes.json Added JSON manifest mapping package identifiers to cryptographic hashes for npm packages.
nix/nixosModule.nix Added comprehensive NixOS module for SourceBot service with system user, firewall, Redis, PostgreSQL, and systemd services.
nix/nixosTest.nix Added NixOS test for SourceBot module verifying service startup and HTTP accessibility.
nix/overlay.nix Added Nix overlay defining sourcebot package and overriding zoekt package with updated source and hash.
nix/sourcebot.nix Added Nix derivation for building and installing SourceBot with build steps, environment setup, and wrapper scripts.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant GitLabManager
    participant GitLabAPI

    Caller->>GitLabManager: getGitLabReposFromConfig(config)
    GitLabManager->>GitLabAPI: fetch all groups (batched, size=10)
    GitLabManager->>GitLabAPI: fetch all users (batched, size=10)
    loop For each group batch
        GitLabManager->>GitLabAPI: fetch group projects (batch)
    end
    loop For each user batch
        GitLabManager->>GitLabAPI: fetch user projects (batch)
    end
    GitLabManager-->>Caller: return repositories
Loading
sequenceDiagram
    participant RepoManager
    participant Scheduler

    RepoManager->>RepoManager: fetchAndScheduleRepoIndexing(repos)
    loop For each batch of 100 repos
        RepoManager->>Scheduler: scheduleRepoIndexingBulk(batch)
    end
Loading
sequenceDiagram
    participant Action
    participant Prisma

    Action->>Action: flagReposForIndex(repoIds)
    loop For each batch of 1000 IDs
        Action->>Prisma: updateMany(batch, status=NEW)
    end
Loading
sequenceDiagram
    participant Initializer
    participant Prisma

    Initializer->>Initializer: syncConnections()
    loop For each batch of 100 failed repo IDs
        Initializer->>Prisma: updateMany(batch, status=NEW)
    end
Loading

Suggested reviewers

  • msukkari

Poem

In batches now, the work proceeds,
Ten by ten, or hundred seeds.
Repos fetched and status set,
No more giant calls to fret!
Rabbits cheer with nimble hops,
As chunked requests avoid the stops.
🐇✨ Batch by batch, the progress leads!

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

Copy link

@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

🧹 Nitpick comments (5)
packages/web/src/actions.ts (1)

923-933: Good implementation of batching to prevent timeouts.

The sequential batching approach effectively addresses the API timeout issues mentioned in the PR objectives. The chunk size of 1000 is reasonable for database operations.

Consider adding error handling to ensure partial failures don't leave the system in an inconsistent state:

 for (let i = 0; i < repoIds.length; i += 1000) {
+    try {
         await prisma.repo.updateMany({
             where: {
                 id: { in: repoIds.slice(i, i + 1000) },
                 orgId: org.id,
             },
             data: {
                 repoIndexingStatus: RepoIndexingStatus.NEW,
             }
         });
+    } catch (error) {
+        logger.error(`Failed to update batch ${i / 1000 + 1}: ${error}`);
+        throw error; // Re-throw to maintain existing error handling behavior
+    }
 }
packages/web/src/initialize.ts (1)

70-81: Effective batching implementation for retry operations.

The batching approach prevents timeouts when retrying failed repositories. The smaller batch size of 100 (compared to 1000 in actions.ts) is appropriate for retry operations which may be more resource-intensive.

Consider adding error handling similar to the suggestion for actions.ts to ensure robustness during batch processing.

packages/backend/src/gitlab.ts (3)

10-10: Remove unused import.

The log import from "console" is not used anywhere in the code.

-import { log } from "console";

81-81: Consider making batch size configurable.

The hardcoded batch size of 10 may not be optimal for all GitLab instances. Consider making this configurable or using different batch sizes based on the instance capabilities.

-        const batchSize = 10;
+        const batchSize = config.batchSize || 10;

Also applies to: 130-130


85-120: Sequential batching may impact performance.

While sequential processing prevents API overloading, it could significantly slow down the operation. Consider processing a few batches concurrently (e.g., 2-3 batches) to balance performance and API limits.

-        // Process groups in batches of 10
-        for (let i = 0; i < config.groups.length; i += batchSize) {
-            const batch = config.groups.slice(i, i + batchSize);
-            logger.debug(`Processing batch ${i/batchSize + 1} of ${Math.ceil(config.groups.length/batchSize)} (${batch.length} groups)`);
-            
-            const batchResults = await Promise.allSettled(batch.map(async (group) => {
+        // Process groups in batches of 10 with limited concurrency
+        const maxConcurrentBatches = 2;
+        const batches = [];
+        for (let i = 0; i < config.groups.length; i += batchSize) {
+            batches.push(config.groups.slice(i, i + batchSize));
+        }
+        
+        for (let i = 0; i < batches.length; i += maxConcurrentBatches) {
+            const concurrentBatches = batches.slice(i, i + maxConcurrentBatches);
+            const batchPromises = concurrentBatches.map(async (batch, index) => {
+                logger.debug(`Processing batch ${i + index + 1} of ${batches.length} (${batch.length} groups)`);
+                return Promise.allSettled(batch.map(async (group) => {

Also applies to: 134-169

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8060ade and d90332d.

📒 Files selected for processing (4)
  • packages/backend/src/gitlab.ts (3 hunks)
  • packages/backend/src/repoManager.ts (1 hunks)
  • packages/web/src/actions.ts (2 hunks)
  • packages/web/src/initialize.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/backend/src/gitlab.ts (1)
packages/backend/src/utils.ts (2)
  • measure (9-17)
  • fetchWithRetry (92-119)
🔇 Additional comments (3)
packages/backend/src/repoManager.ts (1)

168-170: Excellent batching strategy for repository scheduling.

This implementation effectively addresses the core issue described in the PR objectives by preventing overwhelming the system when scheduling large numbers of repositories for indexing. The batch size of 100 aligns well with the database operation limits and job queue constraints.

The sequential processing approach is particularly important here as it prevents:

  • API timeouts from GitLab
  • Database connection exhaustion
  • Job queue overload
packages/backend/src/gitlab.ts (2)

49-78: Excellent implementation of the all-groups/all-users feature.

The logic properly handles the GitLab cloud restriction, uses retry mechanisms, and includes comprehensive error handling and logging. The approach of fetching all groups and users first, then processing them with the existing batched logic is well-designed.


89-118: Good error handling and logging implementation.

The error handling properly distinguishes between 404 (not found) and other errors, and the detailed logging will be helpful for debugging issues with large repository sets. The use of measure utility provides valuable performance insights.

Also applies to: 138-166

});
logger.debug(`Found ${_groups.length} groups in ${groupsDuration}ms.`);

config.groups = _groups.map(g => g.full_path);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid mutating input parameters.

Modifying the config object directly creates unexpected side effects for callers. Consider storing the discovered groups and users in local variables instead.

-                config.groups = _groups.map(g => g.full_path);
+                const discoveredGroups = _groups.map(g => g.full_path);
+                config = { ...config, groups: discoveredGroups };
-                config.users = _users.map(u => u.username);
+                const discoveredUsers = _users.map(u => u.username);
+                config = { ...config, users: discoveredUsers };

Also applies to: 69-69

🤖 Prompt for AI Agents
In packages/backend/src/gitlab.ts at lines 57 and 69, avoid directly mutating
the input parameter `config` by assigning to its properties. Instead, create
local variables to hold the groups and users data derived from `_groups` and
other sources, and use these local variables within the function. This prevents
side effects on the caller's `config` object and maintains functional purity.

msukkari
msukkari previously approved these changes Jul 3, 2025
allRepos = allRepos.concat(validRepos);
notFound.orgs = notFoundOrgs;
logger.debug(`Found ${validRepos.length} valid repositories in groups.`);
logger.debug(`Not found groups: ${notFoundOrgs.join(', ')}`);
logger.debug(`These repositories will be downloaded: ${allRepos.map(repo => repo.path_with_namespace).join('\n')}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: synced not downloaded to be consistent with language elsewhere

@msukkari
Copy link
Contributor

msukkari commented Jul 3, 2025

Thanks for the change! I assume you've already tested this with larger configs? Would love to know if you've noticed a difference

@abraverm
Copy link
Author

abraverm commented Jul 8, 2025

The change is necessary for the sync to work at all, otherwise it fails on timeout. I don't think you should merge the code as is or continue with the batch direction. I think this part should be refactored so every batch of found repository would be processed (filterd/checked) and added to the database and to the sync pipeline. Because when you have a lot of repositories, this step takes a very long time (10 minutes?) and if something fails it might need to start again. It would be nice to see a stream of repositories being detected and processed. Also "100" batch is right for me but maybe not for another instance, another configuration like that is possible but magic numbers are annoying.

abraverm added 2 commits July 10, 2025 08:30
Package Sourcebot with Nix, NixOS module for deployment, integration
test and microvm.
Copy link

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d90332d and ea8e67c.

⛔ Files ignored due to path filters (1)
  • flake.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • docs/docs/deployment-guide.mdx (3 hunks)
  • flake.nix (1 hunks)
  • nix/microvm.nix (1 hunks)
  • nix/missing-hashes.json (1 hunks)
  • nix/nixosModule.nix (1 hunks)
  • nix/nixosTest.nix (1 hunks)
  • nix/overlay.nix (1 hunks)
  • nix/sourcebot.nix (1 hunks)
  • packages/backend/src/gitlab.ts (3 hunks)
  • packages/backend/src/repoManager.ts (1 hunks)
  • packages/web/src/actions.ts (2 hunks)
  • packages/web/src/initialize.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • nix/missing-hashes.json
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/web/src/initialize.ts
  • packages/backend/src/repoManager.ts
  • packages/web/src/actions.ts
  • packages/backend/src/gitlab.ts
🧰 Additional context used
🪛 Gitleaks (8.26.0)
nix/overlay.nix

8-8: Sourcegraph is a code search and navigation engine.

(sourcegraph-access-token)

🔇 Additional comments (7)
docs/docs/deployment-guide.mdx (3)

7-8: Good structural improvement.

Adding the "Container deployment" section improves the documentation hierarchy and makes it clearer that the existing content is about container-based deployment.


12-12: Consistent heading structure.

The demotion of "Walkthrough video" and "Step-by-step guide" to level 3 headings maintains proper hierarchical structure under the new "Container deployment" section.

Also applies to: 26-26


101-208: Comprehensive NixOS deployment documentation.

The new NixOS deployment section provides thorough instructions covering flake setup, secret management with both sops-nix and agenix, and service configuration. The examples are well-structured and include proper configuration options.

nix/overlay.nix (1)

1-12: Well-structured Nix overlay.

The overlay correctly adds the sourcebot package and overrides the zoekt package with a specific revision. The structure follows Nix conventions properly.

nix/nixosTest.nix (1)

1-31: Comprehensive NixOS test implementation.

The test properly validates the sourcebot module by checking all critical systemd services and HTTP connectivity. The test structure follows NixOS testing conventions correctly.

nix/microvm.nix (1)

45-62: Good microVM service configuration.

The sourcebot service configuration is well-structured with appropriate debug logging and a proper JSON configuration for testing.

flake.nix (1)

1-72: Comprehensive and well-structured Nix flake.

The flake configuration properly defines all necessary outputs including NixOS modules, system configurations, packages, checks, and development shells. The structure follows Nix flake conventions and uses flake-utils appropriately for system-specific outputs.

{
mountPoint = "/var";
image = "sourcebot-var.img";
size = 1 * 1024; # 10GB
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent size calculation and comment.

The comment says "10GB" but the calculation 1 * 1024 results in 1GB, not 10GB.

-        size = 1 * 1024; # 10GB
+        size = 10 * 1024; # 10GB
📝 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
size = 1 * 1024; # 10GB
size = 10 * 1024; # 10GB
🤖 Prompt for AI Agents
In nix/microvm.nix at line 33, the size calculation is inconsistent with the
comment; it currently calculates 1GB (1 * 1024) but the comment says 10GB.
Update the calculation to correctly represent 10GB by multiplying 10 * 1024
instead of 1 * 1024, ensuring the comment and value match.

interfaces = [
{
type = "user";
id = "sourecbot";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in interface ID.

The interface ID has a typo: "sourecbot" should be "sourcebot".

-        id = "sourecbot";
+        id = "sourcebot";
📝 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
id = "sourecbot";
id = "sourcebot";
🤖 Prompt for AI Agents
In nix/microvm.nix at line 10, correct the typo in the interface ID by changing
"sourecbot" to "sourcebot" to ensure the identifier is accurate.


mkdir -p $out/bin

rm -rf $out/pacakages/web/.next/cache
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in directory path

There's a typo in the path: pacakages should be packages.

-rm -rf $out/pacakages/web/.next/cache
+rm -rf $out/packages/web/.next/cache
📝 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
rm -rf $out/pacakages/web/.next/cache
rm -rf $out/packages/web/.next/cache
🤖 Prompt for AI Agents
In nix/sourcebot.nix at line 69, fix the typo in the directory path by changing
"pacakages" to "packages" in the rm command to correctly reference the path
$out/packages/web/.next/cache.

runHook preInstall

cp -r packages/web/.next/standalone $out
cp -r node_modules/* $out/node_modules
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify multiple node_modules copies

The node_modules directory is copied multiple times which might cause files to be overwritten. Please verify if this is intentional or if it could be optimized to avoid redundant copies.

Also applies to: 57-57, 65-65


🏁 Script executed:

#!/bin/bash
# Description: Check if there are unique dependencies in each package's node_modules that justify multiple copies

# Look for package.json files to understand the package structure
fd -t f "package.json" packages/

# Check if packages have their own node_modules directories
fd -t d "node_modules" packages/ -d 2

Length of output: 322


Review unnecessary node_modules duplication

It looks like there are no nested node_modules directories under packages/, so each of the three

cp -r node_modules/* $out/node_modules

steps (lines 49, 57 and 65 in nix/sourcebot.nix) is copying the exact same set of dependencies into every output. This not only duplicates files but also makes your derivations larger than necessary.

Consider one of the following optimizations:

  • Consolidate into a single top-level copy of node_modules (e.g. run the cp once before iterating over packages).
  • Split out per-package dependency sets (e.g. prune node_modules to only include each package’s deps).

Files to update:

  • nix/sourcebot.nix (lines 49, 57, 65)
🤖 Prompt for AI Agents
In nix/sourcebot.nix around lines 49, 57, and 65, the cp commands redundantly
copy the entire node_modules directory into each package output, causing
unnecessary duplication and larger derivations. To fix this, refactor the script
to copy node_modules only once at a higher level before processing individual
packages, or alternatively prune node_modules per package to include only its
specific dependencies, thereby avoiding repeated full copies and reducing output
size.

Comment on lines +190 to +193
++ optional (cfg.envFile == null) [
"AUTH_SECRET=00000000000000000000000000000000000000000000"
"SOURCEBOT_ENCRYPTION_KEY=00000000000000000000000000000000"
];
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Security concern: Hardcoded secrets with all zeros

The default AUTH_SECRET and SOURCEBOT_ENCRYPTION_KEY values are hardcoded to all zeros when no environment file is provided. This is insecure and should never be used in production.

Consider one of these approaches:

  1. Generate random secrets during service initialization
  2. Make the environment file mandatory when auth is enabled
  3. Add assertions to prevent the service from starting with default secrets

Example implementation for option 2:

assertions = [
  {
    assertion = !cfg.authEnabled || cfg.envFile != null;
    message = "services.sourcebot.envFile must be set when authEnabled is true";
  }
];

Also applies to: 223-226

🤖 Prompt for AI Agents
In nix/nixosModule.nix around lines 190 to 193 and also lines 223 to 226, the
default AUTH_SECRET and SOURCEBOT_ENCRYPTION_KEY are hardcoded to insecure
all-zero values when no environment file is provided. To fix this, either
generate random secrets during service initialization, make the environment file
mandatory when authentication is enabled by adding an assertion that requires
cfg.envFile to be set if cfg.authEnabled is true, or add assertions to prevent
the service from starting with these default secrets. Implement the assertion
approach by adding a check that throws an error if auth is enabled but envFile
is not provided.

Comment on lines +71 to +72
default = "http://${cfg.hostname}:${toString cfg.port}";
description = "Hostname or IP address for the SourceBot web server to bind to";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect option description

The description for authUrl is incorrect - it appears to be copy-pasted from the hostname option.

-      description = "Hostname or IP address for the SourceBot web server to bind to";
+      description = "Authentication URL for SourceBot";
🤖 Prompt for AI Agents
In nix/nixosModule.nix around lines 71 to 72, the description for the `authUrl`
option is incorrect and mistakenly copied from the `hostname` option. Update the
description to accurately reflect the purpose of the `authUrl` option,
describing it as the URL used for authentication or the endpoint related to
auth, rather than the hostname or IP address for the web server.

openFirewall = mkOption {
type = types.bool;
default = true;
description = "Open Firwall ports for SourceBot";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in option description

-      description = "Open Firwall ports for SourceBot";
+      description = "Open Firewall ports for SourceBot";
📝 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
description = "Open Firwall ports for SourceBot";
description = "Open Firewall ports for SourceBot";
🤖 Prompt for AI Agents
In nix/nixosModule.nix at line 52, there is a typo in the option description
"Open Firwall ports for SourceBot". Correct the typo by changing "Firwall" to
"Firewall" to accurately describe the option.

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