diff --git a/data/.dockerignore b/data/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..958b26c9d6ea21bea38f9de590fc01075da016a9 --- /dev/null +++ b/data/.dockerignore @@ -0,0 +1,5 @@ +node_modules +.git +.gitignore +*.md +dist \ No newline at end of file diff --git a/data/.nvmrc b/data/.nvmrc new file mode 100644 index 0000000000000000000000000000000000000000..593cb75bc5c212129bc486a51f13015214a07cd1 --- /dev/null +++ b/data/.nvmrc @@ -0,0 +1 @@ +20.16.0 \ No newline at end of file diff --git a/data/CONTRIBUTING.md b/data/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac5a3581b24e20deb32da6327f09be811191065 --- /dev/null +++ b/data/CONTRIBUTING.md @@ -0,0 +1,179 @@ +# Contributing + +Hey, thanks for your interest in contributing to Dokploy! We appreciate your help and taking your time to contribute. + +Before you start, please first discuss the feature/bug you want to add with the owners and comunity via github issues. + +We have a few guidelines to follow when contributing to this project: + +- [Commit Convention](#commit-convention) +- [Setup](#setup) +- [Development](#development) +- [Build](#build) +- [Pull Request](#pull-request) + +## Commit Convention + +Before you create a Pull Request, please make sure your commit message follows the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. + +### Commit Message Format + +``` +[optional scope]: + +[optional body] + +[optional footer(s)] +``` + +#### Type + +Must be one of the following: + +- **feat**: A new feature +- **fix**: A bug fix +- **docs**: Documentation only changes +- **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) +- **refactor**: A code change that neither fixes a bug nor adds a feature +- **perf**: A code change that improves performance +- **test**: Adding missing tests or correcting existing tests +- **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) +- **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) +- **chore**: Other changes that don't modify `src` or `test` files +- **revert**: Reverts a previous commit + +Example: + +``` +feat: add new feature +``` + +## Setup + +Before you start, please make the clone based on the `canary` branch, since the `main` branch is the source of truth and should always reflect the latest stable release, also the PRs will be merged to the `canary` branch. + +We use Node v20.16.0 and recommend this specific version. If you have nvm installed, you can run `nvm install 20.16.0 && nvm use` in the root directory. + +```bash +git clone https://github.com/dokploy/dokploy.git +cd dokploy +pnpm install +cp apps/dokploy/.env.example apps/dokploy/.env +``` + +## Requirements + +- [Docker](/GUIDES.md#docker) + +### Setup + +Run the command that will spin up all the required services and files. + +```bash +pnpm run dokploy:setup +``` + +Run this script + +```bash +pnpm run server:script +``` + +Now run the development server. + +```bash +pnpm run dokploy:dev +``` + +Go to http://localhost:3000 to see the development server + +Note: this project uses Biome. If your editor is configured to use another formatter such as Prettier, it's recommended to either change it to use Biome or turn it off. + +## Build + +```bash +pnpm run dokploy:build +``` + +## Docker + +To build the docker image + +```bash +pnpm run docker:build +``` + +To push the docker image + +```bash +pnpm run docker:push +``` + +## Password Reset + +In the case you lost your password, you can reset it using the following command + +```bash +pnpm run reset-password +``` + +If you want to test the webhooks on development mode using localtunnel, make sure to install `localtunnel` + +```bash +bunx lt --port 3000 +``` + +If you run into permission issues of docker run the following command + +```bash +sudo chown -R USERNAME dokploy or sudo chown -R $(whoami) ~/.docker +``` + +## Application deploy + +In case you want to deploy the application on your machine and you selected nixpacks or buildpacks, you need to install first. + +```bash +# Install Nixpacks +curl -sSL https://nixpacks.com/install.sh -o install.sh \ + && chmod +x install.sh \ + && ./install.sh +``` + +```bash +# Install Railpack +curl -sSL https://railpack.com/install.sh | sh +``` + +```bash +# Install Buildpacks +curl -sSL "https://github.com/buildpacks/pack/releases/download/v0.35.0/pack-v0.35.0-linux.tgz" | tar -C /usr/local/bin/ --no-same-owner -xzv pack +``` + +## Pull Request + +- The `main` branch is the source of truth and should always reflect the latest stable release. +- Create a new branch for each feature or bug fix. +- Make sure to add tests for your changes. +- Make sure to update the documentation for any changes Go to the [docs.dokploy.com](https://docs.dokploy.com) website to see the changes. +- When creating a pull request, please provide a clear and concise description of the changes made. +- If you include a video or screenshot, would be awesome so we can see the changes in action. +- If your pull request fixes an open issue, please reference the issue in the pull request description. +- Once your pull request is merged, you will be automatically added as a contributor to the project. + +Thank you for your contribution! + +## Templates + +To add a new template, go to `https://github.com/Dokploy/templates` repository and read the README.md file. + +### Recommendations + +- Use the same name of the folder as the id of the template. +- The logo should be in the public folder. +- If you want to show a domain in the UI, please add the `_HOST` suffix at the end of the variable name. +- Test first on a vps or a server to make sure the template works. + +## Docs & Website + +To contribute to the Dokploy docs or website, please go to this [repository](https://github.com/Dokploy/website). diff --git a/data/Dockerfile b/data/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..00043b0c2ac9683234a2141eac3272cb82b11fe0 --- /dev/null +++ b/data/Dockerfile @@ -0,0 +1,66 @@ +FROM node:20.9-slim AS base +ENV PNPM_HOME="/pnpm" +ENV PATH="$PNPM_HOME:$PATH" +RUN corepack enable + +FROM base AS build +COPY . /usr/src/app +WORKDIR /usr/src/app + +RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/* + +# Install dependencies +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile + +# Deploy only the dokploy app + +ENV NODE_ENV=production +RUN pnpm --filter=@dokploy/server build +RUN pnpm --filter=./apps/dokploy run build + +RUN pnpm --filter=./apps/dokploy --prod deploy /prod/dokploy + +RUN cp -R /usr/src/app/apps/dokploy/.next /prod/dokploy/.next +RUN cp -R /usr/src/app/apps/dokploy/dist /prod/dokploy/dist + +FROM base AS dokploy +WORKDIR /app + +# Set production +ENV NODE_ENV=production + +RUN apt-get update && apt-get install -y curl unzip zip apache2-utils iproute2 rsync git-lfs && git lfs install && rm -rf /var/lib/apt/lists/* + +# Copy only the necessary files +COPY --from=build /prod/dokploy/.next ./.next +COPY --from=build /prod/dokploy/dist ./dist +COPY --from=build /prod/dokploy/next.config.mjs ./next.config.mjs +COPY --from=build /prod/dokploy/public ./public +COPY --from=build /prod/dokploy/package.json ./package.json +COPY --from=build /prod/dokploy/drizzle ./drizzle +COPY .env.production ./.env +COPY --from=build /prod/dokploy/components.json ./components.json +COPY --from=build /prod/dokploy/node_modules ./node_modules + + +# Install docker +RUN curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh && rm get-docker.sh && curl https://rclone.org/install.sh | bash + +# Install Nixpacks and tsx +# | VERBOSE=1 VERSION=1.21.0 bash + +ARG NIXPACKS_VERSION=1.39.0 +RUN curl -sSL https://nixpacks.com/install.sh -o install.sh \ + && chmod +x install.sh \ + && ./install.sh \ + && pnpm install -g tsx + +# Install Railpack +ARG RAILPACK_VERSION=0.0.64 +RUN curl -sSL https://railpack.com/install.sh | bash + +# Install buildpacks +COPY --from=buildpacksio/pack:0.35.0 /usr/local/bin/pack /usr/local/bin/pack + +EXPOSE 3000 +CMD [ "pnpm", "start" ] diff --git a/data/Dockerfile.cloud b/data/Dockerfile.cloud new file mode 100644 index 0000000000000000000000000000000000000000..c1b6679638ebd8a726385db26f4adcba3019d61b --- /dev/null +++ b/data/Dockerfile.cloud @@ -0,0 +1,61 @@ +FROM node:20.9-slim AS base +ENV PNPM_HOME="/pnpm" +ENV PATH="$PNPM_HOME:$PATH" +RUN corepack enable + +FROM base AS build +COPY . /usr/src/app +WORKDIR /usr/src/app + +RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/* + +# Install dependencies +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/dokploy install --frozen-lockfile + + +# Deploy only the dokploy app +ARG NEXT_PUBLIC_UMAMI_HOST +ENV NEXT_PUBLIC_UMAMI_HOST=$NEXT_PUBLIC_UMAMI_HOST + +ARG NEXT_PUBLIC_UMAMI_WEBSITE_ID +ENV NEXT_PUBLIC_UMAMI_WEBSITE_ID=$NEXT_PUBLIC_UMAMI_WEBSITE_ID + +ARG NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY +ENV NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=$NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY + +ENV NODE_ENV=production +RUN pnpm --filter=@dokploy/server build +RUN pnpm --filter=./apps/dokploy run build + +RUN pnpm --filter=./apps/dokploy --prod deploy /prod/dokploy + +RUN cp -R /usr/src/app/apps/dokploy/.next /prod/dokploy/.next +RUN cp -R /usr/src/app/apps/dokploy/dist /prod/dokploy/dist + +FROM base AS dokploy +WORKDIR /app + +# Set production +ENV NODE_ENV=production + +RUN apt-get update && apt-get install -y curl unzip apache2-utils && rm -rf /var/lib/apt/lists/* + +# Copy only the necessary files +COPY --from=build /prod/dokploy/.next ./.next +COPY --from=build /prod/dokploy/dist ./dist +COPY --from=build /prod/dokploy/next.config.mjs ./next.config.mjs +COPY --from=build /prod/dokploy/public ./public +COPY --from=build /prod/dokploy/package.json ./package.json +COPY --from=build /prod/dokploy/drizzle ./drizzle +COPY --from=build /prod/dokploy/components.json ./components.json +COPY --from=build /prod/dokploy/node_modules ./node_modules + + +# Install RCLONE +RUN curl https://rclone.org/install.sh | bash + +# tsx +RUN pnpm install -g tsx + +EXPOSE 3000 +CMD [ "pnpm", "start" ] \ No newline at end of file diff --git a/data/Dockerfile.monitoring b/data/Dockerfile.monitoring new file mode 100644 index 0000000000000000000000000000000000000000..814625dbf0cba882d01ab112a262e7961a59d276 --- /dev/null +++ b/data/Dockerfile.monitoring @@ -0,0 +1,41 @@ +# Build stage +FROM golang:1.21-alpine3.19 AS builder + +# Instalar dependencias necesarias +RUN apk add --no-cache gcc musl-dev sqlite-dev + +# Establecer el directorio de trabajo +WORKDIR /app + +# Copiar todo el código fuente primero +COPY . . + +# Movernos al directorio de la aplicación golang +WORKDIR /app/apps/monitoring + +# Descargar dependencias +RUN go mod download + +# Compilar la aplicación +RUN CGO_ENABLED=1 GOOS=linux go build -o main main.go + +# Etapa final +FROM alpine:3.19 + +# Instalar SQLite y otras dependencias necesarias +RUN apk add --no-cache sqlite-libs docker-cli + +WORKDIR /app + +# Copiar el binario compilado y el archivo monitor.go +COPY --from=builder /app/apps/monitoring/main ./main +COPY --from=builder /app/apps/monitoring/main.go ./monitor.go + +# COPY --from=builder /app/apps/golang/.env ./.env + +# Exponer el puerto +ENV PORT=3001 +EXPOSE 3001 + +# Ejecutar la aplicación +CMD ["./main"] \ No newline at end of file diff --git a/data/Dockerfile.schedule b/data/Dockerfile.schedule new file mode 100644 index 0000000000000000000000000000000000000000..eba08f7ba91b2695ab2957341b29774cd8309214 --- /dev/null +++ b/data/Dockerfile.schedule @@ -0,0 +1,36 @@ +FROM node:20.9-slim AS base +ENV PNPM_HOME="/pnpm" +ENV PATH="$PNPM_HOME:$PATH" +RUN corepack enable + +FROM base AS build +COPY . /usr/src/app +WORKDIR /usr/src/app + +RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/* + +# Install dependencies +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/schedules install --frozen-lockfile + +# Deploy only the dokploy app + +ENV NODE_ENV=production +RUN pnpm --filter=@dokploy/server build +RUN pnpm --filter=./apps/schedules run build + +RUN pnpm --filter=./apps/schedules --prod deploy /prod/schedules + +RUN cp -R /usr/src/app/apps/schedules/dist /prod/schedules/dist + +FROM base AS dokploy +WORKDIR /app + +# Set production +ENV NODE_ENV=production + +# Copy only the necessary files +COPY --from=build /prod/schedules/dist ./dist +COPY --from=build /prod/schedules/package.json ./package.json +COPY --from=build /prod/schedules/node_modules ./node_modules + +CMD HOSTNAME=0.0.0.0 && pnpm start \ No newline at end of file diff --git a/data/Dockerfile.server b/data/Dockerfile.server new file mode 100644 index 0000000000000000000000000000000000000000..8fef514221f9dc279073b283227076c55c644e42 --- /dev/null +++ b/data/Dockerfile.server @@ -0,0 +1,36 @@ +FROM node:20.9-slim AS base +ENV PNPM_HOME="/pnpm" +ENV PATH="$PNPM_HOME:$PATH" +RUN corepack enable + +FROM base AS build +COPY . /usr/src/app +WORKDIR /usr/src/app + +RUN apt-get update && apt-get install -y python3 make g++ git python3-pip pkg-config libsecret-1-dev && rm -rf /var/lib/apt/lists/* + +# Install dependencies +RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server --filter=./apps/api install --frozen-lockfile + +# Deploy only the dokploy app + +ENV NODE_ENV=production +RUN pnpm --filter=@dokploy/server build +RUN pnpm --filter=./apps/api run build + +RUN pnpm --filter=./apps/api --prod deploy /prod/api + +RUN cp -R /usr/src/app/apps/api/dist /prod/api/dist + +FROM base AS dokploy +WORKDIR /app + +# Set production +ENV NODE_ENV=production + +# Copy only the necessary files +COPY --from=build /prod/api/dist ./dist +COPY --from=build /prod/api/package.json ./package.json +COPY --from=build /prod/api/node_modules ./node_modules + +CMD HOSTNAME=0.0.0.0 && pnpm start \ No newline at end of file diff --git a/data/GUIDES.md b/data/GUIDES.md new file mode 100644 index 0000000000000000000000000000000000000000..cfb7cd8128aea5681d1f1a909fd059a147b5a415 --- /dev/null +++ b/data/GUIDES.md @@ -0,0 +1,49 @@ +# Docker + +Here's how to install docker on different operating systems: + +## macOS + +1. Visit [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop) +2. Download the Docker Desktop installer +3. Double-click the downloaded `.dmg` file +4. Drag Docker to your Applications folder +5. Open Docker Desktop from Applications +6. Follow the onboarding tutorial if desired + +## Linux + +### Ubuntu + +```bash +# Update package index +sudo apt-get update + +# Install prerequisites +sudo apt-get install \ + apt-transport-https \ + ca-certificates \ + curl \ + gnupg \ + lsb-release + +# Add Docker's official GPG key +curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg + +# Set up stable repository +echo \ + "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ + $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null + +# Install Docker Engine +sudo apt-get update +sudo apt-get install docker-ce docker-ce-cli containerd.io +``` + +## Windows + +1. Enable WSL2 if not already enabled +2. Visit [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop) +3. Download the installer +4. Run the installer and follow the prompts +5. Start Docker Desktop from the Start menu \ No newline at end of file diff --git a/data/LICENSE.MD b/data/LICENSE.MD new file mode 100644 index 0000000000000000000000000000000000000000..7e49a35ba8290ec9ab377c87deedf12255744130 --- /dev/null +++ b/data/LICENSE.MD @@ -0,0 +1,26 @@ +# License + +## Core License (Apache License 2.0) + +Copyright 2024 Mauricio Siu. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. + +## Additional Terms for Specific Features + +The following additional terms apply to the multi-node support, Docker Compose file, Preview Deployments and Multi Server features of Dokploy. In the event of a conflict, these provisions shall take precedence over those in the Apache License: + +- **Self-Hosted Version Free**: All features of Dokploy, including multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server, will always be free to use in the self-hosted version. +- **Restriction on Resale**: The multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server features cannot be sold or offered as a service by any party other than the copyright holder without prior written consent. +- **Modification Distribution**: Any modifications to the multi-node support, Docker Compose file support, Schedules, Preview Deployments and Multi Server features must be distributed freely and cannot be sold or offered as a service. + +For further inquiries or permissions, please contact us directly. diff --git a/data/SECURITY.md b/data/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..47633ab95f474f73b3efd9c0a798e375d7598f9f --- /dev/null +++ b/data/SECURITY.md @@ -0,0 +1,28 @@ +# Dokploy Security Policy + +At Dokploy, security is a top priority. We appreciate the help of security researchers and the community in identifying and reporting vulnerabilities. + +## How to Report a Vulnerability + +If you have discovered a security vulnerability in Dokploy, we ask that you report it responsibly by following these guidelines: + +1. **Contact us:** Send an email to [contact@dokploy.com](mailto:contact@dokploy.com). +2. **Provide clear details:** Include as much information as possible to help us understand and reproduce the vulnerability. This should include: + * A clear description of the vulnerability. + * Steps to reproduce the vulnerability. + * Any sample code, screenshots, or videos that might be helpful. + * The potential impact of the vulnerability. +3. **Do not make the vulnerability public:** Please refrain from publicly disclosing the vulnerability until we have had the opportunity to investigate and address it. This is crucial for protecting our users. +4. **Allow us time:** We will endeavor to acknowledge receipt of your report as soon as possible and keep you informed of our progress. The time to resolve the vulnerability may vary depending on its complexity and severity. + +## What We Expect From You + +* Do not access user data or systems beyond what is necessary to demonstrate the vulnerability. +* Do not perform denial-of-service (DoS) attacks, spamming, or social engineering. +* Do not modify or destroy data that does not belong to you. + +## Our Commitment + +We are committed to working with you quickly and responsibly to address any legitimate security vulnerability. + +Thank you for helping us keep Dokploy secure for everyone. diff --git a/data/TERMS_AND_CONDITIONS.md b/data/TERMS_AND_CONDITIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..56ef97fb14100f7b7d655a1800563b7dce7c058e --- /dev/null +++ b/data/TERMS_AND_CONDITIONS.md @@ -0,0 +1,22 @@ +# Terms & Conditions + +**Dokploy core** is a free and open-source solution intended as an alternative to established cloud platforms like Vercel and Netlify. + +The Dokploy team endeavors to mitigate potential defects and issues through stringent testing and adherence to principles of clean coding. Dokploy is provided "AS IS" without any warranties, express or implied. Refer to the [License](https://github.com/Dokploy/Dokploy/blob/main/LICENSE) for details on permissions and restrictions. + + +### Description of Service: + +**Dokploy core** is an open-source tool designed to simplify the deployment of applications for both personal and business use. Users are permitted to install, modify, and operate Dokploy independently or within their organizations to improve their development and deployment operations. It is important to note that any commercial resale or redistribution of Dokploy as a service is strictly forbidden without explicit consent. This prohibition ensures the preservation of Dokploy's open-source character for the benefit of the entire community. + +### Our Responsibility + +The Dokploy development team commits to maintaining the functionality of the software and addressing major issues promptly. While we welcome suggestions for new features, the decision to include them rests solely with the core developers of Dokploy. + +### Usage Data + +**Dokploy** does not collect any user data. It is distributed as a free and open-source tool under the terms of "AS IS", without any implied warranties or conditions. + +### Future Changes + +The Terms of Service and Terms & Conditions are subject to change without prior notice. diff --git a/data/apps/api/.env.example b/data/apps/api/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..647e2a077c66b0526cb9ee9afffc44527f3fabcf --- /dev/null +++ b/data/apps/api/.env.example @@ -0,0 +1,2 @@ +LEMON_SQUEEZY_API_KEY="" +LEMON_SQUEEZY_STORE_ID="" \ No newline at end of file diff --git a/data/apps/api/package.json b/data/apps/api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56ea56952d6c2fd3d34ddef00d64eea19737c527 --- /dev/null +++ b/data/apps/api/package.json @@ -0,0 +1,33 @@ +{ + "name": "@dokploy/api", + "version": "0.0.1", + "type": "module", + "scripts": { + "dev": "PORT=4000 tsx watch src/index.ts", + "build": "tsc --project tsconfig.json", + "start": "node dist/index.js", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "pino": "9.4.0", + "pino-pretty": "11.2.2", + "@hono/zod-validator": "0.3.0", + "zod": "^3.23.4", + "react": "18.2.0", + "react-dom": "18.2.0", + "@dokploy/server": "workspace:*", + "@hono/node-server": "^1.12.1", + "hono": "^4.5.8", + "dotenv": "^16.3.1", + "redis": "4.7.0", + "@nerimity/mimiqueue": "1.2.3" + }, + "devDependencies": { + "typescript": "^5.4.2", + "@types/react": "^18.2.37", + "@types/react-dom": "^18.2.15", + "@types/node": "^20.11.17", + "tsx": "^4.7.1" + }, + "packageManager": "pnpm@9.5.0" +} diff --git a/data/apps/api/src/index.ts b/data/apps/api/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0db565995008d2370295f4faf81e45f1d044734b --- /dev/null +++ b/data/apps/api/src/index.ts @@ -0,0 +1,61 @@ +import { serve } from "@hono/node-server"; +import { Hono } from "hono"; +import "dotenv/config"; +import { zValidator } from "@hono/zod-validator"; +import { Queue } from "@nerimity/mimiqueue"; +import { createClient } from "redis"; +import { logger } from "./logger.js"; +import { type DeployJob, deployJobSchema } from "./schema.js"; +import { deploy } from "./utils.js"; + +const app = new Hono(); +const redisClient = createClient({ + url: process.env.REDIS_URL, +}); + +app.use(async (c, next) => { + if (c.req.path === "/health") { + return next(); + } + const authHeader = c.req.header("X-API-Key"); + + if (process.env.API_KEY !== authHeader) { + return c.json({ message: "Invalid API Key" }, 403); + } + + return next(); +}); + +app.post("/deploy", zValidator("json", deployJobSchema), (c) => { + const data = c.req.valid("json"); + queue.add(data, { groupName: data.serverId }); + return c.json( + { + message: "Deployment Added", + }, + 200, + ); +}); + +app.get("/health", async (c) => { + return c.json({ status: "ok" }); +}); + +const queue = new Queue({ + name: "deployments", + process: async (job: DeployJob) => { + logger.info("Deploying job", job); + return await deploy(job); + }, + redisClient, +}); + +(async () => { + await redisClient.connect(); + await redisClient.flushAll(); + logger.info("Redis Cleaned"); +})(); + +const port = Number.parseInt(process.env.PORT || "3000"); +logger.info("Starting Deployments Server ✅", port); +serve({ fetch: app.fetch, port }); diff --git a/data/apps/api/src/logger.ts b/data/apps/api/src/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d8b5840f488c2db4507c08c8aa61d4b1875eabd --- /dev/null +++ b/data/apps/api/src/logger.ts @@ -0,0 +1,10 @@ +import pino from "pino"; + +export const logger = pino({ + transport: { + target: "pino-pretty", + options: { + colorize: true, + }, + }, +}); diff --git a/data/apps/api/src/schema.ts b/data/apps/api/src/schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..609289bf70ef85fcc71e9747f94713418a461d32 --- /dev/null +++ b/data/apps/api/src/schema.ts @@ -0,0 +1,34 @@ +import { z } from "zod"; + +export const deployJobSchema = z.discriminatedUnion("applicationType", [ + z.object({ + applicationId: z.string(), + titleLog: z.string(), + descriptionLog: z.string(), + server: z.boolean().optional(), + type: z.enum(["deploy", "redeploy"]), + applicationType: z.literal("application"), + serverId: z.string().min(1), + }), + z.object({ + composeId: z.string(), + titleLog: z.string(), + descriptionLog: z.string(), + server: z.boolean().optional(), + type: z.enum(["deploy", "redeploy"]), + applicationType: z.literal("compose"), + serverId: z.string().min(1), + }), + z.object({ + applicationId: z.string(), + previewDeploymentId: z.string(), + titleLog: z.string(), + descriptionLog: z.string(), + server: z.boolean().optional(), + type: z.enum(["deploy"]), + applicationType: z.literal("application-preview"), + serverId: z.string().min(1), + }), +]); + +export type DeployJob = z.infer; diff --git a/data/apps/api/src/utils.ts b/data/apps/api/src/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f3c9698b69ef96c9a9a5c7209b1ee815334d91b --- /dev/null +++ b/data/apps/api/src/utils.ts @@ -0,0 +1,82 @@ +import { + deployRemoteApplication, + deployRemoteCompose, + deployRemotePreviewApplication, + rebuildRemoteApplication, + rebuildRemoteCompose, + updateApplicationStatus, + updateCompose, + updatePreviewDeployment, +} from "@dokploy/server"; +import type { DeployJob } from "./schema"; + +export const deploy = async (job: DeployJob) => { + try { + if (job.applicationType === "application") { + await updateApplicationStatus(job.applicationId, "running"); + if (job.server) { + if (job.type === "redeploy") { + await rebuildRemoteApplication({ + applicationId: job.applicationId, + titleLog: job.titleLog, + descriptionLog: job.descriptionLog, + }); + } else if (job.type === "deploy") { + await deployRemoteApplication({ + applicationId: job.applicationId, + titleLog: job.titleLog, + descriptionLog: job.descriptionLog, + }); + } + } + } else if (job.applicationType === "compose") { + await updateCompose(job.composeId, { + composeStatus: "running", + }); + + if (job.server) { + if (job.type === "redeploy") { + await rebuildRemoteCompose({ + composeId: job.composeId, + titleLog: job.titleLog, + descriptionLog: job.descriptionLog, + }); + } else if (job.type === "deploy") { + await deployRemoteCompose({ + composeId: job.composeId, + titleLog: job.titleLog, + descriptionLog: job.descriptionLog, + }); + } + } + } else if (job.applicationType === "application-preview") { + await updatePreviewDeployment(job.previewDeploymentId, { + previewStatus: "running", + }); + if (job.server) { + if (job.type === "deploy") { + await deployRemotePreviewApplication({ + applicationId: job.applicationId, + titleLog: job.titleLog, + descriptionLog: job.descriptionLog, + previewDeploymentId: job.previewDeploymentId, + }); + } + } + } + } catch (_) { + if (job.applicationType === "application") { + await updateApplicationStatus(job.applicationId, "error"); + } else if (job.applicationType === "compose") { + await updateCompose(job.composeId, { + composeStatus: "error", + }); + } else if (job.applicationType === "application-preview") { + await updatePreviewDeployment(job.previewDeploymentId, { + previewStatus: "error", + }); + } + } + + return true; +}; diff --git a/data/apps/api/tsconfig.json b/data/apps/api/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e47c6267d4400397c72bac6467e2afe7bf9a560e --- /dev/null +++ b/data/apps/api/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Node", + "strict": true, + "skipLibCheck": true, + "outDir": "dist", + "jsx": "react-jsx", + "jsxImportSource": "hono/jsx", + "baseUrl": ".", + "paths": { + "@/*": ["./*"], + "@dokploy/server/*": ["../../packages/server/src/*"] + } + }, + "exclude": ["node_modules", "dist"] +} diff --git a/data/apps/dokploy/.dockerignore b/data/apps/dokploy/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..958b26c9d6ea21bea38f9de590fc01075da016a9 --- /dev/null +++ b/data/apps/dokploy/.dockerignore @@ -0,0 +1,5 @@ +node_modules +.git +.gitignore +*.md +dist \ No newline at end of file diff --git a/data/apps/dokploy/.env.example b/data/apps/dokploy/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..ba57ec7bedbc17ab9382be0e3f27cbcd9142c7b8 --- /dev/null +++ b/data/apps/dokploy/.env.example @@ -0,0 +1,3 @@ +DATABASE_URL="postgres://dokploy:amukds4wi9001583845717ad2@localhost:5432/dokploy" +PORT=3000 +NODE_ENV=development \ No newline at end of file diff --git a/data/apps/dokploy/.env.production.example b/data/apps/dokploy/.env.production.example new file mode 100644 index 0000000000000000000000000000000000000000..41e934c3a696f41fabc594431c35b0f2f5f4b968 --- /dev/null +++ b/data/apps/dokploy/.env.production.example @@ -0,0 +1,3 @@ +DATABASE_URL="postgres://dokploy:amukds4wi9001583845717ad2@dokploy-postgres:5432/dokploy" +PORT=3000 +NODE_ENV=production \ No newline at end of file diff --git a/data/apps/dokploy/.nvmrc b/data/apps/dokploy/.nvmrc new file mode 100644 index 0000000000000000000000000000000000000000..593cb75bc5c212129bc486a51f13015214a07cd1 --- /dev/null +++ b/data/apps/dokploy/.nvmrc @@ -0,0 +1 @@ +20.16.0 \ No newline at end of file diff --git a/data/apps/dokploy/LICENSE.MD b/data/apps/dokploy/LICENSE.MD new file mode 100644 index 0000000000000000000000000000000000000000..8a508efb410931c2858a4f88d2aa811cd1292709 --- /dev/null +++ b/data/apps/dokploy/LICENSE.MD @@ -0,0 +1,26 @@ +# License + +## Core License (Apache License 2.0) + +Copyright 2024 Mauricio Siu. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. + +## Additional Terms for Specific Features + +The following additional terms apply to the multi-node support, Docker Compose file, Preview Deployments and Multi Server features of Dokploy. In the event of a conflict, these provisions shall take precedence over those in the Apache License: + +- **Self-Hosted Version Free**: All features of Dokploy, including multi-node support, Docker Compose file support, Preview Deployments and Multi Server, will always be free to use in the self-hosted version. +- **Restriction on Resale**: The multi-node support, Docker Compose file support, Preview Deployments and Multi Server features cannot be sold or offered as a service by any party other than the copyright holder without prior written consent. +- **Modification Distribution**: Any modifications to the multi-node support, Docker Compose file support, Preview Deployments and Multi Server features must be distributed freely and cannot be sold or offered as a service. + +For further inquiries or permissions, please contact us directly. diff --git a/data/apps/dokploy/__test__/compose/compose.test.ts b/data/apps/dokploy/__test__/compose/compose.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d4ba20f5ae679b3401923f50a393d03b0efb512 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/compose.test.ts @@ -0,0 +1,476 @@ +import { addSuffixToAllProperties } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile1 = ` +version: "3.8" + +services: + web: + image: nginx:latest + container_name: web_container + depends_on: + - app + networks: + - frontend + volumes_from: + - data + links: + - db + extends: + service: base_service + configs: + - source: web_config + + app: + image: node:14 + networks: + - backend + - frontend + + db: + image: postgres:13 + networks: + - backend + + data: + image: busybox + volumes: + - /data + + base_service: + image: base:latest + +networks: + frontend: + driver: bridge + backend: + driver: bridge + +volumes: + web_data: + driver: local + +configs: + web_config: + file: ./web_config.yml + +secrets: + db_password: + file: ./db_password.txt +`; + +const expectedComposeFile1 = load(` +version: "3.8" + +services: + web-testhash: + image: nginx:latest + container_name: web_container-testhash + depends_on: + - app-testhash + networks: + - frontend-testhash + volumes_from: + - data-testhash + links: + - db-testhash + extends: + service: base_service-testhash + configs: + - source: web_config-testhash + + app-testhash: + image: node:14 + networks: + - backend-testhash + - frontend-testhash + + db-testhash: + image: postgres:13 + networks: + - backend-testhash + + data-testhash: + image: busybox + volumes: + - /data + + base_service-testhash: + image: base:latest + +networks: + frontend-testhash: + driver: bridge + backend-testhash: + driver: bridge + +volumes: + web_data-testhash: + driver: local + +configs: + web_config-testhash: + file: ./web_config.yml + +secrets: + db_password-testhash: + file: ./db_password.txt +`) as ComposeSpecification; + +test("Add suffix to all properties in compose file 1", () => { + const composeData = load(composeFile1) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllProperties(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile1); +}); + +const composeFile2 = ` +version: "3.8" + +services: + frontend: + image: nginx:latest + depends_on: + - backend + networks: + - public + volumes_from: + - logs + links: + - cache + extends: + service: shared_service + secrets: + - db_password + + backend: + image: node:14 + networks: + - private + - public + + cache: + image: redis:latest + networks: + - private + + logs: + image: busybox + volumes: + - /logs + + shared_service: + image: shared:latest + +networks: + public: + driver: bridge + private: + driver: bridge + +volumes: + logs: + driver: local + +configs: + app_config: + file: ./app_config.yml + +secrets: + db_password: + file: ./db_password.txt +`; + +const expectedComposeFile2 = load(` +version: "3.8" + +services: + frontend-testhash: + image: nginx:latest + depends_on: + - backend-testhash + networks: + - public-testhash + volumes_from: + - logs-testhash + links: + - cache-testhash + extends: + service: shared_service-testhash + secrets: + - db_password-testhash + + backend-testhash: + image: node:14 + networks: + - private-testhash + - public-testhash + + cache-testhash: + image: redis:latest + networks: + - private-testhash + + logs-testhash: + image: busybox + volumes: + - /logs + + shared_service-testhash: + image: shared:latest + +networks: + public-testhash: + driver: bridge + private-testhash: + driver: bridge + +volumes: + logs-testhash: + driver: local + +configs: + app_config-testhash: + file: ./app_config.yml + +secrets: + db_password-testhash: + file: ./db_password.txt +`) as ComposeSpecification; + +test("Add suffix to all properties in compose file 2", () => { + const composeData = load(composeFile2) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllProperties(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile2); +}); + +const composeFile3 = ` +version: "3.8" + +services: + service_a: + image: service_a:latest + depends_on: + - service_b + networks: + - net_a + volumes_from: + - data_volume + links: + - service_c + extends: + service: common_service + configs: + - source: service_a_config + + service_b: + image: service_b:latest + networks: + - net_b + - net_a + + service_c: + image: service_c:latest + networks: + - net_b + + data_volume: + image: busybox + volumes: + - /data + + common_service: + image: common:latest + +networks: + net_a: + driver: bridge + net_b: + driver: bridge + +volumes: + data_volume: + driver: local + +configs: + service_a_config: + file: ./service_a_config.yml + +secrets: + service_secret: + file: ./service_secret.txt +`; + +const expectedComposeFile3 = load(` +version: "3.8" + +services: + service_a-testhash: + image: service_a:latest + depends_on: + - service_b-testhash + networks: + - net_a-testhash + volumes_from: + - data_volume-testhash + links: + - service_c-testhash + extends: + service: common_service-testhash + configs: + - source: service_a_config-testhash + + service_b-testhash: + image: service_b:latest + networks: + - net_b-testhash + - net_a-testhash + + service_c-testhash: + image: service_c:latest + networks: + - net_b-testhash + + data_volume-testhash: + image: busybox + volumes: + - /data + + common_service-testhash: + image: common:latest + +networks: + net_a-testhash: + driver: bridge + net_b-testhash: + driver: bridge + +volumes: + data_volume-testhash: + driver: local + +configs: + service_a_config-testhash: + file: ./service_a_config.yml + +secrets: + service_secret-testhash: + file: ./service_secret.txt +`) as ComposeSpecification; + +test("Add suffix to all properties in compose file 3", () => { + const composeData = load(composeFile3) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllProperties(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile3); +}); + +const composeFile = ` +version: "3.8" + +services: + plausible_db: + image: postgres:16-alpine + restart: always + volumes: + - db-data:/var/lib/postgresql/data + environment: + - POSTGRES_PASSWORD=postgres + + plausible_events_db: + image: clickhouse/clickhouse-server:24.3.3.102-alpine + restart: always + volumes: + - event-data:/var/lib/clickhouse + - event-logs:/var/log/clickhouse-server + - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro + - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro + ulimits: + nofile: + soft: 262144 + hard: 262144 + + plausible: + image: ghcr.io/plausible/community-edition:v2.1.0 + restart: always + command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run" + depends_on: + - plausible_db + - plausible_events_db + ports: + - 127.0.0.1:8000:8000 + env_file: + - plausible-conf.env + +volumes: + db-data: + driver: local + event-data: + driver: local + event-logs: + driver: local +`; + +const expectedComposeFile = load(` +version: "3.8" + +services: + plausible_db-testhash: + image: postgres:16-alpine + restart: always + volumes: + - db-data-testhash:/var/lib/postgresql/data + environment: + - POSTGRES_PASSWORD=postgres + + plausible_events_db-testhash: + image: clickhouse/clickhouse-server:24.3.3.102-alpine + restart: always + volumes: + - event-data-testhash:/var/lib/clickhouse + - event-logs-testhash:/var/log/clickhouse-server + - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro + - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro + ulimits: + nofile: + soft: 262144 + hard: 262144 + + plausible-testhash: + image: ghcr.io/plausible/community-edition:v2.1.0 + restart: always + command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run" + depends_on: + - plausible_db-testhash + - plausible_events_db-testhash + ports: + - 127.0.0.1:8000:8000 + env_file: + - plausible-conf.env + +volumes: + db-data-testhash: + driver: local + event-data-testhash: + driver: local + event-logs-testhash: + driver: local +`) as ComposeSpecification; + +test("Add suffix to all properties in Plausible compose file", () => { + const composeData = load(composeFile) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllProperties(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile); +}); diff --git a/data/apps/dokploy/__test__/compose/config/config-root.test.ts b/data/apps/dokploy/__test__/compose/config/config-root.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b40c073ee562da5cd7b26b1c94540d4208c07ca --- /dev/null +++ b/data/apps/dokploy/__test__/compose/config/config-root.test.ts @@ -0,0 +1,178 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToConfigsRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + +configs: + web-config: + file: ./web-config.yml +`; + +test("Add suffix to configs in root property", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.configs) { + return; + } + const configs = addSuffixToConfigsRoot(composeData.configs, suffix); + + expect(configs).toBeDefined(); + for (const configKey of Object.keys(configs)) { + expect(configKey).toContain(`-${suffix}`); + expect(configs[configKey]).toBeDefined(); + } +}); + +const composeFileMultipleConfigs = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web-config + target: /etc/nginx/nginx.conf + - source: another-config + target: /etc/nginx/another.conf + +configs: + web-config: + file: ./web-config.yml + another-config: + file: ./another-config.yml +`; + +test("Add suffix to multiple configs in root property", () => { + const composeData = load(composeFileMultipleConfigs) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.configs) { + return; + } + const configs = addSuffixToConfigsRoot(composeData.configs, suffix); + + expect(configs).toBeDefined(); + for (const configKey of Object.keys(configs)) { + expect(configKey).toContain(`-${suffix}`); + expect(configs[configKey]).toBeDefined(); + } + expect(configs).toHaveProperty(`web-config-${suffix}`); + expect(configs).toHaveProperty(`another-config-${suffix}`); +}); + +const composeFileDifferentProperties = ` +version: "3.8" + +services: + web: + image: nginx:latest + +configs: + web-config: + file: ./web-config.yml + special-config: + external: true +`; + +test("Add suffix to configs with different properties in root property", () => { + const composeData = load( + composeFileDifferentProperties, + ) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.configs) { + return; + } + const configs = addSuffixToConfigsRoot(composeData.configs, suffix); + + expect(configs).toBeDefined(); + for (const configKey of Object.keys(configs)) { + expect(configKey).toContain(`-${suffix}`); + expect(configs[configKey]).toBeDefined(); + } + expect(configs).toHaveProperty(`web-config-${suffix}`); + expect(configs).toHaveProperty(`special-config-${suffix}`); +}); + +const composeFileConfigRoot = ` +version: "3.8" + +services: + web: + image: nginx:latest + + app: + image: node:latest + + db: + image: postgres:latest + +configs: + web_config: + file: ./web-config.yml + + app_config: + file: ./app-config.json + + db_config: + file: ./db-config.yml +`; + +// Expected compose file con el prefijo `testhash` +const expectedComposeFileConfigRoot = load(` +version: "3.8" + +services: + web: + image: nginx:latest + + app: + image: node:latest + + db: + image: postgres:latest + +configs: + web_config-testhash: + file: ./web-config.yml + + app_config-testhash: + file: ./app-config.json + + db_config-testhash: + file: ./db-config.yml +`) as ComposeSpecification; + +test("Add suffix to configs in root property", () => { + const composeData = load(composeFileConfigRoot) as ComposeSpecification; + + const suffix = "testhash"; + + if (!composeData?.configs) { + return; + } + const configs = addSuffixToConfigsRoot(composeData.configs, suffix); + const updatedComposeData = { ...composeData, configs }; + + // Verificar que el resultado coincide con el archivo esperado + expect(updatedComposeData).toEqual(expectedComposeFileConfigRoot); +}); diff --git a/data/apps/dokploy/__test__/compose/config/config-service.test.ts b/data/apps/dokploy/__test__/compose/config/config-service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..de014eb5e986c1a6805ba50d576c53d654229b1c --- /dev/null +++ b/data/apps/dokploy/__test__/compose/config/config-service.test.ts @@ -0,0 +1,197 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToConfigsInServices } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web-config + target: /etc/nginx/nginx.conf + +configs: + web-config: + file: ./web-config.yml +`; + +test("Add suffix to configs in services", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToConfigsInServices(composeData.services, suffix); + const actualComposeData = { ...composeData, services }; + + expect(actualComposeData.services?.web?.configs).toContainEqual({ + source: `web-config-${suffix}`, + target: "/etc/nginx/nginx.conf", + }); +}); + +const composeFileSingleServiceConfig = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web-config + target: /etc/nginx/nginx.conf + +configs: + web-config: + file: ./web-config.yml +`; + +test("Add suffix to configs in services with single config", () => { + const composeData = load( + composeFileSingleServiceConfig, + ) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToConfigsInServices(composeData.services, suffix); + + expect(services).toBeDefined(); + for (const serviceKey of Object.keys(services)) { + const serviceConfigs = services?.[serviceKey]?.configs; + if (serviceConfigs) { + for (const config of serviceConfigs) { + if (typeof config === "object") { + expect(config.source).toContain(`-${suffix}`); + } + } + } + } +}); + +const composeFileMultipleServicesConfigs = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web-config + target: /etc/nginx/nginx.conf + - source: common-config + target: /etc/nginx/common.conf + + app: + image: node:14 + configs: + - source: app-config + target: /usr/src/app/config.json + - source: common-config + target: /usr/src/app/common.json + +configs: + web-config: + file: ./web-config.yml + app-config: + file: ./app-config.json + common-config: + file: ./common-config.yml +`; + +test("Add suffix to configs in services with multiple configs", () => { + const composeData = load( + composeFileMultipleServicesConfigs, + ) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToConfigsInServices(composeData.services, suffix); + + expect(services).toBeDefined(); + for (const serviceKey of Object.keys(services)) { + const serviceConfigs = services?.[serviceKey]?.configs; + if (serviceConfigs) { + for (const config of serviceConfigs) { + if (typeof config === "object") { + expect(config.source).toContain(`-${suffix}`); + } + } + } + } +}); + +const composeFileConfigServices = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config + target: /etc/nginx/nginx.conf + + app: + image: node:latest + configs: + - source: app_config + target: /usr/src/app/config.json + + db: + image: postgres:latest + configs: + - source: db_config + target: /etc/postgresql/postgresql.conf + +`; + +// Expected compose file con el prefijo `testhash` +const expectedComposeFileConfigServices = load(` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config-testhash + target: /etc/nginx/nginx.conf + + app: + image: node:latest + configs: + - source: app_config-testhash + target: /usr/src/app/config.json + + db: + image: postgres:latest + configs: + - source: db_config-testhash + target: /etc/postgresql/postgresql.conf + +`) as ComposeSpecification; + +test("Add suffix to configs in services", () => { + const composeData = load(composeFileConfigServices) as ComposeSpecification; + + const suffix = "testhash"; + + if (!composeData?.services) { + return; + } + const updatedComposeData = addSuffixToConfigsInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFileConfigServices); +}); diff --git a/data/apps/dokploy/__test__/compose/config/config.test.ts b/data/apps/dokploy/__test__/compose/config/config.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..aed3350f5bccb82c4add19bdd48d0a1254b595ff --- /dev/null +++ b/data/apps/dokploy/__test__/compose/config/config.test.ts @@ -0,0 +1,246 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToAllConfigs } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFileCombinedConfigs = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config + target: /etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config + target: /usr/src/app/config.json + + db: + image: postgres:13 + configs: + - source: db_config + target: /etc/postgresql/postgresql.conf + +configs: + web_config: + file: ./web-config.yml + + app_config: + file: ./app-config.json + + db_config: + file: ./db-config.yml +`; + +const expectedComposeFileCombinedConfigs = load(` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config-testhash + target: /etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config-testhash + target: /usr/src/app/config.json + + db: + image: postgres:13 + configs: + - source: db_config-testhash + target: /etc/postgresql/postgresql.conf + +configs: + web_config-testhash: + file: ./web-config.yml + + app_config-testhash: + file: ./app-config.json + + db_config-testhash: + file: ./db-config.yml +`) as ComposeSpecification; + +test("Add suffix to all configs in root and services", () => { + const composeData = load(composeFileCombinedConfigs) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllConfigs(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFileCombinedConfigs); +}); + +const composeFileWithEnvAndExternal = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config + target: /etc/nginx/nginx.conf + environment: + - NGINX_CONFIG=/etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config + target: /usr/src/app/config.json + + db: + image: postgres:13 + configs: + - source: db_config + target: /etc/postgresql/postgresql.conf + +configs: + web_config: + external: true + + app_config: + file: ./app-config.json + + db_config: + environment: dev + file: ./db-config.yml +`; + +const expectedComposeFileWithEnvAndExternal = load(` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config-testhash + target: /etc/nginx/nginx.conf + environment: + - NGINX_CONFIG=/etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config-testhash + target: /usr/src/app/config.json + + db: + image: postgres:13 + configs: + - source: db_config-testhash + target: /etc/postgresql/postgresql.conf + +configs: + web_config-testhash: + external: true + + app_config-testhash: + file: ./app-config.json + + db_config-testhash: + environment: dev + file: ./db-config.yml +`) as ComposeSpecification; + +test("Add suffix to configs with environment and external", () => { + const composeData = load( + composeFileWithEnvAndExternal, + ) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllConfigs(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFileWithEnvAndExternal); +}); + +const composeFileWithTemplateDriverAndLabels = ` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config + target: /etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config + target: /usr/src/app/config.json + +configs: + web_config: + file: ./web-config.yml + template_driver: golang + + app_config: + file: ./app-config.json + labels: + - app=frontend + + db_config: + file: ./db-config.yml +`; + +const expectedComposeFileWithTemplateDriverAndLabels = load(` +version: "3.8" + +services: + web: + image: nginx:latest + configs: + - source: web_config-testhash + target: /etc/nginx/nginx.conf + + app: + image: node:14 + configs: + - source: app_config-testhash + target: /usr/src/app/config.json + +configs: + web_config-testhash: + file: ./web-config.yml + template_driver: golang + + app_config-testhash: + file: ./app-config.json + labels: + - app=frontend + + db_config-testhash: + file: ./db-config.yml +`) as ComposeSpecification; + +test("Add suffix to configs with template driver and labels", () => { + const composeData = load( + composeFileWithTemplateDriverAndLabels, + ) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllConfigs(composeData, suffix); + + expect(updatedComposeData).toEqual( + expectedComposeFileWithTemplateDriverAndLabels, + ); +}); diff --git a/data/apps/dokploy/__test__/compose/domain/labels.test.ts b/data/apps/dokploy/__test__/compose/domain/labels.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c5f45810f97a078d152368a581bcd1123c491544 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/domain/labels.test.ts @@ -0,0 +1,109 @@ +import type { Domain } from "@dokploy/server"; +import { createDomainLabels } from "@dokploy/server"; +import { describe, expect, it } from "vitest"; + +describe("createDomainLabels", () => { + const appName = "test-app"; + const baseDomain: Domain = { + host: "example.com", + port: 8080, + https: false, + uniqueConfigKey: 1, + customCertResolver: null, + certificateType: "none", + applicationId: "", + composeId: "", + domainType: "compose", + serviceName: "test-app", + domainId: "", + path: "/", + createdAt: "", + previewDeploymentId: "", + }; + + it("should create basic labels for web entrypoint", async () => { + const labels = await createDomainLabels(appName, baseDomain, "web"); + expect(labels).toEqual([ + "traefik.http.routers.test-app-1-web.rule=Host(`example.com`)", + "traefik.http.routers.test-app-1-web.entrypoints=web", + "traefik.http.services.test-app-1-web.loadbalancer.server.port=8080", + "traefik.http.routers.test-app-1-web.service=test-app-1-web", + ]); + }); + + it("should create labels for websecure entrypoint", async () => { + const labels = await createDomainLabels(appName, baseDomain, "websecure"); + expect(labels).toEqual([ + "traefik.http.routers.test-app-1-websecure.rule=Host(`example.com`)", + "traefik.http.routers.test-app-1-websecure.entrypoints=websecure", + "traefik.http.services.test-app-1-websecure.loadbalancer.server.port=8080", + "traefik.http.routers.test-app-1-websecure.service=test-app-1-websecure", + ]); + }); + + it("should add the path prefix if is different than / empty", async () => { + const labels = await createDomainLabels( + appName, + { + ...baseDomain, + path: "/hello", + }, + "websecure", + ); + + expect(labels).toEqual([ + "traefik.http.routers.test-app-1-websecure.rule=Host(`example.com`) && PathPrefix(`/hello`)", + "traefik.http.routers.test-app-1-websecure.entrypoints=websecure", + "traefik.http.services.test-app-1-websecure.loadbalancer.server.port=8080", + "traefik.http.routers.test-app-1-websecure.service=test-app-1-websecure", + ]); + }); + + it("should add redirect middleware for https on web entrypoint", async () => { + const httpsBaseDomain = { ...baseDomain, https: true }; + const labels = await createDomainLabels(appName, httpsBaseDomain, "web"); + expect(labels).toContain( + "traefik.http.routers.test-app-1-web.middlewares=redirect-to-https@file", + ); + }); + + it("should add Let's Encrypt configuration for websecure with letsencrypt certificate", async () => { + const letsencryptDomain = { + ...baseDomain, + https: true, + certificateType: "letsencrypt" as const, + }; + const labels = await createDomainLabels( + appName, + letsencryptDomain, + "websecure", + ); + expect(labels).toContain( + "traefik.http.routers.test-app-1-websecure.tls.certresolver=letsencrypt", + ); + }); + + it("should not add Let's Encrypt configuration for non-letsencrypt certificate", async () => { + const nonLetsencryptDomain = { + ...baseDomain, + https: true, + certificateType: "none" as const, + }; + const labels = await createDomainLabels( + appName, + nonLetsencryptDomain, + "websecure", + ); + expect(labels).not.toContain( + "traefik.http.routers.test-app-1-websecure.tls.certresolver=letsencrypt", + ); + }); + + it("should handle different ports correctly", async () => { + const customPortDomain = { ...baseDomain, port: 3000 }; + const labels = await createDomainLabels(appName, customPortDomain, "web"); + expect(labels).toContain( + "traefik.http.services.test-app-1-web.loadbalancer.server.port=3000", + ); + }); +}); diff --git a/data/apps/dokploy/__test__/compose/domain/network-root.test.ts b/data/apps/dokploy/__test__/compose/domain/network-root.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..73b850a4579144d97eb9f6a01bb414bb555ef478 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/domain/network-root.test.ts @@ -0,0 +1,29 @@ +import { addDokployNetworkToRoot } from "@dokploy/server"; +import { describe, expect, it } from "vitest"; + +describe("addDokployNetworkToRoot", () => { + it("should create network object if networks is undefined", () => { + const result = addDokployNetworkToRoot(undefined); + expect(result).toEqual({ "dokploy-network": { external: true } }); + }); + + it("should add network to an empty object", () => { + const result = addDokployNetworkToRoot({}); + expect(result).toEqual({ "dokploy-network": { external: true } }); + }); + + it("should not modify existing network configuration", () => { + const existing = { "dokploy-network": { external: false } }; + const result = addDokployNetworkToRoot(existing); + expect(result).toEqual({ "dokploy-network": { external: true } }); + }); + + it("should add network alongside existing networks", () => { + const existing = { "other-network": { external: true } }; + const result = addDokployNetworkToRoot(existing); + expect(result).toEqual({ + "other-network": { external: true }, + "dokploy-network": { external: true }, + }); + }); +}); diff --git a/data/apps/dokploy/__test__/compose/domain/network-service.test.ts b/data/apps/dokploy/__test__/compose/domain/network-service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8d03c75141ae12b8ed3ef1c062b43c6ea5d9ef8 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/domain/network-service.test.ts @@ -0,0 +1,24 @@ +import { addDokployNetworkToService } from "@dokploy/server"; +import { describe, expect, it } from "vitest"; + +describe("addDokployNetworkToService", () => { + it("should add network to an empty array", () => { + const result = addDokployNetworkToService([]); + expect(result).toEqual(["dokploy-network"]); + }); + + it("should not add duplicate network to an array", () => { + const result = addDokployNetworkToService(["dokploy-network"]); + expect(result).toEqual(["dokploy-network"]); + }); + + it("should add network to an existing array with other networks", () => { + const result = addDokployNetworkToService(["other-network"]); + expect(result).toEqual(["other-network", "dokploy-network"]); + }); + + it("should add network to an object if networks is an object", () => { + const result = addDokployNetworkToService({ "other-network": {} }); + expect(result).toEqual({ "other-network": {}, "dokploy-network": {} }); + }); +}); diff --git a/data/apps/dokploy/__test__/compose/network/network-root.test.ts b/data/apps/dokploy/__test__/compose/network/network-root.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..980502fff8ab00a5b0550b0fe89dcb0af85571c5 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/network/network-root.test.ts @@ -0,0 +1,310 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToNetworksRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + +networks: + frontend: + driver: bridge + driver_opts: + com.docker.network.driver.mtu: 1200 + + backend: + driver: bridge + attachable: true + + external_network: + external: true + +`; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +test("Add suffix to networks root property", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const volumeKey of Object.keys(networks)) { + expect(volumeKey).toContain(`-${suffix}`); + } +}); + +const composeFile2 = ` +version: "3.8" + +services: + app: + image: myapp:latest + networks: + - app_net + +networks: + app_net: + driver: bridge + driver_opts: + com.docker.network.driver.mtu: 1500 + ipam: + driver: default + config: + - subnet: 172.20.0.0/16 + + database_net: + driver: overlay + attachable: true + + monitoring_net: + driver: bridge + internal: true +`; + +test("Add suffix to advanced networks root property (2 TRY)", () => { + const composeData = load(composeFile2) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const networkKey of Object.keys(networks)) { + expect(networkKey).toContain(`-${suffix}`); + } +}); + +const composeFile3 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + +networks: + frontend: + external: + name: my_external_network + + backend: + driver: bridge + labels: + - "com.example.description=Backend network" + - "com.example.environment=production" + + external_network: + external: true +`; + +test("Add suffix to networks with external properties", () => { + const composeData = load(composeFile3) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const networkKey of Object.keys(networks)) { + expect(networkKey).toContain(`-${suffix}`); + } +}); + +const composeFile4 = ` +version: "3.8" + +services: + db: + image: postgres:13 + networks: + - db_net + +networks: + db_net: + driver: bridge + ipam: + config: + - subnet: 192.168.1.0/24 + - gateway: 192.168.1.1 + - aux_addresses: + host1: 192.168.1.2 + host2: 192.168.1.3 + + external_network: + external: true +`; + +test("Add suffix to networks with IPAM configurations", () => { + const composeData = load(composeFile4) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const networkKey of Object.keys(networks)) { + expect(networkKey).toContain(`-${suffix}`); + } +}); + +const composeFile5 = ` +version: "3.8" + +services: + api: + image: myapi:latest + networks: + - api_net + +networks: + api_net: + driver: bridge + options: + com.docker.network.bridge.name: br0 + enable_ipv6: true + ipam: + driver: default + config: + - subnet: "2001:db8:1::/64" + - gateway: "2001:db8:1::1" + + external_network: + external: true +`; + +test("Add suffix to networks with custom options", () => { + const composeData = load(composeFile5) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const networkKey of Object.keys(networks)) { + expect(networkKey).toContain(`-${suffix}`); + } +}); + +const composeFile6 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + +networks: + frontend: + driver: bridge + driver_opts: + com.docker.network.driver.mtu: 1200 + + backend: + driver: bridge + attachable: true + + external_network: + external: true +`; + +// Expected compose file with static suffix `testhash` +const expectedComposeFile6 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend-testhash + +networks: + frontend-testhash: + driver: bridge + driver_opts: + com.docker.network.driver.mtu: 1200 + + backend-testhash: + driver: bridge + attachable: true + + external_network-testhash: + external: true +`; + +test("Add suffix to networks with static suffix", () => { + const composeData = load(composeFile6) as ComposeSpecification; + + const suffix = "testhash"; + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + const expectedComposeData = load( + expectedComposeFile6, + ) as ComposeSpecification; + expect(networks).toStrictEqual(expectedComposeData.networks); +}); + +const composeFile7 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - dokploy-network + +networks: + dokploy-network: +`; + +test("It shoudn't add suffix to dokploy-network", () => { + const composeData = load(composeFile7) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.networks) { + return; + } + const networks = addSuffixToNetworksRoot(composeData.networks, suffix); + + expect(networks).toBeDefined(); + for (const networkKey of Object.keys(networks)) { + expect(networkKey).toContain("dokploy-network"); + } +}); diff --git a/data/apps/dokploy/__test__/compose/network/network-service.test.ts b/data/apps/dokploy/__test__/compose/network/network-service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee07d9de96bd1dd86c46878dd9b2592a26279e02 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/network/network-service.test.ts @@ -0,0 +1,273 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNetworks } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + + api: + image: myapi:latest + networks: + - backend +`; + +test("Add suffix to networks in services", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToServiceNetworks(composeData.services, suffix); + const actualComposeData = { ...composeData, services }; + + expect(actualComposeData?.services?.web?.networks).toContain( + `frontend-${suffix}`, + ); + + expect(actualComposeData?.services?.api?.networks).toContain( + `backend-${suffix}`, + ); + + const apiNetworks = actualComposeData?.services?.api?.networks; + + expect(apiNetworks).toBeDefined(); + expect(actualComposeData?.services?.api?.networks).toContain( + `backend-${suffix}`, + ); +}); + +// Caso 2: Objeto con aliases +const composeFile2 = ` +version: "3.8" + +services: + api: + image: myapi:latest + networks: + frontend: + aliases: + - api + +networks: + frontend: + driver: bridge +`; + +test("Add suffix to networks in services with aliases", () => { + const composeData = load(composeFile2) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToServiceNetworks(composeData.services, suffix); + const actualComposeData = { ...composeData, services }; + + expect(actualComposeData.services?.api?.networks).toHaveProperty( + `frontend-${suffix}`, + ); + + const networkConfig = actualComposeData?.services?.api?.networks as { + [key: string]: { aliases?: string[] }; + }; + expect(networkConfig[`frontend-${suffix}`]).toBeDefined(); + expect(networkConfig[`frontend-${suffix}`]?.aliases).toContain("api"); + + expect(actualComposeData.services?.api?.networks).not.toHaveProperty( + "frontend-ash", + ); +}); + +const composeFile3 = ` +version: "3.8" + +services: + redis: + image: redis:alpine + networks: + backend: + +networks: + backend: + driver: bridge +`; + +test("Add suffix to networks in services (Object with simple networks)", () => { + const composeData = load(composeFile3) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToServiceNetworks(composeData.services, suffix); + const actualComposeData = { ...composeData, services }; + + expect(actualComposeData.services?.redis?.networks).toHaveProperty( + `backend-${suffix}`, + ); +}); + +const composeFileCombined = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + + api: + image: myapi:latest + networks: + frontend: + aliases: + - api + + redis: + image: redis:alpine + networks: + backend: + +networks: + frontend: + driver: bridge + + backend: + driver: bridge +`; + +test("Add suffix to networks in services (combined case)", () => { + const composeData = load(composeFileCombined) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const services = addSuffixToServiceNetworks(composeData.services, suffix); + const actualComposeData = { ...composeData, services }; + + // Caso 1: ListOfStrings + expect(actualComposeData.services?.web?.networks).toContain( + `frontend-${suffix}`, + ); + expect(actualComposeData.services?.web?.networks).toContain( + `backend-${suffix}`, + ); + + // Caso 2: Objeto con aliases + const apiNetworks = actualComposeData.services?.api?.networks as { + [key: string]: unknown; + }; + expect(apiNetworks).toHaveProperty(`frontend-${suffix}`); + expect(apiNetworks[`frontend-${suffix}`]).toBeDefined(); + expect(apiNetworks).not.toHaveProperty("frontend"); + + // Caso 3: Objeto con redes simples + const redisNetworks = actualComposeData.services?.redis?.networks; + expect(redisNetworks).toHaveProperty(`backend-${suffix}`); + expect(redisNetworks).not.toHaveProperty("backend"); +}); + +const composeFile7 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - dokploy-network +`; + +test("It shoudn't add suffix to dokploy-network in services", () => { + const composeData = load(composeFile7) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const networks = addSuffixToServiceNetworks(composeData.services, suffix); + const service = networks.web; + + expect(service).toBeDefined(); + expect(service?.networks).toContain("dokploy-network"); +}); + +const composeFile8 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + - dokploy-network + + + api: + image: myapi:latest + networks: + frontend: + aliases: + - api + dokploy-network: + aliases: + - api + redis: + image: redis:alpine + networks: + dokploy-network: + db: + image: myapi:latest + networks: + dokploy-network: + aliases: + - apid + +`; + +test("It shoudn't add suffix to dokploy-network in services multiples cases", () => { + const composeData = load(composeFile8) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.services) { + return; + } + const networks = addSuffixToServiceNetworks(composeData.services, suffix); + const service = networks.web; + const api = networks.api; + const redis = networks.redis; + const db = networks.db; + + const dbNetworks = db?.networks as { + [key: string]: unknown; + }; + + const apiNetworks = api?.networks as { + [key: string]: unknown; + }; + + expect(service).toBeDefined(); + expect(service?.networks).toContain("dokploy-network"); + + expect(redis?.networks).toHaveProperty("dokploy-network"); + expect(dbNetworks["dokploy-network"]).toBeDefined(); + expect(apiNetworks["dokploy-network"]).toBeDefined(); +}); diff --git a/data/apps/dokploy/__test__/compose/network/network.test.ts b/data/apps/dokploy/__test__/compose/network/network.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..39cf03958877815b46cf5a78ad84bd666b501050 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/network/network.test.ts @@ -0,0 +1,334 @@ +import { generateRandomHash } from "@dokploy/server"; +import { + addSuffixToAllNetworks, + addSuffixToServiceNetworks, +} from "@dokploy/server"; +import { addSuffixToNetworksRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFileCombined = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + + api: + image: myapi:latest + networks: + frontend: + aliases: + - api + + redis: + image: redis:alpine + networks: + backend: + +networks: + frontend: + driver: bridge + + backend: + driver: bridge +`; + +test("Add suffix to networks in services and root (combined case)", () => { + const composeData = load(composeFileCombined) as ComposeSpecification; + + const suffix = generateRandomHash(); + + // Prefijo para redes definidas en el root + if (composeData.networks) { + composeData.networks = addSuffixToNetworksRoot( + composeData.networks, + suffix, + ); + } + + // Prefijo para redes definidas en los servicios + if (composeData.services) { + composeData.services = addSuffixToServiceNetworks( + composeData.services, + suffix, + ); + } + + const actualComposeData = { ...composeData }; + + // Verificar redes en root + expect(actualComposeData.networks).toHaveProperty(`frontend-${suffix}`); + expect(actualComposeData.networks).toHaveProperty(`backend-${suffix}`); + expect(actualComposeData.networks).not.toHaveProperty("frontend"); + expect(actualComposeData.networks).not.toHaveProperty("backend"); + + // Caso 1: ListOfStrings + expect(actualComposeData.services?.web?.networks).toContain( + `frontend-${suffix}`, + ); + expect(actualComposeData.services?.web?.networks).toContain( + `backend-${suffix}`, + ); + + // Caso 2: Objeto con aliases + const apiNetworks = actualComposeData.services?.api?.networks as { + [key: string]: { aliases?: string[] }; + }; + expect(apiNetworks).toHaveProperty(`frontend-${suffix}`); + expect(apiNetworks?.[`frontend-${suffix}`]?.aliases).toContain("api"); + expect(apiNetworks).not.toHaveProperty("frontend"); + + // Caso 3: Objeto con redes simples + const redisNetworks = actualComposeData.services?.redis?.networks; + expect(redisNetworks).toHaveProperty(`backend-${suffix}`); + expect(redisNetworks).not.toHaveProperty("backend"); +}); + +const expectedComposeFile = load(` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend-testhash + - backend-testhash + + api: + image: myapi:latest + networks: + frontend-testhash: + aliases: + - api + + redis: + image: redis:alpine + networks: + backend-testhash: + +networks: + frontend-testhash: + driver: bridge + + backend-testhash: + driver: bridge +`); + +test("Add suffix to networks in compose file", () => { + const composeData = load(composeFileCombined) as ComposeSpecification; + + const suffix = "testhash"; + if (!composeData?.networks) { + return; + } + const updatedComposeData = addSuffixToAllNetworks(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile); +}); + +const composeFile2 = ` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend + - backend + + db: + image: postgres:latest + networks: + backend: + aliases: + - db + +networks: + frontend: + external: true + + backend: + driver: bridge +`; + +const expectedComposeFile2 = load(` +version: "3.8" + +services: + web: + image: nginx:latest + networks: + - frontend-testhash + - backend-testhash + + db: + image: postgres:latest + networks: + backend-testhash: + aliases: + - db + +networks: + frontend-testhash: + external: true + + backend-testhash: + driver: bridge +`); + +test("Add suffix to networks in compose file with external and internal networks", () => { + const composeData = load(composeFile2) as ComposeSpecification; + + const suffix = "testhash"; + const updatedComposeData = addSuffixToAllNetworks(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile2); +}); + +const composeFile3 = ` +version: "3.8" + +services: + app: + image: myapp:latest + networks: + frontend: + aliases: + - app + backend: + + worker: + image: worker:latest + networks: + - backend + +networks: + frontend: + driver: bridge + attachable: true + + backend: + driver: bridge + driver_opts: + com.docker.network.bridge.enable_icc: "true" +`; + +const expectedComposeFile3 = load(` +version: "3.8" + +services: + app: + image: myapp:latest + networks: + frontend-testhash: + aliases: + - app + backend-testhash: + + worker: + image: worker:latest + networks: + - backend-testhash + +networks: + frontend-testhash: + driver: bridge + attachable: true + + backend-testhash: + driver: bridge + driver_opts: + com.docker.network.bridge.enable_icc: "true" +`); + +test("Add suffix to networks in compose file with multiple services and complex network configurations", () => { + const composeData = load(composeFile3) as ComposeSpecification; + + const suffix = "testhash"; + const updatedComposeData = addSuffixToAllNetworks(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile3); +}); + +const composeFile4 = ` +version: "3.8" + +services: + app: + image: myapp:latest + networks: + frontend: + aliases: + - app + backend: + dokploy-network: + + worker: + image: worker:latest + networks: + - backend + - dokploy-network + +networks: + frontend: + driver: bridge + attachable: true + + backend: + driver: bridge + driver_opts: + com.docker.network.bridge.enable_icc: "true" + + dokploy-network: + driver: bridge + +`; + +const expectedComposeFile4 = load(` +version: "3.8" + +services: + app: + image: myapp:latest + networks: + frontend-testhash: + aliases: + - app + backend-testhash: + dokploy-network: + + worker: + image: worker:latest + networks: + - backend-testhash + - dokploy-network + +networks: + frontend-testhash: + driver: bridge + attachable: true + + backend-testhash: + driver: bridge + driver_opts: + com.docker.network.bridge.enable_icc: "true" + + dokploy-network: + driver: bridge + + + +`); + +test("Expect don't add suffix to dokploy-network in compose file with multiple services and complex network configurations", () => { + const composeData = load(composeFile4) as ComposeSpecification; + + const suffix = "testhash"; + const updatedComposeData = addSuffixToAllNetworks(composeData, suffix); + expect(updatedComposeData).toEqual(expectedComposeFile4); +}); diff --git a/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b1898c59c9f10fde825a35fb481cae7a9eecce8 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/secrets/secret-root.test.ts @@ -0,0 +1,103 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToSecretsRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFileSecretsRoot = ` +version: "3.8" + +services: + web: + image: nginx:latest + +secrets: + db_password: + file: ./db_password.txt +`; + +test("Add suffix to secrets in root property", () => { + const composeData = load(composeFileSecretsRoot) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData?.secrets) { + return; + } + const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix); + expect(secrets).toBeDefined(); + if (secrets) { + for (const secretKey of Object.keys(secrets)) { + expect(secretKey).toContain(`-${suffix}`); + expect(secrets[secretKey]).toBeDefined(); + } + } +}); + +const composeFileSecretsRoot1 = ` +version: "3.8" + +services: + api: + image: myapi:latest + +secrets: + api_key: + file: ./api_key.txt +`; + +test("Add suffix to secrets in root property (Test 1)", () => { + const composeData = load(composeFileSecretsRoot1) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData?.secrets) { + return; + } + const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix); + expect(secrets).toBeDefined(); + + if (secrets) { + for (const secretKey of Object.keys(secrets)) { + expect(secretKey).toContain(`-${suffix}`); + expect(secrets[secretKey]).toBeDefined(); + } + } +}); + +const composeFileSecretsRoot2 = ` +version: "3.8" + +services: + frontend: + image: nginx:latest + +secrets: + frontend_secret: + file: ./frontend_secret.txt + db_password: + external: true +`; + +test("Add suffix to secrets in root property (Test 2)", () => { + const composeData = load(composeFileSecretsRoot2) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData?.secrets) { + return; + } + const secrets = addSuffixToSecretsRoot(composeData.secrets, suffix); + expect(secrets).toBeDefined(); + + if (secrets) { + for (const secretKey of Object.keys(secrets)) { + expect(secretKey).toContain(`-${suffix}`); + expect(secrets[secretKey]).toBeDefined(); + } + } +}); diff --git a/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5206bbbaf1ecd44e1ada3c625ead512734259159 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/secrets/secret-services.test.ts @@ -0,0 +1,113 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToSecretsInServices } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFileSecretsServices = ` +version: "3.8" + +services: + db: + image: postgres:latest + secrets: + - db_password + +secrets: + db_password: + file: ./db_password.txt +`; + +test("Add suffix to secrets in services", () => { + const composeData = load(composeFileSecretsServices) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + + const updatedComposeData = addSuffixToSecretsInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData.services?.db?.secrets).toContain( + `db_password-${suffix}`, + ); +}); + +const composeFileSecretsServices1 = ` +version: "3.8" + +services: + app: + image: node:14 + secrets: + - app_secret + +secrets: + app_secret: + file: ./app_secret.txt +`; + +test("Add suffix to secrets in services (Test 1)", () => { + const composeData = load(composeFileSecretsServices1) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + + const updatedComposeData = addSuffixToSecretsInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData.services?.app?.secrets).toContain( + `app_secret-${suffix}`, + ); +}); + +const composeFileSecretsServices2 = ` +version: "3.8" + +services: + backend: + image: backend:latest + secrets: + - backend_secret + frontend: + image: frontend:latest + secrets: + - frontend_secret + +secrets: + backend_secret: + file: ./backend_secret.txt + frontend_secret: + file: ./frontend_secret.txt +`; + +test("Add suffix to secrets in services (Test 2)", () => { + const composeData = load(composeFileSecretsServices2) as ComposeSpecification; + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + + const updatedComposeData = addSuffixToSecretsInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData.services?.backend?.secrets).toContain( + `backend_secret-${suffix}`, + ); + expect(actualComposeData.services?.frontend?.secrets).toContain( + `frontend_secret-${suffix}`, + ); +}); diff --git a/data/apps/dokploy/__test__/compose/secrets/secret.test.ts b/data/apps/dokploy/__test__/compose/secrets/secret.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d874dc5e786758043f3ce9143ab1db6b6d81100d --- /dev/null +++ b/data/apps/dokploy/__test__/compose/secrets/secret.test.ts @@ -0,0 +1,159 @@ +import { addSuffixToAllSecrets } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFileCombinedSecrets = ` +version: "3.8" + +services: + web: + image: nginx:latest + secrets: + - web_secret + + app: + image: node:14 + secrets: + - app_secret + +secrets: + web_secret: + file: ./web_secret.txt + + app_secret: + file: ./app_secret.txt +`; + +const expectedComposeFileCombinedSecrets = load(` +version: "3.8" + +services: + web: + image: nginx:latest + secrets: + - web_secret-testhash + + app: + image: node:14 + secrets: + - app_secret-testhash + +secrets: + web_secret-testhash: + file: ./web_secret.txt + + app_secret-testhash: + file: ./app_secret.txt +`) as ComposeSpecification; + +test("Add suffix to all secrets", () => { + const composeData = load(composeFileCombinedSecrets) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllSecrets(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets); +}); + +const composeFileCombinedSecrets3 = ` +version: "3.8" + +services: + api: + image: myapi:latest + secrets: + - api_key + + cache: + image: redis:latest + secrets: + - cache_secret + +secrets: + api_key: + file: ./api_key.txt + cache_secret: + file: ./cache_secret.txt +`; + +const expectedComposeFileCombinedSecrets3 = load(` +version: "3.8" + +services: + api: + image: myapi:latest + secrets: + - api_key-testhash + + cache: + image: redis:latest + secrets: + - cache_secret-testhash + +secrets: + api_key-testhash: + file: ./api_key.txt + cache_secret-testhash: + file: ./cache_secret.txt +`) as ComposeSpecification; + +test("Add suffix to all secrets (3rd Case)", () => { + const composeData = load(composeFileCombinedSecrets3) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllSecrets(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets3); +}); + +const composeFileCombinedSecrets4 = ` +version: "3.8" + +services: + web: + image: nginx:latest + secrets: + - web_secret + + db: + image: postgres:latest + secrets: + - db_password + +secrets: + web_secret: + file: ./web_secret.txt + db_password: + file: ./db_password.txt +`; + +const expectedComposeFileCombinedSecrets4 = load(` +version: "3.8" + +services: + web: + image: nginx:latest + secrets: + - web_secret-testhash + + db: + image: postgres:latest + secrets: + - db_password-testhash + +secrets: + web_secret-testhash: + file: ./web_secret.txt + db_password-testhash: + file: ./db_password.txt +`) as ComposeSpecification; + +test("Add suffix to all secrets (4th Case)", () => { + const composeData = load(composeFileCombinedSecrets4) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllSecrets(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFileCombinedSecrets4); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts b/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcb51fd0435a80d9672ca69a13050173bf50a3be --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service-container-name.test.ts @@ -0,0 +1,59 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + container_name: web_container + + api: + image: myapi:latest + +networks: + default: + driver: bridge +`; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +test("Add suffix to service names with container_name in compose file", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que el nombre del contenedor ha cambiado correctamente + expect(actualComposeData.services?.[`web-${suffix}`]?.container_name).toBe( + `web_container-${suffix}`, + ); + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts b/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b27414be5330b5a375722852bbd9d569aa430952 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service-depends-on.test.ts @@ -0,0 +1,150 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile4 = ` +version: "3.8" + +services: + web: + image: nginx:latest + depends_on: + - db + - api + + api: + image: myapi:latest + + db: + image: postgres:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with depends_on (array) in compose file", () => { + const composeData = load(composeFile4) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que los nombres en depends_on tienen el prefijo + expect(actualComposeData.services?.[`web-${suffix}`]?.depends_on).toContain( + `db-${suffix}`, + ); + expect(actualComposeData.services?.[`web-${suffix}`]?.depends_on).toContain( + `api-${suffix}`, + ); + + // Verificar que los servicios `db` y `api` también tienen el prefijo + expect(actualComposeData.services).toHaveProperty(`db-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("db"); + expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe( + "postgres:latest", + ); + expect(actualComposeData.services).toHaveProperty(`api-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("api"); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); +}); + +const composeFile5 = ` +version: "3.8" + +services: + web: + image: nginx:latest + depends_on: + db: + condition: service_healthy + api: + condition: service_started + + api: + image: myapi:latest + + db: + image: postgres:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with depends_on (object) in compose file", () => { + const composeData = load(composeFile5) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que los nombres en depends_on tienen el prefijo + const webDependsOn = actualComposeData.services?.[`web-${suffix}`] + ?.depends_on as Record; + expect(webDependsOn).toHaveProperty(`db-${suffix}`); + expect(webDependsOn).toHaveProperty(`api-${suffix}`); + expect(webDependsOn[`db-${suffix}`].condition).toBe("service_healthy"); + expect(webDependsOn[`api-${suffix}`].condition).toBe("service_started"); + + // Verificar que los servicios `db` y `api` también tienen el prefijo + expect(actualComposeData.services).toHaveProperty(`db-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("db"); + expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe( + "postgres:latest", + ); + expect(actualComposeData.services).toHaveProperty(`api-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("api"); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service-extends.test.ts b/data/apps/dokploy/__test__/compose/service/service-extends.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8309a32fd4fa3d75c6b38b9a47f690da97b85cde --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service-extends.test.ts @@ -0,0 +1,131 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile6 = ` +version: "3.8" + +services: + web: + image: nginx:latest + extends: base_service + + api: + image: myapi:latest + + base_service: + image: base:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with extends (string) in compose file", () => { + const composeData = load(composeFile6) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que el nombre en extends tiene el prefijo + expect(actualComposeData.services?.[`web-${suffix}`]?.extends).toBe( + `base_service-${suffix}`, + ); + + // Verificar que el servicio `base_service` también tiene el prefijo + expect(actualComposeData.services).toHaveProperty(`base_service-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("base_service"); + expect(actualComposeData.services?.[`base_service-${suffix}`]?.image).toBe( + "base:latest", + ); +}); + +const composeFile7 = ` +version: "3.8" + +services: + web: + image: nginx:latest + extends: + service: base_service + file: docker-compose.base.yml + + api: + image: myapi:latest + + base_service: + image: base:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with extends (object) in compose file", () => { + const composeData = load(composeFile7) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que el nombre en extends.service tiene el prefijo + const webExtends = actualComposeData.services?.[`web-${suffix}`]?.extends; + if (typeof webExtends !== "string") { + expect(webExtends?.service).toBe(`base_service-${suffix}`); + } + + // Verificar que el servicio `base_service` también tiene el prefijo + expect(actualComposeData.services).toHaveProperty(`base_service-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("base_service"); + expect(actualComposeData.services?.[`base_service-${suffix}`]?.image).toBe( + "base:latest", + ); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service-links.test.ts b/data/apps/dokploy/__test__/compose/service/service-links.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f9b01ab28d524225c18d6c52c2659e4ff44970c --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service-links.test.ts @@ -0,0 +1,76 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile2 = ` +version: "3.8" + +services: + web: + image: nginx:latest + links: + - db + + api: + image: myapi:latest + + db: + image: postgres:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with links in compose file", () => { + const composeData = load(composeFile2) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que los nombres en links tienen el prefijo + expect(actualComposeData.services?.[`web-${suffix}`]?.links).toContain( + `db-${suffix}`, + ); + + // Verificar que los servicios `db` y `api` también tienen el prefijo + expect(actualComposeData.services).toHaveProperty(`db-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("db"); + expect(actualComposeData.services?.[`db-${suffix}`]?.image).toBe( + "postgres:latest", + ); + expect(actualComposeData.services).toHaveProperty(`api-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("api"); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service-names.test.ts b/data/apps/dokploy/__test__/compose/service/service-names.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..936a32ecc2036dc88390146dee7eabe9a7756ef7 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service-names.test.ts @@ -0,0 +1,49 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + + api: + image: myapi:latest + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names in compose file", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que los nombres de los servicios han cambiado correctamente + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).toHaveProperty(`api-${suffix}`); + // Verificar que las claves originales no existen + expect(actualComposeData.services).not.toHaveProperty("web"); + expect(actualComposeData.services).not.toHaveProperty("api"); +}); diff --git a/data/apps/dokploy/__test__/compose/service/service.test.ts b/data/apps/dokploy/__test__/compose/service/service.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6050f75a2e4fd1248398c3bd15236996ad6573d --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/service.test.ts @@ -0,0 +1,375 @@ +import { + addSuffixToAllServiceNames, + addSuffixToServiceNames, +} from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFileCombinedAllCases = ` +version: "3.8" + +services: + web: + image: nginx:latest + container_name: web_container + links: + - api + depends_on: + - api + extends: base_service + + api: + image: myapi:latest + depends_on: + db: + condition: service_healthy + volumes_from: + - db + + db: + image: postgres:latest + + base_service: + image: base:latest + +networks: + default: + driver: bridge +`; + +const expectedComposeFile = load(` +version: "3.8" + +services: + web-testhash: + image: nginx:latest + container_name: web_container-testhash + links: + - api-testhash + depends_on: + - api-testhash + extends: base_service-testhash + + api-testhash: + image: myapi:latest + depends_on: + db-testhash: + condition: service_healthy + volumes_from: + - db-testhash + + db-testhash: + image: postgres:latest + + base_service-testhash: + image: base:latest + +networks: + default: + driver: bridge +`); + +test("Add suffix to all service names in compose file", () => { + const composeData = load(composeFileCombinedAllCases) as ComposeSpecification; + + const suffix = "testhash"; + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFile); +}); + +const composeFile1 = ` +version: "3.8" + +services: + web: + image: nginx:latest + container_name: web_container + depends_on: + - app + networks: + - frontend + volumes_from: + - data + links: + - db + extends: + service: base_service + + app: + image: node:14 + networks: + - backend + - frontend + + db: + image: postgres:13 + networks: + - backend + + data: + image: busybox + volumes: + - /data + + base_service: + image: base:latest + +networks: + frontend: + driver: bridge + backend: + driver: bridge +`; + +const expectedComposeFile1 = load(` +version: "3.8" + +services: + web-testhash: + image: nginx:latest + container_name: web_container-testhash + depends_on: + - app-testhash + networks: + - frontend + volumes_from: + - data-testhash + links: + - db-testhash + extends: + service: base_service-testhash + + app-testhash: + image: node:14 + networks: + - backend + - frontend + + db-testhash: + image: postgres:13 + networks: + - backend + + data-testhash: + image: busybox + volumes: + - /data + + base_service-testhash: + image: base:latest + +networks: + frontend: + driver: bridge + backend: + driver: bridge +`) as ComposeSpecification; + +test("Add suffix to all service names in compose file 1", () => { + const composeData = load(composeFile1) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile1); +}); + +const composeFile2 = ` +version: "3.8" + +services: + frontend: + image: nginx:latest + depends_on: + - backend + networks: + - public + volumes_from: + - logs + links: + - cache + extends: + service: shared_service + + backend: + image: node:14 + networks: + - private + - public + + cache: + image: redis:latest + networks: + - private + + logs: + image: busybox + volumes: + - /logs + + shared_service: + image: shared:latest + +networks: + public: + driver: bridge + private: + driver: bridge +`; + +const expectedComposeFile2 = load(` +version: "3.8" + +services: + frontend-testhash: + image: nginx:latest + depends_on: + - backend-testhash + networks: + - public + volumes_from: + - logs-testhash + links: + - cache-testhash + extends: + service: shared_service-testhash + + backend-testhash: + image: node:14 + networks: + - private + - public + + cache-testhash: + image: redis:latest + networks: + - private + + logs-testhash: + image: busybox + volumes: + - /logs + + shared_service-testhash: + image: shared:latest + +networks: + public: + driver: bridge + private: + driver: bridge +`) as ComposeSpecification; + +test("Add suffix to all service names in compose file 2", () => { + const composeData = load(composeFile2) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile2); +}); + +const composeFile3 = ` +version: "3.8" + +services: + service_a: + image: service_a:latest + depends_on: + - service_b + networks: + - net_a + volumes_from: + - data_volume + links: + - service_c + extends: + service: common_service + + service_b: + image: service_b:latest + networks: + - net_b + - net_a + + service_c: + image: service_c:latest + networks: + - net_b + + data_volume: + image: busybox + volumes: + - /data + + common_service: + image: common:latest + +networks: + net_a: + driver: bridge + net_b: + driver: bridge +`; + +const expectedComposeFile3 = load(` +version: "3.8" + +services: + service_a-testhash: + image: service_a:latest + depends_on: + - service_b-testhash + networks: + - net_a + volumes_from: + - data_volume-testhash + links: + - service_c-testhash + extends: + service: common_service-testhash + + service_b-testhash: + image: service_b:latest + networks: + - net_b + - net_a + + service_c-testhash: + image: service_c:latest + networks: + - net_b + + data_volume-testhash: + image: busybox + volumes: + - /data + + common_service-testhash: + image: common:latest + +networks: + net_a: + driver: bridge + net_b: + driver: bridge +`) as ComposeSpecification; + +test("Add suffix to all service names in compose file 3", () => { + const composeData = load(composeFile3) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllServiceNames(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedComposeFile3); +}); diff --git a/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts b/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8066a6dd7dfd1ab62a12628cc57abb4908127391 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/service/sevice-volumes-from.test.ts @@ -0,0 +1,78 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToServiceNames } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile3 = ` +version: "3.8" + +services: + web: + image: nginx:latest + volumes_from: + - shared + + api: + image: myapi:latest + volumes_from: + - shared + + shared: + image: busybox + volumes: + - /data + +networks: + default: + driver: bridge +`; + +test("Add suffix to service names with volumes_from in compose file", () => { + const composeData = load(composeFile3) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + const updatedComposeData = addSuffixToServiceNames( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + // Verificar que la nueva clave del servicio tiene el prefijo y la vieja clave no existe + expect(actualComposeData.services).toHaveProperty(`web-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("web"); + + // Verificar que la configuración de la imagen sigue igual + expect(actualComposeData.services?.[`web-${suffix}`]?.image).toBe( + "nginx:latest", + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.image).toBe( + "myapi:latest", + ); + + // Verificar que los nombres en volumes_from tienen el prefijo + expect(actualComposeData.services?.[`web-${suffix}`]?.volumes_from).toContain( + `shared-${suffix}`, + ); + expect(actualComposeData.services?.[`api-${suffix}`]?.volumes_from).toContain( + `shared-${suffix}`, + ); + + // Verificar que el servicio shared también tiene el prefijo + expect(actualComposeData.services).toHaveProperty(`shared-${suffix}`); + expect(actualComposeData.services).not.toHaveProperty("shared"); + expect(actualComposeData.services?.[`shared-${suffix}`]?.image).toBe( + "busybox", + ); +}); diff --git a/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..61cba82d3357affdb98dd4e4d6370a98e818139e --- /dev/null +++ b/data/apps/dokploy/__test__/compose/volume/volume-2.test.ts @@ -0,0 +1,1174 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToAllVolumes, addSuffixToVolumesRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +services: + mail: + image: bytemark/smtp + restart: always + + plausible_db: + image: postgres:14-alpine + restart: always + volumes: + - db-data:/var/lib/postgresql/data + environment: + - POSTGRES_PASSWORD=postgres + + plausible_events_db: + image: clickhouse/clickhouse-server:23.3.7.5-alpine + restart: always + volumes: + - event-data:/var/lib/clickhouse + - event-logs:/var/log/clickhouse-server + - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro + - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro + ulimits: + nofile: + soft: 262144 + hard: 262144 + + plausible: + image: plausible/analytics:v2.0 + restart: always + command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run" + depends_on: + - plausible_db + - plausible_events_db + - mail + ports: + - 127.0.0.1:8000:8000 + env_file: + - plausible-conf.env + volumes: + - type: volume + source: plausible-data + target: /data + + mysql: + image: mysql:5.7 + restart: always + environment: + MYSQL_ROOT_PASSWORD: example + volumes: + - type: volume + source: db-data + target: /var/lib/mysql/data + +volumes: + db-data: + driver: local + event-data: + driver: local + event-logs: + driver: local +`; + +const expectedDockerCompose = load(` +services: + mail: + image: bytemark/smtp + restart: always + + plausible_db: + image: postgres:14-alpine + restart: always + volumes: + - db-data-testhash:/var/lib/postgresql/data + environment: + - POSTGRES_PASSWORD=postgres + + plausible_events_db: + image: clickhouse/clickhouse-server:23.3.7.5-alpine + restart: always + volumes: + - event-data-testhash:/var/lib/clickhouse + - event-logs-testhash:/var/log/clickhouse-server + - ./clickhouse/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro + - ./clickhouse/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro + ulimits: + nofile: + soft: 262144 + hard: 262144 + + plausible: + image: plausible/analytics:v2.0 + restart: always + command: sh -c "sleep 10 && /entrypoint.sh db createdb && /entrypoint.sh db migrate && /entrypoint.sh run" + depends_on: + - plausible_db + - plausible_events_db + - mail + ports: + - 127.0.0.1:8000:8000 + env_file: + - plausible-conf.env + volumes: + - type: volume + source: plausible-data-testhash + target: /data + + mysql: + image: mysql:5.7 + restart: always + environment: + MYSQL_ROOT_PASSWORD: example + volumes: + - type: volume + source: db-data-testhash + target: /var/lib/mysql/data + +volumes: + db-data-testhash: + driver: local + event-data-testhash: + driver: local + event-logs-testhash: + driver: local +`) as ComposeSpecification; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +// Docker compose needs unique names for services, volumes, networks and containers +// So base on a input which is a dockercompose file, it should replace the name with a hash and return a new dockercompose file +test("Add suffix to volumes root property", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.volumes) { + return; + } + const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix); + + // { + // 'db-data-af045046': { driver: 'local' }, + // 'event-data-af045046': { driver: 'local' }, + // 'event-logs-af045046': { driver: 'local' } + // } + + expect(volumes).toBeDefined(); + for (const volumeKey of Object.keys(volumes)) { + expect(volumeKey).toContain(`-${suffix}`); + } +}); + +test("Expect to change the suffix in all the possible places", () => { + const composeData = load(composeFile) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerCompose); +}); + +const composeFile2 = ` +version: '3.8' +services: + app: + image: myapp:latest + build: + context: . + dockerfile: Dockerfile + volumes: + - app-config:/usr/src/app/config + - ./config:/usr/src/app/config:ro + environment: + - NODE_ENV=production + mongo: + image: mongo:4.2 + volumes: + - mongo-data:/data/db +volumes: + app-config: + mongo-data: +`; + +const expectedDockerCompose2 = load(` +version: '3.8' +services: + app: + image: myapp:latest + build: + context: . + dockerfile: Dockerfile + volumes: + - app-config-testhash:/usr/src/app/config + - ./config:/usr/src/app/config:ro + environment: + - NODE_ENV=production + mongo: + image: mongo:4.2 + volumes: + - mongo-data-testhash:/data/db +volumes: + app-config-testhash: + mongo-data-testhash: +`) as ComposeSpecification; + +test("Expect to change the suffix in all the possible places (2 Try)", () => { + const composeData = load(composeFile2) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerCompose2); +}); + +const composeFile3 = ` +version: '3.8' +services: + app: + image: myapp:latest + build: + context: . + dockerfile: Dockerfile + volumes: + - app-config:/usr/src/app/config + - ./config:/usr/src/app/config:ro + environment: + - NODE_ENV=production + mongo: + image: mongo:4.2 + volumes: + - mongo-data:/data/db +volumes: + app-config: + mongo-data: +`; + +const expectedDockerCompose3 = load(` +version: '3.8' +services: + app: + image: myapp:latest + build: + context: . + dockerfile: Dockerfile + volumes: + - app-config-testhash:/usr/src/app/config + - ./config:/usr/src/app/config:ro + environment: + - NODE_ENV=production + mongo: + image: mongo:4.2 + volumes: + - mongo-data-testhash:/data/db +volumes: + app-config-testhash: + mongo-data-testhash: +`) as ComposeSpecification; + +test("Expect to change the suffix in all the possible places (3 Try)", () => { + const composeData = load(composeFile3) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerCompose3); +}); + +const composeFileComplex = ` +version: "3.8" +services: + studio: + container_name: supabase-studio + image: supabase/studio:20240422-5cf8f30 + restart: unless-stopped + healthcheck: + test: + [ + "CMD", + "node", + "-e", + "require('http').get('http://localhost:3000/api/profile', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})" + ] + timeout: 5s + interval: 5s + retries: 3 + depends_on: + analytics: + condition: service_healthy + environment: + STUDIO_PG_META_URL: http://meta:8080 + POSTGRES_PASSWORD: \${POSTGRES_PASSWORD} + DEFAULT_ORGANIZATION_NAME: \${STUDIO_DEFAULT_ORGANIZATION} + DEFAULT_PROJECT_NAME: \${STUDIO_DEFAULT_PROJECT} + SUPABASE_URL: http://kong:8000 + SUPABASE_PUBLIC_URL: \${SUPABASE_PUBLIC_URL} + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY} + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + LOGFLARE_URL: http://analytics:4000 + NEXT_PUBLIC_ENABLE_LOGS: true + NEXT_ANALYTICS_BACKEND_PROVIDER: postgres + + kong: + container_name: supabase-kong + image: kong:2.8.1 + restart: unless-stopped + entrypoint: bash -c 'eval "echo \"$$(cat ~/temp.yml)\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start' + ports: + - \${KONG_HTTP_PORT}:8000/tcp + - \${KONG_HTTPS_PORT}:8443/tcp + depends_on: + analytics: + condition: service_healthy + environment: + KONG_DATABASE: "off" + KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml + KONG_DNS_ORDER: LAST,A,CNAME + KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth + KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k + KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY} + DASHBOARD_USERNAME: \${DASHBOARD_USERNAME} + DASHBOARD_PASSWORD: \${DASHBOARD_PASSWORD} + volumes: + - ./volumes/api/kong.yml:/home/kong/temp.yml:ro + + auth: + container_name: supabase-auth + image: supabase/gotrue:v2.151.0 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://localhost:9999/health" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + GOTRUE_API_HOST: 0.0.0.0 + GOTRUE_API_PORT: 9999 + API_EXTERNAL_URL: \${API_EXTERNAL_URL} + GOTRUE_DB_DRIVER: postgres + GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + GOTRUE_SITE_URL: \${SITE_URL} + GOTRUE_URI_ALLOW_LIST: \${ADDITIONAL_REDIRECT_URLS} + GOTRUE_DISABLE_SIGNUP: \${DISABLE_SIGNUP} + GOTRUE_JWT_ADMIN_ROLES: service_role + GOTRUE_JWT_AUD: authenticated + GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated + GOTRUE_JWT_EXP: \${JWT_EXPIRY} + GOTRUE_JWT_SECRET: \${JWT_SECRET} + GOTRUE_EXTERNAL_EMAIL_ENABLED: \${ENABLE_EMAIL_SIGNUP} + GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: \${ENABLE_ANONYMOUS_USERS} + GOTRUE_MAILER_AUTOCONFIRM: \${ENABLE_EMAIL_AUTOCONFIRM} + GOTRUE_SMTP_ADMIN_EMAIL: \${SMTP_ADMIN_EMAIL} + GOTRUE_SMTP_HOST: \${SMTP_HOST} + GOTRUE_SMTP_PORT: \${SMTP_PORT} + GOTRUE_SMTP_USER: \${SMTP_USER} + GOTRUE_SMTP_PASS: \${SMTP_PASS} + GOTRUE_SMTP_SENDER_NAME: \${SMTP_SENDER_NAME} + GOTRUE_MAILER_URLPATHS_INVITE: \${MAILER_URLPATHS_INVITE} + GOTRUE_MAILER_URLPATHS_CONFIRMATION: \${MAILER_URLPATHS_CONFIRMATION} + GOTRUE_MAILER_URLPATHS_RECOVERY: \${MAILER_URLPATHS_RECOVERY} + GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: \${MAILER_URLPATHS_EMAIL_CHANGE} + GOTRUE_EXTERNAL_PHONE_ENABLED: \${ENABLE_PHONE_SIGNUP} + GOTRUE_SMS_AUTOCONFIRM: \${ENABLE_PHONE_AUTOCONFIRM} + + rest: + container_name: supabase-rest + image: postgrest/postgrest:v12.0.1 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + restart: unless-stopped + environment: + PGRST_DB_URI: postgres://authenticator:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + PGRST_DB_SCHEMAS: \${PGRST_DB_SCHEMAS} + PGRST_DB_ANON_ROLE: anon + PGRST_JWT_SECRET: \${JWT_SECRET} + PGRST_DB_USE_LEGACY_GUCS: "false" + PGRST_APP_SETTINGS_JWT_SECRET: \${JWT_SECRET} + PGRST_APP_SETTINGS_JWT_EXP: \${JWT_EXPIRY} + command: "postgrest" + + realtime: + container_name: realtime-dev.supabase-realtime + image: supabase/realtime:v2.28.32 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + healthcheck: + test: + [ + "CMD", + "curl", + "-sSfL", + "--head", + "-o", + "/dev/null", + "-H", + "Authorization: Bearer \${ANON_KEY}", + "http://localhost:4000/api/tenants/realtime-dev/health" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + PORT: 4000 + DB_HOST: \${POSTGRES_HOST} + DB_PORT: \${POSTGRES_PORT} + DB_USER: supabase_admin + DB_PASSWORD: \${POSTGRES_PASSWORD} + DB_NAME: \${POSTGRES_DB} + DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime' + DB_ENC_KEY: supabaserealtime + API_JWT_SECRET: \${JWT_SECRET} + FLY_ALLOC_ID: fly123 + FLY_APP_NAME: realtime + SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq + ERL_AFLAGS: -proto_dist inet_tcp + ENABLE_TAILSCALE: "false" + DNS_NODES: "''" + command: > + sh -c "/app/bin/migrate && /app/bin/realtime eval 'Realtime.Release.seeds(Realtime.Repo)' && /app/bin/server" + + storage: + container_name: supabase-storage + image: supabase/storage-api:v1.0.6 + depends_on: + db: + condition: service_healthy + rest: + condition: service_started + imgproxy: + condition: service_started + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://localhost:5000/status" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + ANON_KEY: \${ANON_KEY} + SERVICE_KEY: \${SERVICE_ROLE_KEY} + POSTGREST_URL: http://rest:3000 + PGRST_JWT_SECRET: \${JWT_SECRET} + DATABASE_URL: postgres://supabase_storage_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + FILE_SIZE_LIMIT: 52428800 + STORAGE_BACKEND: file + FILE_STORAGE_BACKEND_PATH: /var/lib/storage + TENANT_ID: stub + REGION: stub + GLOBAL_S3_BUCKET: stub + ENABLE_IMAGE_TRANSFORMATION: "true" + IMGPROXY_URL: http://imgproxy:5001 + volumes: + - ./volumes/storage:/var/lib/storage:z + + imgproxy: + container_name: supabase-imgproxy + image: darthsim/imgproxy:v3.8.0 + healthcheck: + test: [ "CMD", "imgproxy", "health" ] + timeout: 5s + interval: 5s + retries: 3 + environment: + IMGPROXY_BIND: ":5001" + IMGPROXY_LOCAL_FILESYSTEM_ROOT: / + IMGPROXY_USE_ETAG: "true" + IMGPROXY_ENABLE_WEBP_DETECTION: \${IMGPROXY_ENABLE_WEBP_DETECTION} + volumes: + - ./volumes/storage:/var/lib/storage:z + + meta: + container_name: supabase-meta + image: supabase/postgres-meta:v0.80.0 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + restart: unless-stopped + environment: + PG_META_PORT: 8080 + PG_META_DB_HOST: \${POSTGRES_HOST} + PG_META_DB_PORT: \${POSTGRES_PORT} + PG_META_DB_NAME: \${POSTGRES_DB} + PG_META_DB_USER: supabase_admin + PG_META_DB_PASSWORD: \${POSTGRES_PASSWORD} + + functions: + container_name: supabase-edge-functions + image: supabase/edge-runtime:v1.45.2 + restart: unless-stopped + depends_on: + analytics: + condition: service_healthy + environment: + JWT_SECRET: \${JWT_SECRET} + SUPABASE_URL: http://kong:8000 + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_ROLE_KEY: \${SERVICE_ROLE_KEY} + SUPABASE_DB_URL: postgresql://postgres:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + VERIFY_JWT: "\${FUNCTIONS_VERIFY_JWT}" + volumes: + - ./volumes/functions:/home/deno/functions:Z + command: + - start + - --main-service + - /home/deno/functions/main + + analytics: + container_name: supabase-analytics + image: supabase/logflare:1.4.0 + healthcheck: + test: [ "CMD", "curl", "http://localhost:4000/health" ] + timeout: 5s + interval: 5s + retries: 10 + restart: unless-stopped + depends_on: + db: + condition: service_healthy + environment: + LOGFLARE_NODE_HOST: 127.0.0.1 + DB_USERNAME: supabase_admin + DB_DATABASE: \${POSTGRES_DB} + DB_HOSTNAME: \${POSTGRES_HOST} + DB_PORT: \${POSTGRES_PORT} + DB_PASSWORD: \${POSTGRES_PASSWORD} + DB_SCHEMA: _analytics + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + LOGFLARE_SINGLE_TENANT: true + LOGFLARE_SUPABASE_MODE: true + LOGFLARE_MIN_CLUSTER_SIZE: 1 + POSTGRES_BACKEND_URL: postgresql://supabase_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + POSTGRES_BACKEND_SCHEMA: _analytics + LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true + ports: + - 4000:4000 + + db: + container_name: supabase-db + image: supabase/postgres:15.1.1.41 + healthcheck: + test: pg_isready -U postgres -h localhost + interval: 5s + timeout: 5s + retries: 10 + depends_on: + vector: + condition: service_healthy + command: + - postgres + - -c + - config_file=/etc/postgresql/postgresql.conf + - -c + - log_min_messages=fatal + restart: unless-stopped + ports: + - \${POSTGRES_PORT}:\${POSTGRES_PORT} + environment: + POSTGRES_HOST: /var/run/postgresql + PGPORT: \${POSTGRES_PORT} + POSTGRES_PORT: \${POSTGRES_PORT} + PGPASSWORD: \${POSTGRES_PASSWORD} + POSTGRES_PASSWORD: \${POSTGRES_PASSWORD} + PGDATABASE: \${POSTGRES_DB} + POSTGRES_DB: \${POSTGRES_DB} + JWT_SECRET: \${JWT_SECRET} + JWT_EXP: \${JWT_EXPIRY} + volumes: + - ./volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z + - ./volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z + - ./volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z + - ./volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z + - ./volumes/db/data:/var/lib/postgresql/data:Z + - ./volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z + - db-config:/etc/postgresql-custom + + vector: + container_name: supabase-vector + image: timberio/vector:0.28.1-alpine + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://vector:9001/health" + ] + timeout: 5s + interval: 5s + retries: 3 + volumes: + - ./volumes/logs/vector.yml:/etc/vector/vector.yml:ro + - "\${DOCKER_SOCKET_LOCATION}:/var/run/docker.sock:ro" + environment: + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + command: [ "--config", "etc/vector/vector.yml" ] + +volumes: + db-config: +`; + +const expectedDockerComposeComplex = load(` +version: "3.8" +services: + studio: + container_name: supabase-studio + image: supabase/studio:20240422-5cf8f30 + restart: unless-stopped + healthcheck: + test: + [ + "CMD", + "node", + "-e", + "require('http').get('http://localhost:3000/api/profile', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})" + ] + timeout: 5s + interval: 5s + retries: 3 + depends_on: + analytics: + condition: service_healthy + environment: + STUDIO_PG_META_URL: http://meta:8080 + POSTGRES_PASSWORD: \${POSTGRES_PASSWORD} + DEFAULT_ORGANIZATION_NAME: \${STUDIO_DEFAULT_ORGANIZATION} + DEFAULT_PROJECT_NAME: \${STUDIO_DEFAULT_PROJECT} + SUPABASE_URL: http://kong:8000 + SUPABASE_PUBLIC_URL: \${SUPABASE_PUBLIC_URL} + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY} + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + LOGFLARE_URL: http://analytics:4000 + NEXT_PUBLIC_ENABLE_LOGS: true + NEXT_ANALYTICS_BACKEND_PROVIDER: postgres + + kong: + container_name: supabase-kong + image: kong:2.8.1 + restart: unless-stopped + entrypoint: bash -c 'eval "echo \"$$(cat ~/temp.yml)\"" > ~/kong.yml && /docker-entrypoint.sh kong docker-start' + ports: + - \${KONG_HTTP_PORT}:8000/tcp + - \${KONG_HTTPS_PORT}:8443/tcp + depends_on: + analytics: + condition: service_healthy + environment: + KONG_DATABASE: "off" + KONG_DECLARATIVE_CONFIG: /home/kong/kong.yml + KONG_DNS_ORDER: LAST,A,CNAME + KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth + KONG_NGINX_PROXY_PROXY_BUFFER_SIZE: 160k + KONG_NGINX_PROXY_PROXY_BUFFERS: 64 160k + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_KEY: \${SERVICE_ROLE_KEY} + DASHBOARD_USERNAME: \${DASHBOARD_USERNAME} + DASHBOARD_PASSWORD: \${DASHBOARD_PASSWORD} + volumes: + - ./volumes/api/kong.yml:/home/kong/temp.yml:ro + + auth: + container_name: supabase-auth + image: supabase/gotrue:v2.151.0 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://localhost:9999/health" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + GOTRUE_API_HOST: 0.0.0.0 + GOTRUE_API_PORT: 9999 + API_EXTERNAL_URL: \${API_EXTERNAL_URL} + GOTRUE_DB_DRIVER: postgres + GOTRUE_DB_DATABASE_URL: postgres://supabase_auth_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + GOTRUE_SITE_URL: \${SITE_URL} + GOTRUE_URI_ALLOW_LIST: \${ADDITIONAL_REDIRECT_URLS} + GOTRUE_DISABLE_SIGNUP: \${DISABLE_SIGNUP} + GOTRUE_JWT_ADMIN_ROLES: service_role + GOTRUE_JWT_AUD: authenticated + GOTRUE_JWT_DEFAULT_GROUP_NAME: authenticated + GOTRUE_JWT_EXP: \${JWT_EXPIRY} + GOTRUE_JWT_SECRET: \${JWT_SECRET} + GOTRUE_EXTERNAL_EMAIL_ENABLED: \${ENABLE_EMAIL_SIGNUP} + GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED: \${ENABLE_ANONYMOUS_USERS} + GOTRUE_MAILER_AUTOCONFIRM: \${ENABLE_EMAIL_AUTOCONFIRM} + GOTRUE_SMTP_ADMIN_EMAIL: \${SMTP_ADMIN_EMAIL} + GOTRUE_SMTP_HOST: \${SMTP_HOST} + GOTRUE_SMTP_PORT: \${SMTP_PORT} + GOTRUE_SMTP_USER: \${SMTP_USER} + GOTRUE_SMTP_PASS: \${SMTP_PASS} + GOTRUE_SMTP_SENDER_NAME: \${SMTP_SENDER_NAME} + GOTRUE_MAILER_URLPATHS_INVITE: \${MAILER_URLPATHS_INVITE} + GOTRUE_MAILER_URLPATHS_CONFIRMATION: \${MAILER_URLPATHS_CONFIRMATION} + GOTRUE_MAILER_URLPATHS_RECOVERY: \${MAILER_URLPATHS_RECOVERY} + GOTRUE_MAILER_URLPATHS_EMAIL_CHANGE: \${MAILER_URLPATHS_EMAIL_CHANGE} + GOTRUE_EXTERNAL_PHONE_ENABLED: \${ENABLE_PHONE_SIGNUP} + GOTRUE_SMS_AUTOCONFIRM: \${ENABLE_PHONE_AUTOCONFIRM} + + rest: + container_name: supabase-rest + image: postgrest/postgrest:v12.0.1 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + restart: unless-stopped + environment: + PGRST_DB_URI: postgres://authenticator:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + PGRST_DB_SCHEMAS: \${PGRST_DB_SCHEMAS} + PGRST_DB_ANON_ROLE: anon + PGRST_JWT_SECRET: \${JWT_SECRET} + PGRST_DB_USE_LEGACY_GUCS: "false" + PGRST_APP_SETTINGS_JWT_SECRET: \${JWT_SECRET} + PGRST_APP_SETTINGS_JWT_EXP: \${JWT_EXPIRY} + command: "postgrest" + + realtime: + container_name: realtime-dev.supabase-realtime + image: supabase/realtime:v2.28.32 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + healthcheck: + test: + [ + "CMD", + "curl", + "-sSfL", + "--head", + "-o", + "/dev/null", + "-H", + "Authorization: Bearer \${ANON_KEY}", + "http://localhost:4000/api/tenants/realtime-dev/health" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + PORT: 4000 + DB_HOST: \${POSTGRES_HOST} + DB_PORT: \${POSTGRES_PORT} + DB_USER: supabase_admin + DB_PASSWORD: \${POSTGRES_PASSWORD} + DB_NAME: \${POSTGRES_DB} + DB_AFTER_CONNECT_QUERY: 'SET search_path TO _realtime' + DB_ENC_KEY: supabaserealtime + API_JWT_SECRET: \${JWT_SECRET} + FLY_ALLOC_ID: fly123 + FLY_APP_NAME: realtime + SECRET_KEY_BASE: UpNVntn3cDxHJpq99YMc1T1AQgQpc8kfYTuRgBiYa15BLrx8etQoXz3gZv1/u2oq + ERL_AFLAGS: -proto_dist inet_tcp + ENABLE_TAILSCALE: "false" + DNS_NODES: "''" + command: > + sh -c "/app/bin/migrate && /app/bin/realtime eval 'Realtime.Release.seeds(Realtime.Repo)' && /app/bin/server" + + storage: + container_name: supabase-storage + image: supabase/storage-api:v1.0.6 + depends_on: + db: + condition: service_healthy + rest: + condition: service_started + imgproxy: + condition: service_started + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://localhost:5000/status" + ] + timeout: 5s + interval: 5s + retries: 3 + restart: unless-stopped + environment: + ANON_KEY: \${ANON_KEY} + SERVICE_KEY: \${SERVICE_ROLE_KEY} + POSTGREST_URL: http://rest:3000 + PGRST_JWT_SECRET: \${JWT_SECRET} + DATABASE_URL: postgres://supabase_storage_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + FILE_SIZE_LIMIT: 52428800 + STORAGE_BACKEND: file + FILE_STORAGE_BACKEND_PATH: /var/lib/storage + TENANT_ID: stub + REGION: stub + GLOBAL_S3_BUCKET: stub + ENABLE_IMAGE_TRANSFORMATION: "true" + IMGPROXY_URL: http://imgproxy:5001 + volumes: + - ./volumes/storage:/var/lib/storage:z + + imgproxy: + container_name: supabase-imgproxy + image: darthsim/imgproxy:v3.8.0 + healthcheck: + test: [ "CMD", "imgproxy", "health" ] + timeout: 5s + interval: 5s + retries: 3 + environment: + IMGPROXY_BIND: ":5001" + IMGPROXY_LOCAL_FILESYSTEM_ROOT: / + IMGPROXY_USE_ETAG: "true" + IMGPROXY_ENABLE_WEBP_DETECTION: \${IMGPROXY_ENABLE_WEBP_DETECTION} + volumes: + - ./volumes/storage:/var/lib/storage:z + + meta: + container_name: supabase-meta + image: supabase/postgres-meta:v0.80.0 + depends_on: + db: + condition: service_healthy + analytics: + condition: service_healthy + restart: unless-stopped + environment: + PG_META_PORT: 8080 + PG_META_DB_HOST: \${POSTGRES_HOST} + PG_META_DB_PORT: \${POSTGRES_PORT} + PG_META_DB_NAME: \${POSTGRES_DB} + PG_META_DB_USER: supabase_admin + PG_META_DB_PASSWORD: \${POSTGRES_PASSWORD} + + functions: + container_name: supabase-edge-functions + image: supabase/edge-runtime:v1.45.2 + restart: unless-stopped + depends_on: + analytics: + condition: service_healthy + environment: + JWT_SECRET: \${JWT_SECRET} + SUPABASE_URL: http://kong:8000 + SUPABASE_ANON_KEY: \${ANON_KEY} + SUPABASE_SERVICE_ROLE_KEY: \${SERVICE_ROLE_KEY} + SUPABASE_DB_URL: postgresql://postgres:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + VERIFY_JWT: "\${FUNCTIONS_VERIFY_JWT}" + volumes: + - ./volumes/functions:/home/deno/functions:Z + command: + - start + - --main-service + - /home/deno/functions/main + + analytics: + container_name: supabase-analytics + image: supabase/logflare:1.4.0 + healthcheck: + test: [ "CMD", "curl", "http://localhost:4000/health" ] + timeout: 5s + interval: 5s + retries: 10 + restart: unless-stopped + depends_on: + db: + condition: service_healthy + environment: + LOGFLARE_NODE_HOST: 127.0.0.1 + DB_USERNAME: supabase_admin + DB_DATABASE: \${POSTGRES_DB} + DB_HOSTNAME: \${POSTGRES_HOST} + DB_PORT: \${POSTGRES_PORT} + DB_PASSWORD: \${POSTGRES_PASSWORD} + DB_SCHEMA: _analytics + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + LOGFLARE_SINGLE_TENANT: true + LOGFLARE_SUPABASE_MODE: true + LOGFLARE_MIN_CLUSTER_SIZE: 1 + POSTGRES_BACKEND_URL: postgresql://supabase_admin:\${POSTGRES_PASSWORD}@\${POSTGRES_HOST}:\${POSTGRES_PORT}/\${POSTGRES_DB} + POSTGRES_BACKEND_SCHEMA: _analytics + LOGFLARE_FEATURE_FLAG_OVERRIDE: multibackend=true + ports: + - 4000:4000 + + db: + container_name: supabase-db + image: supabase/postgres:15.1.1.41 + healthcheck: + test: pg_isready -U postgres -h localhost + interval: 5s + timeout: 5s + retries: 10 + depends_on: + vector: + condition: service_healthy + command: + - postgres + - -c + - config_file=/etc/postgresql/postgresql.conf + - -c + - log_min_messages=fatal + restart: unless-stopped + ports: + - \${POSTGRES_PORT}:\${POSTGRES_PORT} + environment: + POSTGRES_HOST: /var/run/postgresql + PGPORT: \${POSTGRES_PORT} + POSTGRES_PORT: \${POSTGRES_PORT} + PGPASSWORD: \${POSTGRES_PASSWORD} + POSTGRES_PASSWORD: \${POSTGRES_PASSWORD} + PGDATABASE: \${POSTGRES_DB} + POSTGRES_DB: \${POSTGRES_DB} + JWT_SECRET: \${JWT_SECRET} + JWT_EXP: \${JWT_EXPIRY} + volumes: + - ./volumes/db/realtime.sql:/docker-entrypoint-initdb.d/migrations/99-realtime.sql:Z + - ./volumes/db/webhooks.sql:/docker-entrypoint-initdb.d/init-scripts/98-webhooks.sql:Z + - ./volumes/db/roles.sql:/docker-entrypoint-initdb.d/init-scripts/99-roles.sql:Z + - ./volumes/db/jwt.sql:/docker-entrypoint-initdb.d/init-scripts/99-jwt.sql:Z + - ./volumes/db/data:/var/lib/postgresql/data:Z + - ./volumes/db/logs.sql:/docker-entrypoint-initdb.d/migrations/99-logs.sql:Z + - db-config-testhash:/etc/postgresql-custom + + vector: + container_name: supabase-vector + image: timberio/vector:0.28.1-alpine + healthcheck: + test: + [ + "CMD", + "wget", + "--no-verbose", + "--tries=1", + "--spider", + "http://vector:9001/health" + ] + timeout: 5s + interval: 5s + retries: 3 + volumes: + - ./volumes/logs/vector.yml:/etc/vector/vector.yml:ro + - \${DOCKER_SOCKET_LOCATION}:/var/run/docker.sock:ro + environment: + LOGFLARE_API_KEY: \${LOGFLARE_API_KEY} + command: [ "--config", "etc/vector/vector.yml" ] + +volumes: + db-config-testhash: +`); + +test("Expect to change the suffix in all the possible places (4 Try)", () => { + const composeData = load(composeFileComplex) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerComposeComplex); +}); + +const composeFileExample1 = ` +version: "3.8" +services: + web: + image: nginx:latest + ports: + - "80:80" + networks: + - frontend + volumes: + - web-data:/var/www/html + - ./nginx.conf:/etc/nginx/nginx.conf:ro + + app: + image: node:14 + depends_on: + - db + networks: + - backend + - frontend + volumes: + - app-data:/usr/src/app + - ./src:/usr/src/app/src + + db: + image: postgres:13 + environment: + POSTGRES_PASSWORD: example + networks: + - backend + volumes: + - db-data:/var/lib/postgresql/data + +networks: + frontend: + driver: bridge + backend: + driver: bridge + +volumes: + web-data: + app-data: + db-data: +`; + +const expectedDockerComposeExample1 = load(` +version: "3.8" +services: + web: + image: nginx:latest + ports: + - "80:80" + networks: + - frontend + volumes: + - web-data-testhash:/var/www/html + - ./nginx.conf:/etc/nginx/nginx.conf:ro + + app: + image: node:14 + depends_on: + - db + networks: + - backend + - frontend + volumes: + - app-data-testhash:/usr/src/app + - ./src:/usr/src/app/src + + db: + image: postgres:13 + environment: + POSTGRES_PASSWORD: example + networks: + - backend + volumes: + - db-data-testhash:/var/lib/postgresql/data + +networks: + frontend: + driver: bridge + backend: + driver: bridge + +volumes: + web-data-testhash: + app-data-testhash: + db-data-testhash: +`) as ComposeSpecification; + +test("Expect to change the suffix in all the possible places (5 Try)", () => { + const composeData = load(composeFileExample1) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerComposeExample1); +}); + +const composeFileBackrest = ` +services: + backrest: + image: garethgeorge/backrest:v1.7.3 + restart: unless-stopped + ports: + - 9898 + environment: + - BACKREST_PORT=9898 + - BACKREST_DATA=/data + - BACKREST_CONFIG=/config/config.json + - XDG_CACHE_HOME=/cache + - TZ=\${TZ} + volumes: + - backrest/data:/data + - backrest/config:/config + - backrest/cache:/cache + - /:/userdata:ro + +volumes: + backrest: + backrest-cache: +`; + +const expectedDockerComposeBackrest = load(` +services: + backrest: + image: garethgeorge/backrest:v1.7.3 + restart: unless-stopped + ports: + - 9898 + environment: + - BACKREST_PORT=9898 + - BACKREST_DATA=/data + - BACKREST_CONFIG=/config/config.json + - XDG_CACHE_HOME=/cache + - TZ=\${TZ} + volumes: + - backrest-testhash/data:/data + - backrest-testhash/config:/config + - backrest-testhash/cache:/cache + - /:/userdata:ro + +volumes: + backrest-testhash: + backrest-cache-testhash: +`) as ComposeSpecification; + +test("Should handle volume paths with subdirectories correctly", () => { + const composeData = load(composeFileBackrest) as ComposeSpecification; + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + + expect(updatedComposeData).toEqual(expectedDockerComposeBackrest); +}); diff --git a/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d91cb64d3a9fa0690ac4c19571125bc5403f2c66 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/volume/volume-root.test.ts @@ -0,0 +1,195 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToVolumesRoot } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFile = ` +version: "3.8" + +services: + web: + image: nginx:latest + volumes: + - web_data:/var/lib/nginx/data + +volumes: + web_data: + driver: local + +networks: + default: + driver: bridge +`; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +test("Add suffix to volumes in root property", () => { + const composeData = load(composeFile) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.volumes) { + return; + } + const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix); + expect(volumes).toBeDefined(); + for (const volumeKey of Object.keys(volumes)) { + expect(volumeKey).toContain(`-${suffix}`); + expect(volumes[volumeKey]).toBeDefined(); + } +}); + +const composeFile2 = ` +version: "3.8" + +services: + app: + image: node:latest + volumes: + - app_data:/var/lib/app/data + +volumes: + app_data: + driver: local + driver_opts: + type: nfs + o: addr=10.0.0.1,rw + device: ":/exported/path" + +networks: + default: + driver: bridge +`; + +test("Add suffix to volumes in root property (Case 2)", () => { + const composeData = load(composeFile2) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.volumes) { + return; + } + const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix); + expect(volumes).toBeDefined(); + for (const volumeKey of Object.keys(volumes)) { + expect(volumeKey).toContain(`-${suffix}`); + expect(volumes[volumeKey]).toBeDefined(); + } +}); + +const composeFile3 = ` +version: "3.8" + +services: + db: + image: postgres:latest + volumes: + - db_data:/var/lib/postgresql/data + +volumes: + db_data: + external: true + +networks: + default: + driver: bridge +`; + +test("Add suffix to volumes in root property (Case 3)", () => { + const composeData = load(composeFile3) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData?.volumes) { + return; + } + const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix); + + expect(volumes).toBeDefined(); + for (const volumeKey of Object.keys(volumes)) { + expect(volumeKey).toContain(`-${suffix}`); + expect(volumes[volumeKey]).toBeDefined(); + } +}); + +const composeFile4 = ` +version: "3.8" + +services: + web: + image: nginx:latest + + app: + image: node:latest + + db: + image: postgres:latest + +volumes: + web_data: + driver: local + + app_data: + driver: local + driver_opts: + type: nfs + o: addr=10.0.0.1,rw + device: ":/exported/path" + + db_data: + external: true + + +`; + +// Expected compose file con el prefijo `testhash` +const expectedComposeFile4 = load(` +version: "3.8" + +services: + web: + image: nginx:latest + + app: + image: node:latest + + db: + image: postgres:latest + +volumes: + web_data-testhash: + driver: local + + app_data-testhash: + driver: local + driver_opts: + type: nfs + o: addr=10.0.0.1,rw + device: ":/exported/path" + + db_data-testhash: + external: true + + +`) as ComposeSpecification; + +test("Add suffix to volumes in root property", () => { + const composeData = load(composeFile4) as ComposeSpecification; + + const suffix = "testhash"; + + if (!composeData?.volumes) { + return; + } + const volumes = addSuffixToVolumesRoot(composeData.volumes, suffix); + const updatedComposeData = { ...composeData, volumes }; + + // Verificar que el resultado coincide con el archivo esperado + expect(updatedComposeData).toEqual(expectedComposeFile4); +}); diff --git a/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts b/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..04a1a45ae8b4ab4f9f97544354b539d281bffbba --- /dev/null +++ b/data/apps/dokploy/__test__/compose/volume/volume-services.test.ts @@ -0,0 +1,81 @@ +import { generateRandomHash } from "@dokploy/server"; +import { addSuffixToVolumesInServices } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +test("Generate random hash with 8 characters", () => { + const hash = generateRandomHash(); + + expect(hash).toBeDefined(); + expect(hash.length).toBe(8); +}); + +const composeFile1 = ` +version: "3.8" + +services: + db: + image: postgres:latest + volumes: + - db_data:/var/lib/postgresql/data +`; + +test("Add suffix to volumes declared directly in services", () => { + const composeData = load(composeFile1) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + + const updatedComposeData = addSuffixToVolumesInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + expect(actualComposeData.services?.db?.volumes).toContain( + `db_data-${suffix}:/var/lib/postgresql/data`, + ); +}); + +const composeFileTypeVolume = ` +version: "3.8" + +services: + db: + image: postgres:latest + volumes: + - type: volume + source: db-test + target: /var/lib/postgresql/data + +volumes: + db-test: + driver: local +`; + +test("Add suffix to volumes declared directly in services (Case 2)", () => { + const composeData = load(composeFileTypeVolume) as ComposeSpecification; + + const suffix = generateRandomHash(); + + if (!composeData.services) { + return; + } + + const updatedComposeData = addSuffixToVolumesInServices( + composeData.services, + suffix, + ); + const actualComposeData = { ...composeData, services: updatedComposeData }; + + expect(actualComposeData.services?.db?.volumes).toEqual([ + { + type: "volume", + source: `db-test-${suffix}`, + target: "/var/lib/postgresql/data", + }, + ]); +}); diff --git a/data/apps/dokploy/__test__/compose/volume/volume.test.ts b/data/apps/dokploy/__test__/compose/volume/volume.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c43447623cd957c2531a26a3b37c1c8def69ea3 --- /dev/null +++ b/data/apps/dokploy/__test__/compose/volume/volume.test.ts @@ -0,0 +1,284 @@ +import { addSuffixToAllVolumes } from "@dokploy/server"; +import type { ComposeSpecification } from "@dokploy/server"; +import { load } from "js-yaml"; +import { expect, test } from "vitest"; + +const composeFileTypeVolume = ` +version: "3.8" + +services: + db1: + image: postgres:latest + volumes: + - "db-test:/var/lib/postgresql/data" + db2: + image: postgres:latest + volumes: + - type: volume + source: db-test + target: /var/lib/postgresql/data + +volumes: + db-test: + driver: local +`; + +const expectedComposeFileTypeVolume = load(` +version: "3.8" + +services: + db1: + image: postgres:latest + volumes: + - "db-test-testhash:/var/lib/postgresql/data" + db2: + image: postgres:latest + volumes: + - type: volume + source: db-test-testhash + target: /var/lib/postgresql/data + +volumes: + db-test-testhash: + driver: local +`) as ComposeSpecification; + +test("Add suffix to volumes with type: volume in services", () => { + const composeData = load(composeFileTypeVolume) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + const actualComposeData = { ...composeData, ...updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFileTypeVolume); +}); + +const composeFileTypeVolume1 = ` +version: "3.8" + +services: + web: + image: nginx:latest + volumes: + - "web-data:/var/www/html" + - type: volume + source: web-logs + target: /var/log/nginx + +volumes: + web-data: + driver: local + web-logs: + driver: local +`; + +const expectedComposeFileTypeVolume1 = load(` +version: "3.8" + +services: + web: + image: nginx:latest + volumes: + - "web-data-testhash:/var/www/html" + - type: volume + source: web-logs-testhash + target: /var/log/nginx + +volumes: + web-data-testhash: + driver: local + web-logs-testhash: + driver: local +`) as ComposeSpecification; + +test("Add suffix to mixed volumes in services", () => { + const composeData = load(composeFileTypeVolume1) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + const actualComposeData = { ...composeData, ...updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFileTypeVolume1); +}); + +const composeFileTypeVolume2 = ` +version: "3.8" + +services: + app: + image: node:latest + volumes: + - "app-data:/usr/src/app" + - type: volume + source: app-logs + target: /var/log/app + volume: + nocopy: true + +volumes: + app-data: + driver: local + app-logs: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/app/logs +`; + +const expectedComposeFileTypeVolume2 = load(` +version: "3.8" + +services: + app: + image: node:latest + volumes: + - "app-data-testhash:/usr/src/app" + - type: volume + source: app-logs-testhash + target: /var/log/app + volume: + nocopy: true + +volumes: + app-data-testhash: + driver: local + app-logs-testhash: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/app/logs +`) as ComposeSpecification; + +test("Add suffix to complex volume configurations in services", () => { + const composeData = load(composeFileTypeVolume2) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + const actualComposeData = { ...composeData, ...updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFileTypeVolume2); +}); + +const composeFileTypeVolume3 = ` +version: "3.8" + +services: + web: + image: nginx:latest + volumes: + - "web-data:/usr/share/nginx/html" + - type: volume + source: web-logs + target: /var/log/nginx + volume: + nocopy: true + + api: + image: node:latest + volumes: + - "api-data:/usr/src/app" + - type: volume + source: api-logs + target: /var/log/app + volume: + nocopy: true + - type: volume + source: shared-logs + target: /shared/logs + +volumes: + web-data: + driver: local + web-logs: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/web/logs + + api-data: + driver: local + api-logs: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/api/logs + + shared-logs: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/shared/logs +`; + +const expectedComposeFileTypeVolume3 = load(` +version: "3.8" + +services: + web: + image: nginx:latest + volumes: + - "web-data-testhash:/usr/share/nginx/html" + - type: volume + source: web-logs-testhash + target: /var/log/nginx + volume: + nocopy: true + + api: + image: node:latest + volumes: + - "api-data-testhash:/usr/src/app" + - type: volume + source: api-logs-testhash + target: /var/log/app + volume: + nocopy: true + - type: volume + source: shared-logs-testhash + target: /shared/logs + +volumes: + web-data-testhash: + driver: local + web-logs-testhash: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/web/logs + + api-data-testhash: + driver: local + api-logs-testhash: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/api/logs + + shared-logs-testhash: + driver: local + driver_opts: + o: bind + type: none + device: /path/to/shared/logs +`) as ComposeSpecification; + +test("Add suffix to complex nested volumes configuration in services", () => { + const composeData = load(composeFileTypeVolume3) as ComposeSpecification; + + const suffix = "testhash"; + + const updatedComposeData = addSuffixToAllVolumes(composeData, suffix); + const actualComposeData = { ...composeData, ...updatedComposeData }; + + expect(actualComposeData).toEqual(expectedComposeFileTypeVolume3); +}); diff --git a/data/apps/dokploy/__test__/deploy/github.test.ts b/data/apps/dokploy/__test__/deploy/github.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..18d7619abfdec1a121c60159dce513557ecb4bd1 --- /dev/null +++ b/data/apps/dokploy/__test__/deploy/github.test.ts @@ -0,0 +1,98 @@ +import { extractCommitMessage } from "@/pages/api/deploy/[refreshToken]"; +import { describe, expect, it } from "vitest"; + +describe("GitHub Webhook Skip CI", () => { + const mockGithubHeaders = { + "x-github-event": "push", + }; + + const createMockBody = (message: string) => ({ + head_commit: { + message, + }, + }); + + const skipKeywords = [ + "[skip ci]", + "[ci skip]", + "[no ci]", + "[skip actions]", + "[actions skip]", + ]; + + it("should detect skip keywords in commit message", () => { + for (const keyword of skipKeywords) { + const message = `feat: add new feature ${keyword}`; + const commitMessage = extractCommitMessage( + mockGithubHeaders, + createMockBody(message), + ); + expect(commitMessage.includes(keyword)).toBe(true); + } + }); + + it("should not detect skip keywords in normal commit message", () => { + const message = "feat: add new feature"; + const commitMessage = extractCommitMessage( + mockGithubHeaders, + createMockBody(message), + ); + for (const keyword of skipKeywords) { + expect(commitMessage.includes(keyword)).toBe(false); + } + }); + + it("should handle different webhook sources", () => { + // GitHub + expect( + extractCommitMessage( + { "x-github-event": "push" }, + { head_commit: { message: "[skip ci] test" } }, + ), + ).toBe("[skip ci] test"); + + // GitLab + expect( + extractCommitMessage( + { "x-gitlab-event": "push" }, + { commits: [{ message: "[skip ci] test" }] }, + ), + ).toBe("[skip ci] test"); + + // Bitbucket + expect( + extractCommitMessage( + { "x-event-key": "repo:push" }, + { + push: { + changes: [{ new: { target: { message: "[skip ci] test" } } }], + }, + }, + ), + ).toBe("[skip ci] test"); + + // Gitea + expect( + extractCommitMessage( + { "x-gitea-event": "push" }, + { commits: [{ message: "[skip ci] test" }] }, + ), + ).toBe("[skip ci] test"); + }); + + it("should handle missing commit message", () => { + expect(extractCommitMessage(mockGithubHeaders, {})).toBe("NEW COMMIT"); + expect(extractCommitMessage({ "x-gitlab-event": "push" }, {})).toBe( + "NEW COMMIT", + ); + expect( + extractCommitMessage( + { "x-event-key": "repo:push" }, + { push: { changes: [] } }, + ), + ).toBe("NEW COMMIT"); + expect(extractCommitMessage({ "x-gitea-event": "push" }, {})).toBe( + "NEW COMMIT", + ); + }); +}); diff --git a/data/apps/dokploy/__test__/drop/drop.test.test.ts b/data/apps/dokploy/__test__/drop/drop.test.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b18d7b4b1f8958866cea05a5f9df31c9c9d1dfb8 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/drop.test.test.ts @@ -0,0 +1,217 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { paths } from "@dokploy/server/constants"; +const { APPLICATIONS_PATH } = paths(); +import type { ApplicationNested } from "@dokploy/server"; +import { unzipDrop } from "@dokploy/server"; +import AdmZip from "adm-zip"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +vi.mock("@dokploy/server/constants", async (importOriginal) => { + const actual = await importOriginal(); + return { + // @ts-ignore + ...actual, + paths: () => ({ + APPLICATIONS_PATH: "./__test__/drop/zips/output", + }), + }; +}); + +if (typeof window === "undefined") { + const undici = require("undici"); + globalThis.File = undici.File as any; + globalThis.FileList = undici.FileList as any; +} + +const baseApp: ApplicationNested = { + applicationId: "", + herokuVersion: "", + giteaBranch: "", + giteaBuildPath: "", + giteaId: "", + giteaOwner: "", + giteaRepository: "", + cleanCache: false, + watchPaths: [], + enableSubmodules: false, + applicationStatus: "done", + triggerType: "push", + appName: "", + autoDeploy: true, + serverId: "", + registryUrl: "", + branch: null, + dockerBuildStage: "", + isPreviewDeploymentsActive: false, + previewBuildArgs: null, + previewCertificateType: "none", + previewCustomCertResolver: null, + previewEnv: null, + previewHttps: false, + previewPath: "/", + previewPort: 3000, + previewLimit: 0, + previewWildcard: "", + project: { + env: "", + organizationId: "", + name: "", + description: "", + createdAt: "", + projectId: "", + }, + buildArgs: null, + buildPath: "/", + gitlabPathNamespace: "", + buildType: "nixpacks", + bitbucketBranch: "", + bitbucketBuildPath: "", + bitbucketId: "", + bitbucketRepository: "", + bitbucketOwner: "", + githubId: "", + gitlabProjectId: 0, + gitlabBranch: "", + gitlabBuildPath: "", + gitlabId: "", + gitlabRepository: "", + gitlabOwner: "", + command: null, + cpuLimit: null, + cpuReservation: null, + createdAt: "", + customGitBranch: "", + customGitBuildPath: "", + customGitSSHKeyId: null, + customGitUrl: "", + description: "", + dockerfile: null, + dockerImage: null, + dropBuildPath: null, + enabled: null, + env: null, + healthCheckSwarm: null, + labelsSwarm: null, + memoryLimit: null, + memoryReservation: null, + modeSwarm: null, + mounts: [], + name: "", + networkSwarm: null, + owner: null, + password: null, + placementSwarm: null, + ports: [], + projectId: "", + publishDirectory: null, + isStaticSpa: null, + redirects: [], + refreshToken: "", + registry: null, + registryId: null, + replicas: 1, + repository: null, + restartPolicySwarm: null, + rollbackConfigSwarm: null, + security: [], + sourceType: "git", + subtitle: null, + title: null, + updateConfigSwarm: null, + username: null, + dockerContextPath: null, +}; + +describe("unzipDrop using real zip files", () => { + // const { APPLICATIONS_PATH } = paths(); + beforeAll(async () => { + await fs.rm(APPLICATIONS_PATH, { recursive: true, force: true }); + }); + + afterAll(async () => { + await fs.rm(APPLICATIONS_PATH, { recursive: true, force: true }); + }); + + it("should correctly extract a zip with a single root folder", async () => { + baseApp.appName = "single-file"; + // const appName = "single-file"; + try { + const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code"); + const zip = new AdmZip("./__test__/drop/zips/single-file.zip"); + console.log(`Output Path: ${outputPath}`); + const zipBuffer = zip.toBuffer(); + const file = new File([zipBuffer], "single.zip"); + await unzipDrop(file, baseApp); + const files = await fs.readdir(outputPath, { withFileTypes: true }); + expect(files.some((f) => f.name === "test.txt")).toBe(true); + } catch (err) { + console.log(err); + } finally { + } + }); +}); + +// it("should correctly extract a zip with a single root folder and a subfolder", async () => { +// baseApp.appName = "folderwithfile"; +// // const appName = "folderwithfile"; +// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code"); +// const zip = new AdmZip("./__test__/drop/zips/folder-with-file.zip"); + +// const zipBuffer = zip.toBuffer(); +// const file = new File([zipBuffer], "single.zip"); +// await unzipDrop(file, baseApp); + +// const files = await fs.readdir(outputPath, { withFileTypes: true }); +// expect(files.some((f) => f.name === "folder1.txt")).toBe(true); +// }); + +// it("should correctly extract a zip with multiple root folders", async () => { +// baseApp.appName = "two-folders"; +// // const appName = "two-folders"; +// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code"); +// const zip = new AdmZip("./__test__/drop/zips/two-folders.zip"); + +// const zipBuffer = zip.toBuffer(); +// const file = new File([zipBuffer], "single.zip"); +// await unzipDrop(file, baseApp); + +// const files = await fs.readdir(outputPath, { withFileTypes: true }); + +// expect(files.some((f) => f.name === "folder1")).toBe(true); +// expect(files.some((f) => f.name === "folder2")).toBe(true); +// }); + +// it("should correctly extract a zip with a single root with a file", async () => { +// baseApp.appName = "nested"; +// // const appName = "nested"; +// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code"); +// const zip = new AdmZip("./__test__/drop/zips/nested.zip"); + +// const zipBuffer = zip.toBuffer(); +// const file = new File([zipBuffer], "single.zip"); +// await unzipDrop(file, baseApp); + +// const files = await fs.readdir(outputPath, { withFileTypes: true }); + +// expect(files.some((f) => f.name === "folder1")).toBe(true); +// expect(files.some((f) => f.name === "folder2")).toBe(true); +// expect(files.some((f) => f.name === "folder3")).toBe(true); +// }); + +// it("should correctly extract a zip with a single root with a folder", async () => { +// baseApp.appName = "folder-with-sibling-file"; +// // const appName = "folder-with-sibling-file"; +// const outputPath = path.join(APPLICATIONS_PATH, baseApp.appName, "code"); +// const zip = new AdmZip("./__test__/drop/zips/folder-with-sibling-file.zip"); + +// const zipBuffer = zip.toBuffer(); +// const file = new File([zipBuffer], "single.zip"); +// await unzipDrop(file, baseApp); + +// const files = await fs.readdir(outputPath, { withFileTypes: true }); + +// expect(files.some((f) => f.name === "folder1")).toBe(true); +// expect(files.some((f) => f.name === "test.txt")).toBe(true); +// }); +// }); diff --git a/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip b/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip new file mode 100644 index 0000000000000000000000000000000000000000..3c522a9463a50e2c579e8b609806e1d418a51a43 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/folder-with-file.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c753d11eb45c2e64b74669db775e9e217ff5ac251732d05229146c6537d96900 +size 378 diff --git a/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip b/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip new file mode 100644 index 0000000000000000000000000000000000000000..1298657002349b6f7a3b98380a63f88afd6807b9 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/folder-with-sibling-file.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82d3367c279bb6292c0ffcfb0ed76958de77014e5c6562b1506b9bd71e53cbbd +size 560 diff --git a/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt b/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6b61b0bb8e2ad699a01c8ad60f3f6898bfef388 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/folder1/folder1.txt @@ -0,0 +1 @@ +Gogogogogogo \ No newline at end of file diff --git a/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt b/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt new file mode 100644 index 0000000000000000000000000000000000000000..3270d3de7dd881aba13e40cbf7f70d2a2ebe5e53 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/folder2/folder2.txt @@ -0,0 +1 @@ +gogogogogog \ No newline at end of file diff --git a/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt b/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt new file mode 100644 index 0000000000000000000000000000000000000000..80474b746ebfd01f0d6629d884c17da3e610c983 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/folder3/file3.txt @@ -0,0 +1 @@ +gogogogogogogogogo \ No newline at end of file diff --git a/data/apps/dokploy/__test__/drop/zips/nested.zip b/data/apps/dokploy/__test__/drop/zips/nested.zip new file mode 100644 index 0000000000000000000000000000000000000000..9df350a88eef7469b2b244550e7378ecbb34c1bc --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/nested.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b8387b34768406e0554e659dfb86a63bd4f2c1c79dd9624caa5055536e7de82 +size 1270 diff --git a/data/apps/dokploy/__test__/drop/zips/single-file.zip b/data/apps/dokploy/__test__/drop/zips/single-file.zip new file mode 100644 index 0000000000000000000000000000000000000000..f27c892c53c1d337017114a6d8dbad10d88a5b2d --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/single-file.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0229e960bcc6000edb6df21c8894d3922817937994d23838ed9428bd62ada51 +size 204 diff --git a/data/apps/dokploy/__test__/drop/zips/test.txt b/data/apps/dokploy/__test__/drop/zips/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..79f2fde0070c0ea423a4a84ac81bbb4f486e538e --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/test.txt @@ -0,0 +1 @@ +dsafasdfasdf \ No newline at end of file diff --git a/data/apps/dokploy/__test__/drop/zips/two-folders.zip b/data/apps/dokploy/__test__/drop/zips/two-folders.zip new file mode 100644 index 0000000000000000000000000000000000000000..80621c481d084b1a297dfd5fb65b7648227006f2 --- /dev/null +++ b/data/apps/dokploy/__test__/drop/zips/two-folders.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cdb32e9036129b0beb5c5ef00df71bf7f406a8c096851dc92ca094aebe00187 +size 734 diff --git a/data/apps/dokploy/__test__/env/shared.test.ts b/data/apps/dokploy/__test__/env/shared.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a8448aa9d78da6588194acca9a85f7c1819e6f4 --- /dev/null +++ b/data/apps/dokploy/__test__/env/shared.test.ts @@ -0,0 +1,179 @@ +import { prepareEnvironmentVariables } from "@dokploy/server/index"; +import { describe, expect, it } from "vitest"; + +const projectEnv = ` +ENVIRONMENT=staging +DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db +PORT=3000 +`; +const serviceEnv = ` +ENVIRONMENT=\${{project.ENVIRONMENT}} +DATABASE_URL=\${{project.DATABASE_URL}} +SERVICE_PORT=4000 +`; + +describe("prepareEnvironmentVariables", () => { + it("resolves project variables correctly", () => { + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "ENVIRONMENT=staging", + "DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db", + "SERVICE_PORT=4000", + ]); + }); + + it("handles undefined project variables", () => { + const incompleteProjectEnv = ` + NODE_ENV=production + `; + + const invalidServiceEnv = ` + UNDEFINED_VAR=\${{project.UNDEFINED_VAR}} + `; + + expect( + () => + prepareEnvironmentVariables(invalidServiceEnv, incompleteProjectEnv), // Cambiado el orden + ).toThrow("Invalid project environment variable: project.UNDEFINED_VAR"); + }); + it("allows service-specific variables to override project variables", () => { + const serviceSpecificEnv = ` + ENVIRONMENT=production + DATABASE_URL=\${{project.DATABASE_URL}} + `; + + const resolved = prepareEnvironmentVariables( + serviceSpecificEnv, + projectEnv, + ); + + expect(resolved).toEqual([ + "ENVIRONMENT=production", // Overrides project variable + "DATABASE_URL=postgres://postgres:postgres@localhost:5432/project_db", + ]); + }); + + it("resolves complex references for dynamic endpoints", () => { + const projectEnv = ` +BASE_URL=https://api.example.com +API_VERSION=v1 +PORT=8000 +`; + const serviceEnv = ` +API_ENDPOINT=\${{project.BASE_URL}}/\${{project.API_VERSION}}/endpoint +SERVICE_PORT=9000 +`; + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "API_ENDPOINT=https://api.example.com/v1/endpoint", + "SERVICE_PORT=9000", + ]); + }); + + it("handles missing project variables gracefully", () => { + const projectEnv = ` +PORT=8080 +`; + const serviceEnv = ` +MISSING_VAR=\${{project.MISSING_KEY}} +SERVICE_PORT=3000 +`; + + expect(() => prepareEnvironmentVariables(serviceEnv, projectEnv)).toThrow( + "Invalid project environment variable: project.MISSING_KEY", + ); + }); + + it("overrides project variables with service-specific values", () => { + const projectEnv = ` +ENVIRONMENT=staging +DATABASE_URL=postgres://project:project@localhost:5432/project_db +`; + const serviceEnv = ` +ENVIRONMENT=\${{project.ENVIRONMENT}} +DATABASE_URL=postgres://service:service@localhost:5432/service_db +SERVICE_NAME=my-service +`; + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "ENVIRONMENT=staging", + "DATABASE_URL=postgres://service:service@localhost:5432/service_db", + "SERVICE_NAME=my-service", + ]); + }); + + it("handles project variables with normal and unusual characters", () => { + const projectEnv = ` +ENVIRONMENT=PRODUCTION +`; + + // Needs to be in quotes + const serviceEnv = ` +NODE_ENV=\${{project.ENVIRONMENT}} +SPECIAL_VAR="$^@$^@#$^@!#$@#$-\${{project.ENVIRONMENT}}" +`; + + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "NODE_ENV=PRODUCTION", + "SPECIAL_VAR=$^@$^@#$^@!#$@#$-PRODUCTION", + ]); + }); + + it("handles complex cases with multiple references, special characters, and spaces", () => { + const projectEnv = ` +ENVIRONMENT=STAGING +APP_NAME=MyApp +`; + + const serviceEnv = ` +NODE_ENV=\${{project.ENVIRONMENT}} +COMPLEX_VAR="Prefix-$#^!@-\${{project.ENVIRONMENT}}--\${{project.APP_NAME}} Suffix " +`; + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "NODE_ENV=STAGING", + "COMPLEX_VAR=Prefix-$#^!@-STAGING--MyApp Suffix ", + ]); + }); + + it("handles references enclosed in single quotes", () => { + const projectEnv = ` + ENVIRONMENT=STAGING + APP_NAME=MyApp + `; + + const serviceEnv = ` + NODE_ENV='\${{project.ENVIRONMENT}}' + COMPLEX_VAR='Prefix-$#^!@-\${{project.ENVIRONMENT}}--\${{project.APP_NAME}} Suffix' + `; + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "NODE_ENV=STAGING", + "COMPLEX_VAR=Prefix-$#^!@-STAGING--MyApp Suffix", + ]); + }); + + it("handles double and single quotes combined", () => { + const projectEnv = ` +ENVIRONMENT=PRODUCTION +APP_NAME=MyApp +`; + const serviceEnv = ` +NODE_ENV="'\${{project.ENVIRONMENT}}'" +COMPLEX_VAR="'Prefix \"DoubleQuoted\" and \${{project.APP_NAME}}'" +`; + const resolved = prepareEnvironmentVariables(serviceEnv, projectEnv); + + expect(resolved).toEqual([ + "NODE_ENV='PRODUCTION'", + "COMPLEX_VAR='Prefix \"DoubleQuoted\" and MyApp'", + ]); + }); +}); diff --git a/data/apps/dokploy/__test__/requests/request.test.ts b/data/apps/dokploy/__test__/requests/request.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..997bd9ec5f4c1a03ddd0f9a073b5d57a968f8a6a --- /dev/null +++ b/data/apps/dokploy/__test__/requests/request.test.ts @@ -0,0 +1,56 @@ +import { parseRawConfig, processLogs } from "@dokploy/server"; +import { describe, expect, it } from "vitest"; +const sampleLogEntry = `{"ClientAddr":"172.19.0.1:56732","ClientHost":"172.19.0.1","ClientPort":"56732","ClientUsername":"-","DownstreamContentSize":0,"DownstreamStatus":304,"Duration":14729375,"OriginContentSize":0,"OriginDuration":14051833,"OriginStatus":304,"Overhead":677542,"RequestAddr":"s222-umami-c381af.traefik.me","RequestContentSize":0,"RequestCount":122,"RequestHost":"s222-umami-c381af.traefik.me","RequestMethod":"GET","RequestPath":"/dashboard?_rsc=1rugv","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-umami-60e104-47-web@docker","ServiceAddr":"10.0.1.15:3000","ServiceName":"s222-umami-60e104-47-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.15:3000","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T04:34:37.306691884Z","StartUTC":"2024-08-25T04:34:37.306691884Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T04:34:37Z"}`; + +describe("processLogs", () => { + it("should process a single log entry correctly", () => { + const result = processLogs(sampleLogEntry); + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + hour: "2024-08-25T04:00:00Z", + count: 1, + }); + }); + + it("should process multiple log entries and group by hour", () => { + const sampleLogEntry = `{"ClientAddr":"172.19.0.1:58094","ClientHost":"172.19.0.1","ClientPort":"58094","ClientUsername":"-","DownstreamContentSize":50,"DownstreamStatus":200,"Duration":35914250,"OriginContentSize":50,"OriginDuration":35817959,"OriginStatus":200,"Overhead":96291,"RequestAddr":"s222-pocketbase-f4a6e5.traefik.me","RequestContentSize":0,"RequestCount":991,"RequestHost":"s222-pocketbase-f4a6e5.traefik.me","RequestMethod":"GET","RequestPath":"/api/logs/stats?filter=","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-pocketbase-e94e25-44-web@docker","ServiceAddr":"10.0.1.12:80","ServiceName":"s222-pocketbase-e94e25-44-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.12:80","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T17:44:29.274072471Z","StartUTC":"2024-08-25T17:44:29.274072471Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T17:44:29Z"} +{"ClientAddr":"172.19.0.1:58108","ClientHost":"172.19.0.1","ClientPort":"58108","ClientUsername":"-","DownstreamContentSize":30975,"DownstreamStatus":200,"Duration":31406458,"OriginContentSize":30975,"OriginDuration":31046791,"OriginStatus":200,"Overhead":359667,"RequestAddr":"s222-pocketbase-f4a6e5.traefik.me","RequestContentSize":0,"RequestCount":992,"RequestHost":"s222-pocketbase-f4a6e5.traefik.me","RequestMethod":"GET","RequestPath":"/api/logs?page=1\u0026perPage=50\u0026sort=-rowid\u0026skipTotal=1\u0026filter=","RequestPort":"-","RequestProtocol":"HTTP/1.1","RequestScheme":"http","RetryAttempts":0,"RouterName":"s222-pocketbase-e94e25-44-web@docker","ServiceAddr":"10.0.1.12:80","ServiceName":"s222-pocketbase-e94e25-44-web@docker","ServiceURL":{"Scheme":"http","Opaque":"","User":null,"Host":"10.0.1.12:80","Path":"","RawPath":"","ForceQuery":false,"RawQuery":"","Fragment":"","RawFragment":""},"StartLocal":"2024-08-25T17:44:29.278990221Z","StartUTC":"2024-08-25T17:44:29.278990221Z","entryPointName":"web","level":"info","msg":"","time":"2024-08-25T17:44:29Z"} +`; + + const result = processLogs(sampleLogEntry); + expect(result).toHaveLength(1); + expect(result).toEqual([{ hour: "2024-08-25T17:00:00Z", count: 2 }]); + }); + + it("should return an empty array for empty input", () => { + expect(processLogs("")).toEqual([]); + expect(processLogs(null as any)).toEqual([]); + expect(processLogs(undefined as any)).toEqual([]); + }); + + // it("should parse a single log entry correctly", () => { + // const result = parseRawConfig(sampleLogEntry); + // expect(result).toHaveLength(1); + // expect(result.data[0]).toHaveProperty("ClientAddr", "172.19.0.1:56732"); + // expect(result.data[0]).toHaveProperty( + // "StartUTC", + // "2024-08-25T04:34:37.306691884Z", + // ); + // }); + + it("should parse multiple log entries", () => { + const multipleEntries = `${sampleLogEntry}\n${sampleLogEntry}`; + const result = parseRawConfig(multipleEntries); + expect(result.data).toHaveLength(2); + + for (const entry of result.data) { + expect(entry).toHaveProperty("ClientAddr", "172.19.0.1:56732"); + } + }); + + it("should handle whitespace and empty lines", () => { + const entryWithWhitespace = `\n${sampleLogEntry}\n\n${sampleLogEntry}\n`; + const result = parseRawConfig(entryWithWhitespace); + expect(result.data).toHaveLength(2); + }); +}); diff --git a/data/apps/dokploy/__test__/templates/config.template.test.ts b/data/apps/dokploy/__test__/templates/config.template.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..202abdf2d6535dafea4b930f7d7014789e83bc57 --- /dev/null +++ b/data/apps/dokploy/__test__/templates/config.template.test.ts @@ -0,0 +1,497 @@ +import type { Schema } from "@dokploy/server/templates"; +import type { CompleteTemplate } from "@dokploy/server/templates/processors"; +import { processTemplate } from "@dokploy/server/templates/processors"; +import { describe, expect, it } from "vitest"; + +describe("processTemplate", () => { + // Mock schema for testing + const mockSchema: Schema = { + projectName: "test", + serverIp: "127.0.0.1", + }; + + describe("variables processing", () => { + it("should process basic variables with utility functions", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + main_domain: "${domain}", + secret_base: "${base64:64}", + totp_key: "${base64:32}", + password: "${password:32}", + hash: "${hash:16}", + }, + config: { + domains: [], + env: {}, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(0); + expect(result.domains).toHaveLength(0); + expect(result.mounts).toHaveLength(0); + }); + + it("should allow referencing variables in other variables", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + main_domain: "${domain}", + api_domain: "api.${main_domain}", + }, + config: { + domains: [], + env: {}, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(0); + expect(result.domains).toHaveLength(0); + expect(result.mounts).toHaveLength(0); + }); + + it("should allow creation of real jwt secret", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + jwt_secret: "cQsdycq1hDLopQonF6jUTqgQc5WEZTwWLL02J6XJ", + anon_payload: JSON.stringify({ + role: "tester", + iss: "dockploy", + iat: "${timestamps:2025-01-01T00:00:00Z}", + exp: "${timestamps:2030-01-01T00:00:00Z}", + }), + anon_key: "${jwt:jwt_secret:anon_payload}", + }, + config: { + domains: [], + env: { + ANON_KEY: "${anon_key}", + }, + }, + }; + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(1); + expect(result.envs).toContain( + "ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOiIxNzM1Njg5NjAwIiwiZXhwIjoiMTg5MzQ1NjAwMCIsInJvbGUiOiJ0ZXN0ZXIiLCJpc3MiOiJkb2NrcGxveSJ9.BG5JoxL2_NaTFbPgyZdm3kRWenf_O3su_HIRKGCJ_kY", + ); + expect(result.mounts).toHaveLength(0); + expect(result.domains).toHaveLength(0); + }); + }); + + describe("domains processing", () => { + it("should process domains with explicit host", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + main_domain: "${domain}", + }, + config: { + domains: [ + { + serviceName: "plausible", + port: 8000, + host: "${main_domain}", + }, + ], + env: {}, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.domains).toHaveLength(1); + const domain = result.domains[0]; + expect(domain).toBeDefined(); + if (!domain) return; + expect(domain).toMatchObject({ + serviceName: "plausible", + port: 8000, + }); + expect(domain.host).toBeDefined(); + expect(domain.host).toContain(mockSchema.projectName); + }); + + it("should generate random domain if host is not specified", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [ + { + serviceName: "plausible", + port: 8000, + }, + ], + env: {}, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.domains).toHaveLength(1); + const domain = result.domains[0]; + expect(domain).toBeDefined(); + if (!domain || !domain.host) return; + expect(domain.host).toBeDefined(); + expect(domain.host).toContain(mockSchema.projectName); + }); + + it("should allow using ${domain} directly in host", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [ + { + serviceName: "plausible", + port: 8000, + host: "${domain}", + }, + ], + env: {}, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.domains).toHaveLength(1); + const domain = result.domains[0]; + expect(domain).toBeDefined(); + if (!domain || !domain.host) return; + expect(domain.host).toBeDefined(); + expect(domain.host).toContain(mockSchema.projectName); + }); + }); + + describe("environment variables processing", () => { + it("should process env vars with variable references", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + main_domain: "${domain}", + secret_base: "${base64:64}", + }, + config: { + domains: [], + env: { + BASE_URL: "http://${main_domain}", + SECRET_KEY_BASE: "${secret_base}", + }, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(2); + const baseUrl = result.envs.find((env: string) => + env.startsWith("BASE_URL="), + ); + const secretKey = result.envs.find((env: string) => + env.startsWith("SECRET_KEY_BASE="), + ); + + expect(baseUrl).toBeDefined(); + expect(secretKey).toBeDefined(); + if (!baseUrl || !secretKey) return; + + expect(baseUrl).toContain(mockSchema.projectName); + const base64Value = secretKey.split("=")[1]; + expect(base64Value).toBeDefined(); + if (!base64Value) return; + expect(base64Value).toMatch(/^[A-Za-z0-9+/]+={0,2}$/); + expect(base64Value.length).toBeGreaterThanOrEqual(86); + expect(base64Value.length).toBeLessThanOrEqual(88); + }); + + it("should process env vars when provided as an array", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [], + env: [ + 'CLOUDFLARE_TUNNEL_TOKEN=""', + 'ANOTHER_VAR="some value"', + "DOMAIN=${domain}", + ], + mounts: [], + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(3); + + // Should preserve exact format for static values + expect(result.envs[0]).toBe('CLOUDFLARE_TUNNEL_TOKEN=""'); + expect(result.envs[1]).toBe('ANOTHER_VAR="some value"'); + + // Should process variables in array items + expect(result.envs[2]).toContain(mockSchema.projectName); + }); + + it("should allow using utility functions directly in env vars", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [], + env: { + RANDOM_DOMAIN: "${domain}", + SECRET_KEY: "${base64:32}", + }, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(2); + const randomDomainEnv = result.envs.find((env: string) => + env.startsWith("RANDOM_DOMAIN="), + ); + const secretKeyEnv = result.envs.find((env: string) => + env.startsWith("SECRET_KEY="), + ); + expect(randomDomainEnv).toBeDefined(); + expect(secretKeyEnv).toBeDefined(); + if (!randomDomainEnv || !secretKeyEnv) return; + + expect(randomDomainEnv).toContain(mockSchema.projectName); + const base64Value = secretKeyEnv.split("=")[1]; + expect(base64Value).toBeDefined(); + if (!base64Value) return; + expect(base64Value).toMatch(/^[A-Za-z0-9+/]+={0,2}$/); + expect(base64Value.length).toBeGreaterThanOrEqual(42); + expect(base64Value.length).toBeLessThanOrEqual(44); + }); + + it("should handle boolean values in env vars when provided as an array", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [], + env: [ + "ENABLE_USER_SIGN_UP=false", + "DEBUG_MODE=true", + "SOME_NUMBER=42", + ], + mounts: [], + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(3); + expect(result.envs).toContain("ENABLE_USER_SIGN_UP=false"); + expect(result.envs).toContain("DEBUG_MODE=true"); + expect(result.envs).toContain("SOME_NUMBER=42"); + }); + + it("should handle boolean values in env vars when provided as an object", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [], + env: { + ENABLE_USER_SIGN_UP: false, + DEBUG_MODE: true, + SOME_NUMBER: 42, + }, + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(3); + expect(result.envs).toContain("ENABLE_USER_SIGN_UP=false"); + expect(result.envs).toContain("DEBUG_MODE=true"); + expect(result.envs).toContain("SOME_NUMBER=42"); + }); + }); + + describe("mounts processing", () => { + it("should process mounts with variable references", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + config_path: "/etc/config", + secret_key: "${base64:32}", + }, + config: { + domains: [], + env: {}, + mounts: [ + { + filePath: "${config_path}/config.xml", + content: "secret_key=${secret_key}", + }, + ], + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.mounts).toHaveLength(1); + const mount = result.mounts[0]; + expect(mount).toBeDefined(); + if (!mount) return; + expect(mount.filePath).toContain("/etc/config"); + expect(mount.content).toMatch(/secret_key=[A-Za-z0-9+/]{32}/); + }); + + it("should allow using utility functions directly in mount content", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [], + env: {}, + mounts: [ + { + filePath: "/config/secrets.txt", + content: "random_domain=${domain}\nsecret=${base64:32}", + }, + ], + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.mounts).toHaveLength(1); + const mount = result.mounts[0]; + expect(mount).toBeDefined(); + if (!mount) return; + expect(mount.content).toContain(mockSchema.projectName); + expect(mount.content).toMatch(/secret=[A-Za-z0-9+/]{32}/); + }); + }); + + describe("complex template processing", () => { + it("should process a complete template with all features", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: { + main_domain: "${domain}", + secret_base: "${base64:64}", + totp_key: "${base64:32}", + }, + config: { + domains: [ + { + serviceName: "plausible", + port: 8000, + host: "${main_domain}", + }, + { + serviceName: "api", + port: 3000, + host: "api.${main_domain}", + }, + ], + env: { + BASE_URL: "http://${main_domain}", + SECRET_KEY_BASE: "${secret_base}", + TOTP_VAULT_KEY: "${totp_key}", + }, + mounts: [ + { + filePath: "/config/app.conf", + content: ` + domain=\${main_domain} + secret=\${secret_base} + totp=\${totp_key} + `, + }, + ], + }, + }; + + const result = processTemplate(template, mockSchema); + + // Check domains + expect(result.domains).toHaveLength(2); + const [domain1, domain2] = result.domains; + expect(domain1).toBeDefined(); + expect(domain2).toBeDefined(); + if (!domain1 || !domain2) return; + expect(domain1.host).toBeDefined(); + expect(domain1.host).toContain(mockSchema.projectName); + expect(domain2.host).toContain("api."); + expect(domain2.host).toContain(mockSchema.projectName); + + // Check env vars + expect(result.envs).toHaveLength(3); + const baseUrl = result.envs.find((env: string) => + env.startsWith("BASE_URL="), + ); + const secretKey = result.envs.find((env: string) => + env.startsWith("SECRET_KEY_BASE="), + ); + const totpKey = result.envs.find((env: string) => + env.startsWith("TOTP_VAULT_KEY="), + ); + + expect(baseUrl).toBeDefined(); + expect(secretKey).toBeDefined(); + expect(totpKey).toBeDefined(); + if (!baseUrl || !secretKey || !totpKey) return; + + expect(baseUrl).toContain(mockSchema.projectName); + + // Check base64 lengths and format + const secretKeyValue = secretKey.split("=")[1]; + const totpKeyValue = totpKey.split("=")[1]; + + expect(secretKeyValue).toBeDefined(); + expect(totpKeyValue).toBeDefined(); + if (!secretKeyValue || !totpKeyValue) return; + + expect(secretKeyValue).toMatch(/^[A-Za-z0-9+/]+={0,2}$/); + expect(secretKeyValue.length).toBeGreaterThanOrEqual(86); + expect(secretKeyValue.length).toBeLessThanOrEqual(88); + + expect(totpKeyValue).toMatch(/^[A-Za-z0-9+/]+={0,2}$/); + expect(totpKeyValue.length).toBeGreaterThanOrEqual(42); + expect(totpKeyValue.length).toBeLessThanOrEqual(44); + + // Check mounts + expect(result.mounts).toHaveLength(1); + const mount = result.mounts[0]; + expect(mount).toBeDefined(); + if (!mount) return; + expect(mount.content).toContain(mockSchema.projectName); + expect(mount.content).toMatch(/secret=[A-Za-z0-9+/]{86,88}/); + expect(mount.content).toMatch(/totp=[A-Za-z0-9+/]{42,44}/); + }); + }); + + describe("Should populate envs, domains and mounts in the case we didn't used any variable", () => { + it("should populate envs, domains and mounts in the case we didn't used any variable", () => { + const template: CompleteTemplate = { + metadata: {} as any, + variables: {}, + config: { + domains: [ + { + serviceName: "plausible", + port: 8000, + host: "${hash}", + }, + ], + env: { + BASE_URL: "http://${domain}", + SECRET_KEY_BASE: "${password:32}", + TOTP_VAULT_KEY: "${base64:128}", + }, + mounts: [ + { + filePath: "/config/secrets.txt", + content: "random_domain=${domain}\nsecret=${password:32}", + }, + ], + }, + }; + + const result = processTemplate(template, mockSchema); + expect(result.envs).toHaveLength(3); + expect(result.domains).toHaveLength(1); + expect(result.mounts).toHaveLength(1); + }); + }); +}); diff --git a/data/apps/dokploy/__test__/templates/helpers.template.test.ts b/data/apps/dokploy/__test__/templates/helpers.template.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1144b65fe5be31e476cb7a469680d93a6758e8f0 --- /dev/null +++ b/data/apps/dokploy/__test__/templates/helpers.template.test.ts @@ -0,0 +1,232 @@ +import type { Schema } from "@dokploy/server/templates"; +import { processValue } from "@dokploy/server/templates/processors"; +import { describe, expect, it } from "vitest"; + +describe("helpers functions", () => { + // Mock schema for testing + const mockSchema: Schema = { + projectName: "test", + serverIp: "127.0.0.1", + }; + // some helpers to test jwt + type JWTParts = [string, string, string]; + const jwtMatchExp = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/; + const jwtBase64Decode = (str: string) => { + const base64 = str.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + const decoded = Buffer.from(base64 + padding, "base64").toString("utf-8"); + return JSON.parse(decoded); + }; + const jwtCheckHeader = (jwtHeader: string) => { + const decodedHeader = jwtBase64Decode(jwtHeader); + expect(decodedHeader).toHaveProperty("alg"); + expect(decodedHeader).toHaveProperty("typ"); + expect(decodedHeader.alg).toEqual("HS256"); + expect(decodedHeader.typ).toEqual("JWT"); + }; + + describe("${domain}", () => { + it("should generate a random domain", () => { + const domain = processValue("${domain}", {}, mockSchema); + expect(domain.startsWith(`${mockSchema.projectName}-`)).toBeTruthy(); + expect( + domain.endsWith( + `${mockSchema.serverIp.replaceAll(".", "-")}.traefik.me`, + ), + ).toBeTruthy(); + }); + }); + + describe("${base64}", () => { + it("should generate a base64 string", () => { + const base64 = processValue("${base64}", {}, mockSchema); + expect(base64).toMatch(/^[A-Za-z0-9+=/]+={0,2}$/); + }); + it.each([ + [4, 8], + [8, 12], + [16, 24], + [32, 44], + [64, 88], + [128, 172], + ])( + "should generate a base64 string from parameter %d bytes length", + (length, finalLength) => { + const base64 = processValue(`\${base64:${length}}`, {}, mockSchema); + expect(base64).toMatch(/^[A-Za-z0-9+=/]+={0,2}$/); + expect(base64.length).toBe(finalLength); + }, + ); + }); + + describe("${password}", () => { + it("should generate a password string", () => { + const password = processValue("${password}", {}, mockSchema); + expect(password).toMatch(/^[A-Za-z0-9]+$/); + }); + it.each([6, 8, 12, 16, 32])( + "should generate a password string respecting parameter %d length", + (length) => { + const password = processValue(`\${password:${length}}`, {}, mockSchema); + expect(password).toMatch(/^[A-Za-z0-9]+$/); + expect(password.length).toBe(length); + }, + ); + }); + + describe("${hash}", () => { + it("should generate a hash string", () => { + const hash = processValue("${hash}", {}, mockSchema); + expect(hash).toMatch(/^[A-Za-z0-9]+$/); + }); + it.each([6, 8, 12, 16, 32])( + "should generate a hash string respecting parameter %d length", + (length) => { + const hash = processValue(`\${hash:${length}}`, {}, mockSchema); + expect(hash).toMatch(/^[A-Za-z0-9]+$/); + expect(hash.length).toBe(length); + }, + ); + }); + + describe("${uuid}", () => { + it("should generate a UUID string", () => { + const uuid = processValue("${uuid}", {}, mockSchema); + expect(uuid).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ); + }); + }); + + describe("${timestamp}", () => { + it("should generate a timestamp string in milliseconds", () => { + const timestamp = processValue("${timestamp}", {}, mockSchema); + const nowLength = Math.floor(Date.now()).toString().length; + expect(timestamp).toMatch(/^\d+$/); + expect(timestamp.length).toBe(nowLength); + }); + }); + describe("${timestampms}", () => { + it("should generate a timestamp string in milliseconds", () => { + const timestamp = processValue("${timestampms}", {}, mockSchema); + const nowLength = Date.now().toString().length; + expect(timestamp).toMatch(/^\d+$/); + expect(timestamp.length).toBe(nowLength); + }); + it("should generate a timestamp string in milliseconds from parameter", () => { + const timestamp = processValue( + "${timestampms:2025-01-01}", + {}, + mockSchema, + ); + expect(timestamp).toEqual("1735689600000"); + }); + }); + describe("${timestamps}", () => { + it("should generate a timestamp string in seconds", () => { + const timestamps = processValue("${timestamps}", {}, mockSchema); + const nowLength = Math.floor(Date.now() / 1000).toString().length; + expect(timestamps).toMatch(/^\d+$/); + expect(timestamps.length).toBe(nowLength); + }); + it("should generate a timestamp string in seconds from parameter", () => { + const timestamps = processValue( + "${timestamps:2025-01-01}", + {}, + mockSchema, + ); + expect(timestamps).toEqual("1735689600"); + }); + }); + + describe("${randomPort}", () => { + it("should generate a random port string", () => { + const randomPort = processValue("${randomPort}", {}, mockSchema); + expect(randomPort).toMatch(/^\d+$/); + expect(Number(randomPort)).toBeLessThan(65536); + }); + }); + + describe("${username}", () => { + it("should generate a username string", () => { + const username = processValue("${username}", {}, mockSchema); + expect(username).toMatch(/^[a-zA-Z0-9._-]{3,}$/); + }); + }); + + describe("${email}", () => { + it("should generate an email string", () => { + const email = processValue("${email}", {}, mockSchema); + expect(email).toMatch(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/); + }); + }); + + describe("${jwt}", () => { + it("should generate a JWT string", () => { + const jwt = processValue("${jwt}", {}, mockSchema); + expect(jwt).toMatch(jwtMatchExp); + const parts = jwt.split(".") as JWTParts; + const decodedPayload = jwtBase64Decode(parts[1]); + jwtCheckHeader(parts[0]); + expect(decodedPayload).toHaveProperty("iat"); + expect(decodedPayload).toHaveProperty("iss"); + expect(decodedPayload).toHaveProperty("exp"); + expect(decodedPayload.iss).toEqual("dokploy"); + }); + it.each([6, 8, 12, 16, 32])( + "should generate a random hex string from parameter %d byte length", + (length) => { + const jwt = processValue(`\${jwt:${length}}`, {}, mockSchema); + expect(jwt).toMatch(/^[A-Za-z0-9-_.]+$/); + expect(jwt.length).toBeGreaterThanOrEqual(length); // bytes translated to hex can take up to 2x the length + expect(jwt.length).toBeLessThanOrEqual(length * 2); + }, + ); + }); + describe("${jwt:secret}", () => { + it("should generate a JWT string respecting parameter secret from variable", () => { + const jwt = processValue( + "${jwt:secret}", + { secret: "mysecret" }, + mockSchema, + ); + expect(jwt).toMatch(jwtMatchExp); + const parts = jwt.split(".") as JWTParts; + const decodedPayload = jwtBase64Decode(parts[1]); + jwtCheckHeader(parts[0]); + expect(decodedPayload).toHaveProperty("iat"); + expect(decodedPayload).toHaveProperty("iss"); + expect(decodedPayload).toHaveProperty("exp"); + expect(decodedPayload.iss).toEqual("dokploy"); + }); + }); + describe("${jwt:secret:payload}", () => { + it("should generate a JWT string respecting parameters secret and payload from variables", () => { + const iat = Math.floor(new Date("2025-01-01T00:00:00Z").getTime() / 1000); + const expiry = iat + 3600; + const jwt = processValue( + "${jwt:secret:payload}", + { + secret: "mysecret", + payload: `{"iss": "test-issuer", "iat": ${iat}, "exp": ${expiry}, "customprop": "customvalue"}`, + }, + mockSchema, + ); + expect(jwt).toMatch(jwtMatchExp); + const parts = jwt.split(".") as JWTParts; + jwtCheckHeader(parts[0]); + const decodedPayload = jwtBase64Decode(parts[1]); + expect(decodedPayload).toHaveProperty("iat"); + expect(decodedPayload.iat).toEqual(iat); + expect(decodedPayload).toHaveProperty("iss"); + expect(decodedPayload.iss).toEqual("test-issuer"); + expect(decodedPayload).toHaveProperty("exp"); + expect(decodedPayload.exp).toEqual(expiry); + expect(decodedPayload).toHaveProperty("customprop"); + expect(decodedPayload.customprop).toEqual("customvalue"); + expect(jwt).toEqual( + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MzU2ODk2MDAsImV4cCI6MTczNTY5MzIwMCwiaXNzIjoidGVzdC1pc3N1ZXIiLCJjdXN0b21wcm9wIjoiY3VzdG9tdmFsdWUifQ.m42U7PZSUSCf7gBOJrxJir0rQmyPq4rA59Dydr_QahI", + ); + }); + }); +}); diff --git a/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts b/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6858f0f005b1dbf159931427f3f2cea704aa2895 --- /dev/null +++ b/data/apps/dokploy/__test__/traefik/server/update-server-config.test.ts @@ -0,0 +1,133 @@ +import { fs, vol } from "memfs"; + +vi.mock("node:fs", () => ({ + ...fs, + default: fs, +})); + +import type { FileConfig, User } from "@dokploy/server"; +import { + createDefaultServerTraefikConfig, + loadOrCreateConfig, + updateServerTraefik, +} from "@dokploy/server"; +import { beforeEach, expect, test, vi } from "vitest"; + +const baseAdmin: User = { + https: false, + enablePaidFeatures: false, + allowImpersonation: false, + role: "user", + metricsConfig: { + containers: { + refreshRate: 20, + services: { + include: [], + exclude: [], + }, + }, + server: { + type: "Dokploy", + cronJob: "", + port: 4500, + refreshRate: 20, + retentionDays: 2, + token: "", + thresholds: { + cpu: 0, + memory: 0, + }, + urlCallback: "", + }, + }, + cleanupCacheApplications: false, + cleanupCacheOnCompose: false, + cleanupCacheOnPreviews: false, + createdAt: new Date(), + serverIp: null, + certificateType: "none", + host: null, + letsEncryptEmail: null, + sshPrivateKey: null, + enableDockerCleanup: false, + logCleanupCron: null, + serversQuantity: 0, + stripeCustomerId: "", + stripeSubscriptionId: "", + banExpires: new Date(), + banned: true, + banReason: "", + email: "", + expirationDate: "", + id: "", + isRegistered: false, + name: "", + createdAt2: new Date().toISOString(), + emailVerified: false, + image: "", + updatedAt: new Date(), + twoFactorEnabled: false, +}; + +beforeEach(() => { + vol.reset(); + createDefaultServerTraefikConfig(); +}); + +test("Should read the configuration file", () => { + const config: FileConfig = loadOrCreateConfig("dokploy"); + expect(config.http?.routers?.["dokploy-router-app"]?.service).toBe( + "dokploy-service-app", + ); +}); + +test("Should apply redirect-to-https", () => { + updateServerTraefik( + { + ...baseAdmin, + https: true, + certificateType: "letsencrypt", + }, + "example.com", + ); + + const config: FileConfig = loadOrCreateConfig("dokploy"); + + expect(config.http?.routers?.["dokploy-router-app"]?.middlewares).toContain( + "redirect-to-https", + ); +}); + +test("Should change only host when no certificate", () => { + updateServerTraefik(baseAdmin, "example.com"); + + const config: FileConfig = loadOrCreateConfig("dokploy"); + + expect(config.http?.routers?.["dokploy-router-app-secure"]).toBeUndefined(); +}); + +test("Should not touch config without host", () => { + const originalConfig: FileConfig = loadOrCreateConfig("dokploy"); + + updateServerTraefik(baseAdmin, null); + + const config: FileConfig = loadOrCreateConfig("dokploy"); + + expect(originalConfig).toEqual(config); +}); + +test("Should remove websecure if https rollback to http", () => { + updateServerTraefik( + { ...baseAdmin, certificateType: "letsencrypt" }, + "example.com", + ); + + updateServerTraefik({ ...baseAdmin, certificateType: "none" }, "example.com"); + + const config: FileConfig = loadOrCreateConfig("dokploy"); + + expect(config.http?.routers?.["dokploy-router-app-secure"]).toBeUndefined(); + expect( + config.http?.routers?.["dokploy-router-app"]?.middlewares, + ).not.toContain("redirect-to-https"); +}); diff --git a/data/apps/dokploy/__test__/traefik/traefik.test.ts b/data/apps/dokploy/__test__/traefik/traefik.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c136b259dde9efaae30f7935319fe17962a0580 --- /dev/null +++ b/data/apps/dokploy/__test__/traefik/traefik.test.ts @@ -0,0 +1,250 @@ +import type { Domain } from "@dokploy/server"; +import type { Redirect } from "@dokploy/server"; +import type { ApplicationNested } from "@dokploy/server"; +import { createRouterConfig } from "@dokploy/server"; +import { expect, test } from "vitest"; + +const baseApp: ApplicationNested = { + applicationId: "", + herokuVersion: "", + giteaRepository: "", + giteaOwner: "", + giteaBranch: "", + giteaBuildPath: "", + giteaId: "", + cleanCache: false, + applicationStatus: "done", + appName: "", + autoDeploy: true, + enableSubmodules: false, + serverId: "", + branch: null, + dockerBuildStage: "", + registryUrl: "", + watchPaths: [], + buildArgs: null, + isPreviewDeploymentsActive: false, + previewBuildArgs: null, + triggerType: "push", + previewCertificateType: "none", + previewEnv: null, + previewHttps: false, + previewPath: "/", + previewPort: 3000, + previewLimit: 0, + previewCustomCertResolver: null, + previewWildcard: "", + project: { + env: "", + organizationId: "", + name: "", + description: "", + createdAt: "", + projectId: "", + }, + buildPath: "/", + gitlabPathNamespace: "", + buildType: "nixpacks", + bitbucketBranch: "", + bitbucketBuildPath: "", + bitbucketId: "", + bitbucketRepository: "", + bitbucketOwner: "", + githubId: "", + gitlabProjectId: 0, + gitlabBranch: "", + gitlabBuildPath: "", + gitlabId: "", + gitlabRepository: "", + gitlabOwner: "", + command: null, + cpuLimit: null, + cpuReservation: null, + createdAt: "", + customGitBranch: "", + customGitBuildPath: "", + customGitSSHKeyId: null, + customGitUrl: "", + description: "", + dockerfile: null, + dockerImage: null, + dropBuildPath: null, + enabled: null, + env: null, + healthCheckSwarm: null, + labelsSwarm: null, + memoryLimit: null, + memoryReservation: null, + modeSwarm: null, + mounts: [], + name: "", + networkSwarm: null, + owner: null, + password: null, + placementSwarm: null, + ports: [], + projectId: "", + publishDirectory: null, + isStaticSpa: null, + redirects: [], + refreshToken: "", + registry: null, + registryId: null, + replicas: 1, + repository: null, + restartPolicySwarm: null, + rollbackConfigSwarm: null, + security: [], + sourceType: "git", + subtitle: null, + title: null, + updateConfigSwarm: null, + username: null, + dockerContextPath: null, +}; + +const baseDomain: Domain = { + applicationId: "", + certificateType: "none", + createdAt: "", + domainId: "", + host: "", + https: false, + path: null, + port: null, + serviceName: "", + composeId: "", + customCertResolver: null, + domainType: "application", + uniqueConfigKey: 1, + previewDeploymentId: "", +}; + +const baseRedirect: Redirect = { + redirectId: "", + regex: "", + replacement: "", + permanent: false, + uniqueConfigKey: 1, + createdAt: "", + applicationId: "", +}; + +/** Middlewares */ + +test("Web entrypoint on http domain", async () => { + const router = await createRouterConfig( + baseApp, + { ...baseDomain, https: false }, + "web", + ); + + expect(router.middlewares).not.toContain("redirect-to-https"); + expect(router.rule).not.toContain("PathPrefix"); +}); + +test("Web entrypoint on http domain with custom path", async () => { + const router = await createRouterConfig( + baseApp, + { ...baseDomain, path: "/foo", https: false }, + "web", + ); + + expect(router.rule).toContain("PathPrefix(`/foo`)"); +}); + +test("Web entrypoint on http domain with redirect", async () => { + const router = await createRouterConfig( + { + ...baseApp, + appName: "test", + redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }], + }, + { ...baseDomain, https: false }, + "web", + ); + + expect(router.middlewares).not.toContain("redirect-to-https"); + expect(router.middlewares).toContain("redirect-test-1"); +}); + +test("Web entrypoint on http domain with multiple redirect", async () => { + const router = await createRouterConfig( + { + ...baseApp, + appName: "test", + redirects: [ + { ...baseRedirect, uniqueConfigKey: 1 }, + { ...baseRedirect, uniqueConfigKey: 2 }, + ], + }, + { ...baseDomain, https: false }, + "web", + ); + + expect(router.middlewares).not.toContain("redirect-to-https"); + expect(router.middlewares).toContain("redirect-test-1"); + expect(router.middlewares).toContain("redirect-test-2"); +}); + +test("Web entrypoint on https domain", async () => { + const router = await createRouterConfig( + baseApp, + { ...baseDomain, https: true }, + "web", + ); + + expect(router.middlewares).toContain("redirect-to-https"); +}); + +test("Web entrypoint on https domain with redirect", async () => { + const router = await createRouterConfig( + { + ...baseApp, + appName: "test", + redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }], + }, + { ...baseDomain, https: true }, + "web", + ); + + expect(router.middlewares).toContain("redirect-to-https"); + expect(router.middlewares).not.toContain("redirect-test-1"); +}); + +test("Websecure entrypoint on https domain", async () => { + const router = await createRouterConfig( + baseApp, + { ...baseDomain, https: true }, + "websecure", + ); + + expect(router.middlewares).not.toContain("redirect-to-https"); +}); + +test("Websecure entrypoint on https domain with redirect", async () => { + const router = await createRouterConfig( + { + ...baseApp, + appName: "test", + redirects: [{ ...baseRedirect, uniqueConfigKey: 1 }], + }, + { ...baseDomain, https: true }, + "websecure", + ); + + expect(router.middlewares).not.toContain("redirect-to-https"); + expect(router.middlewares).toContain("redirect-test-1"); +}); + +/** Certificates */ + +test("CertificateType on websecure entrypoint", async () => { + const router = await createRouterConfig( + baseApp, + { ...baseDomain, certificateType: "letsencrypt" }, + "websecure", + ); + + expect(router.tls?.certResolver).toBe("letsencrypt"); +}); diff --git a/data/apps/dokploy/__test__/utils/backups.test.ts b/data/apps/dokploy/__test__/utils/backups.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c1e5decc991b25fce568da385326149f16b0d65 --- /dev/null +++ b/data/apps/dokploy/__test__/utils/backups.test.ts @@ -0,0 +1,61 @@ +import { normalizeS3Path } from "@dokploy/server/utils/backups/utils"; +import { describe, expect, test } from "vitest"; + +describe("normalizeS3Path", () => { + test("should handle empty and whitespace-only prefix", () => { + expect(normalizeS3Path("")).toBe(""); + expect(normalizeS3Path("/")).toBe(""); + expect(normalizeS3Path(" ")).toBe(""); + expect(normalizeS3Path("\t")).toBe(""); + expect(normalizeS3Path("\n")).toBe(""); + expect(normalizeS3Path(" \n \t ")).toBe(""); + }); + + test("should trim whitespace from prefix", () => { + expect(normalizeS3Path(" prefix")).toBe("prefix/"); + expect(normalizeS3Path("prefix ")).toBe("prefix/"); + expect(normalizeS3Path(" prefix ")).toBe("prefix/"); + expect(normalizeS3Path("\tprefix\t")).toBe("prefix/"); + expect(normalizeS3Path(" prefix/nested ")).toBe("prefix/nested/"); + }); + + test("should remove leading slashes", () => { + expect(normalizeS3Path("/prefix")).toBe("prefix/"); + expect(normalizeS3Path("///prefix")).toBe("prefix/"); + }); + + test("should remove trailing slashes", () => { + expect(normalizeS3Path("prefix/")).toBe("prefix/"); + expect(normalizeS3Path("prefix///")).toBe("prefix/"); + }); + + test("should remove both leading and trailing slashes", () => { + expect(normalizeS3Path("/prefix/")).toBe("prefix/"); + expect(normalizeS3Path("///prefix///")).toBe("prefix/"); + }); + + test("should handle nested paths", () => { + expect(normalizeS3Path("prefix/nested")).toBe("prefix/nested/"); + expect(normalizeS3Path("/prefix/nested/")).toBe("prefix/nested/"); + expect(normalizeS3Path("///prefix/nested///")).toBe("prefix/nested/"); + }); + + test("should preserve middle slashes", () => { + expect(normalizeS3Path("prefix/nested/deep")).toBe("prefix/nested/deep/"); + expect(normalizeS3Path("/prefix/nested/deep/")).toBe("prefix/nested/deep/"); + }); + + test("should handle special characters", () => { + expect(normalizeS3Path("prefix-with-dashes")).toBe("prefix-with-dashes/"); + expect(normalizeS3Path("prefix_with_underscores")).toBe( + "prefix_with_underscores/", + ); + expect(normalizeS3Path("prefix.with.dots")).toBe("prefix.with.dots/"); + }); + + test("should handle the cases from the bug report", () => { + expect(normalizeS3Path("instance-backups/")).toBe("instance-backups/"); + expect(normalizeS3Path("/instance-backups/")).toBe("instance-backups/"); + expect(normalizeS3Path("instance-backups")).toBe("instance-backups/"); + }); +}); diff --git a/data/apps/dokploy/__test__/vitest.config.ts b/data/apps/dokploy/__test__/vitest.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddc84d6ac3058504daea00f1b1d35a1171c6846b --- /dev/null +++ b/data/apps/dokploy/__test__/vitest.config.ts @@ -0,0 +1,25 @@ +import path from "node:path"; +import tsconfigPaths from "vite-tsconfig-paths"; +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["__test__/**/*.test.ts"], // Incluir solo los archivos de test en el directorio __test__ + exclude: ["**/node_modules/**", "**/dist/**", "**/.docker/**"], + pool: "forks", + }, + define: { + "process.env": { + NODE: "test", + }, + }, + plugins: [tsconfigPaths()], + resolve: { + alias: { + "@dokploy/server": path.resolve( + __dirname, + "../../../packages/server/src", + ), + }, + }, +}); diff --git a/data/apps/dokploy/components.json b/data/apps/dokploy/components.json new file mode 100644 index 0000000000000000000000000000000000000000..81104c1e9ab89d3683d170d88d6e20f2aa670e93 --- /dev/null +++ b/data/apps/dokploy/components.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "styles/globals.css", + "baseColor": "zinc", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils" + } +} diff --git a/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx b/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx new file mode 100644 index 0000000000000000000000000000000000000000..95a559f66280f9a1c21e56afba9f2bedb920cbd8 --- /dev/null +++ b/data/apps/dokploy/components/dashboard/application/advanced/cluster/modify-swarm-settings.tsx @@ -0,0 +1,770 @@ +import { AlertBlock } from "@/components/shared/alert-block"; +import { CodeEditor } from "@/components/shared/code-editor"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { api } from "@/utils/api"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { HelpCircle, Settings } from "lucide-react"; +import { useEffect } from "react"; +import { useForm } from "react-hook-form"; +import { toast } from "sonner"; +import { z } from "zod"; + +const HealthCheckSwarmSchema = z + .object({ + Test: z.array(z.string()).optional(), + Interval: z.number().optional(), + Timeout: z.number().optional(), + StartPeriod: z.number().optional(), + Retries: z.number().optional(), + }) + .strict(); + +const RestartPolicySwarmSchema = z + .object({ + Condition: z.string().optional(), + Delay: z.number().optional(), + MaxAttempts: z.number().optional(), + Window: z.number().optional(), + }) + .strict(); + +const PreferenceSchema = z + .object({ + Spread: z.object({ + SpreadDescriptor: z.string(), + }), + }) + .strict(); + +const PlatformSchema = z + .object({ + Architecture: z.string(), + OS: z.string(), + }) + .strict(); + +const PlacementSwarmSchema = z + .object({ + Constraints: z.array(z.string()).optional(), + Preferences: z.array(PreferenceSchema).optional(), + MaxReplicas: z.number().optional(), + Platforms: z.array(PlatformSchema).optional(), + }) + .strict(); + +const UpdateConfigSwarmSchema = z + .object({ + Parallelism: z.number(), + Delay: z.number().optional(), + FailureAction: z.string().optional(), + Monitor: z.number().optional(), + MaxFailureRatio: z.number().optional(), + Order: z.string(), + }) + .strict(); + +const ReplicatedSchema = z + .object({ + Replicas: z.number().optional(), + }) + .strict(); + +const ReplicatedJobSchema = z + .object({ + MaxConcurrent: z.number().optional(), + TotalCompletions: z.number().optional(), + }) + .strict(); + +const ServiceModeSwarmSchema = z + .object({ + Replicated: ReplicatedSchema.optional(), + Global: z.object({}).optional(), + ReplicatedJob: ReplicatedJobSchema.optional(), + GlobalJob: z.object({}).optional(), + }) + .strict(); + +const NetworkSwarmSchema = z.array( + z + .object({ + Target: z.string().optional(), + Aliases: z.array(z.string()).optional(), + DriverOpts: z.object({}).optional(), + }) + .strict(), +); + +const LabelsSwarmSchema = z.record(z.string()); + +const createStringToJSONSchema = (schema: z.ZodTypeAny) => { + return z + .string() + .transform((str, ctx) => { + if (str === null || str === "") { + return null; + } + try { + return JSON.parse(str); + } catch (_e) { + ctx.addIssue({ code: "custom", message: "Invalid JSON format" }); + return z.NEVER; + } + }) + .superRefine((data, ctx) => { + if (data === null) { + return; + } + + if (Object.keys(data).length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: "Object cannot be empty", + }); + return; + } + + const parseResult = schema.safeParse(data); + if (!parseResult.success) { + for (const error of parseResult.error.issues) { + const path = error.path.join("."); + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${path} ${error.message}`, + }); + } + } + }); +}; + +const addSwarmSettings = z.object({ + healthCheckSwarm: createStringToJSONSchema(HealthCheckSwarmSchema).nullable(), + restartPolicySwarm: createStringToJSONSchema( + RestartPolicySwarmSchema, + ).nullable(), + placementSwarm: createStringToJSONSchema(PlacementSwarmSchema).nullable(), + updateConfigSwarm: createStringToJSONSchema( + UpdateConfigSwarmSchema, + ).nullable(), + rollbackConfigSwarm: createStringToJSONSchema( + UpdateConfigSwarmSchema, + ).nullable(), + modeSwarm: createStringToJSONSchema(ServiceModeSwarmSchema).nullable(), + labelsSwarm: createStringToJSONSchema(LabelsSwarmSchema).nullable(), + networkSwarm: createStringToJSONSchema(NetworkSwarmSchema).nullable(), +}); + +type AddSwarmSettings = z.infer; + +interface Props { + applicationId: string; +} + +export const AddSwarmSettings = ({ applicationId }: Props) => { + const { data, refetch } = api.application.one.useQuery( + { + applicationId, + }, + { + enabled: !!applicationId, + }, + ); + + const { mutateAsync, isError, error, isLoading } = + api.application.update.useMutation(); + + const form = useForm({ + defaultValues: { + healthCheckSwarm: null, + restartPolicySwarm: null, + placementSwarm: null, + updateConfigSwarm: null, + rollbackConfigSwarm: null, + modeSwarm: null, + labelsSwarm: null, + networkSwarm: null, + }, + resolver: zodResolver(addSwarmSettings), + }); + + useEffect(() => { + if (data) { + form.reset({ + healthCheckSwarm: data.healthCheckSwarm + ? JSON.stringify(data.healthCheckSwarm, null, 2) + : null, + restartPolicySwarm: data.restartPolicySwarm + ? JSON.stringify(data.restartPolicySwarm, null, 2) + : null, + placementSwarm: data.placementSwarm + ? JSON.stringify(data.placementSwarm, null, 2) + : null, + updateConfigSwarm: data.updateConfigSwarm + ? JSON.stringify(data.updateConfigSwarm, null, 2) + : null, + rollbackConfigSwarm: data.rollbackConfigSwarm + ? JSON.stringify(data.rollbackConfigSwarm, null, 2) + : null, + modeSwarm: data.modeSwarm + ? JSON.stringify(data.modeSwarm, null, 2) + : null, + labelsSwarm: data.labelsSwarm + ? JSON.stringify(data.labelsSwarm, null, 2) + : null, + networkSwarm: data.networkSwarm + ? JSON.stringify(data.networkSwarm, null, 2) + : null, + }); + } + }, [form, form.reset, data]); + + const onSubmit = async (data: AddSwarmSettings) => { + await mutateAsync({ + applicationId, + healthCheckSwarm: data.healthCheckSwarm, + restartPolicySwarm: data.restartPolicySwarm, + placementSwarm: data.placementSwarm, + updateConfigSwarm: data.updateConfigSwarm, + rollbackConfigSwarm: data.rollbackConfigSwarm, + modeSwarm: data.modeSwarm, + labelsSwarm: data.labelsSwarm, + networkSwarm: data.networkSwarm, + }) + .then(async () => { + toast.success("Swarm settings updated"); + refetch(); + }) + .catch(() => { + toast.error("Error updating the swarm settings"); + }); + }; + return ( + + + + + + + Swarm Settings + + Update certain settings using a json object. + + + {isError && {error?.message}} +
+ + Changing settings such as placements may cause the logs/monitoring + to be unavailable. + +
+ +
+ + ( + + Health Check + + + + + Check the interface + + + + + +
+														{`{
+	Test?: string[] | undefined;
+	Interval?: number | undefined;
+	Timeout?: number | undefined;
+	StartPeriod?: number | undefined;
+	Retries?: number | undefined;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + + ( + + Restart Policy + + + + + Check the interface + + + + + +
+														{`{
+	Condition?: string | undefined;
+	Delay?: number | undefined;
+	MaxAttempts?: number | undefined;
+	Window?: number | undefined;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + + ( + + Placement + + + + + Check the interface + + + + + +
+														{`{
+	Constraints?: string[] | undefined;
+	Preferences?: Array<{ Spread: { SpreadDescriptor: string } }> | undefined;
+	MaxReplicas?: number | undefined;
+	Platforms?:
+		| Array<{
+				Architecture: string;
+				OS: string;
+		  }>
+		| undefined;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + + ( + + Update Config + + + + + Check the interface + + + + + +
+														{`{
+	Parallelism?: number;
+	Delay?: number | undefined;
+	FailureAction?: string | undefined;
+	Monitor?: number | undefined;
+	MaxFailureRatio?: number | undefined;
+	Order: string;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + + ( + + Rollback Config + + + + + Check the interface + + + + + +
+														{`{
+	Parallelism?: number;
+	Delay?: number | undefined;
+	FailureAction?: string | undefined;
+	Monitor?: number | undefined;
+	MaxFailureRatio?: number | undefined;
+	Order: string;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + + ( + + Mode + + + + + Check the interface + + + + + +
+														{`{
+	Replicated?: { Replicas?: number | undefined } | undefined;
+	Global?: {} | undefined;
+	ReplicatedJob?:
+		| {
+				MaxConcurrent?: number | undefined;
+				TotalCompletions?: number | undefined;
+		  }
+		| undefined;
+	GlobalJob?: {} | undefined;
+}`}
+													
+
+
+
+
+ + + + +
+										
+									
+
+ )} + /> + ( + + Network + + + + + Check the interface + + + + + +
+														{`[
+  {
+	"Target" : string | undefined;
+	"Aliases" : string[] | undefined;
+	"DriverOpts" : { [key: string]: string } | undefined;
+  }
+]`}
+													
+
+
+
+
+ + + +
+										
+									
+
+ )} + /> + ( + + Labels + + + + + Check the interface + + + + + +
+														{`{
+	[name: string]: string;
+}`}
+													
+
+
+
+
+ + + +
+										
+									
+
+ )} + /> + + + + + + +
+
+ ); +}; diff --git a/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx b/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx new file mode 100644 index 0000000000000000000000000000000000000000..57f851c9e2e26f905db33a3117d64ce4353473e8 --- /dev/null +++ b/data/apps/dokploy/components/dashboard/application/advanced/cluster/show-cluster-settings.tsx @@ -0,0 +1,212 @@ +import { AlertBlock } from "@/components/shared/alert-block"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { api } from "@/utils/api"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Server } from "lucide-react"; +import Link from "next/link"; +import { useEffect } from "react"; +import { useForm } from "react-hook-form"; +import { toast } from "sonner"; +import { z } from "zod"; +import { AddSwarmSettings } from "./modify-swarm-settings"; + +interface Props { + applicationId: string; +} + +const AddRedirectchema = z.object({ + replicas: z.number().min(1, "Replicas must be at least 1"), + registryId: z.string(), +}); + +type AddCommand = z.infer; + +export const ShowClusterSettings = ({ applicationId }: Props) => { + const { data } = api.application.one.useQuery( + { + applicationId, + }, + { enabled: !!applicationId }, + ); + + const { data: registries } = api.registry.all.useQuery(); + + const utils = api.useUtils(); + + const { mutateAsync, isLoading } = api.application.update.useMutation(); + + const form = useForm({ + defaultValues: { + registryId: data?.registryId || "", + replicas: data?.replicas || 1, + }, + resolver: zodResolver(AddRedirectchema), + }); + + useEffect(() => { + if (data?.command) { + form.reset({ + registryId: data?.registryId || "", + replicas: data?.replicas || 1, + }); + } + }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]); + + const onSubmit = async (data: AddCommand) => { + await mutateAsync({ + applicationId, + registryId: + data?.registryId === "none" || !data?.registryId + ? null + : data?.registryId, + replicas: data?.replicas, + }) + .then(async () => { + toast.success("Command Updated"); + await utils.application.one.invalidate({ + applicationId, + }); + }) + .catch(() => { + toast.error("Error updating the command"); + }); + }; + + return ( + + +
+ Cluster Settings + + Add the registry and the replicas of the application + +
+ +
+ + + Please remember to click Redeploy after modify the cluster settings to + apply the changes. + +
+ +
+ ( + + Replicas + + { + const value = e.target.value; + field.onChange(value === "" ? 0 : Number(value)); + }} + type="number" + value={field.value || ""} + /> + + + + + )} + /> +
+ + {registries && registries?.length === 0 ? ( +
+
+ + + To use a cluster feature, you need to configure at least a + registry first. Please, go to{" "} + + Settings + {" "} + to do so. + +
+
+ ) : ( + <> + ( + + Select a registry + + + )} + /> + + )} + +
+ +
+ + +
+
+ ); +}; diff --git a/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx b/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx new file mode 100644 index 0000000000000000000000000000000000000000..50e36ad7608bc43159e20dc6778dc1f494af5181 --- /dev/null +++ b/data/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx @@ -0,0 +1,120 @@ +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { Input } from "@/components/ui/input"; +import { api } from "@/utils/api"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { useEffect } from "react"; +import { useForm } from "react-hook-form"; +import { toast } from "sonner"; +import { z } from "zod"; +interface Props { + applicationId: string; +} + +const AddRedirectSchema = z.object({ + command: z.string(), +}); + +type AddCommand = z.infer; + +export const AddCommand = ({ applicationId }: Props) => { + const { data } = api.application.one.useQuery( + { + applicationId, + }, + { enabled: !!applicationId }, + ); + + const utils = api.useUtils(); + + const { mutateAsync, isLoading } = api.application.update.useMutation(); + + const form = useForm({ + defaultValues: { + command: "", + }, + resolver: zodResolver(AddRedirectSchema), + }); + + useEffect(() => { + if (data?.command) { + form.reset({ + command: data?.command || "", + }); + } + }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]); + + const onSubmit = async (data: AddCommand) => { + await mutateAsync({ + applicationId, + command: data?.command, + }) + .then(async () => { + toast.success("Command Updated"); + await utils.application.one.invalidate({ + applicationId, + }); + }) + .catch(() => { + toast.error("Error updating the command"); + }); + }; + + return ( + + +
+ Run Command + + Run a custom command in the container after the application + initialized + +
+
+ +
+ +
+ ( + + Command + + + + + + + )} + /> +
+
+ +
+
+ +
+
+ ); +}; diff --git a/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx b/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx new file mode 100644 index 0000000000000000000000000000000000000000..aa359d67bfaa3783a93ea1492aa5713925f84724 --- /dev/null +++ b/data/apps/dokploy/components/dashboard/application/advanced/import/show-import.tsx @@ -0,0 +1,347 @@ +import { AlertBlock } from "@/components/shared/alert-block"; +import { CodeEditor } from "@/components/shared/code-editor"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Separator } from "@/components/ui/separator"; +import { Textarea } from "@/components/ui/textarea"; +import { api } from "@/utils/api"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { Code2, Globe2, HardDrive } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import { toast } from "sonner"; +import { z } from "zod"; + +const ImportSchema = z.object({ + base64: z.string(), +}); + +type ImportType = z.infer; + +interface Props { + composeId: string; +} + +export const ShowImport = ({ composeId }: Props) => { + const [showModal, setShowModal] = useState(false); + const [showMountContent, setShowMountContent] = useState(false); + const [selectedMount, setSelectedMount] = useState<{ + filePath: string; + content: string; + } | null>(null); + const [templateInfo, setTemplateInfo] = useState<{ + compose: string; + template: { + domains: Array<{ + serviceName: string; + port: number; + path?: string; + host?: string; + }>; + envs: string[]; + mounts: Array<{ + filePath: string; + content: string; + }>; + }; + } | null>(null); + + const utils = api.useUtils(); + const { mutateAsync: processTemplate, isLoading: isLoadingTemplate } = + api.compose.processTemplate.useMutation(); + const { + mutateAsync: importTemplate, + isLoading: isImporting, + isSuccess: isImportSuccess, + } = api.compose.import.useMutation(); + + const form = useForm({ + defaultValues: { + base64: "", + }, + resolver: zodResolver(ImportSchema), + }); + + useEffect(() => { + form.reset({ + base64: "", + }); + }, [isImportSuccess]); + + const onSubmit = async () => { + const base64 = form.getValues("base64"); + if (!base64) { + toast.error("Please enter a base64 template"); + return; + } + + try { + await importTemplate({ + composeId, + base64, + }); + toast.success("Template imported successfully"); + await utils.compose.one.invalidate({ + composeId, + }); + setShowModal(false); + } catch (_error) { + toast.error("Error importing template"); + } + }; + + const handleLoadTemplate = async () => { + const base64 = form.getValues("base64"); + if (!base64) { + toast.error("Please enter a base64 template"); + return; + } + + try { + const result = await processTemplate({ + composeId, + base64, + }); + setTemplateInfo(result); + setShowModal(true); + } catch (_error) { + toast.error("Error processing template"); + } + }; + + const handleShowMountContent = (mount: { + filePath: string; + content: string; + }) => { + setSelectedMount(mount); + setShowMountContent(true); + }; + + return ( + <> + + + Import + Import your Template configuration + + + + Warning: Importing a template will remove all existing environment + variables, mounts, and domains from this service. + +
+ + ( + + Configuration (Base64) + +