mirror of
https://github.com/Dokploy/dokploy.git
synced 2026-10-16 05:35:30 +00:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c2d4d5c19 | |||
| fa3cab8bcc | |||
| 8f42dced38 | |||
| 7a0efc7aa4 | |||
| 65c5ccc7b2 | |||
| 5d1731c54f | |||
| c0265b49b4 | |||
| a691b469a1 |
@@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({
|
||||
queueAdd: vi.fn(),
|
||||
verify: vi.fn(),
|
||||
shouldDeploy: vi.fn(),
|
||||
createPreviewDeployment: vi.fn(),
|
||||
findPreviewDeploymentByApplicationId: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("drizzle-orm", () => ({
|
||||
@@ -64,10 +66,11 @@ vi.mock("@dokploy/server", () => ({
|
||||
IS_CLOUD: false,
|
||||
shouldDeploy: mocks.shouldDeploy,
|
||||
checkUserRepositoryPermissions: vi.fn(),
|
||||
createPreviewDeployment: vi.fn(),
|
||||
createPreviewDeployment: mocks.createPreviewDeployment,
|
||||
createSecurityBlockedComment: vi.fn(),
|
||||
findGithubById: vi.fn(),
|
||||
findPreviewDeploymentByApplicationId: vi.fn(),
|
||||
findPreviewDeploymentByApplicationId:
|
||||
mocks.findPreviewDeploymentByApplicationId,
|
||||
findPreviewDeploymentsByPullRequestId: vi.fn(),
|
||||
getBitbucketHeaders: vi.fn(() => ({})),
|
||||
removePreviewDeployment: vi.fn(),
|
||||
@@ -321,3 +324,157 @@ describe("GitHub app webhook auto-deploy", () => {
|
||||
expect(res.json).toHaveBeenCalledWith({ message: "No apps to deploy" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitHub app webhook preview deployments", () => {
|
||||
const createApplication = (
|
||||
overrides: Record<string, unknown> = {},
|
||||
): Record<string, unknown> => ({
|
||||
applicationId: "application-id",
|
||||
name: "my-app",
|
||||
serverId: null,
|
||||
previewLabels: [],
|
||||
previewLimit: 3,
|
||||
previewDeployments: [],
|
||||
previewRequireCollaboratorPermissions: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createPreviewDeployments = (total: number) =>
|
||||
Array.from({ length: total }, (_, index) => ({
|
||||
previewDeploymentId: `existing-preview-${index}`,
|
||||
}));
|
||||
|
||||
const createPullRequestRequest = (action: string) =>
|
||||
({
|
||||
headers: {
|
||||
"x-hub-signature-256": "sha256=test-signature",
|
||||
"x-github-event": "pull_request",
|
||||
},
|
||||
body: {
|
||||
installation: {
|
||||
id: 12345,
|
||||
},
|
||||
action,
|
||||
pull_request: {
|
||||
id: 987,
|
||||
number: 42,
|
||||
title: "feat: add preview",
|
||||
html_url: "https://github.com/agentHits/dokploy/pull/42",
|
||||
labels: [],
|
||||
user: {
|
||||
login: "agentHits",
|
||||
},
|
||||
head: {
|
||||
ref: "feature",
|
||||
sha: "abc123",
|
||||
},
|
||||
base: {
|
||||
ref: "main",
|
||||
},
|
||||
},
|
||||
repository: {
|
||||
name: "dokploy",
|
||||
owner: {
|
||||
login: "agentHits",
|
||||
},
|
||||
},
|
||||
},
|
||||
}) as unknown as NextApiRequest;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.githubFindFirst.mockResolvedValue({
|
||||
githubId: "github-provider-id",
|
||||
githubInstallationId: 12345,
|
||||
githubWebhookSecret: "webhook-secret",
|
||||
});
|
||||
mocks.verify.mockResolvedValue(true);
|
||||
mocks.queueAdd.mockResolvedValue({ id: "job-id" });
|
||||
mocks.createPreviewDeployment.mockResolvedValue({
|
||||
previewDeploymentId: "new-preview-id",
|
||||
});
|
||||
mocks.findPreviewDeploymentByApplicationId.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("redeploys an existing preview even when the limit is reached", async () => {
|
||||
mocks.applicationsFindMany.mockResolvedValue([
|
||||
createApplication({
|
||||
previewLimit: 2,
|
||||
previewDeployments: createPreviewDeployments(3),
|
||||
}),
|
||||
]);
|
||||
mocks.findPreviewDeploymentByApplicationId.mockResolvedValue({
|
||||
previewDeploymentId: "existing-preview-0",
|
||||
});
|
||||
const res = createResponse();
|
||||
|
||||
await handler(createPullRequestRequest("synchronize"), res);
|
||||
|
||||
expect(mocks.createPreviewDeployment).not.toHaveBeenCalled();
|
||||
expect(mocks.queueAdd).toHaveBeenCalledWith(
|
||||
"deployments",
|
||||
expect.objectContaining({
|
||||
applicationId: "application-id",
|
||||
applicationType: "application-preview",
|
||||
previewDeploymentId: "existing-preview-0",
|
||||
type: "deploy",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
removeOnComplete: true,
|
||||
removeOnFail: true,
|
||||
}),
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
});
|
||||
|
||||
it("does not create a new preview once the limit is reached", async () => {
|
||||
mocks.applicationsFindMany.mockResolvedValue([
|
||||
createApplication({
|
||||
previewLimit: 2,
|
||||
previewDeployments: createPreviewDeployments(2),
|
||||
}),
|
||||
]);
|
||||
const res = createResponse();
|
||||
|
||||
await handler(createPullRequestRequest("opened"), res);
|
||||
|
||||
expect(mocks.createPreviewDeployment).not.toHaveBeenCalled();
|
||||
expect(mocks.queueAdd).not.toHaveBeenCalled();
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
});
|
||||
|
||||
it("falls back to the default limit when none is configured", async () => {
|
||||
mocks.applicationsFindMany.mockResolvedValue([
|
||||
createApplication({
|
||||
previewLimit: null,
|
||||
previewDeployments: createPreviewDeployments(2),
|
||||
}),
|
||||
]);
|
||||
const res = createResponse();
|
||||
|
||||
await handler(createPullRequestRequest("opened"), res);
|
||||
|
||||
expect(mocks.createPreviewDeployment).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
applicationId: "application-id",
|
||||
branch: "feature",
|
||||
pullRequestId: 987,
|
||||
pullRequestNumber: 42,
|
||||
}),
|
||||
);
|
||||
expect(mocks.queueAdd).toHaveBeenCalledWith(
|
||||
"deployments",
|
||||
expect.objectContaining({
|
||||
applicationId: "application-id",
|
||||
applicationType: "application-preview",
|
||||
previewDeploymentId: "new-preview-id",
|
||||
type: "deploy",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
removeOnComplete: true,
|
||||
removeOnFail: true,
|
||||
}),
|
||||
);
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,6 +26,11 @@ interface Props {
|
||||
serviceId?: string;
|
||||
}
|
||||
|
||||
// Sentinel the container-picker views fall back to before a real container
|
||||
// is selected/auto-selected — querying logs for it just surfaces Docker's
|
||||
// raw "No such container: select-a-container" daemon error.
|
||||
const PLACEHOLDER_CONTAINER_ID = "select-a-container";
|
||||
|
||||
export const priorities = [
|
||||
{
|
||||
label: "Info",
|
||||
@@ -55,13 +60,16 @@ export const DockerLogsId: React.FC<Props> = ({
|
||||
runType,
|
||||
serviceId,
|
||||
}) => {
|
||||
const hasContainer =
|
||||
!!containerId && containerId !== PLACEHOLDER_CONTAINER_ID;
|
||||
|
||||
const { data } = api.docker.getConfig.useQuery(
|
||||
{
|
||||
containerId,
|
||||
serverId: serverId ?? undefined,
|
||||
},
|
||||
{
|
||||
enabled: !!containerId,
|
||||
enabled: hasContainer,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -134,7 +142,7 @@ export const DockerLogsId: React.FC<Props> = ({
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerId) return;
|
||||
if (!hasContainer) return;
|
||||
|
||||
let isCurrentConnection = true;
|
||||
let noDataTimeout: NodeJS.Timeout;
|
||||
@@ -425,10 +433,15 @@ export const DockerLogsId: React.FC<Props> = ({
|
||||
<div className="flex justify-center items-center h-full text-muted-foreground">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
) : hasContainer ? (
|
||||
<div className="flex justify-center items-center h-full text-muted-foreground">
|
||||
No logs found
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex justify-center items-center h-full text-center text-sm text-muted-foreground px-8">
|
||||
Select a container above to view its logs. If none are listed,
|
||||
make sure the service is deployed and running.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,10 @@ interface Props {
|
||||
serviceId?: string;
|
||||
}
|
||||
|
||||
// Sentinel the container-picker modal renders with before a real container
|
||||
// is selected/auto-selected — never worth opening a connection for.
|
||||
const PLACEHOLDER_CONTAINER_ID = "select-a-container";
|
||||
|
||||
export const DockerTerminal: React.FC<Props> = ({
|
||||
id,
|
||||
containerId,
|
||||
@@ -25,59 +29,105 @@ export const DockerTerminal: React.FC<Props> = ({
|
||||
const [activeWay, setActiveWay] = React.useState<string | undefined>("bash");
|
||||
const { resolvedTheme } = useTheme();
|
||||
useEffect(() => {
|
||||
const container = document.getElementById(id);
|
||||
if (container) {
|
||||
container.innerHTML = "";
|
||||
if (!containerId || containerId === PLACEHOLDER_CONTAINER_ID) {
|
||||
return;
|
||||
}
|
||||
const term = new Terminal({
|
||||
cursorBlink: true,
|
||||
lineHeight: 1.4,
|
||||
convertEol: true,
|
||||
theme: {
|
||||
cursor: resolvedTheme === "light" ? "#000000" : "transparent",
|
||||
background: "rgba(0, 0, 0, 0)",
|
||||
foreground: "currentColor",
|
||||
},
|
||||
|
||||
let cancelled = false;
|
||||
let term: Terminal | null = null;
|
||||
let ws: WebSocket | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
// Deferred a frame so React StrictMode's dev-only phantom mount+cleanup
|
||||
// (which runs synchronously, before anything paints) never creates a
|
||||
// terminal in the first place — dodges a known xterm.js dispose race
|
||||
// (xtermjs/xterm.js#5011) where a deferred internal callback outlives
|
||||
// term.dispose() and reads renderer state that's already gone.
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (cancelled) return;
|
||||
|
||||
const container = document.getElementById(id);
|
||||
if (container) {
|
||||
container.innerHTML = "";
|
||||
}
|
||||
term = new Terminal({
|
||||
cursorBlink: true,
|
||||
lineHeight: 1.4,
|
||||
convertEol: true,
|
||||
theme: {
|
||||
cursor: resolvedTheme === "light" ? "#000000" : "transparent",
|
||||
background: "rgba(0, 0, 0, 0)",
|
||||
foreground: "currentColor",
|
||||
},
|
||||
});
|
||||
const addonFit = new FitAddon();
|
||||
const clipboardAddon = new ClipboardAddon();
|
||||
term.loadAddon(clipboardAddon);
|
||||
fixMacOsAltKeys(term);
|
||||
// @ts-expect-error
|
||||
term.open(termRef.current);
|
||||
term.loadAddon(addonFit);
|
||||
addonFit.fit();
|
||||
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}&cols=${term.cols}&rows=${term.rows}${serverId ? `&serverId=${serverId}` : ""}${serviceId ? `&serviceId=${serviceId}` : ""}`;
|
||||
|
||||
ws = new WebSocket(wsUrl);
|
||||
const addonAttach = new AttachAddon(ws);
|
||||
term.loadAddon(addonAttach);
|
||||
|
||||
const sendResize = (cols: number, rows: number) => {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: "resize", cols, rows }));
|
||||
}
|
||||
};
|
||||
term.onResize(({ cols, rows }) => sendResize(cols, rows));
|
||||
|
||||
resizeObserver = new ResizeObserver(() => addonFit.fit());
|
||||
if (termRef.current) {
|
||||
resizeObserver.observe(termRef.current);
|
||||
}
|
||||
});
|
||||
const addonFit = new FitAddon();
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
|
||||
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}${serviceId ? `&serviceId=${serviceId}` : ""}`;
|
||||
|
||||
const ws = new WebSocket(wsUrl);
|
||||
|
||||
const addonAttach = new AttachAddon(ws);
|
||||
const clipboardAddon = new ClipboardAddon();
|
||||
term.loadAddon(clipboardAddon);
|
||||
fixMacOsAltKeys(term);
|
||||
// @ts-ignore
|
||||
term.open(termRef.current);
|
||||
// @ts-ignore
|
||||
term.loadAddon(addonFit);
|
||||
term.loadAddon(addonAttach);
|
||||
addonFit.fit();
|
||||
return () => {
|
||||
ws.readyState === WebSocket.OPEN && ws.close();
|
||||
term.dispose();
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(frame);
|
||||
resizeObserver?.disconnect();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.close();
|
||||
}
|
||||
term?.dispose();
|
||||
};
|
||||
}, [containerId, activeWay, id]);
|
||||
|
||||
const hasContainer =
|
||||
!!containerId && containerId !== PLACEHOLDER_CONTAINER_ID;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2 mt-4">
|
||||
<span>
|
||||
Select way to connect to <b>{containerId}</b>
|
||||
</span>
|
||||
<Tabs value={activeWay} onValueChange={setActiveWay}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="bash">Bash</TabsTrigger>
|
||||
<TabsTrigger value="sh">/bin/sh</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
<div className="w-full h-full rounded-lg p-2 bg-transparent border">
|
||||
<div id={id} ref={termRef} />
|
||||
</div>
|
||||
{hasContainer && (
|
||||
<div className="flex flex-col gap-2 mt-4">
|
||||
<span>
|
||||
Select way to connect to <b>{containerId}</b>
|
||||
</span>
|
||||
<Tabs value={activeWay} onValueChange={setActiveWay}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="bash">Bash</TabsTrigger>
|
||||
<TabsTrigger value="sh">/bin/sh</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
{hasContainer ? (
|
||||
<div className="w-full h-[420px] rounded-lg p-2 bg-transparent border">
|
||||
<div id={id} ref={termRef} className="h-full" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-[420px] w-full items-center justify-center rounded-lg border border-dashed p-4 text-center text-sm text-muted-foreground">
|
||||
Select a container above to open a terminal. If none are listed, make
|
||||
sure the service is deployed and running.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -53,9 +53,14 @@ type Tag = z.infer<typeof TagSchema>;
|
||||
|
||||
interface HandleTagProps {
|
||||
tagId?: string;
|
||||
/**
|
||||
* Called with the new tag's id after it is created, so callers embedding
|
||||
* this dialog (e.g. the tag selector) can select the tag right away.
|
||||
*/
|
||||
onCreated?: (tagId: string) => void;
|
||||
}
|
||||
|
||||
export const HandleTag = ({ tagId }: HandleTagProps) => {
|
||||
export const HandleTag = ({ tagId, onCreated }: HandleTagProps) => {
|
||||
const utils = api.useUtils();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const colorInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -101,8 +106,11 @@ export const HandleTag = ({ tagId }: HandleTagProps) => {
|
||||
color: data.color,
|
||||
tagId: tagId || "",
|
||||
})
|
||||
.then(async () => {
|
||||
.then(async (result) => {
|
||||
await utils.tag.all.invalidate();
|
||||
if (!tagId && result?.tagId) {
|
||||
onCreated?.(result.tagId);
|
||||
}
|
||||
toast.success(tagId ? "Tag Updated" : "Tag Created");
|
||||
setIsOpen(false);
|
||||
form.reset();
|
||||
@@ -139,9 +147,18 @@ export const HandleTag = ({ tagId }: HandleTagProps) => {
|
||||
</DialogHeader>
|
||||
{isError && <AlertBlock type="error">{error?.message}</AlertBlock>}
|
||||
<Form {...form}>
|
||||
{/*
|
||||
* This dialog can be rendered inside another form (e.g. the tag
|
||||
* selector in the project dialog). React propagates events through the
|
||||
* React tree, not the DOM tree, so without stopPropagation submitting
|
||||
* this form would also submit the outer one.
|
||||
*/}
|
||||
<form
|
||||
id="hook-form-tag"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
onSubmit={(e) => {
|
||||
e.stopPropagation();
|
||||
form.handleSubmit(onSubmit)(e);
|
||||
}}
|
||||
className="grid w-full gap-4"
|
||||
>
|
||||
<FormField
|
||||
|
||||
@@ -41,11 +41,22 @@ export const Terminal: React.FC<Props> = ({ id, serverId }) => {
|
||||
});
|
||||
|
||||
const addonFit = new FitAddon();
|
||||
const clipboardAddon = new ClipboardAddon();
|
||||
term.loadAddon(clipboardAddon);
|
||||
fixMacOsAltKeys(term);
|
||||
|
||||
// @ts-ignore
|
||||
term.open(termRef.current);
|
||||
// @ts-ignore
|
||||
term.loadAddon(addonFit);
|
||||
addonFit.fit();
|
||||
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
|
||||
const urlParams = new URLSearchParams();
|
||||
urlParams.set("serverId", serverId);
|
||||
urlParams.set("cols", term.cols.toString());
|
||||
urlParams.set("rows", term.rows.toString());
|
||||
|
||||
if (serverId === "local") {
|
||||
const { port, username } = getLocalServerData();
|
||||
@@ -57,17 +68,22 @@ export const Terminal: React.FC<Props> = ({ id, serverId }) => {
|
||||
|
||||
const ws = new WebSocket(wsUrl);
|
||||
const addonAttach = new AttachAddon(ws);
|
||||
const clipboardAddon = new ClipboardAddon();
|
||||
term.loadAddon(clipboardAddon);
|
||||
fixMacOsAltKeys(term);
|
||||
|
||||
// @ts-ignore
|
||||
term.open(termRef.current);
|
||||
// @ts-ignore
|
||||
term.loadAddon(addonFit);
|
||||
term.loadAddon(addonAttach);
|
||||
addonFit.fit();
|
||||
|
||||
const sendResize = (cols: number, rows: number) => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: "resize", cols, rows }));
|
||||
}
|
||||
};
|
||||
term.onResize(({ cols, rows }) => sendResize(cols, rows));
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => addonFit.fit());
|
||||
if (termRef.current) {
|
||||
resizeObserver.observe(termRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
ws.readyState === WebSocket.OPEN && ws.close();
|
||||
};
|
||||
}, [id, serverId]);
|
||||
|
||||
@@ -147,7 +147,13 @@ export function TagSelector({
|
||||
})}
|
||||
</CommandGroup>
|
||||
<div className="flex items-center justify-center p-2 border-t">
|
||||
<HandleTag />
|
||||
<HandleTag
|
||||
onCreated={(tagId) => {
|
||||
if (!selectedTags.includes(tagId)) {
|
||||
onTagsChange([...selectedTags, tagId]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</CommandList>
|
||||
</Command>
|
||||
|
||||
@@ -22,7 +22,7 @@ function Switch({
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[18px] group-data-[size=sm]/switch:data-checked:translate-x-[10px] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dokploy",
|
||||
"version": "v0.30.0",
|
||||
"version": "v0.30.2",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
|
||||
@@ -484,10 +484,6 @@ export default async function handler(
|
||||
if (!hasLabel) continue;
|
||||
}
|
||||
|
||||
const previewLimit = app?.previewLimit || 0;
|
||||
if (app?.previewDeployments?.length > previewLimit) {
|
||||
continue;
|
||||
}
|
||||
const previewDeploymentResult =
|
||||
await findPreviewDeploymentByApplicationId(app.applicationId, prId);
|
||||
|
||||
@@ -495,6 +491,15 @@ export default async function handler(
|
||||
previewDeploymentResult?.previewDeploymentId || "";
|
||||
|
||||
if (!previewDeploymentResult && shouldCreateDeployment) {
|
||||
// The limit only applies to new previews, existing ones must
|
||||
// still be redeployed when the pull request is updated.
|
||||
const previewLimit = app?.previewLimit ?? 3;
|
||||
if ((app?.previewDeployments?.length ?? 0) >= previewLimit) {
|
||||
console.warn(
|
||||
`⚠️ Preview deployment limit (${previewLimit}) reached for ${app.name}, skipping preview for pull request #${prNumber}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const previewDeployment = await createPreviewDeployment({
|
||||
applicationId: app.applicationId as string,
|
||||
branch: prBranch,
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
checkProjectAccess,
|
||||
findMemberByUserId,
|
||||
} from "@dokploy/server/services/permission";
|
||||
import { serviceColumns } from "@dokploy/server/services/project";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, desc, eq, ilike, or, sql } from "drizzle-orm";
|
||||
import type { AnyPgColumn } from "drizzle-orm/pg-core";
|
||||
@@ -130,39 +131,63 @@ export const projectRouter = createTRPCRouter({
|
||||
environments: {
|
||||
with: {
|
||||
applications: {
|
||||
columns: {
|
||||
...serviceColumns,
|
||||
applicationId: true,
|
||||
icon: true,
|
||||
},
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(
|
||||
applications.applicationId,
|
||||
accessedServices,
|
||||
),
|
||||
},
|
||||
compose: {
|
||||
columns: {
|
||||
...serviceColumns,
|
||||
composeId: true,
|
||||
composeStatus: true,
|
||||
},
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(
|
||||
compose.composeId,
|
||||
accessedServices,
|
||||
),
|
||||
},
|
||||
libsql: {
|
||||
columns: { ...serviceColumns, libsqlId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(libsql.libsqlId, accessedServices),
|
||||
},
|
||||
mariadb: {
|
||||
columns: { ...serviceColumns, mariadbId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(
|
||||
mariadb.mariadbId,
|
||||
accessedServices,
|
||||
),
|
||||
},
|
||||
mongo: {
|
||||
columns: { ...serviceColumns, mongoId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(mongo.mongoId, accessedServices),
|
||||
},
|
||||
mysql: {
|
||||
columns: { ...serviceColumns, mysqlId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(mysql.mysqlId, accessedServices),
|
||||
},
|
||||
postgres: {
|
||||
columns: { ...serviceColumns, postgresId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(
|
||||
postgres.postgresId,
|
||||
accessedServices,
|
||||
),
|
||||
},
|
||||
redis: {
|
||||
columns: { ...serviceColumns, redisId: true },
|
||||
with: { server: { columns: { name: true } } },
|
||||
where: buildServiceFilter(redis.redisId, accessedServices),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -4,7 +4,12 @@ import { spawn } from "node-pty";
|
||||
import { Client } from "ssh2";
|
||||
import { WebSocketServer } from "ws";
|
||||
import { canAccessDockerOverWss } from "./authorize";
|
||||
import { isValidContainerId, isValidShell } from "./utils";
|
||||
import {
|
||||
isValidContainerId,
|
||||
isValidShell,
|
||||
parseResizeMessage,
|
||||
parseTerminalSize,
|
||||
} from "./utils";
|
||||
|
||||
export const setupDockerContainerTerminalWebSocketServer = (
|
||||
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
|
||||
@@ -34,6 +39,10 @@ export const setupDockerContainerTerminalWebSocketServer = (
|
||||
const activeWay = url.searchParams.get("activeWay");
|
||||
const serverId = url.searchParams.get("serverId");
|
||||
const serviceId = url.searchParams.get("serviceId");
|
||||
const { cols, rows } = parseTerminalSize(
|
||||
url.searchParams.get("cols"),
|
||||
url.searchParams.get("rows"),
|
||||
);
|
||||
const { user, session } = await validateRequest(req);
|
||||
|
||||
if (!containerId) {
|
||||
@@ -92,7 +101,7 @@ export const setupDockerContainerTerminalWebSocketServer = (
|
||||
containerId,
|
||||
shell,
|
||||
].join(" ");
|
||||
conn.exec(dockerCommand, { pty: true }, (err, stream) => {
|
||||
conn.exec(dockerCommand, { pty: { cols, rows } }, (err, stream) => {
|
||||
if (err) {
|
||||
console.error("SSH exec error:", err);
|
||||
ws.close();
|
||||
@@ -123,7 +132,13 @@ export const setupDockerContainerTerminalWebSocketServer = (
|
||||
} else {
|
||||
command = message;
|
||||
}
|
||||
stream.write(command.toString());
|
||||
const text = command.toString();
|
||||
const resize = parseResizeMessage(text);
|
||||
if (resize) {
|
||||
stream.setWindow(resize.rows, resize.cols, 0, 0);
|
||||
return;
|
||||
}
|
||||
stream.write(text);
|
||||
} catch (error) {
|
||||
// @ts-ignore
|
||||
const errorMessage = error?.message as unknown as string;
|
||||
@@ -161,7 +176,7 @@ export const setupDockerContainerTerminalWebSocketServer = (
|
||||
const ptyProcess = spawn(
|
||||
"docker",
|
||||
["exec", "-it", "-w", "/", containerId, shell],
|
||||
{},
|
||||
{ cols, rows },
|
||||
);
|
||||
|
||||
ptyProcess.onData((data) => {
|
||||
@@ -178,7 +193,13 @@ export const setupDockerContainerTerminalWebSocketServer = (
|
||||
} else {
|
||||
command = message;
|
||||
}
|
||||
ptyProcess.write(command.toString());
|
||||
const text = command.toString();
|
||||
const resize = parseResizeMessage(text);
|
||||
if (resize) {
|
||||
ptyProcess.resize(resize.cols, resize.rows);
|
||||
return;
|
||||
}
|
||||
ptyProcess.write(text);
|
||||
} catch (error) {
|
||||
// @ts-ignore
|
||||
const errorMessage = error?.message as unknown as string;
|
||||
|
||||
@@ -10,7 +10,11 @@ import { Client, type ConnectConfig } from "ssh2";
|
||||
import { WebSocketServer } from "ws";
|
||||
import { getDockerHost } from "../utils/docker";
|
||||
import { canAccessTerminalOverWss } from "./authorize";
|
||||
import { setupLocalServerSSHKey } from "./utils";
|
||||
import {
|
||||
parseResizeMessage,
|
||||
parseTerminalSize,
|
||||
setupLocalServerSSHKey,
|
||||
} from "./utils";
|
||||
|
||||
const COMMAND_TO_ALLOW_LOCAL_ACCESS = `
|
||||
# ----------------------------------------
|
||||
@@ -88,6 +92,10 @@ export const setupTerminalWebSocketServer = (
|
||||
wssTerm.on("connection", async (ws, req) => {
|
||||
const url = new URL(req.url || "", `http://${req.headers.host}`);
|
||||
const serverId = url.searchParams.get("serverId");
|
||||
const { cols, rows } = parseTerminalSize(
|
||||
url.searchParams.get("cols"),
|
||||
url.searchParams.get("rows"),
|
||||
);
|
||||
const { user, session } = await validateRequest(req);
|
||||
if (!user || !session || !serverId) {
|
||||
ws.close();
|
||||
@@ -190,7 +198,7 @@ export const setupTerminalWebSocketServer = (
|
||||
// Clear terminal content once connected
|
||||
ws.send("\x1bc");
|
||||
|
||||
conn.shell({}, (err, stream) => {
|
||||
conn.shell({ cols, rows }, (err, stream) => {
|
||||
if (err) throw err;
|
||||
|
||||
stream
|
||||
@@ -216,7 +224,13 @@ export const setupTerminalWebSocketServer = (
|
||||
} else {
|
||||
command = message;
|
||||
}
|
||||
stream.write(command.toString());
|
||||
const text = command.toString();
|
||||
const resize = parseResizeMessage(text);
|
||||
if (resize) {
|
||||
stream.setWindow(resize.rows, resize.cols, 0, 0);
|
||||
return;
|
||||
}
|
||||
stream.write(text);
|
||||
} catch (error) {
|
||||
// @ts-ignore
|
||||
const errorMessage = error?.message as unknown as string;
|
||||
|
||||
@@ -63,6 +63,48 @@ export const isValidShell = (shell: string): boolean => {
|
||||
return allowedShells.includes(shell);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clamps cols/rows read from the client's initial connection query params
|
||||
* to a sane range, falling back to the standard 80x24 default.
|
||||
*/
|
||||
export const parseTerminalSize = (
|
||||
colsParam: string | null,
|
||||
rowsParam: string | null,
|
||||
) => {
|
||||
const cols = Number(colsParam);
|
||||
const rows = Number(rowsParam);
|
||||
return {
|
||||
cols: Number.isInteger(cols) && cols > 0 && cols <= 1000 ? cols : 80,
|
||||
rows: Number.isInteger(rows) && rows > 0 && rows <= 1000 ? rows : 24,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Terminal input and resize control messages share the same websocket
|
||||
* channel. Resize messages are JSON envelopes; regular keystrokes never
|
||||
* start with "{", so this distinguishes them without an extra channel.
|
||||
*/
|
||||
export const parseResizeMessage = (data: string) => {
|
||||
if (!data.startsWith("{")) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
if (
|
||||
parsed?.type === "resize" &&
|
||||
Number.isInteger(parsed.cols) &&
|
||||
Number.isInteger(parsed.rows) &&
|
||||
parsed.cols > 0 &&
|
||||
parsed.cols <= 1000 &&
|
||||
parsed.rows > 0 &&
|
||||
parsed.rows <= 1000
|
||||
) {
|
||||
return { cols: parsed.cols, rows: parsed.rows };
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getShell = () => {
|
||||
if (IS_CLOUD) {
|
||||
return "NO_AVAILABLE";
|
||||
|
||||
@@ -47,16 +47,16 @@ export const createProject = async (
|
||||
};
|
||||
};
|
||||
|
||||
export const findProjectById = async (projectId: string) => {
|
||||
const serviceColumns = {
|
||||
name: true,
|
||||
description: true,
|
||||
appName: true,
|
||||
createdAt: true,
|
||||
serverId: true,
|
||||
applicationStatus: true,
|
||||
} as const;
|
||||
export const serviceColumns = {
|
||||
name: true,
|
||||
description: true,
|
||||
appName: true,
|
||||
createdAt: true,
|
||||
serverId: true,
|
||||
applicationStatus: true,
|
||||
} as const;
|
||||
|
||||
export const findProjectById = async (projectId: string) => {
|
||||
const project = await db.query.projects.findFirst({
|
||||
where: eq(projects.projectId, projectId),
|
||||
with: {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { writeDomainsToCompose } from "../docker/domain";
|
||||
import {
|
||||
encodeBase64,
|
||||
getEnvironmentVariablesObject,
|
||||
prepareEnvironmentVariables,
|
||||
prepareEnvironmentVariablesForFile,
|
||||
} from "../docker/utils";
|
||||
import { withResolvedVaultRefs } from "../vault";
|
||||
@@ -157,10 +158,18 @@ export const getCreateEnvFileCommand = (compose: ComposeNested) => {
|
||||
envContent += `\nCOMPOSE_PREFIX=${compose.suffix}`;
|
||||
}
|
||||
|
||||
const envFileContent = prepareEnvironmentVariablesForFile(
|
||||
envContent,
|
||||
compose.environment.project.env,
|
||||
compose.environment.env,
|
||||
const envFileContent = (
|
||||
compose.composeType === "stack"
|
||||
? prepareEnvironmentVariables(
|
||||
envContent,
|
||||
compose.environment.project.env,
|
||||
compose.environment.env,
|
||||
)
|
||||
: prepareEnvironmentVariablesForFile(
|
||||
envContent,
|
||||
compose.environment.project.env,
|
||||
compose.environment.env,
|
||||
)
|
||||
).join("\n");
|
||||
|
||||
const encodedContent = encodeBase64(envFileContent);
|
||||
|
||||
Reference in New Issue
Block a user