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(core): adding coolify.json for predefined configuration #5123

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

Conversation

andrasbacsai
Copy link
Member

No description provided.

@andrasbacsai
Copy link
Member Author

@coderabbitai review

Copy link

coderabbitai bot commented Feb 12, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Introduced dynamic repository configuration forms with conditional input fields and a built-in configuration editor for advanced setups.
    • Enabled a functional “Download Config” button and quick example configuration selections in configuration views.
  • Bug Fixes
    • Enhanced deployment reliability by ensuring essential credentials are securely processed.
  • Refactor
    • Streamlined configuration management with improved validations and atomic updates.
  • Chores
    • Updated system version numbers for enhanced stability and compatibility.

Walkthrough

The update removes the deprecated MagicController and its routes, adds a step in deployment to store the server’s private key, and enhances repository management with Coolify configuration support. Significant changes include updates in Livewire components for Git repositories, modifications in model methods to handle configuration and transactions, revisions in helper functions and configuration generation, introduction of a new JSON schema for Coolify, and adjustments in versioning and UI elements in Blade views. Minor database seeder modifications are also included.

Changes

File(s) Change Summary
app/Http/Controllers/MagicController.php, routes/web.php Removed deprecated MagicController and its associated "magic" routes.
app/Jobs/ApplicationDeploymentJob.php Added a step to store the server’s private key in the filesystem before continuing the deployment process.
app/Livewire/Project/New/{GithubPrivateRepository.php, PublicGitRepository.php} Introduced properties (coolify_config, use_coolify_config) and a new private method getCoolifyConfig(). Methods such as updatedBaseDirectory() and form submission flows were updated to conditionally process Coolify configuration.
app/Livewire/Project/Shared/UploadConfig.php Added new properties for project, environment, and destination UUIDs while removing the $applicationId property; updated configuration generation and error handling.
app/Models/{Application.php, GithubApp.php, LocalPersistentVolume.php, Server.php} Refactored Application::setConfig to use DB transactions and update related entities; added GithubApp::getCoolifyConfig (with Carbon import); enhanced LocalPersistentVolume with a boot method and dynamic relationship; removed Server::destinationsByServer method.
app/Services/ConfigurationGenerator.php Restructured config generation with new groupings and keys; added methods cleanupNullEmptyValues(), getTags(), getScheduledTasks(), and getPersistentStorages().
bootstrap/helpers/applications.php Added a new configValidator() function for JSON configuration data validation.
config/constants.php, versions.json Updated Coolify version numbers.
coolify.schema.json Introduced a new JSON schema defining the configuration structure and validation rules for Coolify.
database/seeders/ApplicationSeeder.php Removed the repository_project_id field from one of the seeded application entries.
resources/views/livewire/project/{application/general.blade.php, new/github-private-repository.blade.php, new/public-git-repository.blade.php, new/select.blade.php, shared/upload-config.blade.php} Modified Blade templates to adjust UI elements and conditional rendering, including toggling Coolify config inputs and replacing modal components with example configuration buttons.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Component as Livewire Component (Repo Form)
    participant AppModel as Application Model
    participant DB as Database
    participant GithubAPI as GitHub API (via GithubApp)

    User->>Component: Fill form & select options
    Component->>Component: Trigger getCoolifyConfig() on update
    alt Coolify config enabled
        Component->>AppModel: Submit form with Coolify configuration
    else
        Component->>AppModel: Submit form using default settings
    end
    AppModel->>DB: Begin transaction & save configuration data
Loading
sequenceDiagram
    participant Job as ApplicationDeploymentJob
    participant Server as Server Instance

    Job->>Server: Verify server functionality
    Job->>Server: Execute privateKey->storeInFileSystem()
    Job->>Job: Continue deployment with updated configuration
Loading

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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

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

🧹 Nitpick comments (16)
app/Jobs/ApplicationDeploymentJob.php (2)

315-321: Consider catching Throwable instead of Exception.

The catch block only handles Exception, which might miss PHP errors and fatal errors. Consider using Throwable for more comprehensive error handling.

-        } catch (Exception $e) {
+        } catch (Throwable $e) {

2436-2459: Enhance error logging in the failed method.

Consider enhancing error logging to include stack traces for better debugging capabilities. This would help in troubleshooting deployment failures more effectively.

     public function failed(Throwable $exception): void
     {
         $this->next(ApplicationDeploymentStatus::FAILED->value);
         $this->application_deployment_queue->addLogEntry('Oops something is not okay, are you okay? 😢', 'stderr');
         if (str($exception->getMessage())->isNotEmpty()) {
             $this->application_deployment_queue->addLogEntry($exception->getMessage(), 'stderr');
+            $this->application_deployment_queue->addLogEntry($exception->getTraceAsString(), 'stderr');
         }
app/Livewire/Project/Shared/UploadConfig.php (2)

33-153: Consider externalizing large JSON blocks for better maintainability.

The multi-case switch includes large hardcoded JSON strings. Storing these configurations in separate template files—or using a dedicated helper—can simplify updates and reduce the risk of errors.


164-170: Handle multiple-server scenarios more gracefully.

Currently, if more than one server is owned by the current team, the code raises an exception instead of letting the user select the intended server. Consider providing a clearer fallback or user prompt for multi-server environments.

app/Livewire/Project/New/GithubPrivateRepository.php (1)

204-259: Consider wrapping the non-Coolify application creation path in a transaction for consistency.

The Coolify-based code path uses transactions and rolls back on failure, but the fallback code path creates and saves an application without a transaction. If partial failures occur, the resulting data might remain in an inconsistent state.

app/Livewire/Project/New/PublicGitRepository.php (3)

109-109: Potential repeated config fetch
Calling getCoolifyConfig() whenever the base directory updates might trigger unnecessary fetches in some edge cases. Consider caching or debouncing calls if performance becomes an issue.


242-249: Robust error handling for config fetch
Wrapping getCoolifyConfig() in a try/catch is good. Consider logging or showing user-friendly alerts in case of missing or invalid config to improve debugging.


270-324: Handling coolify config within submit()
This block decodes, validates, and applies $this->coolify_config under a transaction, which is comprehensive. For maintainability:

  • Extract the code for processing $config into a dedicated method to reduce submit() complexity.
  • Confirm configValidator() gracefully handles all invalid or partial schemas.
  • If multiple users may update simultaneously, watch for potential concurrency conflicts.
app/Models/LocalPersistentVolume.php (1)

12-22: Enhance name generation robustness.

The name generation logic could be improved to handle edge cases and ensure uniqueness.

Consider this enhanced implementation:

 public static function boot()
 {
     parent::boot();

     static::creating(function ($model) {
         if (blank($model->name)) {
-            $name = $model->resource->uuid.str_replace('/', '-', $model->mount_path);
+            $name = str($model->resource->uuid)
+                ->append('-')
+                ->append(str($model->mount_path)->trim('/')->slug('-'))
+                ->limit(255)
+                ->toString();
             $model->name = $name;
         }
     });
 }
resources/views/livewire/project/new/public-git-repository.blade.php (1)

83-84: Add validation feedback for coolify.json editor.

The Monaco editor for coolify.json should provide immediate feedback about JSON validity to prevent submission of invalid configurations.

Add validation attributes to the textarea:

-<x-forms.textarea id="coolify_config" wire:model="coolify_config"
-    monacoEditorLanguage="json" useMonacoEditor />
+<x-forms.textarea id="coolify_config" wire:model="coolify_config"
+    monacoEditorLanguage="json" useMonacoEditor
+    wire:model.live.debounce.500ms="coolify_config"
+    x-on:change="validateJson($event.target.value)"
+    :class="{'border-red-500': !isValidJson}" />
+<div x-show="!isValidJson" class="text-red-500 text-sm mt-1">
+    Invalid JSON format
+</div>
bootstrap/helpers/applications.php (2)

136-191: Consider using translation keys for error messages.

The error messages are hardcoded strings. Consider moving them to language files for better internationalization support.

-    $messages = [
-        'config.coolify.project_uuid.required' => 'Project UUID is required (coolify.project_uuid) in the coolify configuration.',
+    $messages = [
+        'config.coolify.project_uuid.required' => __('validation.coolify.project_uuid_required'),

193-340: Consider splitting validation rules into smaller chunks.

The validation rules are quite extensive. Consider splitting them into smaller, more manageable chunks by category (e.g., build, network, health check) to improve maintainability.

-    $deepValidator = Validator::make(['config' => $config], [
+    $buildRules = [
+        'config.build' => 'required|array',
+        // ... build related rules
+    ];
+    $networkRules = [
+        'config.network' => 'array',
+        // ... network related rules
+    ];
+    $deepValidator = Validator::make(['config' => $config], array_merge(
+        $buildRules,
+        $networkRules,
+        // ... other rule sets
+    ), $messages);
coolify.schema.json (4)

1-7: Consider using a more recent JSON Schema version.

The schema uses draft-07, but newer versions (2019-09, 2020-12) offer additional features and improvements.

-    "$schema": "http://json-schema.org/draft-07/schema#",
+    "$schema": "https://json-schema.org/draft/2020-12/schema",

8-121: Add descriptions for better documentation.

Consider adding descriptions to properties to improve schema documentation.

     "properties": {
         "name": {
-            "type": "string"
+            "type": "string",
+            "description": "The name of the application"
         },

128-135: Enhance domain validation pattern.

The current pattern only checks for http/https prefix. Consider adding more comprehensive domain validation.

-                            "pattern": "^(http://|https://).+",
+                            "pattern": "^(http://|https://)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])(/.*)?$",

244-305: Add format validation for environment variables.

Consider adding format validation for common environment variable patterns.

                             "key": {
-                                "type": "string"
+                                "type": "string",
+                                "pattern": "^[A-Z][A-Z0-9_]*$",
+                                "description": "Environment variable name in uppercase with underscores"
                             },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 592dd76 and 8101efc.

📒 Files selected for processing (21)
  • app/Http/Controllers/MagicController.php (0 hunks)
  • app/Jobs/ApplicationDeploymentJob.php (1 hunks)
  • app/Livewire/Project/New/GithubPrivateRepository.php (7 hunks)
  • app/Livewire/Project/New/PublicGitRepository.php (8 hunks)
  • app/Livewire/Project/Shared/UploadConfig.php (1 hunks)
  • app/Models/Application.php (1 hunks)
  • app/Models/GithubApp.php (2 hunks)
  • app/Models/LocalPersistentVolume.php (1 hunks)
  • app/Models/Server.php (0 hunks)
  • app/Services/ConfigurationGenerator.php (4 hunks)
  • bootstrap/helpers/applications.php (2 hunks)
  • config/constants.php (1 hunks)
  • coolify.schema.json (1 hunks)
  • database/seeders/ApplicationSeeder.php (0 hunks)
  • resources/views/livewire/project/application/general.blade.php (1 hunks)
  • resources/views/livewire/project/new/github-private-repository.blade.php (1 hunks)
  • resources/views/livewire/project/new/public-git-repository.blade.php (2 hunks)
  • resources/views/livewire/project/new/select.blade.php (1 hunks)
  • resources/views/livewire/project/shared/upload-config.blade.php (1 hunks)
  • routes/web.php (0 hunks)
  • versions.json (1 hunks)
💤 Files with no reviewable changes (4)
  • database/seeders/ApplicationSeeder.php
  • app/Http/Controllers/MagicController.php
  • routes/web.php
  • app/Models/Server.php
✅ Files skipped from review due to trivial changes (3)
  • resources/views/livewire/project/new/select.blade.php
  • versions.json
  • config/constants.php
🔇 Additional comments (15)
app/Jobs/ApplicationDeploymentJob.php (1)

256-258: LGTM! Private key storage is properly handled.

The addition ensures that the server's private key is available in the filesystem before proceeding with deployment operations, which is essential for secure SSH communications.

app/Livewire/Project/Shared/UploadConfig.php (1)

195-197: Environment ownership validation is robust and straightforward.

These lines correctly check if the environment belongs to the specified project, preventing cross-project misconfiguration.

app/Livewire/Project/New/GithubPrivateRepository.php (1)

161-165: Branch fallback logic is clear and user-friendly.

Properly checks for a 'main' then 'master' branch, and defaults to the first branch if neither is found. This covers common Git branching patterns neatly.

app/Services/ConfigurationGenerator.php (1)

23-133: Configuration structure reorganization looks well-structured and easier to extend.

Splitting the config into logical sections like coolify, source, build, and deployment provides clarity and facilitates future enhancements.

app/Livewire/Project/New/PublicGitRepository.php (6)

13-14: Additional imports look consistent
The usage of DB and Collection is in line with the new transaction logic and possible coolify-related data handling.


17-17: CUID integration
Importing Cuid2 for generating unique IDs is a suitable choice, enhancing uniqueness and preventing collisions.


33-33: Review the new property
The $coolify_config property stores a JSON-based configuration. Confirm that downstream code properly sanitizes and validates its contents to avoid malformed configuration issues.


41-41: Boolean toggle
$use_coolify_config defaults to false, which is a safe default. Verify that user actions or UI flows correctly set this property to true only when appropriate.


132-132: Ensuring correct build pack logic
Enabling $this->show_is_static for non-'nixpacks' or non-'static' build packs aligns well with the existing approach.


176-176: Reloading config on branch change
Fetching the config after changing the branch helps ensure the application creation process uses the correct data.

app/Models/Application.php (1)

1670-1859: Revised setConfig method
The transaction-based approach to updating application data in bulk is cohesive. However, the current create-only logic for environment variables, storage, etc. could lead to duplicates if setConfig() is called multiple times. Consider cleaning up or syncing existing records beforehand to avoid stale entries. Validate that repeated calls won’t generate unintended data growth.

resources/views/livewire/project/shared/upload-config.blade.php (1)

2-11: New config example buttons
Offering multiple example config buttons improves usability. Verify that user edits in the textarea aren’t overwritten unintentionally when choosing another example, ensuring clarity around how these presets interact with local changes.

bootstrap/helpers/applications.php (2)

127-135: LGTM! Initial JSON validation looks good.

The function correctly validates that the input is a valid JSON string before proceeding with deeper validation.


347-370: Add unit tests for custom validation logic.

The custom validation logic for dockerfile content and domains is critical but lacks test coverage.

Let's verify if there are any existing tests:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for test files related to configValidator
rg -l "configValidator" tests/

Length of output: 30


I'll now run an additional query to search for any test cases that reference the specific exception messages (e.g. “Validation failed:”) used in the custom validation logic. This should help confirm whether unit tests exist for these validations.


🏁 Script executed:

#!/bin/bash
rg "Validation failed:" tests/

Length of output: 32


Missing Unit Tests for Critical Custom Validation Logic

The custom validations in bootstrap/helpers/applications.php (lines 347-370) are not covered by any unit tests. Searches for test cases referencing terms like "configValidator" and "Validation failed:" produced no results. It's important to add tests that specifically verify:

  • The exception is thrown when using the 'dockerfile' build pack without the necessary Git repository/branch or Dockerfile content.
  • The proper handling of domain validations (checking for valid protocols and domain formats).
resources/views/livewire/project/application/general.blade.php (1)

9-11: LGTM! Download Config button is properly enabled.

The button is correctly uncommented and uses the appropriate wire:click directive.

Comment on lines +38 to +59
case 'dockerfile':
$this->config = '{
"name": "Example Application",
"description": "This is an example application configuration",
"coolify": {
"project_uuid": "'.$this->project_uuid.'",
"environment_uuid": "'.$this->environment_uuid.'",
"destination_uuid": "'.$this->destination_uuid.'"
},
"build": {
"build_pack": "dockerfile",
"dockerfile": {
"content": "FROM nginx:latest"
}
},
"network": {
"ports": {
"expose": "80"
}
}
}';
case 'dockerfile-without-coolify':
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add the missing break to avoid unintended case fall-through.

Currently, the 'dockerfile' case does not include a break, causing the code to continue into the 'dockerfile-without-coolify' case and overwrite $this->config. Below is a suggested fix:

 case 'dockerfile':
     $this->config = '{
         ...
     }';
+    break;
 case 'dockerfile-without-coolify':
     $this->config = '{
         ...
📝 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
case 'dockerfile':
$this->config = '{
"name": "Example Application",
"description": "This is an example application configuration",
"coolify": {
"project_uuid": "'.$this->project_uuid.'",
"environment_uuid": "'.$this->environment_uuid.'",
"destination_uuid": "'.$this->destination_uuid.'"
},
"build": {
"build_pack": "dockerfile",
"dockerfile": {
"content": "FROM nginx:latest"
}
},
"network": {
"ports": {
"expose": "80"
}
}
}';
case 'dockerfile-without-coolify':
case 'dockerfile':
$this->config = '{
"name": "Example Application",
"description": "This is an example application configuration",
"coolify": {
"project_uuid": "'.$this->project_uuid.'",
"environment_uuid": "'.$this->environment_uuid.'",
"destination_uuid": "'.$this->destination_uuid.'"
},
"build": {
"build_pack": "dockerfile",
"dockerfile": {
"content": "FROM nginx:latest"
}
},
"network": {
"ports": {
"expose": "80"
}
}
}';
break;
case 'dockerfile-without-coolify':

Comment on lines +139 to +151
protected function cleanupNullEmptyValues(array $config): array
{
return collect($config)->map(function ($value) {
if (is_array($value)) {
return $this->cleanupNullEmptyValues($value);
}

return $value;
})->filter(function ($value) {
return filled($value) &&
(! is_array($value) || ! empty($value));
})->toArray();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid removing valid boolean or numeric values in cleanupNullEmptyValues.

Using filled($value) discards false, 0, or "0", potentially removing legitimate settings from the config. Below is a suggested fix to preserve these values:

-        })->filter(function ($value) {
-            return filled($value) && (! is_array($value) || ! empty($value));
+        })->filter(function ($value) {
+            if (is_array($value)) {
+                return !empty($value);
+            }
+            // Keep boolean false or numeric zero
+            return !is_null($value) && $value !== '';
         })
📝 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
protected function cleanupNullEmptyValues(array $config): array
{
return collect($config)->map(function ($value) {
if (is_array($value)) {
return $this->cleanupNullEmptyValues($value);
}
return $value;
})->filter(function ($value) {
return filled($value) &&
(! is_array($value) || ! empty($value));
})->toArray();
}
protected function cleanupNullEmptyValues(array $config): array
{
return collect($config)->map(function ($value) {
if (is_array($value)) {
return $this->cleanupNullEmptyValues($value);
}
return $value;
})->filter(function ($value) {
if (is_array($value)) {
return !empty($value);
}
// Keep boolean false or numeric zero
return !is_null($value) && $value !== '';
})->toArray();
}

Comment on lines +24 to +27
public function resource()
{
return $this->morphTo('resource');
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider consolidating polymorphic relationships.

The file has multiple identical polymorphic relationships (resource, application, service, database, standalone_postgresql) that all use the same morphTo configuration. This could lead to confusion about which relationship to use.

Consider consolidating these into a single relationship or documenting the specific use case for each:

  1. Add PHPDoc comments explaining when to use each relationship
  2. Or consolidate into a single relationship if they serve the same purpose

Example:

/**
 * Get the owning resource model.
 * @return \Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function resource()
{
    return $this->morphTo('resource');
}

Also applies to: 29-32, 34-37, 39-42, 44-47

Comment on lines +76 to +97
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch)
{
try {
if ($baseDirectory !== '/') {
$baseDirectory = $baseDirectory.'/';
}
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}";
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath);
$coolify_config = base64_decode(data_get($coolifyJson, 'content'));
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s');

return [
'coolify_config' => $coolify_config,
'rate_limit_reset' => $rate_limit_reset
];
} catch (\Throwable $e) {
return [
'coolify_config' => null,
'rate_limit_reset' => null
];
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and validation in getCoolifyConfig.

The method could benefit from improved validation and more specific error handling.

Consider these improvements:

 public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch)
 {
     try {
         if ($baseDirectory !== '/') {
             $baseDirectory = $baseDirectory.'/';
         }
         $githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}";
         ['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath);
+        if (!isset($coolifyJson['content']) || !isset($coolifyJson['encoding']) || $coolifyJson['encoding'] !== 'base64') {
+            throw new \InvalidArgumentException('Invalid coolify.json format');
+        }
         $coolify_config = base64_decode(data_get($coolifyJson, 'content'));
+        if ($coolify_config === false) {
+            throw new \RuntimeException('Failed to decode base64 content');
+        }
+        if (!json_decode($coolify_config)) {
+            throw new \JsonException('Invalid JSON content');
+        }
         $rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s');

         return [
             'coolify_config' => $coolify_config,
             'rate_limit_reset' => $rate_limit_reset
         ];
-    } catch (\Throwable $e) {
+    } catch (\InvalidArgumentException $e) {
+        \Log::warning('Invalid coolify.json format: ' . $e->getMessage());
+        return ['coolify_config' => null, 'rate_limit_reset' => null];
+    } catch (\RuntimeException $e) {
+        \Log::error('Base64 decode failed: ' . $e->getMessage());
+        return ['coolify_config' => null, 'rate_limit_reset' => null];
+    } catch (\JsonException $e) {
+        \Log::error('JSON decode failed: ' . $e->getMessage());
+        return ['coolify_config' => null, 'rate_limit_reset' => null];
+    } catch (\Throwable $e) {
+        \Log::error('Unexpected error in getCoolifyConfig: ' . $e->getMessage());
         return [
             'coolify_config' => null,
             'rate_limit_reset' => null
         ];
     }
 }
📝 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
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch)
{
try {
if ($baseDirectory !== '/') {
$baseDirectory = $baseDirectory.'/';
}
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}";
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath);
$coolify_config = base64_decode(data_get($coolifyJson, 'content'));
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s');
return [
'coolify_config' => $coolify_config,
'rate_limit_reset' => $rate_limit_reset
];
} catch (\Throwable $e) {
return [
'coolify_config' => null,
'rate_limit_reset' => null
];
}
}
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch)
{
try {
if ($baseDirectory !== '/') {
$baseDirectory = $baseDirectory.'/';
}
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}";
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath);
if (!isset($coolifyJson['content']) || !isset($coolifyJson['encoding']) || $coolifyJson['encoding'] !== 'base64') {
throw new \InvalidArgumentException('Invalid coolify.json format');
}
$coolify_config = base64_decode(data_get($coolifyJson, 'content'));
if ($coolify_config === false) {
throw new \RuntimeException('Failed to decode base64 content');
}
if (!json_decode($coolify_config)) {
throw new \JsonException('Invalid JSON content');
}
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s');
return [
'coolify_config' => $coolify_config,
'rate_limit_reset' => $rate_limit_reset
];
} catch (\InvalidArgumentException $e) {
\Log::warning('Invalid coolify.json format: ' . $e->getMessage());
return ['coolify_config' => null, 'rate_limit_reset' => null];
} catch (\RuntimeException $e) {
\Log::error('Base64 decode failed: ' . $e->getMessage());
return ['coolify_config' => null, 'rate_limit_reset' => null];
} catch (\JsonException $e) {
\Log::error('JSON decode failed: ' . $e->getMessage());
return ['coolify_config' => null, 'rate_limit_reset' => null];
} catch (\Throwable $e) {
\Log::error('Unexpected error in getCoolifyConfig: ' . $e->getMessage());
return [
'coolify_config' => null,
'rate_limit_reset' => null
];
}
}

Comment on lines +66 to +134
<form class="flex flex-col space-y-4" wire:submit='submit'>
<div class="flex flex-col gap-2">
@if ($use_coolify_config === false)
<div class="flex gap-2">
<x-forms.select wire:model.live="selected_branch_name" label="Branch">
<option value="default" disabled selected>Select a branch</option>
@foreach ($branches as $branch)
@if ($loop->first)
<option selected value="{{ data_get($branch, 'name') }}">
{{ data_get($branch, 'name') }}
</option>
@else
<option value="{{ data_get($branch, 'name') }}">
{{ data_get($branch, 'name') }}
</option>
@endif
@endforeach
</x-forms.select>
<x-forms.select wire:model.live="build_pack" label="Build Pack" required>
<option value="nixpacks">Nixpacks</option>
<option value="static">Static</option>
<option value="dockerfile">Dockerfile</option>
<option value="dockercompose">Docker Compose</option>
</x-forms.select>
@if ($is_static)
<x-forms.input id="publish_directory" label="Publish Directory"
helper="If there is a build process involved (like Svelte, React, Next, etc..), please specify the output directory for the build assets." />
@endif
</div>
@if ($build_pack === 'dockercompose')
<x-forms.input placeholder="/" wire:model.live.debounce.500ms="base_directory"
label="Base Directory"
helper="Directory to use as root. Useful for monorepos." />
<x-forms.input placeholder="/docker-compose.yaml" id="docker_compose_location"
label="Docker Compose Location"
helper="It is calculated together with the Base Directory:<br><span class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>" />
Compose file location in your repository:<span
class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>
@else
<x-forms.input wire:model.live.debounce.500ms="base_directory"
label="Base Directory"
helper="Directory to use as root. Useful for monorepos." />
@endif
@if ($show_is_static)
<x-forms.input type="number" id="port" label="Port" :readonly="$is_static || $build_pack === 'static'"
helper="The port your application listens on." />
@if ($build_pack !== 'dockerfile')
<div class="w-52">
<x-forms.checkbox instantSave id="is_static"
label="Is it a static site?"
helper="If your application is a static site or the final build assets should be served as a static site, enable this." />
</div>
@endif
@endif
</div>
@if ($build_pack === 'dockercompose')
<x-forms.input placeholder="/" wire:model.blur="base_directory"
label="Base Directory"
helper="Directory to use as root. Useful for monorepos." />
<x-forms.input placeholder="/docker-compose.yaml" id="docker_compose_location"
label="Docker Compose Location"
helper="It is calculated together with the Base Directory:<br><span class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>" />
Compose file location in your repository:<span
class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>
@endif
@if ($show_is_static)
<x-forms.input type="number" id="port" label="Port" :readonly="$is_static || $build_pack === 'static'"
helper="The port your application listens on." />
@if (filled($coolify_config))
<div class="w-52">
<x-forms.checkbox instantSave id="is_static" label="Is it a static site?"
helper="If your application is a static site or the final build assets should be served as a static site, enable this." />
<x-forms.checkbox wire:model.live="use_coolify_config"
label="Use coolify.json?" />
</div>
@endif
</div>
@if (filled($coolify_config))
<div class="flex flex-col gap-2">
<div>coolify.json</div>
<x-forms.textarea id="coolify_config" wire:model="coolify_config"
monacoEditorLanguage="json" useMonacoEditor />
</div>
@endif
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract shared repository configuration form into a component.

The configuration form logic is duplicated between public and private repository views. This could lead to maintenance issues.

Create a shared component to reduce duplication:

  1. Extract the form into resources/views/components/repository-config-form.blade.php
  2. Use the component in both views:
<x-repository-config-form
    :use-coolify-config="$use_coolify_config"
    :build-pack="$build_pack"
    :is-static="$is_static"
    :base-directory="$base_directory"
    :coolify-config="$coolify_config"
    wire:submit="submit"
/>

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