feat(containers): add configuration editing and safe lifecycle orchestration

This commit is contained in:
KodekaTeam committed 2026-08-24 18:18:36 +07:00
1 parent 27bc971fb5
commit c11472ead9
52 files changed
+6992 -556

No files matched your search

@@ -0,0 +1,120 @@
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'BUILDING';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'VALIDATING';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'SWITCHING';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'ACTIVE';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'FAILED_ROLLED_BACK';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'ROLLBACK_RUNNING';
ALTER TYPE "DeploymentStatus" ADD VALUE IF NOT EXISTS 'SUPERSEDED';
ALTER TYPE "DeploymentTrigger" ADD VALUE IF NOT EXISTS 'REDEPLOY';
ALTER TYPE "DeploymentTrigger" ADD VALUE IF NOT EXISTS 'CONFIG_APPLY';
CREATE TYPE "DeploymentEventLevel" AS ENUM ('INFO', 'WARNING', 'ERROR');
ALTER TABLE "deployments"
ADD COLUMN "projectId" TEXT,
ADD COLUMN "environmentId" TEXT,
ADD COLUMN "idempotencyKey" TEXT,
ADD COLUMN "sourceSnapshot" JSONB,
ADD COLUMN "configRevision" TEXT,
ADD COLUMN "strategy" TEXT,
ADD COLUMN "candidateRef" TEXT,
ADD COLUMN "previousDeploymentId" TEXT,
ADD COLUMN "failureReason" TEXT,
ADD COLUMN "rollbackReason" TEXT,
ADD COLUMN "logReference" TEXT,
ADD COLUMN "updatedAt" TIMESTAMP(3);
UPDATE "deployments" AS deployment
SET
"environmentId" = container."environmentId",
"projectId" = environment."projectId",
"sourceSnapshot" = jsonb_strip_nulls(jsonb_build_object(
'trigger', deployment."trigger",
'version', deployment."version",
'branch', deployment."branch",
'commitSha', deployment."commitSha",
'image', deployment."image",
'imageDigest', deployment."imageDigest"
)),
"configRevision" = md5(deployment."configSnapshot"::text),
"failureReason" = CASE
WHEN deployment."status" = 'FAILED' THEN deployment."error"
ELSE NULL
END,
"updatedAt" = COALESCE(deployment."completedAt", deployment."createdAt")
FROM "containers" AS container
LEFT JOIN "environments" AS environment
ON environment."id" = container."environmentId"
WHERE container."id" = deployment."containerId";
UPDATE "deployments"
SET
"sourceSnapshot" = COALESCE("sourceSnapshot", '{}'::jsonb),
"configRevision" = COALESCE("configRevision", md5("configSnapshot"::text)),
"failureReason" = CASE
WHEN "status" = 'FAILED' THEN COALESCE("failureReason", "error")
ELSE "failureReason"
END,
"updatedAt" = COALESCE("updatedAt", "completedAt", "createdAt");
ALTER TABLE "deployments"
ALTER COLUMN "updatedAt" SET NOT NULL;
CREATE TABLE "deployment_events" (
"id" TEXT NOT NULL,
"deploymentId" TEXT NOT NULL,
"status" "DeploymentStatus" NOT NULL,
"level" "DeploymentEventLevel" NOT NULL DEFAULT 'INFO',
"message" TEXT NOT NULL,
"metadata" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "deployment_events_pkey" PRIMARY KEY ("id")
);
INSERT INTO "deployment_events" (
"id",
"deploymentId",
"status",
"level",
"message",
"createdAt"
)
SELECT
'legacy_' || md5("id"),
"id",
"status",
CASE
WHEN "status" = 'FAILED' THEN 'ERROR'::"DeploymentEventLevel"
WHEN "status" = 'CANCELLED' THEN 'WARNING'::"DeploymentEventLevel"
ELSE 'INFO'::"DeploymentEventLevel"
END,
'Imported legacy deployment state.',
COALESCE("completedAt", "createdAt")
FROM "deployments";
CREATE UNIQUE INDEX "deployments_containerId_idempotencyKey_key"
ON "deployments"("containerId", "idempotencyKey");
CREATE INDEX "deployments_containerId_status_createdAt_idx"
ON "deployments"("containerId", "status", "createdAt");
CREATE INDEX "deployments_projectId_createdAt_idx"
ON "deployments"("projectId", "createdAt");
CREATE INDEX "deployments_environmentId_createdAt_idx"
ON "deployments"("environmentId", "createdAt");
CREATE INDEX "deployments_previousDeploymentId_idx"
ON "deployments"("previousDeploymentId");
CREATE INDEX "deployment_events_deploymentId_createdAt_idx"
ON "deployment_events"("deploymentId", "createdAt");
ALTER TABLE "deployments" ADD CONSTRAINT "deployments_projectId_fkey"
FOREIGN KEY ("projectId") REFERENCES "projects"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "deployments" ADD CONSTRAINT "deployments_environmentId_fkey"
FOREIGN KEY ("environmentId") REFERENCES "environments"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "deployments" ADD CONSTRAINT "deployments_previousDeploymentId_fkey"
FOREIGN KEY ("previousDeploymentId") REFERENCES "deployments"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "deployment_events" ADD CONSTRAINT "deployment_events_deploymentId_fkey"
FOREIGN KEY ("deploymentId") REFERENCES "deployments"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
+54
View File
@@ -96,6 +96,7 @@ model Project {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
environments Environment[]
deployments Deployment[]
@@unique([organizationId, slug])
@@index([organizationId])
@@ -116,6 +117,7 @@ model Environment {
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
server Server @relation(fields: [serverId], references: [id], onDelete: Restrict)
containers Container[]
deployments Deployment[]
@@unique([projectId, slug])
@@index([projectId])
@@ -511,7 +513,10 @@ model Deployment {
containerId String
organizationId String
serverId String
projectId String?
environmentId String?
userId String?
idempotencyKey String?
status DeploymentStatus
trigger DeploymentTrigger
version String?
@@ -519,24 +524,58 @@ model Deployment {
branch String?
image String?
imageDigest String?
sourceSnapshot Json?
configSnapshot Json
configRevision String?
rollbackSnapshotEnc String?
strategy String?
candidateRef String?
previousDeploymentId String?
failureReason String?
rollbackReason String?
logReference String?
error String?
startedAt DateTime?
completedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
container Container @relation(fields: [containerId], references: [id], onDelete: Cascade)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
server Server @relation(fields: [serverId], references: [id], onDelete: Cascade)
project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)
environment Environment? @relation(fields: [environmentId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
previousDeployment Deployment? @relation("DeploymentPredecessor", fields: [previousDeploymentId], references: [id], onDelete: SetNull)
nextDeployments Deployment[] @relation("DeploymentPredecessor")
events DeploymentEvent[]
@@unique([containerId, idempotencyKey])
@@index([containerId, createdAt])
@@index([containerId, status, createdAt])
@@index([organizationId, createdAt])
@@index([serverId, createdAt])
@@index([projectId, createdAt])
@@index([environmentId, createdAt])
@@index([previousDeploymentId])
@@map("deployments")
}
model DeploymentEvent {
id String @id @default(cuid())
deploymentId String
status DeploymentStatus
level DeploymentEventLevel @default(INFO)
message String
metadata Json?
createdAt DateTime @default(now())
deployment Deployment @relation(fields: [deploymentId], references: [id], onDelete: Cascade)
@@index([deploymentId, createdAt])
@@map("deployment_events")
}
model DeploymentLock {
containerId String @id
token String @unique
@@ -552,17 +591,32 @@ model DeploymentLock {
enum DeploymentStatus {
QUEUED
BUILDING
RUNNING
VALIDATING
SWITCHING
ACTIVE
SUCCESS
FAILED
FAILED_ROLLED_BACK
CANCELLED
ROLLBACK_RUNNING
ROLLED_BACK
SUPERSEDED
}
enum DeploymentEventLevel {
INFO
WARNING
ERROR
}
enum DeploymentTrigger {
MANUAL
GIT_WEBHOOK
REBUILD
REDEPLOY
CONFIG_APPLY
ROLLBACK
APP_INSTALLER
}
@@ -1,6 +1,6 @@
import Link from "next/link";
import TablePagination from "@/components/TablePagination";
import { Container as ContainerIcon, PencilIcon } from "lucide-react";
import { Container as ContainerIcon } from "lucide-react";
import type { EnvironmentContainer } from "../../types/environment-container-types";
import EnvironmentStatusBadge from "./EnvironmentStatusBadge";
@@ -142,7 +142,30 @@ export default function EnvironmentContainersTable({
</div>
</div>
</td>
<td style={{ fontSize: 12 }}>{container.source}</td>
<td>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
gap: 5,
}}
>
<span style={{ fontSize: 12 }}>{container.source}</span>
<span
className={`ui-badge ${
container.managed ? "badge-online" : ""
}`}
title={
container.managed
? "Deployment lifecycle is tracked by Doktainer."
: "Discovered from Docker; no Doktainer deployment history is available yet."
}
>
{container.managementLabel}
</span>
</div>
</td>
<td>
<EnvironmentStatusBadge status={container.status} />
</td>
@@ -197,7 +220,48 @@ export default function EnvironmentContainersTable({
</span>
</div>
</td> */}
<td style={{ fontSize: 12 }}>{container.lastDeployed}</td>
<td style={{ fontSize: 12 }}>
<div
style={{ display: "flex", flexDirection: "column", gap: 3 }}
>
<span>{container.lastDeployed}</span>
<span
style={{
color: container.deploymentInProgress
? "var(--accent-blue)"
: "var(--text-muted)",
fontFamily: "var(--font--code)",
fontSize: 10,
}}
>
{container.deploymentInProgress
? "Deployment in progress"
: container.revision}
</span>
{container.rollbackAvailable ? (
<span
style={{ color: "var(--accent-green)", fontSize: 10 }}
>
Rollback available
</span>
) : null}
{container.lastDeploymentError ? (
<span
title={container.lastDeploymentError}
style={{
color: "var(--accent-red)",
fontSize: 10,
maxWidth: 220,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
Last deployment failed
</span>
) : null}
</div>
</td>
<td>
<div
style={{
@@ -14,6 +14,7 @@ interface EnvironmentContainersToolbarProps {
search: string;
statusFilter: string;
syncing: boolean;
canManage: boolean;
onSearchChange: (value: string) => void;
onStatusFilterChange: (value: string) => void;
onSync: () => void | Promise<void>;
@@ -26,6 +27,7 @@ export default function EnvironmentContainersToolbar({
search,
statusFilter,
syncing,
canManage,
onSearchChange,
onStatusFilterChange,
onSync,
@@ -95,13 +97,14 @@ export default function EnvironmentContainersToolbar({
<option value="STARTING">Starting</option>
<option value="ERROR">Error</option>
</select>
<div className="ui-toolbar-actions">
{canManage ? <div className="ui-toolbar-actions">
<button
type="button"
className="btn btn-ghost"
style={{ fontSize: 12 }}
onClick={() => void onSync()}
disabled={syncing}
title="Refresh Docker inventory only; deployment revision history is unchanged."
>
{syncing ? (
<Loader2 size={12} className="animate-spin" />
@@ -191,7 +194,7 @@ export default function EnvironmentContainersToolbar({
</div>
) : null}
</div>
</div>
</div> : null}
</section>
);
}
@@ -1,94 +1,14 @@
import {
Clock3,
Cpu,
Database,
RefreshCcw,
ShieldCheck,
ToggleLeft,
ToggleRight,
} from "lucide-react";
import type {
AdvancedAuditEvent,
AdvancedSettingItem,
AdvancedTabData,
AppAction,
} from "../../types/app-detail-types";
import type { AdvancedTabData } from "../../types/app-detail-types";
import PanelShell from "../overview/PanelShell";
import AdvancedSummaryCard from "./AdvancedSummaryCard";
interface AdvancedTabPanelProps {
advanced: AdvancedTabData;
activeAction?: AppAction["id"] | null;
onReset: () => void;
onRemove: () => void;
}
const auditToneColor: Record<AdvancedAuditEvent["tone"], string> = {
info: "var(--accent-blue)",
success: "var(--accent-green)",
warning: "var(--accent-yellow)",
};
function SettingsRow({ item }: { item: AdvancedSettingItem }) {
return (
<div
style={{
display: "grid",
gridTemplateColumns: "minmax(0, 1fr) auto",
gap: 10,
alignItems: "center",
padding: "10px 11px",
border: "1px solid var(--border)",
borderRadius: 7,
background: "var(--bg-input)",
}}
>
<div style={{ minWidth: 0 }}>
<p
style={{
margin: 0,
color: "var(--text-primary)",
fontSize: 12,
fontWeight: 700,
}}
>
{item.label}
</p>
<p
style={{
marginTop: 4,
color: "var(--text-muted)",
fontSize: 11,
lineHeight: 1.45,
}}
>
{item.description}
</p>
</div>
<button
type="button"
className="btn btn-ghost"
aria-label={`${item.label} status`}
style={{
minHeight: 30,
padding: "4px 8px",
color: item.enabled ? "var(--accent-green)" : "var(--text-muted)",
}}
>
{item.enabled ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}
</button>
</div>
);
}
export default function AdvancedTabPanel({
advanced,
activeAction,
onReset,
onRemove,
}: AdvancedTabPanelProps) {
const actionBusy = activeAction !== null && activeAction !== undefined;
return (
<section style={{ display: "flex", flexDirection: "column", gap: 12 }}>
<div
@@ -0,0 +1,433 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { AlertTriangle, Loader2, Settings2, X } from "lucide-react";
import {
containers as containersApi,
type ContainerConfigurationDraft,
type ContainerConfigurationEditorData,
type ContainerConfigurationPlan,
} from "@/lib/api";
type Props = {
containerId: string;
onClose: () => void;
onApplied: () => Promise<void> | void;
};
function formatValue(value: string | number | string[]) {
if (Array.isArray(value)) return value.join(", ") || "None";
if (typeof value === "number" && value === 0) return "Unlimited";
return String(value);
}
export default function EditContainerConfigurationModal({
containerId,
onClose,
onApplied,
}: Props) {
const nameInputRef = useRef<HTMLInputElement | null>(null);
const [editor, setEditor] = useState<ContainerConfigurationEditorData | null>(null);
const [draft, setDraft] = useState<ContainerConfigurationDraft | null>(null);
const [plan, setPlan] = useState<ContainerConfigurationPlan | null>(null);
const [loading, setLoading] = useState(true);
const [previewing, setPreviewing] = useState(false);
const [applying, setApplying] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && !applying) onClose();
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [applying, onClose]);
useEffect(() => {
let active = true;
containersApi
.configuration(containerId)
.then((response) => {
if (!active) return;
setEditor(response.data);
setDraft(response.data.draft);
window.requestAnimationFrame(() => nameInputRef.current?.focus());
})
.catch((loadError: unknown) => {
if (!active) return;
setError(
loadError instanceof Error
? loadError.message
: "Failed to load container configuration.",
);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [containerId]);
const updateDraft = <K extends keyof ContainerConfigurationDraft>(
field: K,
value: ContainerConfigurationDraft[K],
) => {
setDraft((current) => (current ? { ...current, [field]: value } : current));
setPlan(null);
setError("");
};
const preview = async () => {
if (!draft) return;
setPreviewing(true);
setError("");
try {
const response = await containersApi.previewConfiguration(containerId, draft);
setPlan(response.data);
} catch (previewError) {
setError(
previewError instanceof Error
? previewError.message
: "Configuration preview failed.",
);
} finally {
setPreviewing(false);
}
};
const apply = async () => {
if (!draft || !plan) return;
setApplying(true);
setError("");
try {
await containersApi.applyConfiguration(containerId, {
draft,
expectedConfigRevision: plan.expectedConfigRevision,
idempotencyKey: crypto.randomUUID(),
});
await onApplied();
onClose();
} catch (applyError) {
setError(
applyError instanceof Error
? applyError.message
: "Failed to apply container configuration.",
);
setPlan(null);
} finally {
setApplying(false);
}
};
return (
<div
className="modal-overlay"
onMouseDown={(event) => {
if (event.target === event.currentTarget && !applying) onClose();
}}
>
<div
className="modal-shell modal-shell-wide"
style={{ maxWidth: 720 }}
onMouseDown={(event) => event.stopPropagation()}
>
<button
type="button"
className="modal-close"
aria-label="Close configuration editor"
disabled={applying}
onClick={onClose}
>
<X size={22} />
</button>
<div
role="dialog"
aria-modal="true"
aria-labelledby="edit-container-configuration-title"
className="modal animate-slide-in"
style={{ width: "100%", maxWidth: 720, padding: 28 }}
>
<header
style={{
display: "flex",
alignItems: "flex-start",
gap: 12,
marginBottom: 20,
paddingRight: 36,
}}
>
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
<Settings2 size={19} style={{ color: "var(--accent-blue)" }} />
<div>
<h2
id="edit-container-configuration-title"
style={{ margin: 0, color: "var(--text-primary)", fontSize: 17 }}
>
Edit configuration
</h2>
<p style={{ margin: "3px 0 0", color: "var(--text-muted)", fontSize: 12 }}>
Preview the runtime impact before applying changes.
</p>
</div>
</div>
</header>
<div style={{ display: "grid", gap: 18 }}>
{loading ? (
<div
role="status"
aria-live="polite"
style={{
minHeight: 96,
width: "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 10,
color: "var(--text-muted)",
textAlign: "center",
fontSize: 13,
}}
>
<Loader2 size={20} className="animate-spin" aria-hidden="true" />
<span>Loading effective Docker configuration...</span>
</div>
) : null}
{!loading && draft && editor ? (
<>
{editor.blockedReasons.length > 0 ? (
<div
role="alert"
style={{
padding: "12px 14px",
border: "1px solid rgba(245,158,11,0.28)",
borderRadius: 10,
background: "rgba(245,158,11,0.08)",
color: "var(--text-secondary)",
fontSize: 13,
lineHeight: 1.6,
}}
>
{editor.blockedReasons.join(" ")}
</div>
) : null}
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(230px, 1fr))", gap: 14 }}>
<label style={{ display: "grid", gap: 7, color: "var(--text-secondary)", fontSize: 12 }}>
Docker name
<input
ref={nameInputRef}
className="input"
value={draft.name}
disabled={applying}
onChange={(event) => updateDraft("name", event.target.value)}
autoComplete="off"
/>
</label>
<label style={{ display: "grid", gap: 7, color: "var(--text-secondary)", fontSize: 12 }}>
Restart policy
<select
className="input"
value={draft.restartPolicy}
disabled={applying}
onChange={(event) =>
updateDraft(
"restartPolicy",
event.target.value as ContainerConfigurationDraft["restartPolicy"],
)
}
>
<option value="no">No automatic restart</option>
<option value="unless-stopped">Unless stopped</option>
<option value="always">Always</option>
<option value="on-failure">On failure</option>
</select>
</label>
<label style={{ display: "grid", gap: 7, color: "var(--text-secondary)", fontSize: 12 }}>
CPU limit
<input
className="input"
type="number"
min={0}
max={256}
step={0.1}
value={draft.cpuLimit}
disabled={applying}
onChange={(event) => updateDraft("cpuLimit", Number(event.target.value))}
/>
<span style={{ color: "var(--text-muted)" }}>Use 0 for unlimited.</span>
</label>
<label style={{ display: "grid", gap: 7, color: "var(--text-secondary)", fontSize: 12 }}>
Memory limit (MB)
<input
className="input"
type="number"
min={0}
max={1_048_576}
step={1}
value={draft.memoryLimitMb}
disabled={applying}
onChange={(event) => updateDraft("memoryLimitMb", Number(event.target.value))}
/>
<span style={{ color: "var(--text-muted)" }}>Use 0 for unlimited.</span>
</label>
</div>
<fieldset style={{ margin: 0, padding: 0, border: 0 }}>
<legend style={{ color: "var(--text-secondary)", fontSize: 12, marginBottom: 9 }}>
Network attachments
</legend>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(190px, 1fr))",
gap: 8,
maxHeight: 320,
overflowY: "auto",
scrollbarGutter: "stable",
}}
>
{editor.availableNetworks.map((network) => {
const checked = draft.networks.includes(network.name);
const isPrimary = editor.current.primaryNetwork === network.name;
return (
<label
key={network.name}
style={{
display: "flex",
gap: 10,
alignItems: "center",
padding: "10px 12px",
border: `1px solid ${checked ? "rgba(59,130,246,0.28)" : "var(--border)"}`,
borderRadius: 8,
background: checked
? "rgba(59,130,246,0.08)"
: "var(--bg-input)",
color: "var(--text-secondary)",
fontSize: 12,
cursor: isPrimary || applying ? "not-allowed" : "pointer",
}}
>
<input
type="checkbox"
checked={checked}
disabled={applying || isPrimary}
style={{ accentColor: "#3b82f6" }}
onChange={() =>
updateDraft(
"networks",
checked
? draft.networks.filter((item) => item !== network.name)
: [...draft.networks, network.name],
)
}
/>
<span>
<strong style={{ display: "block", color: "var(--text-primary)" }}>
{network.name}{isPrimary ? " (primary)" : ""}
</strong>
{network.driver} · {network.scope}
</span>
</label>
);
})}
</div>
</fieldset>
<div style={{ color: "var(--text-muted)", fontSize: 12, lineHeight: 1.6 }}>
This editor applies live-safe fields only. Image, ports, environment variables, volumes, command, healthcheck, and primary network changes require a separate runtime-replacement flow and are not available here.
</div>
{plan ? (
<section style={{ display: "grid", gap: 10, borderTop: "1px solid var(--border)", paddingTop: 16 }}>
<strong style={{ color: "var(--text-primary)", fontSize: 14 }}>Change preview</strong>
{plan.changes.length === 0 ? (
<p style={{ margin: 0, color: "var(--text-muted)", fontSize: 13 }}>No configuration changes detected.</p>
) : (
<div style={{ display: "grid", gap: 8 }}>
{plan.changes.map((change) => (
<div key={change.field} style={{ padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 9, fontSize: 12 }}>
<strong style={{ color: "var(--text-primary)" }}>{change.label}</strong>
<div style={{ marginTop: 5, color: "var(--text-muted)", overflowWrap: "anywhere" }}>
{formatValue(change.before)} → {formatValue(change.after)}
</div>
<span
className={`ui-badge ${
change.impact === "LIVE_UPDATE"
? "badge-online"
: "badge-warning"
}`}
style={{ marginTop: 7 }}
>
{change.impact === "LIVE_UPDATE"
? "Live update"
: "Live disruptive"}
</span>
</div>
))}
</div>
)}
{plan.warnings.map((warning) => (
<div key={warning} style={{ display: "flex", gap: 8, color: "#d97706", fontSize: 12, lineHeight: 1.5 }}>
<AlertTriangle size={14} style={{ flexShrink: 0, marginTop: 2 }} />
{warning}
</div>
))}
{plan.blockedReasons.length > 0 ? (
<div role="alert" style={{ color: "var(--text-danger)", fontSize: 12, lineHeight: 1.5 }}>
{plan.blockedReasons.join(" ")}
</div>
) : null}
</section>
) : null}
</>
) : null}
{error ? (
<div role="alert" style={{ color: "var(--text-danger)", fontSize: 13, lineHeight: 1.6 }}>
{error}
</div>
) : null}
</div>
<footer
style={{
display: "grid",
gridTemplateColumns: "1fr 2fr",
gap: 5,
marginTop: 20,
}}
>
<button type="button" className="btn btn-ghost" disabled={applying} onClick={onClose}>
Cancel
</button>
{!plan ? (
<button
type="button"
className="btn btn-primary"
disabled={!draft || loading || previewing || editor?.blockedReasons.length !== 0}
onClick={() => void preview()}
>
{previewing ? <Loader2 size={14} className="animate-spin" /> : null}
Preview changes
</button>
) : (
<button
type="button"
className="btn btn-primary"
disabled={applying || plan.changes.length === 0 || plan.blockedReasons.length > 0}
onClick={() => void apply()}
>
{applying ? <Loader2 size={14} className="animate-spin" /> : <Settings2 size={14} />}
{applying ? "Applying..." : "Apply live changes"}
</button>
)}
</footer>
</div>
</div>
</div>
);
}
@@ -16,6 +16,7 @@ interface DeploymentsTabPanelProps {
onRollback: (deploymentId: string) => void;
onViewDetails: (deploymentId: string) => void;
rollingBackId?: string | null;
allowRollback?: boolean;
}
const statusClass: Record<DeploymentHistoryItem["status"], string> = {
@@ -30,6 +31,7 @@ export default function DeploymentsTabPanel({
onRollback,
onViewDetails,
rollingBackId = null,
allowRollback = false,
}: DeploymentsTabPanelProps) {
const [statusFilter, setStatusFilter] = useState<
"ALL" | DeploymentHistoryItem["status"]
@@ -219,7 +221,7 @@ export default function DeploymentsTabPanel({
>
<Eye size={13} />
</button>
{deployment.canRollback ? (
{allowRollback && deployment.canRollback ? (
<button
type="button"
className="btn btn-ghost btn-small"
@@ -77,6 +77,23 @@ export default function AppDetailHeader({
const hasActiveMenuAction = menuActions.some(
(action) => action.id === activeAction,
);
const normalizedStatus = app.status.trim().toUpperCase();
const statusColor =
normalizedStatus === "RUNNING"
? "var(--accent-green)"
: normalizedStatus === "ERROR"
? "var(--accent-red)"
: normalizedStatus === "STARTING" || normalizedStatus === "RESTARTING"
? "#d97706"
: "var(--text-muted)";
const statusGlow =
normalizedStatus === "RUNNING"
? "rgba(34,197,94,0.12)"
: normalizedStatus === "ERROR"
? "rgba(239,68,68,0.12)"
: normalizedStatus === "STARTING" || normalizedStatus === "RESTARTING"
? "rgba(245,158,11,0.12)"
: "rgba(148,163,184,0.12)";
return (
<section
@@ -168,7 +185,7 @@ export default function AppDetailHeader({
display: "inline-flex",
alignItems: "center",
gap: 6,
color: "var(--accent-green)",
color: statusColor,
fontSize: 12,
fontWeight: 700,
flexShrink: 0,
@@ -179,8 +196,8 @@ export default function AppDetailHeader({
width: 7,
height: 7,
borderRadius: "50%",
background: "var(--accent-green)",
boxShadow: "0 0 0 4px rgba(34,197,94,0.12)",
background: statusColor,
boxShadow: `0 0 0 4px ${statusGlow}`,
}}
/>
{app.status}
@@ -237,8 +254,9 @@ export default function AppDetailHeader({
type="button"
key={action.label}
onClick={() => onAction(action.id)}
disabled={actionBusy}
disabled={actionBusy || action.disabled}
aria-busy={isBusy}
title={action.disabledReason}
className={getActionClassName(action)}
style={{ flex: "1 1 92px", minWidth: 0, maxWidth: 132 }}
>
@@ -251,6 +269,7 @@ export default function AppDetailHeader({
</button>
);
})}
{menuActions.length > 0 ? (
<div ref={menuRef} style={{ position: "relative", flex: "0 0 44px" }}>
<button
ref={menuButtonRef}
@@ -295,8 +314,9 @@ export default function AppDetailHeader({
type="button"
key={action.id}
className="btn btn-ghost"
disabled={actionBusy}
disabled={actionBusy || action.disabled}
aria-busy={isBusy}
title={action.disabledReason}
onClick={() => {
setMenuOpen(false);
onAction(action.id);
@@ -324,6 +344,7 @@ export default function AppDetailHeader({
)
: null}
</div>
) : null}
</div>
</div>
</section>
@@ -1,4 +1,4 @@
import { CheckCircle2 } from "lucide-react";
import { AlertTriangle, CheckCircle2, CircleHelp } from "lucide-react";
import type { HealthSummary } from "../../types/app-detail-types";
import InfoRows from "./InfoRows";
import PanelShell from "./PanelShell";
@@ -8,6 +8,16 @@ interface HealthPanelProps {
}
export default function HealthPanel({ health }: HealthPanelProps) {
const normalizedStatus = health.status.toLowerCase();
const isHealthy = normalizedStatus === "healthy";
const isWarning =
normalizedStatus === "unhealthy" || normalizedStatus === "starting";
const StatusIcon = isHealthy
? CheckCircle2
: isWarning
? AlertTriangle
: CircleHelp;
return (
<PanelShell title="Health">
<InfoRows
@@ -17,13 +27,17 @@ export default function HealthPanel({ health }: HealthPanelProps) {
value: (
<span
style={{
color: "var(--accent-green)",
color: isHealthy
? "var(--accent-green)"
: isWarning
? "var(--accent-amber)"
: "var(--text-muted)",
display: "inline-flex",
alignItems: "center",
gap: 5,
}}
>
<CheckCircle2 size={13} />
<StatusIcon size={13} />
{health.status}
</span>
),
@@ -3,7 +3,9 @@ import {
FolderOpen,
History,
Play,
RefreshCw,
RotateCcw,
Settings2,
Square,
Terminal,
Trash,
@@ -27,7 +29,24 @@ export const primaryActions: AppAction[] = [
{ id: "start", label: "Start", icon: Play, tone: "ghost" },
{ id: "restart", label: "Restart", icon: RotateCcw, tone: "ghost" },
{ id: "stop", label: "Stop", icon: Square, tone: "danger" },
{ id: "rebuild", label: "Rebuild", icon: History, tone: "ghost" },
{
id: "edit",
label: "Edit configuration",
icon: Settings2,
tone: "ghost",
},
{
id: "redeploy",
label: "Redeploy current revision",
icon: RefreshCw,
tone: "ghost",
},
{
id: "rebuild",
label: "Rebuild from source",
icon: History,
tone: "ghost",
},
{ id: "files", label: "File Manager", icon: FolderOpen, tone: "ghost" },
{ id: "terminal", label: "Terminal", icon: Terminal, tone: "ghost" },
{ id: "open", label: "Open App", icon: ExternalLink, tone: "ghost" },
@@ -53,10 +53,27 @@ function formatDeploymentDuration(item: DeploymentRecord) {
function formatDeploymentStatus(
status: DeploymentRecord["status"],
): DeploymentHistoryItem["status"] {
if (status === "SUCCESS") return "Success";
if (
status === "SUCCESS" ||
status === "ACTIVE" ||
status === "SUPERSEDED"
) {
return "Success";
}
if (status === "FAILED") return "Failed";
if (status === "RUNNING" || status === "QUEUED") return "Running";
return status === "ROLLED_BACK" ? "Rolled Back" : "Failed";
if (
status === "QUEUED" ||
status === "BUILDING" ||
status === "RUNNING" ||
status === "VALIDATING" ||
status === "SWITCHING" ||
status === "ROLLBACK_RUNNING"
) {
return "Running";
}
return status === "ROLLED_BACK" || status === "FAILED_ROLLED_BACK"
? "Rolled Back"
: "Failed";
}
function formatDeploymentTrigger(trigger: DeploymentRecord["trigger"]) {
@@ -64,11 +81,23 @@ function formatDeploymentTrigger(trigger: DeploymentRecord["trigger"]) {
MANUAL: "Manual deploy",
GIT_WEBHOOK: "Git webhook",
REBUILD: "Rebuild",
REDEPLOY: "Redeploy",
CONFIG_APPLY: "Configuration apply",
ROLLBACK: "Rollback",
APP_INSTALLER: "App installer",
}[trigger];
}
export function isDeploymentRollbackAvailable(item: DeploymentRecord) {
return (
(item.status === "SUCCESS" ||
item.status === "ACTIVE" ||
item.status === "SUPERSEDED") &&
Boolean(item.image) &&
item.rollbackArtifactAvailable === true
);
}
function mapDeploymentHistory(items: DeploymentRecord[]) {
return items.map((item) => ({
id: item.id,
@@ -78,8 +107,8 @@ function mapDeploymentHistory(items: DeploymentRecord[]) {
commit: item.commitSha || "-",
branch: item.branch || "-",
duration: formatDeploymentDuration(item),
deployedAt: formatDate(item.createdAt),
canRollback: item.status === "SUCCESS" && Boolean(item.image),
deployedAt: formatDate(item.completedAt ?? item.createdAt),
canRollback: isDeploymentRollbackAvailable(item),
}));
}
@@ -2,6 +2,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useCurrentUser } from "@/lib/auth-state";
import { getRoleCapabilities } from "@/lib/rbac";
import ConfirmActionDialog from "@/components/ConfirmActionDialog";
import DashboardLayout from "@/components/DashboardLayout";
import IssueDetailsSummary from "@/components/IssueDetailsSummary";
@@ -24,6 +26,7 @@ import {
type ProjectRecord,
} from "@/lib/api";
import ContainerFileManagerModal from "@/components/containers/modals/ContainerFileManagerModal";
import EditContainerConfigurationModal from "./components/configuration/EditContainerConfigurationModal";
import AdvancedTabPanel from "./components/advanced/AdvancedTabPanel";
import DeploymentsTabPanel from "./components/deployments/DeploymentsTabPanel";
import DeploymentDetailsModal from "./components/deployments/DeploymentDetailsModal";
@@ -76,6 +79,14 @@ function formatStatus(value: string) {
return value.charAt(0) + value.slice(1).toLowerCase();
}
function formatDeploymentPhase(value: DeploymentRecord["status"]) {
return value
.toLowerCase()
.split("_")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(" ");
}
function formatDateTime(value: string | null | undefined) {
if (!value) return "-";
const date = new Date(value);
@@ -83,6 +94,69 @@ function formatDateTime(value: string | null | undefined) {
return date.toLocaleString();
}
function formatDeploymentDuration(deployment: DeploymentRecord | undefined) {
if (!deployment?.startedAt || !deployment.completedAt) return "-";
const duration =
new Date(deployment.completedAt).getTime() -
new Date(deployment.startedAt).getTime();
if (!Number.isFinite(duration) || duration < 0) return "-";
const seconds = Math.floor(duration / 1000);
return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}
function findActiveDeployment(deployments: DeploymentRecord[]) {
return (
deployments.find((item) => item.status === "ACTIVE") ??
deployments.find(
(item) => item.status === "SUCCESS" || item.status === "SUPERSEDED",
)
);
}
function isDeploymentInProgress(status: DeploymentRecord["status"]) {
return [
"QUEUED",
"BUILDING",
"RUNNING",
"VALIDATING",
"SWITCHING",
"ROLLBACK_RUNNING",
].includes(status);
}
function getDockerHealthSummary(inspect: Record<string, unknown>) {
const state = inspect.State;
if (!state || typeof state !== "object" || Array.isArray(state)) {
return {
status: "Unavailable",
responseTime: "-",
httpStatus: "Not probed",
lastCheck: "Docker inspect unavailable",
};
}
const stateRecord = state as Record<string, unknown>;
const health = stateRecord.Health;
const dockerHealth =
health && typeof health === "object" && !Array.isArray(health)
? (health as Record<string, unknown>).Status
: null;
const runtimeStatus = stateRecord.Status;
return {
status:
typeof dockerHealth === "string" && dockerHealth.trim()
? formatStatus(dockerHealth)
: "Not configured",
responseTime: "-",
httpStatus: "Not probed",
lastCheck:
typeof dockerHealth === "string" && dockerHealth.trim()
? "From Docker healthcheck"
: `Runtime ${typeof runtimeStatus === "string" ? runtimeStatus : "unknown"}; no healthcheck`,
};
}
function formatSourcePath(container: Container) {
if (container.sourceType === "GIT_PROVIDER") return "Git provider";
if (container.sourceType === "GIT_CLONE") return "Git repository";
@@ -348,7 +422,9 @@ function buildAppDetail({
metrics?: RuntimeMetricSource | null;
}): AppDetail {
const status = formatStatus(container.status);
const isRunning = container.status === "RUNNING";
const activeRevision = container.deploymentSummary?.activeRevision;
const currentOperation = container.deploymentSummary?.currentOperation;
const deployedAt = activeRevision?.completedAt ?? activeRevision?.createdAt;
const metricSource = metrics ?? detail;
const serverName = detail?.server.name ?? container.server?.name ?? "-";
const serverIp = detail?.server.ip ?? container.server?.ip ?? "-";
@@ -365,13 +441,15 @@ function buildAppDetail({
name: container.name,
image: container.image,
status,
managementLabel:
container.capabilities?.managementLabel ?? "Docker import",
path: formatSourcePath(container),
projectName: project.name,
environmentName: environment.name,
serverName,
serverIp,
owner: "-",
lastDeployed: formatDateTime(container.createdAt),
lastDeployed: deployedAt ? formatDateTime(deployedAt) : "Never",
openUrl:
getDomainUrl(domains, container) ?? getContainerWebUiUrl(container),
domains: getLinkedDomains(domains, container),
@@ -393,18 +471,26 @@ function buildAppDetail({
terminal: createTerminalData(container, detail),
metrics: buildMetrics(metricSource, container),
deployment: {
status: isRunning ? "Success" : status,
commit: "-",
branch: "-",
message: container.sourceType ?? "Manual container",
deployedAt: formatDateTime(container.createdAt),
duration: "-",
status: currentOperation
? formatDeploymentPhase(currentOperation.status)
: activeRevision
? "Success"
: "No deployment",
commit: activeRevision?.commitSha ?? "-",
branch: activeRevision?.branch ?? "-",
message: currentOperation
? `${currentOperation.trigger} deployment in progress`
: activeRevision?.trigger ?? container.sourceType ?? "Manual container",
deployedAt: deployedAt ? formatDateTime(deployedAt) : "-",
duration: formatDeploymentDuration(activeRevision ?? undefined),
},
health: {
status: isRunning ? "Healthy" : status,
status: container.status === "RUNNING" ? "Unknown" : status,
responseTime: "-",
httpStatus: isRunning ? "200" : "-",
lastCheck: runtimeNotice ? "Runtime unavailable" : "Loaded just now",
httpStatus: "Not probed",
lastCheck: runtimeNotice
? "Runtime unavailable"
: "Awaiting Docker inspect",
},
replicas: 1,
runtimeContainers: [
@@ -421,16 +507,27 @@ function buildAppDetail({
};
}
function createRebuildTimeline(activeStep: number): ProcessLogStep[] {
function createDeploymentOperationTimeline(
operation: "redeploy" | "rebuild",
activeStep: number,
): ProcessLogStep[] {
const operationLabel =
operation === "redeploy"
? "Redeploy current revision"
: "Rebuild from source";
const steps = [
{ id: "prepare", label: "Preparing rebuild request", progress: 10 },
{
id: "rebuild",
label: "Waiting for rebuild process",
id: "prepare",
label: `Preparing ${operationLabel.toLowerCase()}`,
progress: 10,
},
{
id: operation,
label: `Waiting for ${operationLabel.toLowerCase()}`,
progress: "Running",
},
{ id: "sync", label: "Refreshing container detail", progress: 85 },
{ id: "complete", label: "Rebuild completed", progress: 100 },
{ id: "complete", label: `${operationLabel} completed`, progress: 100 },
];
return steps.map((step, index) => ({
@@ -444,16 +541,48 @@ function createRebuildTimeline(activeStep: number): ProcessLogStep[] {
}));
}
function createFailedRebuildTimeline(activeStep: number): ProcessLogStep[] {
return createRebuildTimeline(activeStep).map((step, index) =>
index === activeStep
? { ...step, status: "error" as const }
: index < activeStep
? { ...step, status: "success" as const }
: { ...step, status: "pending" as const },
function createFailedDeploymentOperationTimeline(
operation: "redeploy" | "rebuild",
activeStep: number,
): ProcessLogStep[] {
return createDeploymentOperationTimeline(operation, activeStep).map(
(step, index) =>
index === activeStep
? { ...step, status: "error" as const }
: index < activeStep
? { ...step, status: "success" as const }
: { ...step, status: "pending" as const },
);
}
function describeRedeployJobResult(result: unknown) {
if (!result || typeof result !== "object" || Array.isArray(result)) return [];
const response = result as {
message?: unknown;
meta?: {
strategy?: unknown;
proxyTrafficContinuous?: unknown;
directPortInterruptionPossible?: unknown;
};
};
const lines: string[] = [];
if (typeof response.meta?.strategy === "string") {
lines.push(`[redeploy] Strategy: ${response.meta.strategy}`);
}
if (response.meta?.proxyTrafficContinuous === true) {
lines.push("[redeploy] Managed proxy traffic stayed on a validated runtime");
}
if (response.meta?.directPortInterruptionPossible === true) {
lines.push(
"[redeploy] Direct host-port traffic may have been briefly interrupted",
);
}
if (typeof response.message === "string") {
lines.push(`[redeploy] ${response.message}`);
}
return lines;
}
export default function AppContainerDetailPage() {
const params = useParams<{
projectId: string;
@@ -461,6 +590,9 @@ export default function AppContainerDetailPage() {
containerId: string;
}>();
const router = useRouter();
const currentUser = useCurrentUser();
const roleCapabilities = getRoleCapabilities(currentUser?.role);
const canMutateContainers = roleCapabilities.canManageDeveloperTools;
const [activeTab, setActiveTab] = useState<AppDetailTab>("overview");
const [terminalWasOpened, setTerminalWasOpened] = useState(false);
const [appDetail, setAppDetail] = useState<AppDetail | null>(null);
@@ -483,6 +615,7 @@ export default function AppContainerDetailPage() {
null,
);
const [showFileManager, setShowFileManager] = useState(false);
const [showConfigurationEditor, setShowConfigurationEditor] = useState(false);
const [error, setError] = useState("");
const [actionError, setActionError] = useState("");
const [runtimeNotice, setRuntimeNotice] = useState("");
@@ -640,14 +773,44 @@ export default function AppContainerDetailPage() {
deploymentHistoryRef.current = response.data.items;
setAppDetail((current) =>
current
? {
...current,
deployments: createDeploymentsData(
container,
runtimeDetailRef.current,
response.data.items,
),
}
? (() => {
const records = response.data.items;
const active =
findActiveDeployment(records) ??
container.deploymentSummary?.activeRevision ??
undefined;
const inProgress =
records.find((item) =>
isDeploymentInProgress(item.status),
) ?? container.deploymentSummary?.currentOperation ?? undefined;
const deployedAt = active?.completedAt ?? active?.createdAt;
return {
...current,
lastDeployed: deployedAt
? formatDateTime(deployedAt)
: "Never",
deployment: {
status: inProgress
? formatDeploymentPhase(inProgress.status)
: active
? "Success"
: "No deployment",
commit: active?.commitSha ?? "-",
branch: active?.branch ?? "-",
message: inProgress
? `${inProgress.trigger} deployment in progress`
: active?.trigger ?? "No successful deployment",
deployedAt: deployedAt ? formatDateTime(deployedAt) : "-",
duration: formatDeploymentDuration(active),
},
deployments: createDeploymentsData(
container,
runtimeDetailRef.current,
records,
),
};
})()
: current,
);
} catch {
@@ -680,6 +843,7 @@ export default function AppContainerDetailPage() {
const requestRollback = useCallback(
(deploymentId: string) => {
if (!canMutateContainers) return;
const deployment = appDetail?.deployments.history.find(
(item) => item.id === deploymentId,
);
@@ -696,7 +860,7 @@ export default function AppContainerDetailPage() {
},
});
},
[appDetail, runRollback],
[appDetail, canMutateContainers, runRollback],
);
const openDeploymentDetails = useCallback(
@@ -762,12 +926,6 @@ export default function AppContainerDetailPage() {
? {
...current,
metrics: buildMetrics(metrics, container),
health: {
...current.health,
status: "Healthy",
httpStatus: "200",
lastCheck: "Updated just now",
},
runtimeContainers: [
{
name: container.name,
@@ -869,6 +1027,7 @@ export default function AppContainerDetailPage() {
serverName: detail.server.name,
serverIp: detail.server.ip,
metrics: buildMetrics(detail, container),
health: getDockerHealthSummary(detail.inspect),
runtime: createRuntimeData(container, detail),
deployments: createDeploymentsData(
container,
@@ -986,10 +1145,6 @@ export default function AppContainerDetailPage() {
recentLogs: nextLogStream,
})
: current.logsDetail,
health: {
...current.health,
lastCheck: "Refreshed just now",
},
}
: current,
);
@@ -1024,22 +1179,75 @@ export default function AppContainerDetailPage() {
const isStopped =
containerRecord?.status === "STOPPED" ||
containerRecord?.status === "ERROR";
const deploymentBusy = Boolean(
containerRecord?.deploymentSummary?.currentOperation,
);
return headerActions
.filter((action) => !(isStopped && action.id === "stop"))
.filter((action) => {
if (action.id === "open") return Boolean(appDetail?.openUrl);
if (!canMutateContainers) return false;
return !(isStopped && action.id === "stop");
})
.map((action) =>
action.id === "restart" && isStopped
? { ...action, id: "start" as const, label: "Start" }
: action,
)
.map((action) =>
action.id !== "open" && deploymentBusy
? {
...action,
disabled: true,
disabledReason:
"Another deployment operation is currently running.",
}
: action,
);
}, [containerRecord?.status]);
}, [appDetail?.openUrl, canMutateContainers, containerRecord]);
const headerMenuActions = useMemo(
() =>
primaryActions.filter((action) =>
["files", "rebuild", "remove"].includes(action.id),
),
[],
() => {
const deploymentBusy = Boolean(
containerRecord?.deploymentSummary?.currentOperation,
);
const capabilities = containerRecord?.capabilities;
return primaryActions
.filter((action) => {
if (action.id === "files") {
return containerRecord?.status === "RUNNING";
}
if (!canMutateContainers) return false;
if (action.id === "edit") {
return Boolean(capabilities?.editConfiguration.available);
}
if (action.id === "redeploy") {
return Boolean(capabilities?.redeploy.available);
}
if (action.id === "rebuild") {
return Boolean(capabilities?.rebuild.available);
}
return action.id === "remove";
})
.map((action) => {
const composeRebuild =
action.id === "rebuild" &&
capabilities?.rebuild.mode === "COMPOSE_RECREATE";
const adjusted = composeRebuild
? { ...action, label: "Rebuild Compose project" }
: action;
return deploymentBusy && action.id !== "files"
? {
...adjusted,
disabled: true,
disabledReason:
"Another deployment operation is currently running.",
}
: adjusted;
});
},
[canMutateContainers, containerRecord],
);
const handleTabChange = useCallback((tab: AppDetailTab) => {
@@ -1147,18 +1355,23 @@ export default function AppContainerDetailPage() {
[params.containerId],
);
const runRebuild = useCallback(async () => {
if (!containerRecord) return;
const runDeploymentOperation = useCallback(
async (operation: "redeploy" | "rebuild") => {
if (!containerRecord) return;
const isRedeploy = operation === "redeploy";
const operationLabel = isRedeploy
? "Redeploy current revision"
: "Rebuild from source";
setActing(true);
setActiveAction("rebuild");
setActiveAction(operation);
setActionError("");
rebuildJobIdRef.current = null;
rebuildCancelRequestedRef.current = false;
const baseTerminalLines = [
`[rebuild] Starting rebuild for ${containerRecord.name}`,
`[rebuild] Source: ${containerRecord.sourceType ?? "unknown"}`,
`[rebuild] Server ID: ${containerRecord.serverId}`,
`[${operation}] Starting ${operationLabel.toLowerCase()} for ${containerRecord.name}`,
`[${operation}] Source: ${containerRecord.sourceType ?? "unknown"}`,
`[${operation}] Server ID: ${containerRecord.serverId}`,
];
let latestTerminalLines = [...baseTerminalLines];
@@ -1174,12 +1387,13 @@ export default function AppContainerDetailPage() {
};
openProcessLogs({
title: `Rebuild Logs - ${containerRecord.name}`,
description:
"Rebuild progress, inventory sync, and terminal-style output for this request.",
title: `${operationLabel} logs - ${containerRecord.name}`,
description: isRedeploy
? "Runtime replacement from the stored current revision. No source fetch or image build is performed."
: "Source rebuild progress, inventory sync, and terminal-style output for this request.",
imageUrl: "/assets/images/img-chibi-fixing.png",
imageAlt: "Illustration of a character fixing something",
timelineLogs: createRebuildTimeline(0),
timelineLogs: createDeploymentOperationTimeline(operation, 0),
terminalLogs: latestTerminalLines,
initialTab: "timeline",
statusLabel: "Starting",
@@ -1188,30 +1402,31 @@ export default function AppContainerDetailPage() {
try {
latestTerminalLines = [
...baseTerminalLines,
"[rebuild] Creating backend rebuild job",
`[${operation}] Creating backend ${operation} job`,
];
updateProcessLogs({
timelineLogs: createRebuildTimeline(1),
timelineLogs: createDeploymentOperationTimeline(operation, 1),
terminalLogs: latestTerminalLines,
statusLabel: "Starting",
});
const jobResponse = await containersApi.createRebuildJob(
params.containerId,
);
const jobResponse = isRedeploy
? await containersApi.createRedeployJob(params.containerId)
: await containersApi.createRebuildJob(params.containerId);
const job = jobResponse.data;
rebuildJobIdRef.current = job.id;
let finalStatus = job.status;
let finalError = job.error;
let finalResult = job.result;
updateProcessTerminal(
[
...latestTerminalLines,
`[job] Rebuild job created: ${job.id}`,
"[job] Streaming backend rebuild logs",
`[job] ${operationLabel} job created: ${job.id}`,
`[job] Streaming backend ${operation} logs`,
],
{
timelineLogs: createRebuildTimeline(1),
timelineLogs: createDeploymentOperationTimeline(operation, 1),
statusLabel: "Streaming",
},
);
@@ -1244,13 +1459,14 @@ export default function AppContainerDetailPage() {
await containersApi.streamJob(job.id, {
onLog: (entry) => {
updateProcessTerminal([...latestTerminalLines, entry.message], {
timelineLogs: createRebuildTimeline(1),
timelineLogs: createDeploymentOperationTimeline(operation, 1),
statusLabel: "Streaming",
});
},
onStatus: (nextJob) => {
finalStatus = nextJob.status;
finalError = nextJob.error;
finalResult = nextJob.result;
},
});
@@ -1262,23 +1478,24 @@ export default function AppContainerDetailPage() {
finalError =
cancelledJob?.data.error ??
cancelledJob?.data.cancelReason ??
"Rebuild cancelled";
`${operationLabel} cancelled`;
}
if (finalStatus === "error") {
throw new Error(finalError || "Rebuild job failed");
throw new Error(finalError || `${operationLabel} job failed`);
}
if (finalStatus === "cancelled") {
throw new Error(finalError || "Rebuild cancelled");
throw new Error(finalError || `${operationLabel} cancelled`);
}
updateProcessLogs({
timelineLogs: createRebuildTimeline(2),
timelineLogs: createDeploymentOperationTimeline(operation, 2),
terminalLogs: [
...latestTerminalLines,
"[rebuild] Rebuild command completed",
"[rebuild] Refreshing container detail",
...(isRedeploy ? describeRedeployJobResult(finalResult) : []),
`[${operation}] ${operationLabel} command completed`,
`[${operation}] Refreshing container detail`,
].filter(Boolean),
statusLabel: "Syncing",
});
@@ -1286,28 +1503,31 @@ export default function AppContainerDetailPage() {
await load();
updateProcessLogs({
timelineLogs: createRebuildTimeline(3).map((step) => ({
timelineLogs: createDeploymentOperationTimeline(operation, 3).map((step) => ({
...step,
status: "success",
})),
terminalLogs: [
...latestTerminalLines,
"[rebuild] Rebuild command completed",
"[rebuild] Container detail refreshed",
"[rebuild] Done",
...(isRedeploy ? describeRedeployJobResult(finalResult) : []),
`[${operation}] ${operationLabel} command completed`,
`[${operation}] Container detail refreshed`,
`[${operation}] Done`,
].filter(Boolean),
statusLabel: "100%",
});
updateProcessLogs({ cancelAction: undefined });
} catch (rebuildError) {
} catch (operationError) {
const message =
rebuildError instanceof Error ? rebuildError.message : "Rebuild failed";
operationError instanceof Error
? operationError.message
: `${operationLabel} failed`;
setActionError(message);
updateProcessLogs({
timelineLogs: createFailedRebuildTimeline(1),
timelineLogs: createFailedDeploymentOperationTimeline(operation, 1),
terminalLogs: [
...baseTerminalLines,
"[rebuild] Rebuild failed",
`[${operation}] ${operationLabel} failed`,
`[error] ${message}`,
],
statusLabel: "Failed",
@@ -1318,23 +1538,110 @@ export default function AppContainerDetailPage() {
setActing(false);
setActiveAction(null);
}
},
[
containerRecord,
load,
openProcessLogs,
params.containerId,
updateProcessLogs,
],
);
const openRedeployConfirmation = useCallback(async () => {
if (!containerRecord?.capabilities?.redeploy.available) {
setActionError(
containerRecord?.capabilities?.redeploy.reason ??
"Redeploy is unavailable for this container.",
);
return;
}
setActing(true);
setActiveAction("redeploy");
setActionError("");
try {
const response = await containersApi.redeployPlan(params.containerId);
const plan = response.data;
if (plan.blocked) {
setActionError(`Redeploy unavailable: ${plan.reason}`);
return;
}
const availabilityNote = plan.proxyTrafficContinuous
? plan.directPortInterruptionPossible
? "Managed domain traffic will switch to a validated candidate before replacement. Direct host-port traffic may still be briefly interrupted."
: "Managed domain traffic will switch to a validated candidate before the previous runtime is removed."
: "This runtime cannot use a proxy candidate. A brief interruption may occur while Docker replaces the runtime and verifies recovery.";
const overlapNote = plan.overlappingRuntime
? "The candidate briefly runs beside the current runtime; verify that the app does not contain a singleton worker or scheduler that must never overlap."
: "";
setConfirmDialog({
title: "Redeploy current revision",
description: appDetail
? `Replace the runtime for "${appDetail.name}" using its current stored revision?`
: "Replace this runtime using its current stored revision?",
confirmLabel: "Redeploy revision",
tone: "warning",
note: `${availabilityNote} ${overlapNote} ${plan.reason} No source code will be fetched and no image will be built.`.replaceAll(
/\s+/g,
" ",
),
onConfirm: () => {
void runDeploymentOperation("redeploy");
},
});
} catch (previewError) {
setActionError(
previewError instanceof Error
? previewError.message
: "Redeploy preview failed.",
);
} finally {
setActing(false);
setActiveAction(null);
}
}, [
appDetail,
containerRecord,
load,
openProcessLogs,
params.containerId,
updateProcessLogs,
runDeploymentOperation,
]);
const handleAction = useCallback(
(action: AppAction["id"]) => {
if (acting) return;
const mutationActions: AppAction["id"][] = [
"edit",
"start",
"restart",
"redeploy",
"rebuild",
"stop",
"remove",
];
if (mutationActions.includes(action) && !canMutateContainers) {
setActionError("Your role has read-only access to containers.");
return;
}
if (action === "open") {
openApp();
return;
}
if (action === "edit") {
if (!containerRecord?.capabilities?.editConfiguration.available) {
setActionError(
containerRecord?.capabilities?.editConfiguration.reason ??
"Configuration editing is unavailable for this container.",
);
return;
}
setActionError("");
setShowConfigurationEditor(true);
return;
}
if (action === "files") {
if (containerRecord?.status !== "RUNNING") {
setActionError(
@@ -1379,23 +1686,38 @@ export default function AppContainerDetailPage() {
return;
}
if (action === "rebuild") {
const isGitSource =
containerRecord?.sourceType === "GIT_CLONE" ||
containerRecord?.sourceType === "GIT_PROVIDER";
if (action === "redeploy") {
void openRedeployConfirmation();
return;
}
if (action === "rebuild") {
const rebuildCapability = containerRecord?.capabilities?.rebuild;
if (!rebuildCapability?.available) {
setActionError(
rebuildCapability?.reason ??
"Rebuild is unavailable for this container.",
);
return;
}
const isComposeRebuild =
rebuildCapability.mode === "COMPOSE_RECREATE";
setConfirmDialog({
title: "Rebuild Container",
title: isComposeRebuild
? "Rebuild Compose project"
: "Rebuild from source",
description: appDetail
? `Rebuild container "${appDetail.name}" now?`
: "Rebuild this container now?",
confirmLabel: "Rebuild Container",
? `Fetch and rebuild the source for "${appDetail.name}" now?`
: "Fetch and rebuild this container from its source now?",
confirmLabel: isComposeRebuild
? "Rebuild Compose project"
: "Rebuild from source",
tone: "warning",
note: isGitSource
? "Doktainer will fetch the latest changes from the repository, rebuild the image if necessary, and then redeploy the container."
: "The container will be stopped, removed, and then restarted. Doktainer will attempt to pull the latest image first if available in the registry.",
note: isComposeRebuild
? "Docker Compose will rebuild and recreate the project services. This is not a safe single-container candidate switch and service interruption may occur."
: "Doktainer prepares an immutable image before runtime replacement, then uses the configured candidate/readiness strategy. Managed proxy traffic can stay on a validated runtime; direct host ports may still be briefly interrupted.",
onConfirm: () => {
void runRebuild();
void runDeploymentOperation("rebuild");
},
});
return;
@@ -1435,9 +1757,11 @@ export default function AppContainerDetailPage() {
[
acting,
appDetail,
canMutateContainers,
containerRecord,
openApp,
runRebuild,
openRedeployConfirmation,
runDeploymentOperation,
runRestart,
runStart,
runStop,
@@ -1462,6 +1786,7 @@ export default function AppContainerDetailPage() {
}
if (
activeTab === "overview" ||
activeTab === "runtime" ||
activeTab === "storage" ||
activeTab === "advanced" ||
@@ -1576,6 +1901,13 @@ export default function AppContainerDetailPage() {
onClose={() => setShowFileManager(false)}
/>
) : null}
{showConfigurationEditor && containerRecord ? (
<EditContainerConfigurationModal
containerId={containerRecord.id}
onClose={() => setShowConfigurationEditor(false)}
onApplied={load}
/>
) : null}
<div
className="animate-slide-in"
@@ -1676,14 +2008,10 @@ export default function AppContainerDetailPage() {
onRollback={requestRollback}
onViewDetails={openDeploymentDetails}
rollingBackId={rollingBackDeploymentId}
allowRollback={canMutateContainers}
/>
) : activeTab === "advanced" ? (
<AdvancedTabPanel
advanced={appDetail.advanced}
activeAction={activeAction}
onReset={() => handleAction("rebuild")}
onRemove={() => handleAction("remove")}
/>
<AdvancedTabPanel advanced={appDetail.advanced} />
) : activeTab === "environment" ? (
<EnvironmentTabPanel
environment={appDetail.environment}
@@ -22,8 +22,10 @@ export interface AppMetric {
export interface AppAction {
id:
| "open"
| "edit"
| "deploy"
| "restart"
| "redeploy"
| "rebuild"
| "stop"
| "start"
@@ -33,6 +35,8 @@ export interface AppAction {
label: string;
icon: LucideIcon;
tone: "primary" | "ghost" | "danger";
disabled?: boolean;
disabledReason?: string;
}
export interface DeploymentSummary {
@@ -386,6 +390,7 @@ export interface AppDetail {
name: string;
image: string;
status: string;
managementLabel: "Doktainer managed" | "Docker import";
path: string;
projectName: string;
environmentName: string;
@@ -2,6 +2,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { useCurrentUser } from "@/lib/auth-state";
import { getRoleCapabilities } from "@/lib/rbac";
import DashboardLayout from "@/components/DashboardLayout";
import IssueDetailsSummary from "@/components/IssueDetailsSummary";
import ProcessLogsModal, {
@@ -52,17 +54,32 @@ function formatEndpoint(container: Container) {
}
function mapContainer(container: Container): EnvironmentContainer {
const deployment = container.deploymentSummary;
const revision = deployment?.activeRevision;
const deployedAt = revision?.completedAt ?? revision?.createdAt;
return {
id: container.id,
name: container.name,
image: container.image,
source: formatSource(container),
managed: container.capabilities?.managed ?? false,
managementLabel:
container.capabilities?.managementLabel ?? "Docker import",
status: container.status as EnvironmentContainerStatus,
ports: container.ports,
domain: formatEndpoint(container),
cpu: container.cpuUsage ?? "-",
memory: container.ramUsage ?? "-",
lastDeployed: formatDateTime(container.createdAt),
lastDeployed: deployedAt ? formatDateTime(deployedAt) : "Never",
revision:
revision?.commitSha?.slice(0, 8) ||
revision?.imageDigest?.replace(/^sha256:/, "").slice(0, 12) ||
revision?.version ||
"No revision",
deploymentInProgress: Boolean(deployment?.currentOperation),
rollbackAvailable: deployment?.rollbackAvailable ?? false,
lastDeploymentError: deployment?.lastError ?? null,
uptime: "-",
};
}
@@ -87,6 +104,10 @@ function buildEnvironmentSummary(
export default function EnvironmentContainersPage() {
const params = useParams<{ projectId: string; environmentId: string }>();
const currentUser = useCurrentUser();
const canManageContainers = getRoleCapabilities(
currentUser?.role,
).canManageDeveloperTools;
const [activeEnvironment, setActiveEnvironment] =
useState<ProjectEnvironmentRecord | null>(null);
const [summary, setSummary] = useState<EnvironmentSummary | null>(null);
@@ -172,8 +193,9 @@ export default function EnvironmentContainersPage() {
await load();
pushToast({
tone: "success",
title: "Containers synced",
message: "Environment containers have been refreshed from Docker.",
title: "Docker inventory refreshed",
message:
"Container inventory was refreshed. Existing deployment revision history was not modified.",
});
} catch (syncError) {
setError(
@@ -245,7 +267,7 @@ export default function EnvironmentContainersPage() {
onClose={dismissToast}
position="top-right"
/>
{showDeploy && activeEnvironment ? (
{canManageContainers && showDeploy && activeEnvironment ? (
<DeployContainerModal
serverList={serverList}
initialServerId={activeEnvironment.serverId}
@@ -258,7 +280,7 @@ export default function EnvironmentContainersPage() {
onToast={pushToast}
/>
) : null}
{showDeployDatabase && activeEnvironment ? (
{canManageContainers && showDeployDatabase && activeEnvironment ? (
<AddDatabaseModal
serverList={serverList}
initialServerId={activeEnvironment.serverId}
@@ -271,7 +293,7 @@ export default function EnvironmentContainersPage() {
}}
/>
) : null}
{showImportFromSync && activeEnvironment ? (
{canManageContainers && showImportFromSync && activeEnvironment ? (
<ImportFromSyncModal
environmentId={activeEnvironment.id}
serverId={activeEnvironment.serverId}
@@ -319,6 +341,7 @@ export default function EnvironmentContainersPage() {
search={search}
statusFilter={statusFilter}
syncing={syncing}
canManage={canManageContainers}
onSearchChange={setSearch}
onStatusFilterChange={setStatusFilter}
onSync={handleSync}
@@ -11,12 +11,18 @@ export interface EnvironmentContainer {
name: string;
image: string;
source: string;
managed: boolean;
managementLabel: "Doktainer managed" | "Docker import";
status: EnvironmentContainerStatus;
ports: string[];
domain: string;
cpu: string;
memory: string;
lastDeployed: string;
revision: string;
deploymentInProgress: boolean;
rollbackAvailable: boolean;
lastDeploymentError: string | null;
uptime: string;
}
+195 -1
View File
@@ -1903,6 +1903,82 @@ export interface Container {
ramUsage?: string | null;
createdAt: string;
server?: { name: string; ip: string };
deploymentSummary?: {
activeRevision: DeploymentRecord | null;
currentOperation: DeploymentRecord | null;
latestAttempt: DeploymentRecord | null;
lastError: string | null;
redeployAvailable: boolean;
rollbackAvailable: boolean;
} | null;
capabilities?: ContainerCapabilities;
}
export interface ContainerCapability {
available: boolean;
reason: string | null;
}
export interface ContainerCapabilities {
managed: boolean;
managementLabel: "Doktainer managed" | "Docker import";
editConfiguration: ContainerCapability;
redeploy: ContainerCapability;
rebuild: ContainerCapability & {
mode: "ORCHESTRATED_SINGLE_CONTAINER" | "COMPOSE_RECREATE" | null;
};
rollback: ContainerCapability;
}
export interface ContainerConfigurationDraft {
name: string;
restartPolicy: "no" | "always" | "unless-stopped" | "on-failure";
cpuLimit: number;
memoryLimitMb: number;
networks: string[];
}
export interface ContainerConfiguration extends ContainerConfigurationDraft {
primaryNetwork: string | null;
}
export interface ContainerConfigurationPlan {
current: ContainerConfiguration;
draft: ContainerConfigurationDraft;
changes: Array<{
field: keyof ContainerConfigurationDraft;
label: string;
before: string | number | string[];
after: string | number | string[];
impact: "LIVE_UPDATE" | "LIVE_DISRUPTIVE";
}>;
addedNetworks: string[];
removedNetworks: string[];
warnings: string[];
blockedReasons: string[];
strategy: "NO_CHANGE" | "LIVE_UPDATE";
requiresDowntime: false;
expectedConfigRevision: string;
}
export interface ContainerConfigurationEditorData {
current: ContainerConfiguration;
draft: ContainerConfigurationDraft;
expectedConfigRevision: string;
availableNetworks: Array<{ name: string; driver: string; scope: string }>;
editableFields: Array<keyof ContainerConfigurationDraft>;
deferredFields: string[];
blockedReasons: string[];
}
export interface ContainerRedeployPlan {
revisionDeploymentId: string;
strategy: string;
blocked: boolean;
proxyTrafficContinuous: boolean;
directPortInterruptionPossible: boolean;
overlappingRuntime: boolean;
reason: string;
}
export interface ContainerProcess {
@@ -1963,16 +2039,25 @@ export interface ContainerDetails {
export type DeploymentStatus =
| "QUEUED"
| "BUILDING"
| "RUNNING"
| "VALIDATING"
| "SWITCHING"
| "ACTIVE"
| "SUCCESS"
| "FAILED"
| "FAILED_ROLLED_BACK"
| "CANCELLED"
| "ROLLED_BACK";
| "ROLLBACK_RUNNING"
| "ROLLED_BACK"
| "SUPERSEDED";
export type DeploymentTrigger =
| "MANUAL"
| "GIT_WEBHOOK"
| "REBUILD"
| "REDEPLOY"
| "CONFIG_APPLY"
| "ROLLBACK"
| "APP_INSTALLER";
@@ -1987,14 +2072,43 @@ export interface DeploymentRecord {
branch: string | null;
image: string | null;
imageDigest: string | null;
projectId?: string | null;
environmentId?: string | null;
sourceSnapshot?: Record<string, unknown> | null;
configSnapshot?: Record<string, unknown>;
configRevision?: string | null;
strategy?: string | null;
candidateRef?: string | null;
previousDeploymentId?: string | null;
rollbackArtifactAvailable?: boolean;
failureReason?: string | null;
rollbackReason?: string | null;
error: string | null;
startedAt: string | null;
completedAt: string | null;
createdAt: string;
updatedAt?: string;
user: { id: string; name: string } | null;
}
export interface DeploymentEventRecord {
id: string;
deploymentId: string;
status: DeploymentStatus;
level: "INFO" | "WARNING" | "ERROR";
message: string;
metadata: Record<string, unknown> | null;
createdAt: string;
}
export interface ContainerDeploymentState {
activeRevision: DeploymentRecord | null;
currentOperation: DeploymentRecord | null;
latestAttempt: DeploymentRecord | null;
rollbackRevision: DeploymentRecord | null;
lock: { expiresAt: string; updatedAt: string } | null;
}
export interface ContainerMetrics {
container: {
id: string;
@@ -2146,6 +2260,35 @@ export const containers = {
},
get: (id: string) =>
get<{ success: boolean; data: Container }>(`/containers/${id}`),
configuration: (id: string) =>
get<{ success: boolean; data: ContainerConfigurationEditorData }>(
`/containers/${id}/configuration`,
{ timeoutMs: 45000 },
),
previewConfiguration: (id: string, draft: ContainerConfigurationDraft) =>
post<{ success: boolean; data: ContainerConfigurationPlan }>(
`/containers/${id}/configuration/preview`,
{ draft },
{ timeoutMs: 45000 },
),
applyConfiguration: (
id: string,
body: {
draft: ContainerConfigurationDraft;
expectedConfigRevision: string;
idempotencyKey: string;
},
) =>
post<{
success: boolean;
data: Container;
meta: {
deploymentId: string;
configRevision: string | null;
plan: ContainerConfigurationPlan;
};
message?: string;
}>(`/containers/${id}/configuration/apply`, body, { timeoutMs: 90000 }),
deployments: (id: string, params?: { page?: number; pageSize?: number }) => {
const qs = new URLSearchParams();
if (params?.page) qs.set("page", String(params.page));
@@ -2161,6 +2304,31 @@ export const containers = {
};
}>(`/containers/${id}/deployments${query ? `?${query}` : ""}`);
},
deploymentState: (id: string) =>
get<{ success: boolean; data: ContainerDeploymentState }>(
`/containers/${id}/deployment-state`,
),
deploymentLogs: (
containerId: string,
deploymentId: string,
params?: { page?: number; pageSize?: number },
) => {
const qs = new URLSearchParams();
if (params?.page) qs.set("page", String(params.page));
if (params?.pageSize) qs.set("pageSize", String(params.pageSize));
const query = qs.toString();
return get<{
success: boolean;
data: {
items: DeploymentEventRecord[];
total: number;
page: number;
pageSize: number;
};
}>(
`/containers/${containerId}/deployments/${deploymentId}/logs${query ? `?${query}` : ""}`,
);
},
rollbackDeployment: (containerId: string, deploymentId: string) =>
post<{
success: boolean;
@@ -2283,11 +2451,37 @@ export const containers = {
`/containers/${id}/rebuild`,
{},
),
redeployPlan: (id: string) =>
get<{ success: boolean; data: ContainerRedeployPlan }>(
`/containers/${id}/redeploy-plan`,
),
redeploy: (id: string) =>
post<{
success: boolean;
data?: Container;
message?: string;
meta?: {
deploymentId: string;
revisionDeploymentId: string;
idempotentReplay: boolean;
strategy: string;
proxyTrafficContinuous: boolean;
directPortInterruptionPossible: boolean;
overlappingRuntime: boolean;
};
}>(`/containers/${id}/redeploy`, {
idempotencyKey: crypto.randomUUID(),
}),
createRebuildJob: (id: string) =>
post<{ success: boolean; data: ProcessJobRecord }>(
`/containers/${id}/rebuild-job`,
{},
),
createRedeployJob: (id: string) =>
post<{ success: boolean; data: ProcessJobRecord }>(
`/containers/${id}/redeploy-job`,
{},
),
logs: (id: string, tail?: number) =>
get<{ success: boolean; data: { logs: string; containerName: string } }>(
`/containers/${id}/logs${tail ? `?lines=${tail}` : ""}`,
+8
View File
@@ -1220,7 +1220,15 @@ export async function appsRoutes(app: FastifyInstance) {
data: {
status: "FAILED",
error: errorMessage,
failureReason: errorMessage,
completedAt: new Date(),
events: {
create: {
status: "FAILED",
level: "ERROR",
message: "App installation failed.",
},
},
},
}),
]);
File diff suppressed because it is too large. Load diff
@@ -15,8 +15,16 @@ import {
formatDockerInspectMountBindings,
type DockerInspectMount,
} from "./docker-inspect-format";
import {
orchestratePreparedRuntimeReplacement,
resolveCurrentRuntimeSpec,
resolveRuntimeReplacementPlan,
RollbackRuntimeError,
type RuntimeReplacementSpec,
} from "./deployment-rollback.service";
type DockerInspectRuntime = {
Id?: string;
Config?: {
Image?: string;
Env?: string[];
@@ -155,6 +163,7 @@ export async function rebuildAppInstall(options: {
if (!install.containerName) {
throw new Error("Install has no container name to rebuild");
}
const containerName = install.containerName;
const dockerStatus = await ssh.getDockerRuntimeStatus(install.server);
if (!dockerStatus.available) {
@@ -181,6 +190,8 @@ export async function rebuildAppInstall(options: {
let deploymentLockHeartbeat: ReturnType<
typeof startDeploymentLockHeartbeat
> | null = null;
let previousRuntime: RuntimeReplacementSpec | null = null;
let managedRuntimeFound = false;
try {
const currentContainer = await prisma.container.findFirst({
@@ -188,9 +199,19 @@ export async function rebuildAppInstall(options: {
serverId: install.serverId,
name: { equals: install.containerName, mode: "insensitive" },
},
select: { id: true },
select: {
id: true,
name: true,
dockerId: true,
image: true,
ports: true,
envVars: true,
volumes: true,
restartPolicy: true,
},
});
if (currentContainer) {
managedRuntimeFound = true;
const lock = await acquireDeploymentLock({ containerId: currentContainer.id });
deploymentLockToken = lock.token;
deploymentLockContainerId = currentContainer.id;
@@ -198,12 +219,18 @@ export async function rebuildAppInstall(options: {
containerId: currentContainer.id,
token: lock.token,
});
previousRuntime = await resolveCurrentRuntimeSpec({
container: {
...currentContainer,
server: install.server,
},
});
const deployment = await createDeployment({
containerId: currentContainer.id,
organizationId: options.organizationId ?? install.server.organizationId,
serverId: install.serverId,
userId: options.userId,
status: "RUNNING",
status: "BUILDING",
trigger: "REBUILD",
version: runtimeConfig.image,
image: runtimeConfig.image,
@@ -225,61 +252,138 @@ export async function rebuildAppInstall(options: {
usedImageCache = true;
}
try {
await ssh.dockerAction(install.server, install.containerName, "stop");
} catch {
// Best effort only.
const imageInspect = (await ssh.dockerInspect(
install.server,
runtimeConfig.image,
)) as DockerInspectRuntime;
const immutableImage = imageInspect.Id?.trim() || "";
if (!/^sha256:[a-f0-9]{64}$/i.test(immutableImage)) {
throw new Error(
"The rebuilt image could not be resolved to an immutable Docker image ID",
);
}
try {
await ssh.dockerAction(install.server, install.containerName, "rm");
} catch {
// Best effort only.
}
const targetRuntime: RuntimeReplacementSpec = previousRuntime
? {
...previousRuntime,
image: immutableImage,
mountValidation: resolveAppMountValidation(install.appId),
}
: {
image: immutableImage,
ports: runtimeConfig.ports,
env: runtimeConfig.env,
volumes: runtimeConfig.volumes,
network: runtimeConfig.network,
networks: [runtimeConfig.network],
restartPolicy: runtimeConfig.restartPolicy,
command: runtimeConfig.command,
mountValidation: resolveAppMountValidation(install.appId),
};
const dockerId = await ssh.runContainer(install.server, {
name: install.containerName,
image: runtimeConfig.image,
ports: runtimeConfig.ports,
env: runtimeConfig.env,
volumes: runtimeConfig.volumes,
network: runtimeConfig.network,
restartPolicy: runtimeConfig.restartPolicy,
command: runtimeConfig.command,
mountValidation: resolveAppMountValidation(install.appId),
});
const normalizedDockerId = dockerId.trim().slice(0, 12);
deploymentLockHeartbeat?.assertOwned();
await prisma.container.updateMany({
where: {
serverId: install.serverId,
name: { equals: install.containerName, mode: "insensitive" },
},
data: {
image: runtimeConfig.image,
status: "RUNNING",
dockerId: normalizedDockerId || null,
},
});
const updated = await prisma.appInstall.update({
where: { id: install.id },
data: { status: "RUNNING", error: null },
include: {
server: { select: { name: true, ip: true, organizationId: true } },
},
});
if (deploymentId) {
await updateDeployment(deploymentId, {
status: "SUCCESS",
completedAt: new Date(),
image: runtimeConfig.image,
});
}
const updated =
currentContainer && deploymentId && previousRuntime
? (
await (async () => {
const plan = await resolveRuntimeReplacementPlan({
containerId: currentContainer.id,
serverId: install.serverId,
targetRuntime,
});
await updateDeployment(deploymentId, {
status: "BUILDING",
image: runtimeConfig.image,
imageDigest: immutableImage,
strategy: plan.recordedStrategy,
eventMessage:
"Latest image prepared; handing runtime replacement to the deployment orchestrator.",
});
return orchestratePreparedRuntimeReplacement({
container: {
id: currentContainer.id,
serverId: install.serverId,
name: currentContainer.name,
dockerId: currentContainer.dockerId,
server: install.server,
},
deploymentId,
operationLabel: "rebuild",
targetRuntime,
previousRuntime,
plan,
finalize: async ({ dockerId }) => {
deploymentLockHeartbeat?.assertOwned();
await prisma.container.update({
where: { id: currentContainer.id },
data: {
image: runtimeConfig.image,
status: "RUNNING",
dockerId: dockerId.trim().slice(0, 12) || null,
},
});
const finalizedInstall = await prisma.appInstall.update({
where: { id: install.id },
data: { status: "RUNNING", error: null },
include: {
server: {
select: { name: true, ip: true, organizationId: true },
},
},
});
await updateDeployment(deploymentId!, {
status: "SUCCESS",
completedAt: new Date(),
image: runtimeConfig.image,
imageDigest: immutableImage,
configSnapshot: {
...targetRuntime,
image: runtimeConfig.image,
imageDigest: immutableImage,
},
});
return finalizedInstall;
},
});
})()
).result
: await (async () => {
for (const action of ["stop", "rm"] as const) {
await ssh
.dockerAction(install.server, containerName, action)
.catch(() => undefined);
}
const dockerId = await ssh.runContainer(install.server, {
name: containerName,
image: immutableImage,
ports: runtimeConfig.ports,
env: runtimeConfig.env,
volumes: runtimeConfig.volumes,
network: runtimeConfig.network,
restartPolicy: runtimeConfig.restartPolicy,
command: runtimeConfig.command,
mountValidation: resolveAppMountValidation(install.appId),
});
await prisma.container.updateMany({
where: {
serverId: install.serverId,
name: { equals: containerName, mode: "insensitive" },
},
data: {
image: runtimeConfig.image,
status: "RUNNING",
dockerId: dockerId.trim().slice(0, 12) || null,
},
});
return prisma.appInstall.update({
where: { id: install.id },
data: { status: "RUNNING", error: null },
include: {
server: {
select: { name: true, ip: true, organizationId: true },
},
},
});
})();
await auditLog({
userId: options.userId,
@@ -331,26 +435,51 @@ export async function rebuildAppInstall(options: {
}
const message =
error instanceof Error ? error.message : "Failed to rebuild app";
const runtimeError =
error instanceof RollbackRuntimeError ? error : null;
const runtimePreserved =
managedRuntimeFound && runtimeError?.recoveryMode !== "FAILED";
await prisma.appInstall.update({
where: { id: install.id },
data: { status: "FAILED", error: message },
data: {
status: runtimePreserved ? "RUNNING" : "FAILED",
error: message,
},
});
await prisma.container.updateMany({
where: {
serverId: install.serverId,
name: { equals: install.containerName, mode: "insensitive" },
},
data: { status: "ERROR" },
});
if (runtimePreserved) {
if (runtimeError?.recoveryDockerId && deploymentLockContainerId) {
await prisma.container.update({
where: { id: deploymentLockContainerId },
data: {
status: "RUNNING",
dockerId:
runtimeError.recoveryDockerId.trim().slice(0, 12) || undefined,
},
});
}
} else {
await prisma.container.updateMany({
where: {
serverId: install.serverId,
name: { equals: install.containerName, mode: "insensitive" },
},
data: { status: "ERROR" },
});
}
if (deploymentId) {
await updateDeployment(deploymentId, {
status: "FAILED",
status: runtimePreserved ? "FAILED_ROLLED_BACK" : "FAILED",
error: message,
completedAt: new Date(),
image: runtimeConfig.image,
rollbackReason: runtimePreserved
? runtimeError?.recoveryMode === "RECREATED"
? "Previous runtime was recreated after rebuild failure."
: "Rebuild failed before the previous runtime was removed."
: null,
}).catch(() => undefined);
}
@@ -0,0 +1,88 @@
import type {
ContainerDeployMode,
ContainerSourceType,
} from "@prisma/client";
export type ContainerCapability = {
available: boolean;
reason: string | null;
};
export type ContainerCapabilities = {
managed: boolean;
managementLabel: "Doktainer managed" | "Docker import";
editConfiguration: ContainerCapability;
redeploy: ContainerCapability;
rebuild: ContainerCapability & {
mode: "ORCHESTRATED_SINGLE_CONTAINER" | "COMPOSE_RECREATE" | null;
};
rollback: ContainerCapability;
};
export function buildContainerCapabilities(input: {
sourceType: ContainerSourceType;
deployMode: ContainerDeployMode | null;
hasDeploymentSource: boolean;
hasGitSource: boolean;
hasAppInstall: boolean;
hasDeploymentHistory: boolean;
redeployAvailable: boolean;
rollbackAvailable: boolean;
}): ContainerCapabilities {
const managed =
input.hasDeploymentSource ||
input.hasAppInstall ||
input.hasDeploymentHistory;
const composeManaged = input.deployMode === "COMPOSE";
const rebuildFromAppInstaller =
input.sourceType === "APP_INSTALLER" && input.hasAppInstall;
const rebuildFromGit =
(input.sourceType === "GIT_CLONE" ||
input.sourceType === "GIT_PROVIDER") &&
input.hasGitSource;
const rebuildAvailable = rebuildFromAppInstaller || rebuildFromGit;
return {
managed,
managementLabel: managed ? "Doktainer managed" : "Docker import",
editConfiguration: composeManaged
? {
available: false,
reason:
"Compose-managed containers must be edited through their Compose project.",
}
: { available: true, reason: null },
redeploy: input.redeployAvailable
? { available: true, reason: null }
: {
available: false,
reason:
"No active stored revision with a rollback artifact is available.",
},
rebuild: rebuildAvailable
? {
available: true,
reason: composeManaged
? "Compose rebuild recreates the project and is not a safe single-container switch."
: null,
mode: composeManaged
? "COMPOSE_RECREATE"
: "ORCHESTRATED_SINGLE_CONTAINER",
}
: {
available: false,
reason:
input.sourceType === "MANUAL"
? "This container has no rebuildable source metadata."
: "The configured source metadata is missing or incomplete.",
mode: null,
},
rollback: input.rollbackAvailable
? { available: true, reason: null }
: {
available: false,
reason: "No previous successful revision with a rollback artifact exists.",
},
};
}
@@ -0,0 +1,260 @@
import { createConfigRevision } from "./deployment.service";
export const CONTAINER_RESTART_POLICIES = [
"no",
"always",
"unless-stopped",
"on-failure",
] as const;
export type ContainerConfigurationDraft = {
name: string;
restartPolicy: (typeof CONTAINER_RESTART_POLICIES)[number];
cpuLimit: number;
memoryLimitMb: number;
networks: string[];
};
export type ContainerConfiguration = ContainerConfigurationDraft & {
primaryNetwork: string | null;
};
export type ContainerConfigurationChange = {
field: "name" | "restartPolicy" | "cpuLimit" | "memoryLimitMb" | "networks";
label: string;
before: string | number | string[];
after: string | number | string[];
impact: "LIVE_UPDATE" | "LIVE_DISRUPTIVE";
};
export type ContainerConfigurationPlan = {
current: ContainerConfiguration;
draft: ContainerConfigurationDraft;
changes: ContainerConfigurationChange[];
addedNetworks: string[];
removedNetworks: string[];
warnings: string[];
blockedReasons: string[];
strategy: "NO_CHANGE" | "LIVE_UPDATE";
requiresDowntime: false;
expectedConfigRevision: string;
};
type DockerInspectConfiguration = {
Name?: unknown;
HostConfig?: {
RestartPolicy?: { Name?: unknown; MaximumRetryCount?: unknown };
NanoCpus?: unknown;
Memory?: unknown;
MemorySwap?: unknown;
NetworkMode?: unknown;
};
NetworkSettings?: { Networks?: unknown };
};
function finiteNumber(value: unknown) {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
function normalizeRestartPolicy(
value: unknown,
): ContainerConfigurationDraft["restartPolicy"] {
return CONTAINER_RESTART_POLICIES.includes(
value as ContainerConfigurationDraft["restartPolicy"],
)
? (value as ContainerConfigurationDraft["restartPolicy"])
: "no";
}
function normalizeNetworks(value: string[]) {
return Array.from(new Set(value.map((item) => item.trim()).filter(Boolean))).sort();
}
export function extractContainerConfiguration(
inspect: DockerInspectConfiguration,
): ContainerConfiguration {
const rawNetworks = inspect.NetworkSettings?.Networks;
const networks = normalizeNetworks(
rawNetworks && typeof rawNetworks === "object" && !Array.isArray(rawNetworks)
? Object.keys(rawNetworks)
: [],
);
const networkMode =
typeof inspect.HostConfig?.NetworkMode === "string"
? inspect.HostConfig.NetworkMode.trim()
: "";
const primaryNetwork = networks.includes(networkMode)
? networkMode
: networks[0] ?? null;
const nanoCpus = finiteNumber(inspect.HostConfig?.NanoCpus);
const memoryBytes = finiteNumber(inspect.HostConfig?.Memory);
return {
name:
typeof inspect.Name === "string"
? inspect.Name.replace(/^\/+/, "")
: "",
restartPolicy: normalizeRestartPolicy(
inspect.HostConfig?.RestartPolicy?.Name,
),
cpuLimit: nanoCpus > 0 ? nanoCpus / 1_000_000_000 : 0,
memoryLimitMb:
memoryBytes > 0 ? Math.round(memoryBytes / (1024 * 1024)) : 0,
networks,
primaryNetwork,
};
}
export function extractContainerMemorySwapMb(
inspect: DockerInspectConfiguration,
) {
const memorySwapBytes = finiteNumber(inspect.HostConfig?.MemorySwap);
if (memorySwapBytes === -1) return -1;
return memorySwapBytes > 0
? Math.round(memorySwapBytes / (1024 * 1024))
: 0;
}
export function resolveMemorySwapLimitMb(input: {
currentMemoryLimitMb: number;
currentMemorySwapMb: number;
targetMemoryLimitMb: number;
}) {
if (input.targetMemoryLimitMb === 0) return 0;
if (input.currentMemorySwapMb === -1) return -1;
if (
input.currentMemoryLimitMb > 0 &&
input.currentMemorySwapMb >= input.currentMemoryLimitMb
) {
const currentRatio =
input.currentMemorySwapMb / input.currentMemoryLimitMb;
return Math.max(
input.targetMemoryLimitMb,
Math.round(input.targetMemoryLimitMb * currentRatio),
);
}
// Match Docker's default for a newly limited container: the combined
// memory+swap allowance is twice the memory limit.
return input.targetMemoryLimitMb * 2;
}
export function configurationRevision(config: ContainerConfiguration) {
return createConfigRevision(config);
}
export function buildContainerConfigurationPlan(input: {
current: ContainerConfiguration;
draft: ContainerConfigurationDraft;
availableNetworks: string[];
composeManaged?: boolean;
}): ContainerConfigurationPlan {
const current = {
...input.current,
networks: normalizeNetworks(input.current.networks),
};
const draft = {
...input.draft,
name: input.draft.name.trim(),
networks: normalizeNetworks(input.draft.networks),
};
const available = new Set(normalizeNetworks(input.availableNetworks));
const changes: ContainerConfigurationChange[] = [];
const warnings: string[] = [];
const blockedReasons: string[] = [];
if (input.composeManaged) {
blockedReasons.push(
"Compose-managed containers must be edited through their Compose project.",
);
}
const unavailableNetworks = draft.networks.filter((name) => !available.has(name));
if (unavailableNetworks.length > 0) {
blockedReasons.push(
`Network no longer available: ${unavailableNetworks.join(", ")}.`,
);
}
if (current.primaryNetwork && !draft.networks.includes(current.primaryNetwork)) {
blockedReasons.push(
`Primary network ${current.primaryNetwork} cannot be disconnected with a live update.`,
);
}
if (draft.networks.length === 0) {
blockedReasons.push("A container must remain attached to at least one network.");
}
if (current.name !== draft.name) {
changes.push({
field: "name",
label: "Docker name",
before: current.name,
after: draft.name,
impact: "LIVE_DISRUPTIVE",
});
warnings.push(
"Renaming can affect Docker DNS, proxy labels, monitoring, and scripts that reference the current name.",
);
}
if (current.restartPolicy !== draft.restartPolicy) {
changes.push({
field: "restartPolicy",
label: "Restart policy",
before: current.restartPolicy,
after: draft.restartPolicy,
impact: "LIVE_UPDATE",
});
}
if (current.cpuLimit !== draft.cpuLimit) {
changes.push({
field: "cpuLimit",
label: "CPU limit",
before: current.cpuLimit,
after: draft.cpuLimit,
impact: "LIVE_UPDATE",
});
}
if (current.memoryLimitMb !== draft.memoryLimitMb) {
changes.push({
field: "memoryLimitMb",
label: "Memory limit",
before: current.memoryLimitMb,
after: draft.memoryLimitMb,
impact: "LIVE_UPDATE",
});
}
const addedNetworks = draft.networks.filter(
(network) => !current.networks.includes(network),
);
const removedNetworks = current.networks.filter(
(network) => !draft.networks.includes(network),
);
if (addedNetworks.length > 0 || removedNetworks.length > 0) {
changes.push({
field: "networks",
label: "Network attachments",
before: current.networks,
after: draft.networks,
impact: "LIVE_DISRUPTIVE",
});
warnings.push(
"Network attachment changes can interrupt connections that use the affected network.",
);
}
return {
current,
draft,
changes,
addedNetworks,
removedNetworks,
warnings,
blockedReasons,
strategy: changes.length > 0 ? "LIVE_UPDATE" : "NO_CHANGE",
requiresDowntime: false,
expectedConfigRevision: configurationRevision(current),
};
}
@@ -16,6 +16,7 @@ export type ContainerHealthResult = {
healthy: boolean;
status:
| "healthy"
| "running_unverified"
| "unhealthy"
| "starting"
| "not_running"
@@ -68,9 +69,10 @@ export function evaluateDockerHealth(
}
return {
healthy: true,
status: "healthy",
reason: "Container is running and the image has no Docker health check",
healthy: false,
status: "running_unverified",
reason:
"Container is running, but the image has no Docker health check to verify readiness",
};
}
@@ -101,7 +103,8 @@ export async function waitForDockerHealth(input: {
}
if (
result.status === "unhealthy" ||
result.status === "not_running"
result.status === "not_running" ||
result.status === "running_unverified"
) {
return { ...result, attempts, durationMs: Date.now() - startedAt };
}
@@ -122,5 +125,3 @@ export async function waitForDockerHealth(input: {
durationMs: Date.now() - startedAt,
};
}
@@ -73,4 +73,49 @@ export function sanitizeDeploymentError(
return message.slice(0, 800);
}
export function sanitizeContainerConfigurationError(error: unknown) {
const message = redactDeploymentErrorDetails(error);
if (/minimum memory limit|memory limit.*(?:too small|at least)/i.test(message)) {
return "The memory limit is below the minimum supported by the Docker host.";
}
if (/memory.*(?:usage|used).*(?:exceed|larger|greater)|new memory limit.*current/i.test(message)) {
return "The memory limit is below the container's current memory usage.";
}
if (/memory.*swap|memoryswap/i.test(message)) {
return "Docker rejected the memory limit because it conflicts with the container's existing memory-swap limit.";
}
if (/invalid cpu|minimum cpu|cpu.*(?:too small|at least)/i.test(message)) {
return "The CPU limit is outside the range supported by the Docker host.";
}
if (/cgroup|kernel does not support|not supported.*(?:memory|cpu)/i.test(message)) {
return "This Docker host does not support updating the requested resource limit on a running container.";
}
if (/command queue timed out|command timed out|timed out after/i.test(message)) {
return "The Docker host did not apply the configuration before the operation timed out.";
}
if (/permission denied|docker\.sock|you must be root/i.test(message)) {
return "Docker access was denied for the configured SSH user.";
}
const daemonDetail = message.match(/error response from daemon:\s*([^\r\n]+)/i)?.[1];
if (daemonDetail) {
const safeDetail = daemonDetail
.replace(/\b[0-9a-f]{12,64}\b/gi, "[container]")
.trim()
.slice(0, 400);
if (safeDetail) {
return `Docker rejected the requested container configuration: ${safeDetail}`;
}
}
return sanitizeDeploymentError(error, {
fallback: "Failed to apply container configuration",
});
}
@@ -0,0 +1,141 @@
import type { Server } from "@prisma/client";
import { execStrict } from "./ssh-services/commands";
import { escapeShellArg } from "./ssh-services/internal/shell";
import { sanitizeDeploymentError } from "./deployment-error.service";
type ReadinessDependencies = {
execStrict: typeof execStrict;
wait: (durationMs: number) => Promise<void>;
};
const defaultDependencies: ReadinessDependencies = {
execStrict,
wait: (durationMs) =>
new Promise((resolve) => setTimeout(resolve, durationMs)),
};
export function publishedHttpReadinessCandidates(ports: string) {
const candidates = new Set<string>();
for (const rawMapping of ports.split(",")) {
const mapping = rawMapping.trim();
if (!mapping) continue;
const [withoutProtocol, protocol = "tcp"] = mapping.split("/");
if (protocol.toLowerCase() !== "tcp") continue;
const parts = withoutProtocol.split(":");
const hostIp = parts.length === 3 ? parts[0]?.trim() : "127.0.0.1";
const hostPort = (parts.length === 3 ? parts[1] : parts[0])?.trim();
if (!hostPort || !/^\d+$/.test(hostPort)) continue;
const port = Number.parseInt(hostPort, 10);
if (port < 1 || port > 65_535) continue;
const probeIp =
!hostIp || hostIp === "0.0.0.0" || hostIp === "::"
? "127.0.0.1"
: hostIp;
if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(probeIp)) continue;
candidates.add(`http://${probeIp}:${port}/`);
}
return [...candidates].slice(0, 4);
}
export async function findReachablePublishedHttpUpstream(
input: {
server: Server;
ports: string;
timeoutMs?: number;
},
dependencies: ReadinessDependencies = defaultDependencies,
) {
const candidates = publishedHttpReadinessCandidates(input.ports);
for (const upstream of candidates) {
const result = await waitForHttpReadiness(
{
server: input.server,
upstream,
timeoutMs: input.timeoutMs ?? 7_000,
intervalMs: 750,
},
dependencies,
);
if (result.ready) return { upstream, result };
}
return null;
}
function validateReadinessUrl(value: string) {
const parsed = new URL(value);
if (parsed.protocol !== "http:") {
throw new Error("Candidate readiness probes require an HTTP upstream");
}
if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(parsed.hostname)) {
throw new Error("Candidate readiness probes require an IP upstream");
}
return parsed.toString();
}
function validateHostHeader(value: string | undefined) {
const host = value?.trim();
if (!host) return undefined;
if (!/^[a-z0-9.-]+(?::\d+)?$/i.test(host)) {
throw new Error("Candidate readiness Host header is invalid");
}
return host;
}
export async function waitForHttpReadiness(
input: {
server: Server;
upstream: string;
hostHeader?: string;
timeoutMs?: number;
intervalMs?: number;
},
dependencies: ReadinessDependencies = defaultDependencies,
) {
const upstream = validateReadinessUrl(input.upstream);
const hostHeader = validateHostHeader(input.hostHeader);
const timeoutMs = Math.max(1_000, input.timeoutMs ?? 20_000);
const intervalMs = Math.max(250, input.intervalMs ?? 1_000);
const startedAt = Date.now();
let attempts = 0;
let lastReason = "Candidate HTTP readiness probe did not complete";
while (Date.now() - startedAt <= timeoutMs) {
attempts += 1;
try {
await dependencies.execStrict(
input.server,
[
"command -v curl >/dev/null 2>&1",
`code=$(curl --max-time 5 -sS -o /dev/null -w '%{http_code}'${
hostHeader ? ` -H ${escapeShellArg(`Host: ${hostHeader}`)}` : ""
} ${escapeShellArg(upstream)} || true)`,
'case "$code" in 2*|3*) exit 0 ;; *) exit 1 ;; esac',
].join(" && "),
{ timeoutMs: 7_000, queueTimeoutMs: 7_000 },
);
return {
ready: true,
attempts,
durationMs: Date.now() - startedAt,
reason: "Candidate HTTP endpoint accepted a request",
};
} catch (error) {
lastReason = sanitizeDeploymentError(error, {
fallback: "Candidate HTTP readiness probe failed",
});
}
await dependencies.wait(intervalMs);
}
return {
ready: false,
attempts,
durationMs: Date.now() - startedAt,
reason: `Candidate HTTP readiness timed out after ${timeoutMs}ms: ${lastReason}`,
};
}
@@ -1,6 +1,7 @@
import type { Server } from "@prisma/client";
import prisma from "../lib/prisma";
import { isDeploymentLockActive } from "./deployment-lock.service";
import { IN_PROGRESS_DEPLOYMENT_STATUSES } from "./deployment-state-machine";
const RUNTIME_CREATION_CLOCK_SKEW_MS = 5_000;
const INTERRUPTED_REBUILD_ERROR =
@@ -55,10 +56,10 @@ export async function reconcileInterruptedRebuild(input: {
where: {
containerId: input.container.id,
trigger: "REBUILD",
status: "RUNNING",
status: { in: IN_PROGRESS_DEPLOYMENT_STATUSES },
},
orderBy: { createdAt: "desc" },
select: { id: true, startedAt: true, createdAt: true },
select: { id: true, status: true, startedAt: true, createdAt: true },
});
if (!deployment) return null;
@@ -101,11 +102,13 @@ export async function reconcileInterruptedRebuild(input: {
const recovered = await prisma.$transaction(async (tx) => {
const updated = await tx.deployment.updateMany({
where: { id: deployment.id, status: "RUNNING" },
where: { id: deployment.id, status: deployment.status },
data: {
status,
completedAt: now,
error: status === "SUCCESS" ? null : INTERRUPTED_REBUILD_ERROR,
failureReason:
status === "SUCCESS" ? null : INTERRUPTED_REBUILD_ERROR,
...(status === "SUCCESS"
? { image: runtimeImage, imageDigest }
: {}),
@@ -114,6 +117,18 @@ export async function reconcileInterruptedRebuild(input: {
if (updated.count !== 1) return false;
await tx.deploymentEvent.create({
data: {
deploymentId: deployment.id,
status,
level: status === "SUCCESS" ? "INFO" : "ERROR",
message:
status === "SUCCESS"
? "Interrupted rebuild reconciled from the running replacement runtime."
: "Interrupted rebuild could not be confirmed and was marked failed.",
},
});
if (lock) {
await tx.deploymentLock.deleteMany({
where: { containerId: input.container.id, token: lock.token },
@@ -0,0 +1,66 @@
import type { DeploymentStatus } from "@prisma/client";
import {
IN_PROGRESS_DEPLOYMENT_STATUSES,
ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES,
} from "./deployment-state-machine";
export type DeploymentRetentionCandidate = {
id: string;
status: DeploymentStatus;
createdAt: Date;
previousDeploymentId?: string | null;
};
export function selectDeploymentArtifactRetention(
deployments: DeploymentRetentionCandidate[],
successfulRevisionCount = 3,
) {
const retainCount = Math.max(1, Math.floor(successfulRevisionCount));
const newestFirst = [...deployments].sort(
(left, right) => right.createdAt.getTime() - left.createdAt.getTime(),
);
const retainedIds = new Set<string>();
for (const deployment of newestFirst) {
if (
deployment.status === "ACTIVE" ||
IN_PROGRESS_DEPLOYMENT_STATUSES.includes(deployment.status)
) {
retainedIds.add(deployment.id);
}
}
for (const deployment of newestFirst
.filter((item) =>
ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES.includes(item.status),
)
.slice(0, retainCount)) {
retainedIds.add(deployment.id);
}
let previousSize = -1;
while (previousSize !== retainedIds.size) {
previousSize = retainedIds.size;
for (const deployment of newestFirst) {
if (
retainedIds.has(deployment.id) &&
deployment.previousDeploymentId
) {
retainedIds.add(deployment.previousDeploymentId);
}
}
}
const cleanupEligibleArtifactIds = newestFirst
.filter(
(deployment) =>
ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES.includes(deployment.status) &&
!retainedIds.has(deployment.id),
)
.map((deployment) => deployment.id);
return {
retainedArtifactIds: Array.from(retainedIds),
cleanupEligibleArtifactIds,
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,91 @@
import type { DeploymentStatus } from "@prisma/client";
const ALLOWED_TRANSITIONS: Record<DeploymentStatus, ReadonlySet<DeploymentStatus>> = {
QUEUED: new Set([
"BUILDING",
"RUNNING",
"ROLLBACK_RUNNING",
"FAILED",
"CANCELLED",
]),
BUILDING: new Set([
"VALIDATING",
"FAILED",
"FAILED_ROLLED_BACK",
"CANCELLED",
]),
RUNNING: new Set([
"VALIDATING",
"SWITCHING",
"ACTIVE",
"SUCCESS",
"FAILED",
"FAILED_ROLLED_BACK",
"CANCELLED",
]),
VALIDATING: new Set([
"SWITCHING",
"ACTIVE",
"SUCCESS",
"FAILED",
"FAILED_ROLLED_BACK",
"CANCELLED",
]),
SWITCHING: new Set([
"ACTIVE",
"SUCCESS",
"FAILED",
"FAILED_ROLLED_BACK",
]),
ACTIVE: new Set(["SUPERSEDED", "ROLLED_BACK"]),
SUCCESS: new Set(["ACTIVE", "SUPERSEDED", "ROLLED_BACK"]),
FAILED: new Set(),
FAILED_ROLLED_BACK: new Set(),
CANCELLED: new Set(),
ROLLBACK_RUNNING: new Set([
"VALIDATING",
"SWITCHING",
"ACTIVE",
"SUCCESS",
"FAILED",
"FAILED_ROLLED_BACK",
"CANCELLED",
]),
ROLLED_BACK: new Set(),
SUPERSEDED: new Set(["ACTIVE", "ROLLED_BACK"]),
};
export const IN_PROGRESS_DEPLOYMENT_STATUSES: DeploymentStatus[] = [
"QUEUED",
"BUILDING",
"RUNNING",
"VALIDATING",
"SWITCHING",
"ROLLBACK_RUNNING",
];
export const ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES: DeploymentStatus[] = [
"ACTIVE",
"SUCCESS",
"SUPERSEDED",
];
export function canTransitionDeployment(
from: DeploymentStatus,
to: DeploymentStatus,
) {
return from === to || ALLOWED_TRANSITIONS[from].has(to);
}
export function assertDeploymentTransition(
from: DeploymentStatus,
to: DeploymentStatus,
) {
if (!canTransitionDeployment(from, to)) {
throw new Error(`Invalid deployment transition: ${from} -> ${to}`);
}
}
export function isRollbackEligibleDeployment(status: DeploymentStatus) {
return ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES.includes(status);
}
@@ -1,7 +1,98 @@
export type DeploymentStrategy = "ATOMIC_RENAME" | "RECREATE_WITH_RECOVERY";
export type SafeRedeployStrategy =
| DeploymentStrategy
| "PROXY_CANDIDATE_SWITCH"
| "BLOCKED_UNSUPPORTED_PROXY";
export type SafeRedeployDomainBinding = {
proxy: "TRAEFIK" | "NGINX" | "CADDY" | "NONE";
configMode: "SHARED" | "ISOLATED";
targetPort: number | null;
};
export function resolveDeploymentStrategy(ports: string): DeploymentStrategy {
return ports.trim() ? "RECREATE_WITH_RECOVERY" : "ATOMIC_RENAME";
}
export function resolveSafeRedeployStrategy(input: {
ports: string;
volumes: string;
domains: SafeRedeployDomainBinding[];
}): {
strategy: SafeRedeployStrategy;
proxyTrafficContinuous: boolean;
directPortInterruptionPossible: boolean;
reason: string;
} {
const fallback = resolveDeploymentStrategy(input.ports);
const managedDomains = input.domains.filter(
(domain) => domain.proxy !== "NONE",
);
if (managedDomains.length === 0) {
return {
strategy: fallback,
proxyTrafficContinuous: false,
directPortInterruptionPossible: fallback === "RECREATE_WITH_RECOVERY",
reason:
fallback === "ATOMIC_RENAME"
? "No managed proxy switch is required and no host ports conflict."
: "Published host ports require runtime recreation because Docker cannot bind the same port twice.",
};
}
const proxySwitchSupported = managedDomains.every(
(domain) =>
domain.configMode === "ISOLATED" &&
domain.targetPort !== null &&
["NGINX", "CADDY", "TRAEFIK"].includes(domain.proxy),
);
if (proxySwitchSupported && input.volumes.trim()) {
if (input.ports.trim()) {
return {
strategy: "RECREATE_WITH_RECOVERY",
proxyTrafficContinuous: false,
directPortInterruptionPossible: true,
reason:
"The runtime mounts persistent storage, so Doktainer will not run an overlapping candidate against the same data.",
};
}
return {
strategy: "BLOCKED_UNSUPPORTED_PROXY",
proxyTrafficContinuous: false,
directPortInterruptionPossible: false,
reason:
"The runtime mounts persistent storage and its internal-IP proxy would become stale without an overlapping candidate.",
};
}
if (proxySwitchSupported) {
return {
strategy: "PROXY_CANDIDATE_SWITCH",
proxyTrafficContinuous: true,
directPortInterruptionPossible: Boolean(input.ports.trim()),
reason:
"Managed isolated proxies can switch to a validated candidate before the previous runtime is removed.",
};
}
if (input.ports.trim()) {
return {
strategy: "RECREATE_WITH_RECOVERY",
proxyTrafficContinuous: false,
directPortInterruptionPossible: true,
reason:
"The linked proxy configuration cannot be switched independently; published-port recreation remains available with recovery.",
};
}
return {
strategy: "BLOCKED_UNSUPPORTED_PROXY",
proxyTrafficContinuous: false,
directPortInterruptionPossible: false,
reason:
"The linked proxy configuration cannot be switched independently and would retain the previous container IP.",
};
}
+546 -41
View File
@@ -1,10 +1,18 @@
import { createHash } from "node:crypto";
import {
DeploymentEventLevel,
DeploymentStatus,
DeploymentTrigger,
Prisma,
} from "@prisma/client";
import prisma from "../lib/prisma";
import { decrypt, encrypt } from "../lib/crypto";
import { redactDeploymentErrorDetails } from "./deployment-error.service";
import {
assertDeploymentTransition,
IN_PROGRESS_DEPLOYMENT_STATUSES,
ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES,
} from "./deployment-state-machine";
const SENSITIVE_KEY_PATTERN = /(pass(word)?|secret|token|api[-_]?key|private[-_]?key|credential)/i;
@@ -32,14 +40,28 @@ function sanitizeSnapshotValue(value: unknown, key?: string): unknown {
}
if (Array.isArray(value)) {
return value.map((item) => sanitizeSnapshotValue(item));
return value.map((item) => sanitizeSnapshotValue(item, key));
}
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const declaredKey =
typeof record.key === "string"
? record.key
: typeof record.name === "string"
? record.name
: null;
const masksDeclaredValue = Boolean(
declaredKey && SENSITIVE_KEY_PATTERN.test(declaredKey),
);
return Object.fromEntries(
Object.entries(value).map(([entryKey, entryValue]) => [
Object.entries(record).map(([entryKey, entryValue]) => [
entryKey,
sanitizeSnapshotValue(entryValue, entryKey),
masksDeclaredValue &&
["value", "currentValue", "defaultValue"].includes(entryKey)
? "<redacted>"
: sanitizeSnapshotValue(entryValue, entryKey),
]),
);
}
@@ -49,6 +71,18 @@ function sanitizeSnapshotValue(value: unknown, key?: string): unknown {
export type DeploymentSnapshot = Record<string, unknown>;
export function toPublicDeploymentRecord<
T extends { rollbackSnapshotEnc: string | null },
>(deployment: T): Omit<T, "rollbackSnapshotEnc"> & {
rollbackArtifactAvailable: boolean;
} {
const { rollbackSnapshotEnc, ...publicDeployment } = deployment;
return {
...publicDeployment,
rollbackArtifactAvailable: Boolean(rollbackSnapshotEnc),
};
}
export type CreateDeploymentInput = {
containerId: string;
organizationId: string;
@@ -61,7 +95,13 @@ export type CreateDeploymentInput = {
branch?: string | null;
image?: string | null;
imageDigest?: string | null;
idempotencyKey?: string | null;
sourceSnapshot?: DeploymentSnapshot;
configSnapshot: DeploymentSnapshot;
strategy?: string | null;
candidateRef?: string | null;
previousDeploymentId?: string | null;
logReference?: string | null;
error?: string | null;
startedAt?: Date | null;
completedAt?: Date | null;
@@ -73,27 +113,154 @@ export function sanitizeDeploymentSnapshot(
return sanitizeSnapshotValue(snapshot) as Prisma.InputJsonValue;
}
function stableSnapshotValue(value: unknown): unknown {
if (Array.isArray(value)) return value.map(stableSnapshotValue);
if (!value || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => [key, stableSnapshotValue(entry)]),
);
}
export function createConfigRevision(snapshot: DeploymentSnapshot) {
return createHash("sha256")
.update(JSON.stringify(stableSnapshotValue(snapshot)))
.digest("hex");
}
export function sanitizeDeploymentEventMessage(message: unknown) {
const sanitized = redactDeploymentErrorDetails(message);
return (sanitized || "Deployment lifecycle event").slice(0, 2_000);
}
function eventLevelForStatus(status: DeploymentStatus): DeploymentEventLevel {
if (status === "FAILED" || status === "FAILED_ROLLED_BACK") return "ERROR";
if (status === "CANCELLED" || status === "ROLLED_BACK") return "WARNING";
return "INFO";
}
function defaultSourceSnapshot(input: CreateDeploymentInput) {
return {
trigger: input.trigger,
version: input.version ?? null,
branch: input.branch ?? null,
commitSha: input.commitSha ?? null,
image: input.image ?? null,
imageDigest: input.imageDigest ?? null,
};
}
function defaultEventMessage(status: DeploymentStatus) {
return `Deployment entered ${status.toLowerCase().replaceAll("_", " ")}.`;
}
function normalizeIdempotencyKey(value: string | null | undefined) {
const normalized = value?.trim() || null;
if (normalized && normalized.length > 200) {
throw new Error("Idempotency key must not exceed 200 characters");
}
return normalized;
}
export async function createDeployment(input: CreateDeploymentInput) {
return prisma.deployment.create({
data: {
containerId: input.containerId,
organizationId: input.organizationId,
serverId: input.serverId,
userId: input.userId ?? null,
status: input.status,
trigger: input.trigger,
version: input.version ?? null,
commitSha: input.commitSha ?? null,
branch: input.branch ?? null,
image: input.image ?? null,
imageDigest: input.imageDigest ?? null,
configSnapshot: sanitizeDeploymentSnapshot(input.configSnapshot),
rollbackSnapshotEnc: encrypt(JSON.stringify(input.configSnapshot)),
error: input.error ?? null,
startedAt: input.startedAt ?? null,
completedAt: input.completedAt ?? null,
const idempotencyKey = normalizeIdempotencyKey(input.idempotencyKey);
if (idempotencyKey) {
const existing = await prisma.deployment.findUnique({
where: {
containerId_idempotencyKey: {
containerId: input.containerId,
idempotencyKey,
},
},
});
if (existing) return existing;
}
const containerContext = await prisma.container.findUnique({
where: { id: input.containerId },
select: {
environmentId: true,
environment: { select: { projectId: true } },
},
});
const previousDeployment = input.previousDeploymentId
? null
: await prisma.deployment.findFirst({
where: {
containerId: input.containerId,
status: { in: ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES },
},
orderBy: { createdAt: "desc" },
select: { id: true },
});
const sanitizedConfig = sanitizeDeploymentSnapshot(input.configSnapshot);
const sanitizedSource = sanitizeDeploymentSnapshot(
input.sourceSnapshot ?? defaultSourceSnapshot(input),
);
const error = input.error
? sanitizeDeploymentEventMessage(input.error)
: null;
try {
return await prisma.deployment.create({
data: {
containerId: input.containerId,
organizationId: input.organizationId,
serverId: input.serverId,
projectId: containerContext?.environment?.projectId ?? null,
environmentId: containerContext?.environmentId ?? null,
userId: input.userId ?? null,
idempotencyKey,
status: input.status,
trigger: input.trigger,
version: input.version ?? null,
commitSha: input.commitSha ?? null,
branch: input.branch ?? null,
image: input.image ?? null,
imageDigest: input.imageDigest ?? null,
sourceSnapshot: sanitizedSource,
configSnapshot: sanitizedConfig,
configRevision: createConfigRevision(input.configSnapshot),
rollbackSnapshotEnc: encrypt(JSON.stringify(input.configSnapshot)),
strategy: input.strategy ?? null,
candidateRef: input.candidateRef ?? null,
previousDeploymentId:
input.previousDeploymentId ?? previousDeployment?.id ?? null,
logReference: input.logReference ?? null,
failureReason:
input.status === "FAILED" || input.status === "FAILED_ROLLED_BACK"
? error
: null,
error,
startedAt: input.startedAt ?? null,
completedAt: input.completedAt ?? null,
events: {
create: {
status: input.status,
level: eventLevelForStatus(input.status),
message: defaultEventMessage(input.status),
},
},
},
});
} catch (error) {
if (idempotencyKey && error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === "P2002") {
const existing = await prisma.deployment.findUnique({
where: {
containerId_idempotencyKey: {
containerId: input.containerId,
idempotencyKey,
},
},
});
if (existing) return existing;
}
}
throw error;
}
}
export async function getRollbackSnapshot(input: {
@@ -106,7 +273,7 @@ export async function getRollbackSnapshot(input: {
id: input.deploymentId,
containerId: input.containerId,
organizationId: input.organizationId,
status: "SUCCESS",
status: { in: ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES },
},
select: {
id: true,
@@ -152,28 +319,113 @@ export async function updateDeployment(
commitSha?: string | null;
branch?: string | null;
configSnapshot?: DeploymentSnapshot;
sourceSnapshot?: DeploymentSnapshot;
candidateRef?: string | null;
strategy?: string | null;
rollbackReason?: string | null;
eventMessage?: string;
eventMetadata?: DeploymentSnapshot;
},
) {
return prisma.deployment.update({
const current = await prisma.deployment.findUnique({
where: { id },
select: { status: true },
});
if (!current) throw new Error("Deployment not found");
assertDeploymentTransition(current.status, patch.status);
const error = patch.error
? sanitizeDeploymentEventMessage(patch.error)
: null;
const eventMessage = sanitizeDeploymentEventMessage(
patch.eventMessage ?? defaultEventMessage(patch.status),
);
return prisma.$transaction(async (tx) => {
const updated = await tx.deployment.updateMany({
where: { id, status: current.status },
data: {
status: patch.status,
error,
...(patch.completedAt === undefined
? {}
: { completedAt: patch.completedAt }),
failureReason:
patch.status === "FAILED" || patch.status === "FAILED_ROLLED_BACK"
? error
: null,
...(patch.image === undefined ? {} : { image: patch.image }),
...(patch.imageDigest === undefined
? {}
: { imageDigest: patch.imageDigest }),
...(patch.commitSha === undefined ? {} : { commitSha: patch.commitSha }),
...(patch.branch === undefined ? {} : { branch: patch.branch }),
...(patch.candidateRef === undefined
? {}
: { candidateRef: patch.candidateRef }),
...(patch.strategy === undefined ? {} : { strategy: patch.strategy }),
...(patch.rollbackReason === undefined
? {}
: {
rollbackReason:
patch.rollbackReason === null
? null
: sanitizeDeploymentEventMessage(patch.rollbackReason),
}),
...(patch.sourceSnapshot === undefined
? {}
: {
sourceSnapshot: sanitizeDeploymentSnapshot(patch.sourceSnapshot),
}),
...(patch.configSnapshot === undefined
? {}
: {
configSnapshot: sanitizeDeploymentSnapshot(patch.configSnapshot),
configRevision: createConfigRevision(patch.configSnapshot),
rollbackSnapshotEnc: encrypt(
JSON.stringify(patch.configSnapshot),
),
}),
},
});
if (updated.count !== 1) {
throw new Error("Deployment state changed concurrently; retry the request");
}
await tx.deploymentEvent.create({
data: {
deploymentId: id,
status: patch.status,
level: eventLevelForStatus(patch.status),
message: eventMessage,
metadata:
patch.eventMetadata === undefined
? undefined
: sanitizeDeploymentSnapshot(patch.eventMetadata),
},
});
return tx.deployment.findUniqueOrThrow({ where: { id } });
});
}
export async function appendDeploymentEvent(input: {
deploymentId: string;
status: DeploymentStatus;
level?: DeploymentEventLevel;
message: string;
metadata?: DeploymentSnapshot;
}) {
return prisma.deploymentEvent.create({
data: {
status: patch.status,
error: patch.error ?? null,
completedAt: patch.completedAt ?? null,
...(patch.image === undefined ? {} : { image: patch.image }),
...(patch.imageDigest === undefined
? {}
: { imageDigest: patch.imageDigest }),
...(patch.commitSha === undefined ? {} : { commitSha: patch.commitSha }),
...(patch.branch === undefined ? {} : { branch: patch.branch }),
...(patch.configSnapshot === undefined
? {}
: {
configSnapshot: sanitizeDeploymentSnapshot(patch.configSnapshot),
rollbackSnapshotEnc: encrypt(
JSON.stringify(patch.configSnapshot),
),
}),
deploymentId: input.deploymentId,
status: input.status,
level: input.level ?? eventLevelForStatus(input.status),
message: sanitizeDeploymentEventMessage(input.message),
metadata:
input.metadata === undefined
? undefined
: sanitizeDeploymentSnapshot(input.metadata),
},
});
}
@@ -206,6 +458,12 @@ export async function listDeployments(input: {
branch: true,
image: true,
imageDigest: true,
projectId: true,
environmentId: true,
configRevision: true,
strategy: true,
previousDeploymentId: true,
rollbackSnapshotEnc: true,
error: true,
startedAt: true,
completedAt: true,
@@ -216,7 +474,12 @@ export async function listDeployments(input: {
prisma.deployment.count({ where }),
]);
return { items, total, page: input.page, pageSize: input.pageSize };
return {
items: items.map(toPublicDeploymentRecord),
total,
page: input.page,
pageSize: input.pageSize,
};
}
export async function getDeployment(input: {
@@ -241,7 +504,16 @@ export async function getDeployment(input: {
branch: true,
image: true,
imageDigest: true,
projectId: true,
environmentId: true,
sourceSnapshot: true,
configSnapshot: true,
configRevision: true,
strategy: true,
candidateRef: true,
previousDeploymentId: true,
failureReason: true,
rollbackReason: true,
error: true,
startedAt: true,
completedAt: true,
@@ -251,4 +523,237 @@ export async function getDeployment(input: {
});
}
const deploymentStateSelect = {
id: true,
containerId: true,
projectId: true,
environmentId: true,
serverId: true,
status: true,
trigger: true,
version: true,
commitSha: true,
branch: true,
image: true,
imageDigest: true,
configRevision: true,
strategy: true,
previousDeploymentId: true,
failureReason: true,
rollbackReason: true,
error: true,
startedAt: true,
completedAt: true,
createdAt: true,
updatedAt: true,
user: { select: { id: true, name: true } },
} as const;
type DeploymentStateRecord = Prisma.DeploymentGetPayload<{
select: typeof deploymentStateSelect;
}>;
export type ContainerDeploymentSummary = {
activeRevision: DeploymentStateRecord | null;
currentOperation: DeploymentStateRecord | null;
latestAttempt: DeploymentStateRecord | null;
lastError: string | null;
redeployAvailable: boolean;
rollbackAvailable: boolean;
};
export async function getContainerDeploymentSummaries(input: {
containerIds: string[];
organizationId: string;
}) {
if (input.containerIds.length === 0) {
return new Map<string, ContainerDeploymentSummary>();
}
const scope = {
containerId: { in: input.containerIds },
organizationId: input.organizationId,
};
const [
currentOperations,
activeRevisions,
legacyRevisions,
latestAttempts,
rollbackEligibleRevisions,
] =
await prisma.$transaction([
prisma.deployment.findMany({
where: {
...scope,
status: { in: IN_PROGRESS_DEPLOYMENT_STATUSES },
},
orderBy: [{ containerId: "asc" }, { createdAt: "desc" }],
distinct: ["containerId"],
select: deploymentStateSelect,
}),
prisma.deployment.findMany({
where: { ...scope, status: "ACTIVE" },
orderBy: [{ containerId: "asc" }, { createdAt: "desc" }],
distinct: ["containerId"],
select: deploymentStateSelect,
}),
prisma.deployment.findMany({
where: {
...scope,
status: { in: ["SUCCESS", "SUPERSEDED"] },
},
orderBy: [{ containerId: "asc" }, { completedAt: "desc" }],
distinct: ["containerId"],
select: deploymentStateSelect,
}),
prisma.deployment.findMany({
where: scope,
orderBy: [{ containerId: "asc" }, { createdAt: "desc" }],
distinct: ["containerId"],
select: deploymentStateSelect,
}),
prisma.deployment.findMany({
where: {
...scope,
status: { in: ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES },
rollbackSnapshotEnc: { not: null },
},
select: { id: true, containerId: true },
}),
]);
const byContainer = <T extends { containerId: string }>(items: T[]) =>
new Map(items.map((item) => [item.containerId, item]));
const currentByContainer = byContainer(currentOperations);
const activeByContainer = byContainer(activeRevisions);
const legacyByContainer = byContainer(legacyRevisions);
const latestByContainer = byContainer(latestAttempts);
return new Map<string, ContainerDeploymentSummary>(
input.containerIds.map((containerId) => {
const activeRevision =
activeByContainer.get(containerId) ??
legacyByContainer.get(containerId) ??
null;
const latestAttempt = latestByContainer.get(containerId) ?? null;
return [
containerId,
{
activeRevision,
currentOperation: currentByContainer.get(containerId) ?? null,
latestAttempt,
lastError:
latestAttempt?.status === "FAILED" ||
latestAttempt?.status === "FAILED_ROLLED_BACK"
? latestAttempt.failureReason ?? latestAttempt.error
: null,
redeployAvailable: rollbackEligibleRevisions.some(
(revision) => revision.id === activeRevision?.id,
),
rollbackAvailable: rollbackEligibleRevisions.some(
(revision) =>
revision.containerId === containerId &&
revision.id !== activeRevision?.id,
),
},
];
}),
);
}
export async function getDeploymentState(input: {
containerId: string;
organizationId: string;
}) {
const scope = {
containerId: input.containerId,
organizationId: input.organizationId,
};
const [currentOperation, activeRevision, previousRevision, latestAttempt, lock] =
await prisma.$transaction([
prisma.deployment.findFirst({
where: {
...scope,
status: { in: IN_PROGRESS_DEPLOYMENT_STATUSES },
},
orderBy: { createdAt: "desc" },
select: deploymentStateSelect,
}),
prisma.deployment.findFirst({
where: { ...scope, status: "ACTIVE" },
orderBy: { createdAt: "desc" },
select: deploymentStateSelect,
}),
prisma.deployment.findFirst({
where: {
...scope,
status: { in: ["SUCCESS", "SUPERSEDED"] },
},
orderBy: { completedAt: "desc" },
select: deploymentStateSelect,
}),
prisma.deployment.findFirst({
where: scope,
orderBy: { createdAt: "desc" },
select: deploymentStateSelect,
}),
prisma.deploymentLock.findUnique({
where: { containerId: input.containerId },
select: { expiresAt: true, updatedAt: true },
}),
]);
const effectiveActiveRevision = activeRevision ?? previousRevision;
const rollbackRevision = effectiveActiveRevision
? await prisma.deployment.findFirst({
where: {
...scope,
id: { not: effectiveActiveRevision.id },
status: { in: ROLLBACK_ELIGIBLE_DEPLOYMENT_STATUSES },
rollbackSnapshotEnc: { not: null },
},
orderBy: { completedAt: "desc" },
select: deploymentStateSelect,
})
: null;
return {
activeRevision: effectiveActiveRevision,
currentOperation,
latestAttempt,
rollbackRevision,
lock,
};
}
export async function listDeploymentEvents(input: {
containerId: string;
deploymentId: string;
organizationId: string;
page: number;
pageSize: number;
}) {
const deployment = await prisma.deployment.findFirst({
where: {
id: input.deploymentId,
containerId: input.containerId,
organizationId: input.organizationId,
},
select: { id: true },
});
if (!deployment) return null;
const skip = (input.page - 1) * input.pageSize;
const where = { deploymentId: input.deploymentId };
const [items, total] = await prisma.$transaction([
prisma.deploymentEvent.findMany({
where,
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
skip,
take: input.pageSize,
}),
prisma.deploymentEvent.count({ where }),
]);
return { items, total, page: input.page, pageSize: input.pageSize };
}
@@ -444,6 +444,20 @@ export function withCommandLogSink<T>(
);
}
export function withMutedCommandLog<T>(execute: () => Promise<T>): Promise<T> {
return commandLogSink.run(() => undefined, execute);
}
export function withNonCancellableCommandContext<T>(
execute: () => Promise<T>,
): Promise<T> {
const current = commandRunContext.getStore();
return commandRunContext.run(
{ runIdPrefix: current?.runIdPrefix },
execute,
);
}
export async function execStrictIsolated(
server: Server,
command: string,
@@ -3,7 +3,7 @@ import { randomBytes } from "crypto";
import { posix as pathPosix } from "path";
import { TextDecoder } from "util";
import { Server } from "@prisma/client";
import { execStrict } from "./commands";
import { execStrict, withMutedCommandLog } from "./commands";
import {
DOCKER_ACCESS_DENIED_MESSAGE,
execDocker,
@@ -237,6 +237,18 @@ function validatePortMapping(entry: string): string {
if (!/^(?:\d{1,3}\.){3}\d{1,3}$/.test(hostIp)) {
throw new Error(`Invalid host IP in port mapping: ${entry}`);
}
if (!hostPort) {
if (hostIp !== "127.0.0.1") {
throw new Error(
"Random host ports may only bind to the loopback address",
);
}
parsePortNumber(containerPort, "Container port");
return `${hostIp}::${containerPort}/${protocol}`.replace(
/\/tcp$/,
protocol === "tcp" && !entry.includes("/") ? "" : "/tcp",
);
}
parsePortNumber(hostPort, "Host port");
parsePortNumber(containerPort, "Container port");
return `${hostIp}:${hostPort}:${containerPort}/${protocol}`.replace(
@@ -434,6 +446,8 @@ export function buildDockerRunCommand(opts: {
restartPolicy: string;
volumes?: string;
network?: string;
cpuLimit?: number;
memoryLimitMb?: number;
entrypoint?: string;
commandArgs?: string[];
command?: string;
@@ -454,6 +468,28 @@ export function buildDockerRunCommand(opts: {
args.push("--network", network);
}
if (opts.cpuLimit !== undefined) {
if (!Number.isFinite(opts.cpuLimit) || opts.cpuLimit < 0 || opts.cpuLimit > 256) {
throw new Error("CPU limit must be between 0 and 256");
}
if (opts.cpuLimit > 0) {
args.push("--cpus", String(opts.cpuLimit));
}
}
if (opts.memoryLimitMb !== undefined) {
if (
!Number.isInteger(opts.memoryLimitMb) ||
opts.memoryLimitMb < 0 ||
opts.memoryLimitMb > 1_048_576
) {
throw new Error("Memory limit must be an integer between 0 and 1048576 MB");
}
if (opts.memoryLimitMb > 0) {
args.push("--memory", `${opts.memoryLimitMb}m`);
}
}
const entrypoint = opts.entrypoint?.trim();
if (entrypoint) {
args.push("--entrypoint", entrypoint);
@@ -925,6 +961,17 @@ export type GitBuildType =
| "DOCKERFILE"
| "COMPOSE";
export type PreparedGitRuntime = {
image: string;
ports: string;
env: string;
volumes: string;
network: string;
restartPolicy: string;
entrypoint?: string;
commandArgs?: string[];
};
async function execContainerShell(
server: Server,
containerId: string,
@@ -1012,10 +1059,12 @@ export async function dockerInspect(
server: Server,
containerId: string,
): Promise<DockerContainerInspect> {
const stdout = await execDockerStrict(
server,
`docker inspect ${escapeShellArg(containerId)}`,
shortDockerCommandTimeout(DOCKER_INSPECT_TIMEOUT_MS),
const stdout = await withMutedCommandLog(() =>
execDockerStrict(
server,
`docker inspect ${escapeShellArg(containerId)}`,
shortDockerCommandTimeout(DOCKER_INSPECT_TIMEOUT_MS),
),
);
const parsed = parseDockerJson<DockerContainerInspect[]>(
stdout,
@@ -1169,12 +1218,123 @@ export async function dockerRename(
);
}
export type DockerContainerUpdateOptions = {
restartPolicy?: string;
cpuLimit?: number;
memoryLimitMb?: number;
memorySwapLimitMb?: number;
};
export function buildDockerUpdateCommand(
containerId: string,
opts: DockerContainerUpdateOptions,
): string | null {
const args: string[] = [];
if (opts.restartPolicy !== undefined) {
args.push("--restart", escapeShellArg(validateRestartPolicy(opts.restartPolicy)));
}
if (opts.cpuLimit !== undefined) {
if (!Number.isFinite(opts.cpuLimit) || opts.cpuLimit < 0 || opts.cpuLimit > 256) {
throw new Error("CPU limit must be between 0 and 256");
}
args.push("--cpus", escapeShellArg(String(opts.cpuLimit)));
}
if (opts.memoryLimitMb !== undefined) {
if (
!Number.isInteger(opts.memoryLimitMb) ||
opts.memoryLimitMb < 0 ||
opts.memoryLimitMb > 1_048_576
) {
throw new Error("Memory limit must be a whole number between 0 and 1048576 MB");
}
args.push(
"--memory",
escapeShellArg(opts.memoryLimitMb === 0 ? "0" : `${opts.memoryLimitMb}m`),
);
}
if (opts.memorySwapLimitMb !== undefined) {
if (
!Number.isInteger(opts.memorySwapLimitMb) ||
opts.memorySwapLimitMb < -1 ||
opts.memorySwapLimitMb > 2_097_152
) {
throw new Error(
"Memory-swap limit must be -1 or a whole number between 0 and 2097152 MB",
);
}
if (
opts.memoryLimitMb !== undefined &&
opts.memoryLimitMb > 0 &&
opts.memorySwapLimitMb > 0 &&
opts.memorySwapLimitMb < opts.memoryLimitMb
) {
throw new Error("Memory-swap limit cannot be lower than memory limit");
}
args.push(
"--memory-swap",
escapeShellArg(
opts.memorySwapLimitMb === -1
? "-1"
: opts.memorySwapLimitMb === 0
? "0"
: `${opts.memorySwapLimitMb}m`,
),
);
}
if (args.length === 0) return null;
return `docker update ${args.join(" ")} ${escapeShellArg(containerId)}`;
}
export async function dockerUpdateContainer(
server: Server,
containerId: string,
opts: DockerContainerUpdateOptions,
): Promise<void> {
const command = buildDockerUpdateCommand(containerId, opts);
if (!command) return;
await execDockerStrict(
server,
command,
shortDockerCommandTimeout(DOCKER_ACTION_TIMEOUT_MS),
);
}
export async function dockerConnectNetwork(
server: Server,
containerId: string,
networkName: string,
): Promise<void> {
const network = validateNetworkName(networkName);
if (!network) throw new Error("Network name is required");
await execDockerStrict(
server,
`docker network connect ${escapeShellArg(network)} ${escapeShellArg(containerId)}`,
shortDockerCommandTimeout(DOCKER_ACTION_TIMEOUT_MS),
);
}
export async function dockerDisconnectNetwork(
server: Server,
containerId: string,
networkName: string,
): Promise<void> {
const network = validateNetworkName(networkName);
if (!network) throw new Error("Network name is required");
await execDockerStrict(
server,
`docker network disconnect ${escapeShellArg(network)} ${escapeShellArg(containerId)}`,
shortDockerCommandTimeout(DOCKER_ACTION_TIMEOUT_MS),
);
}
export async function getContainerMainProcessWorkingDirectory(
server: Server,
containerId: string,
): Promise<string | null> {
const script = [
'CWD=$(readlink -f /proc/1/cwd 2>/dev/null || true)',
"CWD=$(readlink -f /proc/1/cwd 2>/dev/null || true)",
'if [ -z "$CWD" ] || [ ! -d "$CWD" ]; then exit 0; fi',
'CWD_B64=$(printf "%s" "$CWD" | base64 | tr -d "\\n")',
'printf "__CWD__\t%s\n" "$CWD_B64"',
@@ -1542,6 +1702,8 @@ export async function runContainer(
restartPolicy: string;
volumes?: string;
network?: string;
cpuLimit?: number;
memoryLimitMb?: number;
entrypoint?: string;
commandArgs?: string[];
command?: string;
@@ -2118,7 +2280,7 @@ async function buildImageWithNixpacks(
"fi",
...(buildEnvs.length > 0
? [
"echo \"[doktainer] Nixpacks build env overrides:\"",
'echo "[doktainer] Nixpacks build env overrides:"',
...buildEnvs.map(
(value) => `printf " - %s\\n" ${escapeShellArg(value)}`,
),
@@ -2245,10 +2407,7 @@ async function inspectSourceProject(
const separatorIndex = line.indexOf("=");
const key = line.slice(0, separatorIndex);
const value = line.slice(separatorIndex + 1);
return [
key,
key === "PHP_REQUIRE" ? value : value === "1",
];
return [key, key === "PHP_REQUIRE" ? value : value === "1"];
}),
) as Record<string, string | boolean>;
@@ -2520,6 +2679,18 @@ export async function buildAndRunContainerFromDockerfileContent(
};
}
export function toImmutableBuildImageTag(imageTag: string, commitSha: string) {
const suffix = commitSha.trim().slice(0, 12).toLowerCase();
if (!/^[a-f0-9]{7,12}$/.test(suffix)) {
throw new Error("A valid Git commit SHA is required for an immutable rebuild image");
}
const lastSlash = imageTag.lastIndexOf("/");
const lastColon = imageTag.lastIndexOf(":");
const repository =
lastColon > lastSlash ? imageTag.slice(0, lastColon) : imageTag;
return `${repository}:git-${suffix}`;
}
export async function deployContainerFromGitSource(
server: Server,
opts: {
@@ -2544,6 +2715,8 @@ export async function deployContainerFromGitSource(
network?: string;
deploymentPath?: string;
composeEnvFiles?: ComposeEnvFileOverride[];
startRuntime?: boolean;
immutableImageTag?: boolean;
},
): Promise<{
deploymentPath: string;
@@ -2551,6 +2724,7 @@ export async function deployContainerFromGitSource(
imageTag?: string;
composeFilePath?: string;
commitSha: string;
preparedRuntime?: PreparedGitRuntime;
}> {
const projectName = sanitizeProjectName(opts.projectName);
const deploymentPath =
@@ -2568,7 +2742,7 @@ export async function deployContainerFromGitSource(
const dockerContextPath = normalizeDockerBuildContextPath(
opts.dockerContextPath || (buildType === "DOCKERFILE" ? buildPath : "."),
);
const imageTag =
const requestedImageTag =
opts.imageTag?.trim() ||
`doktainer/${sanitizeProjectName(projectName)}:latest`;
const runOverride = resolveRunOverride(opts.startCommand);
@@ -2623,6 +2797,10 @@ export async function deployContainerFromGitSource(
);
}
const imageTag = opts.immutableImageTag
? toImmutableBuildImageTag(requestedImageTag, commitSha)
: requestedImageTag;
if (buildType === "COMPOSE") {
try {
await writeComposeEnvFiles({
@@ -2740,27 +2918,34 @@ export async function deployContainerFromGitSource(
? ensureLaravelRuntimeEnv(opts.env)
: opts.env;
const dockerId = await runContainer(server, {
name: opts.containerName?.trim() || projectName,
const preparedRuntime: PreparedGitRuntime = {
image: imageTag,
ports: autoPorts,
env: runtimeEnv,
ports: autoPorts ?? "",
env: runtimeEnv ?? "",
restartPolicy: opts.restartPolicy?.trim() || "unless-stopped",
volumes: opts.volumes,
network: opts.network,
volumes: opts.volumes ?? "",
network: opts.network?.trim() || "bridge",
entrypoint: shouldApplyRuntimeOverride
? runOverride?.entrypoint
: undefined,
commandArgs: shouldApplyRuntimeOverride
? runOverride?.commandArgs
: undefined,
});
};
const dockerId =
opts.startRuntime === false
? undefined
: await runContainer(server, {
name: opts.containerName?.trim() || projectName,
...preparedRuntime,
});
return {
deploymentPath,
dockerId,
imageTag,
commitSha,
preparedRuntime,
};
}
@@ -2852,21 +3037,28 @@ export async function deployContainerFromGitSource(
? ensureLaravelRuntimeEnv(opts.env)
: opts.env;
const dockerId = await runContainer(server, {
name: opts.containerName?.trim() || projectName,
const preparedRuntime: PreparedGitRuntime = {
image: imageTag,
ports: autoPorts,
env: runtimeEnv,
ports: autoPorts ?? "",
env: runtimeEnv ?? "",
restartPolicy: opts.restartPolicy?.trim() || "unless-stopped",
volumes: opts.volumes,
network: opts.network,
});
volumes: opts.volumes ?? "",
network: opts.network?.trim() || "bridge",
};
const dockerId =
opts.startRuntime === false
? undefined
: await runContainer(server, {
name: opts.containerName?.trim() || projectName,
...preparedRuntime,
});
return {
deploymentPath,
dockerId,
imageTag,
commitSha,
preparedRuntime,
};
}
@@ -2885,27 +3077,34 @@ export async function deployContainerFromGitSource(
defaultPort: "80",
});
const dockerId = await runContainer(server, {
name: opts.containerName?.trim() || projectName,
const preparedRuntime: PreparedGitRuntime = {
image: imageTag,
ports: autoPorts,
env: opts.env,
ports: autoPorts ?? "",
env: opts.env ?? "",
restartPolicy: opts.restartPolicy?.trim() || "unless-stopped",
volumes: opts.volumes,
network: opts.network,
volumes: opts.volumes ?? "",
network: opts.network?.trim() || "bridge",
entrypoint: shouldApplyRuntimeOverride
? runOverride?.entrypoint
: undefined,
commandArgs: shouldApplyRuntimeOverride
? runOverride?.commandArgs
: undefined,
});
};
const dockerId =
opts.startRuntime === false
? undefined
: await runContainer(server, {
name: opts.containerName?.trim() || projectName,
...preparedRuntime,
});
return {
deploymentPath,
dockerId,
imageTag,
commitSha,
preparedRuntime,
};
}
@@ -2951,26 +3150,33 @@ export async function deployContainerFromGitSource(
exposedPorts: await inspectImageExposedPorts(server, imageTag),
});
const dockerId = await runContainer(server, {
name: opts.containerName?.trim() || projectName,
const preparedRuntime: PreparedGitRuntime = {
image: imageTag,
ports: autoPorts,
env: opts.env,
ports: autoPorts ?? "",
env: opts.env ?? "",
restartPolicy: opts.restartPolicy?.trim() || "unless-stopped",
volumes: opts.volumes,
network: opts.network,
volumes: opts.volumes ?? "",
network: opts.network?.trim() || "bridge",
entrypoint: shouldApplyRuntimeOverride
? runOverride?.entrypoint
: undefined,
commandArgs: shouldApplyRuntimeOverride
? runOverride?.commandArgs
: undefined,
});
};
const dockerId =
opts.startRuntime === false
? undefined
: await runContainer(server, {
name: opts.containerName?.trim() || projectName,
...preparedRuntime,
});
return {
deploymentPath,
dockerId,
imageTag,
commitSha,
preparedRuntime,
};
}
@@ -49,7 +49,7 @@ export interface DockerNetworkInspect {
raw: Record<string, unknown>;
}
export async function listDockerNetworks(
export async function listDockerNetworkSummaries(
server: Server,
): Promise<DockerNetworkInfo[]> {
const networkList = await execDockerStrict(
@@ -60,7 +60,7 @@ export async function listDockerNetworks(
if (!networkList.trim()) return [];
const rawNetworks = networkList
return networkList
.trim()
.split("\n")
.map((line) => {
@@ -69,9 +69,17 @@ export async function listDockerNetworks(
name: name?.trim() || "",
driver: driver?.trim() || "bridge",
scope: scope?.trim() || "local",
};
containers: 0,
} satisfies DockerNetworkInfo;
})
.filter((item) => item.name);
.filter((item) => item.name)
.sort((left, right) => left.name.localeCompare(right.name));
}
export async function listDockerNetworks(
server: Server,
): Promise<DockerNetworkInfo[]> {
const rawNetworks = await listDockerNetworkSummaries(server);
const inspected = await Promise.all(
rawNetworks.map(async (network) => {
@@ -0,0 +1,117 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildContainerCapabilities } from "../../src/server/services/container-capabilities.service";
describe("container capabilities", () => {
it("keeps an imported manual container readable without inventing deployment actions", () => {
const capabilities = buildContainerCapabilities({
sourceType: "MANUAL",
deployMode: null,
hasDeploymentSource: false,
hasGitSource: false,
hasAppInstall: false,
hasDeploymentHistory: false,
redeployAvailable: false,
rollbackAvailable: false,
});
assert.equal(capabilities.managed, false);
assert.equal(capabilities.managementLabel, "Docker import");
assert.equal(capabilities.editConfiguration.available, true);
assert.equal(capabilities.redeploy.available, false);
assert.equal(capabilities.rebuild.available, false);
assert.equal(capabilities.rollback.available, false);
});
it("enables supported actions for a tracked Git single-container deployment", () => {
const capabilities = buildContainerCapabilities({
sourceType: "GIT_PROVIDER",
deployMode: "DOCKERFILE",
hasDeploymentSource: true,
hasGitSource: true,
hasAppInstall: false,
hasDeploymentHistory: true,
redeployAvailable: true,
rollbackAvailable: true,
});
assert.equal(capabilities.managed, true);
assert.equal(capabilities.managementLabel, "Doktainer managed");
assert.equal(capabilities.redeploy.available, true);
assert.equal(capabilities.rebuild.available, true);
assert.equal(capabilities.rebuild.mode, "ORCHESTRATED_SINGLE_CONTAINER");
assert.equal(capabilities.rollback.available, true);
});
it("labels Compose rebuild honestly and blocks per-container configuration editing", () => {
const capabilities = buildContainerCapabilities({
sourceType: "GIT_CLONE",
deployMode: "COMPOSE",
hasDeploymentSource: true,
hasGitSource: true,
hasAppInstall: false,
hasDeploymentHistory: true,
redeployAvailable: false,
rollbackAvailable: false,
});
assert.equal(capabilities.editConfiguration.available, false);
assert.match(capabilities.editConfiguration.reason ?? "", /Compose project/);
assert.equal(capabilities.rebuild.available, true);
assert.equal(capabilities.rebuild.mode, "COMPOSE_RECREATE");
assert.match(capabilities.rebuild.reason ?? "", /not a safe/);
});
it("does not expose rebuild when source metadata is incomplete", () => {
const capabilities = buildContainerCapabilities({
sourceType: "GIT_CLONE",
deployMode: "DOCKERFILE",
hasDeploymentSource: true,
hasGitSource: false,
hasAppInstall: false,
hasDeploymentHistory: false,
redeployAvailable: false,
rollbackAvailable: false,
});
assert.equal(capabilities.rebuild.available, false);
assert.equal(capabilities.rebuild.mode, null);
assert.match(capabilities.rebuild.reason ?? "", /missing or incomplete/);
});
it("supports App Installer rebuild without pretending that redeploy is available", () => {
const capabilities = buildContainerCapabilities({
sourceType: "APP_INSTALLER",
deployMode: null,
hasDeploymentSource: false,
hasGitSource: false,
hasAppInstall: true,
hasDeploymentHistory: true,
redeployAvailable: false,
rollbackAvailable: false,
});
assert.equal(capabilities.managed, true);
assert.equal(capabilities.rebuild.available, true);
assert.equal(capabilities.rebuild.mode, "ORCHESTRATED_SINGLE_CONTAINER");
assert.equal(capabilities.redeploy.available, false);
});
it("keeps redeploy and rollback eligibility independent", () => {
const capabilities = buildContainerCapabilities({
sourceType: "MANUAL",
deployMode: null,
hasDeploymentSource: false,
hasGitSource: false,
hasAppInstall: false,
hasDeploymentHistory: true,
redeployAvailable: true,
rollbackAvailable: false,
});
assert.equal(capabilities.managementLabel, "Doktainer managed");
assert.equal(capabilities.redeploy.available, true);
assert.equal(capabilities.rollback.available, false);
assert.equal(capabilities.rebuild.available, false);
});
});
@@ -0,0 +1,109 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildContainerConfigurationPlan,
extractContainerConfiguration,
} from "../../src/server/services/container-configuration.service.ts";
test("extracts editable values from Docker inspect", () => {
assert.deepEqual(
extractContainerConfiguration({
Name: "/web",
HostConfig: {
RestartPolicy: { Name: "unless-stopped" },
NanoCpus: 1_500_000_000,
Memory: 512 * 1024 * 1024,
NetworkMode: "app-net",
},
NetworkSettings: { Networks: { "app-net": {}, monitoring: {} } },
}),
{
name: "web",
restartPolicy: "unless-stopped",
cpuLimit: 1.5,
memoryLimitMb: 512,
networks: ["app-net", "monitoring"],
primaryNetwork: "app-net",
},
);
});
test("plans live updates and reports disruptive changes", () => {
const plan = buildContainerConfigurationPlan({
current: {
name: "web",
restartPolicy: "unless-stopped",
cpuLimit: 1,
memoryLimitMb: 256,
networks: ["app-net"],
primaryNetwork: "app-net",
},
draft: {
name: "web-v2",
restartPolicy: "always",
cpuLimit: 2,
memoryLimitMb: 512,
networks: ["app-net", "monitoring"],
},
availableNetworks: ["app-net", "monitoring"],
});
assert.equal(plan.strategy, "LIVE_UPDATE");
assert.equal(plan.requiresDowntime, false);
assert.deepEqual(plan.addedNetworks, ["monitoring"]);
assert.deepEqual(plan.removedNetworks, []);
assert.deepEqual(
plan.changes.map((change) => change.field),
["name", "restartPolicy", "cpuLimit", "memoryLimitMb", "networks"],
);
assert.ok(plan.warnings.some((warning) => warning.includes("Docker DNS")));
assert.equal(plan.blockedReasons.length, 0);
});
test("blocks primary network removal and Compose-managed mutation", () => {
const plan = buildContainerConfigurationPlan({
current: {
name: "web",
restartPolicy: "no",
cpuLimit: 0,
memoryLimitMb: 0,
networks: ["app-net", "monitoring"],
primaryNetwork: "app-net",
},
draft: {
name: "web",
restartPolicy: "no",
cpuLimit: 0,
memoryLimitMb: 0,
networks: ["monitoring"],
},
availableNetworks: ["app-net", "monitoring"],
composeManaged: true,
});
assert.ok(plan.blockedReasons.some((reason) => reason.includes("Compose-managed")));
assert.ok(plan.blockedReasons.some((reason) => reason.includes("Primary network")));
});
test("produces a stable revision independent of network ordering", () => {
const base = {
name: "web",
restartPolicy: "no" as const,
cpuLimit: 0,
memoryLimitMb: 0,
primaryNetwork: "app-net",
};
const first = buildContainerConfigurationPlan({
current: { ...base, networks: ["monitoring", "app-net"] },
draft: { ...base, networks: ["app-net", "monitoring"] },
availableNetworks: ["app-net", "monitoring"],
});
const second = buildContainerConfigurationPlan({
current: { ...base, networks: ["app-net", "monitoring"] },
draft: { ...base, networks: ["monitoring", "app-net"] },
availableNetworks: ["monitoring", "app-net"],
});
assert.equal(first.expectedConfigRevision, second.expectedConfigRevision);
assert.equal(first.changes.length, 0);
});
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const routes = readFileSync("src/server/routes/containers.ts", "utf8");
const api = readFileSync("src/lib/api.ts", "utf8");
const detailPage = readFileSync(
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/page.tsx",
"utf8",
);
test("configuration endpoints require container authorization", () => {
for (const path of [
'"/:id/configuration"',
'"/:id/configuration/preview"',
'"/:id/configuration/apply"',
]) {
const start = routes.indexOf(path);
assert.ok(start >= 0, `${path} route should exist`);
assert.match(
routes.slice(start, start + 180),
path.includes("preview") || path.includes("apply")
? /containerWriteAccess/
: /containerReadAccess/,
);
}
});
test("configuration apply is guarded by revision, idempotency, and lock", () => {
const applyStart = routes.indexOf('"/:id/configuration/apply"');
const applyRoute = routes.slice(applyStart, applyStart + 17000);
assert.match(applyRoute, /expectedConfigRevision/);
assert.match(applyRoute, /containerId_idempotencyKey/);
assert.match(applyRoute, /acquireDeploymentLock/);
assert.match(applyRoute, /FAILED_ROLLED_BACK/);
assert.match(applyRoute, /compensationErrors/);
assert.match(applyRoute, /requestedResources/);
assert.match(applyRoute, /const resourceUpdate: ssh\.DockerContainerUpdateOptions/);
assert.match(applyRoute, /resourceFields\.has\("cpuLimit"\)/);
assert.match(applyRoute, /resourceFields\.has\("memoryLimitMb"\)/);
assert.match(applyRoute, /Docker did not retain the requested/);
assert.match(applyRoute, /sanitizeContainerConfigurationError\(error\)/);
assert.match(applyRoute, /resolveMemorySwapLimitMb/);
assert.match(applyRoute, /memorySwapLimitMb/);
});
test("configuration editor uses the lightweight network path and a remote-aware timeout", () => {
assert.match(routes, /ssh\.listDockerNetworkSummaries/);
assert.match(
routes,
/draft\.name\.trim\(\)\.toLowerCase\(\) !== current\.name\.toLowerCase\(\)/,
);
assert.match(
api,
/`\/containers\/\$\{id\}\/configuration`[\s\S]*?timeoutMs: 45000/,
);
});
test("client and detail page expose the working configuration editor", () => {
assert.match(api, /previewConfiguration/);
assert.match(api, /applyConfiguration/);
assert.match(detailPage, /EditContainerConfigurationModal/);
assert.match(detailPage, /setShowConfigurationEditor\(true\)/);
});
+3 -5
View File
@@ -2,10 +2,10 @@ import assert from "node:assert/strict";
import test from "node:test";
import { evaluateDockerHealth } from "../../src/server/services/container-health.service";
test("docker health gate accepts a running image without a healthcheck", () => {
test("docker health gate keeps a running image without a healthcheck unverified", () => {
const result = evaluateDockerHealth({ State: { Status: "running" } });
assert.equal(result.healthy, true);
assert.equal(result.status, "healthy");
assert.equal(result.healthy, false);
assert.equal(result.status, "running_unverified");
});
test("docker health gate rejects unhealthy containers", () => {
@@ -27,5 +27,3 @@ test("docker runtime verification keeps polling while a container is restarting"
assert.equal(result.healthy, false);
assert.equal(result.status, "starting");
});
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const routes = readFileSync("src/server/routes/containers.ts", "utf8");
const api = readFileSync("src/lib/api.ts", "utf8");
const redeployService = readFileSync(
"src/server/services/deployment-rollback.service.ts",
"utf8",
);
const detailPage = readFileSync(
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/page.tsx",
"utf8",
);
const actionConstants = readFileSync(
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/data/app-detail-constants.ts",
"utf8",
);
test("redeploy endpoints require container write authorization", () => {
for (const path of ['"/:id/redeploy-job"', '"/:id/redeploy"']) {
const start = routes.indexOf(path);
assert.ok(start >= 0, `${path} route should exist`);
assert.match(routes.slice(start, start + 180), /containerWriteAccess/);
}
const previewStart = routes.indexOf('"/:id/redeploy-plan"');
assert.ok(previewStart >= 0, "redeploy preview route should exist");
assert.match(routes.slice(previewStart, previewStart + 180), /containerReadAccess/);
});
test("redeploy restores the stored current revision without invoking source rebuild", () => {
assert.match(redeployService, /redeployContainerCurrentRevision/);
assert.match(redeployService, /getRollbackSnapshot\(input\)/);
assert.match(redeployService, /trigger: input\.operation/);
assert.match(redeployService, /operation: "REDEPLOY"/);
assert.match(redeployService, /containerId_idempotencyKey/);
assert.match(redeployService, /replaceRuntimeWithProxyCandidate/);
assert.match(redeployService, /status: "VALIDATING"/);
assert.match(redeployService, /status: "SWITCHING"/);
const redeployStart = routes.indexOf('"/:id/redeploy"');
const redeployRoute = routes.slice(redeployStart, redeployStart + 1800);
assert.match(redeployRoute, /redeployContainerCurrentRevision/);
assert.match(redeployRoute, /ContainerRedeploySchema\.safeParse/);
assert.doesNotMatch(redeployRoute, /rebuildAppInstall|repoUrl|gitClone/);
});
test("client presents redeploy and rebuild as separate operations", () => {
assert.match(api, /createRedeployJob/);
assert.match(api, /redeployPlan/);
assert.match(api, /createRebuildJob/);
assert.match(actionConstants, /label: "Redeploy current revision"/);
assert.match(actionConstants, /label: "Rebuild from source"/);
assert.match(detailPage, /runDeploymentOperation\("redeploy"\)/);
assert.match(detailPage, /runDeploymentOperation\("rebuild"\)/);
assert.match(detailPage, /No source code will be fetched and no image will be built/);
assert.match(detailPage, /proxyTrafficContinuous/);
assert.match(detailPage, /overlappingRuntime/);
});
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sanitizeContainerConfigurationError } from "../../src/server/services/deployment-error.service";
import {
extractContainerMemorySwapMb,
resolveMemorySwapLimitMb,
} from "../../src/server/services/container-configuration.service";
import { buildDockerUpdateCommand } from "../../src/server/services/ssh-services/docker-containers";
test("resource update translates CPU cores and memory MB for Docker CLI", () => {
assert.equal(
buildDockerUpdateCommand("nextcloud-app1", {
cpuLimit: 1,
memoryLimitMb: 1024,
memorySwapLimitMb: 2048,
}),
"docker update --cpus '1' --memory '1024m' --memory-swap '2048m' 'nextcloud-app1'",
);
});
test("memory updates preserve or establish an explicit Docker swap policy", () => {
assert.equal(
extractContainerMemorySwapMb({ HostConfig: { MemorySwap: 0 } }),
0,
);
assert.equal(
extractContainerMemorySwapMb({ HostConfig: { MemorySwap: -1 } }),
-1,
);
assert.equal(
resolveMemorySwapLimitMb({
currentMemoryLimitMb: 0,
currentMemorySwapMb: 0,
targetMemoryLimitMb: 1024,
}),
2048,
);
assert.equal(
resolveMemorySwapLimitMb({
currentMemoryLimitMb: 512,
currentMemorySwapMb: 512,
targetMemoryLimitMb: 1024,
}),
1024,
);
assert.equal(
resolveMemorySwapLimitMb({
currentMemoryLimitMb: 512,
currentMemorySwapMb: -1,
targetMemoryLimitMb: 1024,
}),
-1,
);
});
test("resource update includes only fields selected by the caller", () => {
assert.equal(
buildDockerUpdateCommand("example", { cpuLimit: 0.5 }),
"docker update --cpus '0.5' 'example'",
);
assert.equal(
buildDockerUpdateCommand("example", { memoryLimitMb: 0 }),
"docker update --memory '0' 'example'",
);
assert.equal(buildDockerUpdateCommand("example", {}), null);
});
test("resource update rejects invalid values before reaching Docker", () => {
assert.throws(
() => buildDockerUpdateCommand("example", { cpuLimit: -1 }),
/CPU limit/,
);
assert.throws(
() => buildDockerUpdateCommand("example", { memoryLimitMb: 1.5 }),
/Memory limit/,
);
assert.throws(
() =>
buildDockerUpdateCommand("example", {
memoryLimitMb: 1024,
memorySwapLimitMb: 512,
}),
/Memory-swap limit/,
);
});
test("container configuration errors expose safe actionable causes", () => {
assert.equal(
sanitizeContainerConfigurationError(
new Error(
"Command failed: Error response from daemon: Minimum memory limit allowed is 6MB",
),
),
"The memory limit is below the minimum supported by the Docker host.",
);
assert.equal(
sanitizeContainerConfigurationError(
new Error(
"Command failed: Memory limit should be smaller than already set memoryswap limit",
),
),
"Docker rejected the memory limit because it conflicts with the container's existing memory-swap limit.",
);
assert.equal(
sanitizeContainerConfigurationError(
new Error("Command failed: docker update --cpus 1 secret-container"),
),
"Failed to apply container configuration",
);
assert.equal(
sanitizeContainerConfigurationError(
new Error(
"Command failed: Error response from daemon: Cannot update container abcdef123456: runtime rejected the limit",
),
),
"Docker rejected the requested container configuration: Cannot update container [container]: runtime rejected the limit",
);
});
@@ -32,6 +32,23 @@ test("container detail runtime polling uses the lightweight metrics API", () =>
assert.doesNotMatch(refreshBlock, /containersApi\.details/);
});
test("overview hydrates Docker inspect and does not synthesize HTTP health", () => {
const source = readSource(CONTAINER_DETAIL_PAGE);
const hydrationBlock = sourceBlock(
source,
"if (!appDetailId) return;",
"if (!appDetailId || containerRecord?.status",
);
assert.match(
hydrationBlock,
/activeTab === "overview"[\s\S]*?hydrateRuntimeDetail/,
);
assert.doesNotMatch(source, /httpStatus:\s*"200"/);
assert.match(source, /httpStatus:\s*"Not probed"/);
assert.match(source, /health:\s*getDockerHealthSummary\(detail\.inspect\)/);
});
test("metrics endpoint does not call heavy Docker detail commands", () => {
const source = readSource(CONTAINER_ROUTES);
const metricsRouteBlock = sourceBlock(
@@ -0,0 +1,144 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const paths = {
api: "src/lib/api.ts",
capabilities: "src/server/services/container-capabilities.service.ts",
deploymentService: "src/server/services/deployment.service.ts",
routes: "src/server/routes/containers.ts",
environmentPage:
"src/app/projects/[projectId]/environments/[environmentId]/page.tsx",
environmentToolbar:
"src/app/projects/[projectId]/environments/[environmentId]/components/toolbar/EnvironmentContainersToolbar.tsx",
environmentTable:
"src/app/projects/[projectId]/environments/[environmentId]/components/containers/EnvironmentContainersTable.tsx",
detailPage:
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/page.tsx",
detailHeader:
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/components/header/AppDetailHeader.tsx",
actionConstants:
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/data/app-detail-constants.ts",
deploymentsPanel:
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/components/deployments/DeploymentsTabPanel.tsx",
configurationModal:
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/components/configuration/EditContainerConfigurationModal.tsx",
} as const;
function read(path: (typeof paths)[keyof typeof paths]) {
return readFileSync(path, "utf8");
}
test("container list and detail expose the same backend-derived capability contract", () => {
const routes = read(paths.routes);
const api = read(paths.api);
assert.ok(
(routes.match(/capabilities:\s*buildContainerCapabilities\(/g) ?? [])
.length >= 2,
"list and detail responses must both build capabilities",
);
assert.ok(
(routes.match(/const \{ deploymentSource, \.\.\.publicContainer \} = container;/g) ?? [])
.length >= 2,
"internal deployment source metadata must not be copied to public responses",
);
assert.match(routes, /hasDeploymentHistory:\s*Boolean\(deploymentSummary\?\.latestAttempt\)/);
assert.match(routes, /redeployAvailable:\s*deploymentSummary\?\.redeployAvailable \?\? false/);
assert.match(routes, /rollbackAvailable:\s*deploymentSummary\?\.rollbackAvailable \?\? false/);
assert.match(api, /capabilities\?: ContainerCapabilities/);
assert.match(api, /mode: "ORCHESTRATED_SINGLE_CONTAINER" \| "COMPOSE_RECREATE" \| null/);
});
test("redeploy capability belongs to the active eligible revision", () => {
const service = read(paths.deploymentService);
assert.match(
service,
/redeployAvailable:\s*rollbackEligibleRevisions\.some\(\s*\(revision\) => revision\.id === activeRevision\?\.id,?\s*\)/,
);
assert.match(
service,
/rollbackAvailable:\s*rollbackEligibleRevisions\.some\([\s\S]*?revision\.id !== activeRevision\?\.id/,
);
});
test("detail actions combine backend capability with frontend role gating", () => {
const detailPage = read(paths.detailPage);
const deploymentsPanel = read(paths.deploymentsPanel);
const detailHeader = read(paths.detailHeader);
assert.match(detailPage, /getRoleCapabilities\(currentUser\?\.role/);
assert.match(detailPage, /canMutateContainers/);
assert.match(detailPage, /capabilities\?\.editConfiguration\.available/);
assert.match(detailPage, /capabilities\?\.redeploy\.available/);
assert.match(detailPage, /capabilities\?\.rebuild\.available/);
assert.match(detailPage, /allowRollback=\{canMutateContainers\}/);
assert.match(deploymentsPanel, /allowRollback && deployment\.canRollback/);
assert.match(detailHeader, /menuActions\.length > 0/);
assert.match(detailHeader, /disabled=\{actionBusy \|\| action\.disabled\}/);
});
test("viewer cannot open environment mutation controls", () => {
const environmentPage = read(paths.environmentPage);
const toolbar = read(paths.environmentToolbar);
assert.match(environmentPage, /canManageContainers && showDeploy/);
assert.match(environmentPage, /canManageContainers && showDeployDatabase/);
assert.match(environmentPage, /canManageContainers && showImportFromSync/);
assert.match(environmentPage, /canManage=\{canManageContainers\}/);
assert.match(toolbar, /canManage: boolean/);
assert.match(toolbar, /\{canManage \? <div className="ui-toolbar-actions">/);
});
test("environment inventory distinguishes managed and imported containers", () => {
const capabilities = read(paths.capabilities);
const environmentPage = read(paths.environmentPage);
const environmentTable = read(paths.environmentTable);
const toolbar = read(paths.environmentToolbar);
assert.match(capabilities, /managementLabel: managed \? "Doktainer managed" : "Docker import"/);
assert.match(environmentPage, /container\.capabilities\?\.managementLabel \?\? "Docker import"/);
assert.match(environmentTable, /container\.managementLabel/);
assert.match(environmentTable, /className=\{`ui-badge/);
assert.match(
environmentPage,
/Existing deployment revision history was not modified/,
);
assert.match(toolbar, /deployment revision history is unchanged/);
});
test("Compose remains visibly outside safe single-container orchestration", () => {
const capabilities = read(paths.capabilities);
const detailPage = read(paths.detailPage);
assert.match(capabilities, /mode: composeManaged\s*\? "COMPOSE_RECREATE"\s*: "ORCHESTRATED_SINGLE_CONTAINER"/);
assert.match(capabilities, /must be edited through their Compose project/);
assert.match(detailPage, /label: "Rebuild Compose project"/);
assert.match(
detailPage,
/This is not a safe single-container candidate switch and service interruption may occur/,
);
});
test("configuration preview and header reuse established UI primitives", () => {
const modal = read(paths.configurationModal);
const header = read(paths.detailHeader);
const actions = read(paths.actionConstants);
const primaryActions = actions.slice(
actions.indexOf("export const primaryActions"),
actions.indexOf("export const headerActions"),
);
const headerActions = actions.slice(actions.indexOf("export const headerActions"));
assert.match(modal, /className="modal-close"/);
assert.match(modal, /className="input"/);
assert.match(modal, /className=\{`ui-badge/);
assert.match(modal, /require(?:s)? a separate runtime-replacement flow/);
assert.match(header, /const statusColor =/);
assert.match(header, /normalizedStatus === "ERROR"/);
assert.doesNotMatch(header, /app\.managementLabel/);
assert.match(primaryActions, /id: "edit"/);
assert.match(primaryActions, /label: "Edit configuration"/);
assert.doesNotMatch(headerActions, /id: "edit"/);
});
+100 -1
View File
@@ -1,6 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sanitizeDeploymentSnapshot } from "../../src/server/services/deployment.service";
import {
createConfigRevision,
sanitizeDeploymentEventMessage,
sanitizeDeploymentSnapshot,
toPublicDeploymentRecord,
} from "../../src/server/services/deployment.service";
import { isDeploymentRollbackAvailable } from "../../src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/data/deployments-data";
test("deployment snapshots redact sensitive configuration values", () => {
const snapshot = sanitizeDeploymentSnapshot({
@@ -19,4 +25,97 @@ test("deployment snapshots redact sensitive configuration values", () => {
assert.equal(snapshot.image, "nginx:latest");
});
test("config revision is stable across object key ordering and masks secrets", () => {
const first = createConfigRevision({
image: "example/app:1",
env: "APP_ENV=production\nAPI_TOKEN=secret",
});
const second = createConfigRevision({
env: "APP_ENV=production\nAPI_TOKEN=secret",
image: "example/app:1",
});
const changedSecret = createConfigRevision({
image: "example/app:1",
env: "APP_ENV=production\nAPI_TOKEN=replaced-secret",
});
assert.equal(first, second);
assert.notEqual(first, changedSecret);
assert.match(first, /^[a-f0-9]{64}$/);
});
test("deployment snapshots mask structured environment secrets", () => {
const snapshot = sanitizeDeploymentSnapshot({
envVars: [
{ key: "PUBLIC_URL", value: "https://example.test" },
{ key: "API_TOKEN", value: "plain-secret" },
],
}) as { envVars: Array<{ key: string; value: string }> };
assert.equal(snapshot.envVars[0]?.value, "https://example.test");
assert.equal(snapshot.envVars[1]?.value, "<redacted>");
});
test("persistent deployment event messages redact credentials", () => {
const message = sanitizeDeploymentEventMessage(
"Readiness failed: token=plain-secret authorization: Bearer abc.def",
);
assert.doesNotMatch(message, /plain-secret|abc\.def/);
assert.match(message, /REDACTED/);
});
test("deployment history exposes rollback capability without exposing ciphertext", () => {
const publicRecord = toPublicDeploymentRecord({
id: "deployment-1",
rollbackSnapshotEnc: "encrypted-secret-artifact",
});
const legacyRecord = toPublicDeploymentRecord({
id: "legacy-deployment",
rollbackSnapshotEnc: null,
});
assert.deepEqual(publicRecord, {
id: "deployment-1",
rollbackArtifactAvailable: true,
});
assert.deepEqual(legacyRecord, {
id: "legacy-deployment",
rollbackArtifactAvailable: false,
});
assert.equal("rollbackSnapshotEnc" in publicRecord, false);
});
test("legacy deployments without an encrypted artifact cannot offer rollback", () => {
const base = {
id: "deployment-1",
containerId: "container-1",
status: "SUCCESS" as const,
trigger: "MANUAL" as const,
version: "1.0.0",
commitSha: null,
branch: null,
image: "example/app:1.0.0",
imageDigest: null,
error: null,
startedAt: null,
completedAt: null,
createdAt: new Date().toISOString(),
user: null,
};
assert.equal(
isDeploymentRollbackAvailable({
...base,
rollbackArtifactAvailable: false,
}),
false,
);
assert.equal(
isDeploymentRollbackAvailable({
...base,
rollbackArtifactAvailable: true,
}),
true,
);
});
@@ -1,11 +1,16 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { toImmutableBuildImageTag } from "../../src/server/services/ssh-services/docker-containers";
const CONTAINER_ROUTES = "src/server/routes/containers.ts";
const APP_ROUTES = "src/server/routes/apps.ts";
const DOCKER_CONTAINERS =
"src/server/services/ssh-services/docker-containers.ts";
const APP_REBUILD_SERVICE =
"src/server/services/app-install-rebuild.service.ts";
const RUNTIME_ORCHESTRATOR =
"src/server/services/deployment-rollback.service.ts";
function readSource(path: string) {
return readFileSync(path, "utf8");
@@ -30,16 +35,29 @@ test("Git rebuild follows the deployment history lifecycle", () => {
);
const acquireIndex = rebuildRoute.indexOf("acquireDeploymentLock");
const runningIndex = rebuildRoute.indexOf('status: "RUNNING"');
const buildingIndex = rebuildRoute.indexOf('status: buildType === "COMPOSE" ? "RUNNING" : "BUILDING"');
const mutationIndex = rebuildRoute.indexOf("deployContainerFromGitSource");
const orchestrationIndex = rebuildRoute.indexOf(
"orchestratePreparedRuntimeReplacement",
);
const successIndex = rebuildRoute.indexOf('status: "SUCCESS"', mutationIndex);
assert.ok(acquireIndex >= 0);
assert.ok(runningIndex > acquireIndex);
assert.ok(mutationIndex > runningIndex);
assert.ok(buildingIndex > acquireIndex);
assert.ok(mutationIndex > buildingIndex);
assert.ok(orchestrationIndex > mutationIndex);
assert.ok(successIndex > mutationIndex);
assert.match(rebuildRoute, /startRuntime: buildType === "COMPOSE" \? undefined : false/);
assert.match(rebuildRoute, /immutableImageTag: buildType === "COMPOSE" \? undefined : true/);
assert.doesNotMatch(
rebuildRoute.slice(buildingIndex, mutationIndex),
/dockerAction\([^)]*,\s*"(?:stop|rm)"/,
);
assert.doesNotMatch(rebuildRoute, /waitForDeploymentHealth/);
assert.match(rebuildRoute, /status: "FAILED"/);
assert.match(
rebuildRoute,
/status: runtimePreserved \? "FAILED_ROLLED_BACK" : "FAILED"/,
);
assert.match(rebuildRoute, /releaseDeploymentLock/);
assert.match(rebuildRoute, /commitSha: gitDeploymentResult\.commitSha/);
assert.match(rebuildRoute, /imageDigest/);
@@ -80,6 +98,59 @@ test("Git deployment resolves and returns the cloned commit SHA", () => {
assert.match(gitDeployFunction, /git -C .* rev-parse HEAD/);
assert.match(gitDeployFunction, /commitSha: string/);
assert.match(gitDeployFunction, /commitSha,/);
assert.match(gitDeployFunction, /toImmutableBuildImageTag/);
assert.match(gitDeployFunction, /opts\.startRuntime === false/);
assert.match(gitDeployFunction, /preparedRuntime/);
});
test("Git rebuild image tags are immutable and preserve registry ports", () => {
assert.equal(
toImmutableBuildImageTag(
"registry.example.test:5000/team/app:latest",
"abcdef1234567890",
),
"registry.example.test:5000/team/app:git-abcdef123456",
);
assert.equal(
toImmutableBuildImageTag("team/app", "0123456789abcdef"),
"team/app:git-0123456789ab",
);
assert.throws(
() => toImmutableBuildImageTag("team/app:latest", "not-a-sha"),
/valid Git commit SHA/,
);
});
test("App Installer rebuild prepares an immutable image before orchestration", () => {
const source = readSource(APP_REBUILD_SERVICE);
const pullIndex = source.indexOf("dockerPullImage");
const immutableIndex = source.indexOf(
"The rebuilt image could not be resolved to an immutable Docker image ID",
);
const orchestrationIndex = source.indexOf(
"orchestratePreparedRuntimeReplacement",
immutableIndex,
);
assert.ok(pullIndex >= 0);
assert.ok(immutableIndex > pullIndex);
assert.ok(orchestrationIndex > immutableIndex);
assert.match(source, /status: "BUILDING"/);
assert.match(source, /status: runtimePreserved \? "FAILED_ROLLED_BACK" : "FAILED"/);
});
test("stored rollback and redeploy share the prepared runtime orchestrator", () => {
const source = readSource(RUNTIME_ORCHESTRATOR);
const storedRevision = sourceBlock(
source,
"async function deployStoredRevision",
"export async function rollbackContainerToDeployment",
);
assert.match(storedRevision, /resolveRuntimeReplacementPlan/);
assert.match(storedRevision, /orchestratePreparedRuntimeReplacement/);
assert.doesNotMatch(
storedRevision,
/input\.operation === "REDEPLOY"\s*&&\s*strategy/,
);
});
@@ -0,0 +1,67 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
publishedHttpReadinessCandidates,
waitForHttpReadiness,
} from "../../src/server/services/deployment-readiness.service";
const server = { id: "server-1" } as never;
test("published HTTP candidates normalize Docker host bindings", () => {
assert.deepEqual(
publishedHttpReadinessCandidates(
"8085:80,0.0.0.0:8085:80,[::]:8085:80,5353:53/udp",
),
["http://127.0.0.1:8085/"],
);
});
test("HTTP readiness accepts a reachable candidate endpoint", async () => {
let command = "";
const result = await waitForHttpReadiness(
{
server,
upstream: "http://127.0.0.1:49152",
hostHeader: "app.example.test",
timeoutMs: 1_000,
},
{
execStrict: async (_server, value) => {
command = value;
return "";
},
wait: async () => undefined,
},
);
assert.equal(result.ready, true);
assert.equal(result.attempts, 1);
assert.match(command, /Host: app\.example\.test/);
assert.match(command, /2\*\|3\*/);
assert.doesNotMatch(command, /4\*/);
});
test("HTTP readiness rejects non-IP and non-HTTP probe targets", async () => {
await assert.rejects(() =>
waitForHttpReadiness(
{ server, upstream: "https://example.com" },
{
execStrict: async () => "",
wait: async () => undefined,
},
),
);
await assert.rejects(() =>
waitForHttpReadiness(
{
server,
upstream: "http://127.0.0.1:49152",
hostHeader: "invalid host",
},
{
execStrict: async () => "",
wait: async () => undefined,
},
),
);
});
@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
const routes = readFileSync("src/server/routes/containers.ts", "utf8");
const environmentPage = readFileSync(
"src/app/projects/[projectId]/environments/[environmentId]/page.tsx",
"utf8",
);
const containerDetailPage = readFileSync(
"src/app/projects/[projectId]/environments/[environmentId]/containers/[containerId]/page.tsx",
"utf8",
);
test("container routes expose persistent deployment state and logs", () => {
assert.match(routes, /"\/:id\/deployment-state"/);
assert.match(routes, /getDeploymentState/);
assert.match(routes, /"\/:id\/deployments\/:deploymentId\/logs"/);
assert.match(routes, /listDeploymentEvents/);
});
test("container list and detail expose the same persistent revision summary", () => {
assert.match(routes, /getContainerDeploymentSummaries/);
assert.match(routes, /deploymentSummary/);
assert.match(environmentPage, /const deployment = container\.deploymentSummary/);
assert.match(environmentPage, /deployment\?\.activeRevision/);
assert.match(containerDetailPage, /deploymentSummary\?\.activeRevision/);
assert.doesNotMatch(environmentPage, /lastDeployed:\s*formatDateTime\(container\.createdAt\)/);
assert.doesNotMatch(containerDetailPage, /lastDeployed:\s*formatDateTime\(container\.createdAt\)/);
});
test("deployment reconnect endpoints use container read authorization", () => {
const stateStart = routes.indexOf('"/:id/deployment-state"');
const logsStart = routes.indexOf('"/:id/deployments/:deploymentId/logs"');
assert.ok(stateStart >= 0);
assert.ok(logsStart >= 0);
assert.match(routes.slice(stateStart, stateStart + 180), /containerReadAccess/);
assert.match(routes.slice(logsStart, logsStart + 220), /containerReadAccess/);
});
+9 -2
View File
@@ -22,6 +22,11 @@ test("deployment migrations include the history and rollback schema", () => {
assert.ok(migrations.some((name) => name.includes("add_deployment_history")));
assert.ok(migrations.some((name) => name.includes("add_deployment_rollback_snapshot")));
assert.ok(migrations.some((name) => name.includes("add_deployment_locks")));
assert.ok(
migrations.some((name) =>
name.includes("add_deployment_revision_lifecycle"),
),
);
assert.equal(
migrations.some((name) =>
/deployment_attempt|process_job|service_lease|deployment_health_policy/.test(
@@ -33,10 +38,12 @@ test("deployment migrations include the history and rollback schema", () => {
const schema = readFileSync(join(process.cwd(), "prisma", "schema.prisma"), "utf8");
assert.match(schema, /model Deployment\s*\{/);
assert.match(schema, /model DeploymentEvent\s*\{/);
assert.match(schema, /rollbackSnapshotEnc\s+String\?/);
assert.match(schema, /idempotencyKey\s+String\?/);
assert.match(schema, /configRevision\s+String\?/);
assert.match(schema, /FAILED_ROLLED_BACK/);
assert.doesNotMatch(schema, /model DeploymentAttempt\s*\{/);
assert.doesNotMatch(schema, /model ProcessJob\s*\{/);
assert.doesNotMatch(schema, /model ServiceLease\s*\{/);
});
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";
import { selectDeploymentArtifactRetention } from "../../src/server/services/deployment-retention.service";
function revision(
id: string,
status: "ACTIVE" | "SUPERSEDED" | "SUCCESS" | "FAILED" | "BUILDING",
day: number,
previousDeploymentId?: string,
) {
return {
id,
status,
createdAt: new Date(`2026-08-${String(day).padStart(2, "0")}T00:00:00Z`),
previousDeploymentId,
};
}
test("deployment retention keeps active, previous, and three successful revisions", () => {
const result = selectDeploymentArtifactRetention([
revision("active", "ACTIVE", 10, "previous"),
revision("previous", "SUPERSEDED", 9),
revision("third", "SUCCESS", 8),
revision("old", "SUCCESS", 7),
revision("failed", "FAILED", 11),
]);
assert.deepEqual(
new Set(result.retainedArtifactIds),
new Set(["active", "previous", "third"]),
);
assert.deepEqual(result.cleanupEligibleArtifactIds, ["old"]);
});
test("deployment retention never marks an in-progress artifact for cleanup", () => {
const result = selectDeploymentArtifactRetention([
revision("building", "BUILDING", 12),
revision("active", "ACTIVE", 11),
revision("old", "SUCCESS", 5),
], 1);
assert.ok(result.retainedArtifactIds.includes("building"));
assert.ok(!result.cleanupEligibleArtifactIds.includes("building"));
});
@@ -1,8 +1,11 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildCandidatePortMappings,
normalizeRollbackPortMappings,
replaceRuntimeForRollback,
replaceRuntimeWithProxyCandidate,
resolveDirectRuntimeReadiness,
resolveRollbackImageReference,
RollbackRuntimeError,
} from "../../src/server/services/deployment-rollback.service";
@@ -11,6 +14,10 @@ type RollbackInput = Parameters<typeof replaceRuntimeForRollback>[0];
type RollbackDependencies = NonNullable<
Parameters<typeof replaceRuntimeForRollback>[1]
>;
type SafeSwitchInput = Parameters<typeof replaceRuntimeWithProxyCandidate>[0];
type SafeSwitchDependencies = NonNullable<
Parameters<typeof replaceRuntimeWithProxyCandidate>[1]
>;
const server = {} as RollbackInput["server"];
@@ -27,6 +34,13 @@ test("normalizes Docker display port mappings for rollback", () => {
);
});
test("candidate ports use random loopback bindings without claiming production ports", () => {
assert.equal(
buildCandidatePortMappings("8080:80,8443:443,9000:90/udp", [80, 3000]),
"127.0.0.1::80,127.0.0.1::443,127.0.0.1::90/udp,127.0.0.1::3000",
);
});
test("uses a locally available Docker image ID without creating an invalid registry reference", async () => {
const inspected: string[] = [];
const pulled: string[] = [];
@@ -83,6 +97,9 @@ function runtime(overrides: Partial<RollbackInput["targetRuntime"]> = {}) {
env: "APP_ENV=production",
volumes: "/data:/data",
network: "bridge",
networks: ["bridge"],
cpuLimit: 1.5,
memoryLimitMb: 512,
restartPolicy: "unless-stopped",
command: "",
...overrides,
@@ -96,6 +113,10 @@ function dependencies(
runContainer: async () => "new-container-id",
stopAndRemoveContainer: async () => undefined,
dockerRename: async () => undefined,
dockerConnectNetwork: async () => undefined,
dockerInspect: async () => ({
Config: { Healthcheck: { Test: ["CMD", "true"] } },
}),
waitForDockerHealth: async () => ({
healthy: true,
reason: "running",
@@ -103,10 +124,52 @@ function dependencies(
attempts: 1,
durationMs: 0,
}),
waitForHttpReadiness: async () => ({
ready: true,
reason: "ready",
attempts: 1,
durationMs: 0,
}),
findReachablePublishedHttpUpstream: async () => ({
upstream: "http://127.0.0.1:8080/",
result: {
ready: true,
reason: "ready",
attempts: 1,
durationMs: 0,
},
}),
...overrides,
};
}
test("direct readiness falls back to a proven published HTTP endpoint", async () => {
const readiness = await resolveDirectRuntimeReadiness(
{
server,
runtime: runtime({ ports: "8080:80" }),
},
{
dockerInspect: async () => ({ Config: {} }),
findReachablePublishedHttpUpstream: async () => ({
upstream: "http://127.0.0.1:8080/",
result: {
ready: true,
reason: "ready",
attempts: 1,
durationMs: 0,
},
}),
},
);
assert.equal(readiness.mode, "PUBLISHED_HTTP");
assert.equal(
readiness.mode === "PUBLISHED_HTTP" ? readiness.upstream : null,
"http://127.0.0.1:8080/",
);
});
test("published-port rollback removes the active runtime before claiming its name and host port", async () => {
const events: string[] = [];
@@ -167,6 +230,7 @@ test("failed published-port rollback recreates and verifies the previous runtime
previousRuntime: runtime({
image: "example/app:previous",
ports: "8080:80",
networks: ["bridge", "recovery-net"],
}),
},
dependencies({
@@ -178,6 +242,9 @@ test("failed published-port rollback recreates and verifies the previous runtime
events.push(`run:${options.image}`);
return runCount === 1 ? "failed-target-id" : "recovered-container-id";
},
dockerConnectNetwork: async (_server, containerRef, network) => {
events.push(`network:${containerRef}:${network}`);
},
waitForDockerHealth: async ({ containerRef }) => {
events.push(`runtime-check:${containerRef}`);
if (containerRef === "failed-target-id") {
@@ -213,10 +280,165 @@ test("failed published-port rollback recreates and verifies the previous runtime
"runtime-check:failed-target-id",
"remove:failed-target-id,app-rollback,app",
"run:example/app:previous",
"network:recovered-container-id:recovery-net",
"runtime-check:recovered-container-id",
]);
});
test("published-port replacement without a healthcheck is blocked before the active runtime is touched", async () => {
const events: string[] = [];
await assert.rejects(
replaceRuntimeForRollback(
{
server,
containerName: "app",
currentContainerRefs: ["old-container-id", "app"],
temporaryName: "app-redeploy",
strategy: "RECREATE_WITH_RECOVERY",
targetRuntime: runtime({ ports: "8080:80" }),
previousRuntime: runtime({
image: "example/app:previous",
ports: "8080:80",
}),
},
dependencies({
dockerInspect: async () => ({ Config: {} }),
findReachablePublishedHttpUpstream: async () => null,
stopAndRemoveContainer: async () => {
events.push("remove");
},
runContainer: async () => {
events.push("run");
return "unexpected-container";
},
}),
),
/requires a Docker healthcheck/,
);
assert.deepEqual(events, []);
});
test("published HTTP readiness validates a recreated runtime without Docker healthcheck", async () => {
const events: string[] = [];
await replaceRuntimeForRollback(
{
server,
containerName: "app",
currentContainerRefs: ["old-container-id", "app"],
temporaryName: "app-redeploy",
strategy: "RECREATE_WITH_RECOVERY",
targetRuntime: runtime({ ports: "8080:80" }),
previousRuntime: runtime({
image: "example/app:previous",
ports: "8080:80",
}),
},
dependencies({
dockerInspect: async () => ({ Config: {} }),
stopAndRemoveContainer: async (_server, refs) => {
events.push(`remove:${refs.join(",")}`);
},
runContainer: async () => {
events.push("run");
return "new-container-id";
},
waitForDockerHealth: async () => ({
healthy: false,
reason: "running without Docker healthcheck",
status: "running_unverified",
attempts: 1,
durationMs: 0,
}),
waitForHttpReadiness: async ({ upstream }) => {
events.push(`http:${upstream}`);
return {
ready: true,
reason: "HTTP 302",
attempts: 1,
durationMs: 0,
};
},
}),
);
assert.deepEqual(events, [
"remove:old-container-id,app",
"run",
"http:http://127.0.0.1:8080/",
]);
});
test("failed published HTTP readiness recreates the previous runtime", async () => {
const events: string[] = [];
let runCount = 0;
await assert.rejects(
replaceRuntimeForRollback(
{
server,
containerName: "app",
currentContainerRefs: ["old-container-id", "app"],
temporaryName: "app-redeploy",
strategy: "RECREATE_WITH_RECOVERY",
targetRuntime: runtime({ ports: "8080:80" }),
previousRuntime: runtime({
image: "example/app:previous",
ports: "8080:80",
}),
},
dependencies({
dockerInspect: async () => ({ Config: {} }),
stopAndRemoveContainer: async (_server, refs) => {
events.push(`remove:${refs.join(",")}`);
},
runContainer: async (_server, options) => {
runCount += 1;
events.push(`run:${options.image}`);
return runCount === 1 ? "failed-target-id" : "recovered-id";
},
waitForDockerHealth: async ({ containerRef }) => {
events.push(`runtime:${containerRef}`);
return {
healthy: false,
reason: "running without Docker healthcheck",
status: "running_unverified",
attempts: 1,
durationMs: 0,
};
},
waitForHttpReadiness: async () => {
events.push("http:failed");
return {
ready: false,
reason: "HTTP readiness timed out",
attempts: 3,
durationMs: 3_000,
};
},
}),
),
(error: unknown) => {
assert.ok(error instanceof RollbackRuntimeError);
assert.equal(error.recoveryMode, "RECREATED");
assert.equal(error.recoveryDockerId, "recovered-id");
return true;
},
);
assert.deepEqual(events, [
"remove:old-container-id,app",
"run:example/app:target",
"runtime:failed-target-id",
"http:failed",
"remove:failed-target-id,app-redeploy,app",
"run:example/app:previous",
"runtime:recovered-id",
]);
});
test("failed atomic candidate leaves the active runtime in place", async () => {
const removedRefs: string[][] = [];
let runCount = 0;
@@ -272,4 +494,270 @@ test("failed atomic candidate leaves the active runtime in place", async () => {
assert.deepEqual(removedRefs, [["failed-target-id", "app-rollback"]]);
});
test("proxy candidate is ready before traffic switches and the previous runtime is removed", async () => {
const events: string[] = [];
let runCount = 0;
const input: SafeSwitchInput = {
server,
containerId: "container-1",
containerName: "app",
currentContainerRefs: ["old-id", "app"],
temporaryName: "app-redeploy",
targetRuntime: runtime({
ports: "8080:80",
volumes: "",
networks: ["bridge", "private-app"],
}),
previousRuntime: runtime({
image: "example/app:previous",
ports: "8080:80",
volumes: "",
}),
domains: [
{
name: "app.example.test",
proxy: "NGINX",
configMode: "ISOLATED",
sslEnabled: true,
targetPort: 80,
},
],
deploymentId: "deployment-1",
finalize: async ({ dockerId }) => {
events.push(`finalize:${dockerId}`);
return dockerId;
},
};
const deps: SafeSwitchDependencies = {
runContainer: async (_server, options) => {
runCount += 1;
assert.equal(options.cpuLimit, 1.5);
assert.equal(options.memoryLimitMb, 512);
events.push(`run:${options.name}:${options.ports}`);
return runCount === 1 ? "candidate-id" : "final-id";
},
stopAndRemoveContainer: async (_server, refs) => {
events.push(`remove:${refs.join(",")}`);
},
dockerRename: async () => undefined,
dockerConnectNetwork: async (_server, containerRef, network) => {
events.push(`network:${containerRef}:${network}`);
},
dockerInspect: async () => ({}),
waitForDockerHealth: async ({ containerRef }) => {
events.push(`docker-ready:${containerRef}`);
return {
healthy: false,
reason: "running without Docker healthcheck",
status: "running_unverified",
attempts: 1,
durationMs: 0,
};
},
resolveContainerUpstream: async (_server, container) => ({
upstream:
container.dockerId === "candidate-id"
? "http://127.0.0.1:49152"
: "http://127.0.0.1:8080",
selectedPort: 80,
}),
waitForHttpReadiness: async ({ upstream, hostHeader }) => {
events.push(`http-ready:${upstream}:${hostHeader}`);
return {
ready: true,
reason: "ready",
attempts: 1,
durationMs: 0,
};
},
findReachablePublishedHttpUpstream: async () => null,
provisionDomainProxyConfig: async ({ container }) => {
events.push(`proxy:${container.dockerId}`);
return { upstream: "", configPath: "", reloadTarget: "nginx" };
},
updateDeployment: async (_id, patch) => {
events.push(`deployment:${patch.status}`);
return {} as never;
},
};
const result = await replaceRuntimeWithProxyCandidate(input, deps);
assert.equal(result.result, "final-id");
assert.deepEqual(events, [
"run:app-redeploy:127.0.0.1::80",
"network:candidate-id:private-app",
"deployment:VALIDATING",
"docker-ready:candidate-id",
"http-ready:http://127.0.0.1:49152:app.example.test",
"deployment:SWITCHING",
"proxy:candidate-id",
"remove:old-id,app",
"run:app:8080:80",
"network:final-id:private-app",
"docker-ready:final-id",
"http-ready:http://127.0.0.1:8080:app.example.test",
"proxy:final-id",
"remove:candidate-id,app-redeploy",
"finalize:final-id",
]);
});
test("failed candidate readiness leaves the previous runtime and proxy untouched", async () => {
const removed: string[][] = [];
let proxyWrites = 0;
await assert.rejects(
replaceRuntimeWithProxyCandidate(
{
server,
containerId: "container-1",
containerName: "app",
currentContainerRefs: ["old-id", "app"],
temporaryName: "app-redeploy",
targetRuntime: runtime({ ports: "8080:80", volumes: "" }),
previousRuntime: runtime({ ports: "8080:80", volumes: "" }),
domains: [
{
name: "app.example.test",
proxy: "NGINX",
configMode: "ISOLATED",
sslEnabled: false,
targetPort: 80,
},
],
deploymentId: "deployment-1",
finalize: async () => undefined,
},
{
runContainer: async () => "candidate-id",
stopAndRemoveContainer: async (_server, refs) => {
removed.push(refs);
},
dockerRename: async () => undefined,
dockerConnectNetwork: async () => undefined,
dockerInspect: async () => ({}),
waitForDockerHealth: async () => ({
healthy: true,
reason: "running",
status: "healthy",
attempts: 1,
durationMs: 0,
}),
resolveContainerUpstream: async () => ({
upstream: "http://127.0.0.1:49152",
selectedPort: 80,
}),
waitForHttpReadiness: async () => ({
ready: false,
reason: "HTTP timeout",
attempts: 3,
durationMs: 20_000,
}),
findReachablePublishedHttpUpstream: async () => null,
provisionDomainProxyConfig: async () => {
proxyWrites += 1;
return { upstream: "", configPath: "", reloadTarget: "nginx" };
},
updateDeployment: async () => ({} as never),
},
),
(error: unknown) => {
assert.ok(error instanceof RollbackRuntimeError);
assert.equal(error.recoveryMode, "UNCHANGED");
return true;
},
);
assert.equal(proxyWrites, 0);
assert.deepEqual(removed, [["candidate-id", "app-redeploy"]]);
});
test("partial proxy switch is restored before a failed candidate is removed", async () => {
const proxyTargets: string[] = [];
const removed: string[][] = [];
let candidateProxyWrites = 0;
await assert.rejects(
replaceRuntimeWithProxyCandidate(
{
server,
containerId: "container-1",
containerName: "app",
currentContainerRefs: ["old-id", "app"],
temporaryName: "app-redeploy",
targetRuntime: runtime({ ports: "8080:80", volumes: "" }),
previousRuntime: runtime({ ports: "8080:80", volumes: "" }),
domains: [
{
name: "one.example.test",
proxy: "NGINX",
configMode: "ISOLATED",
sslEnabled: false,
targetPort: 80,
},
{
name: "two.example.test",
proxy: "NGINX",
configMode: "ISOLATED",
sslEnabled: false,
targetPort: 80,
},
],
deploymentId: "deployment-1",
finalize: async () => undefined,
},
{
runContainer: async () => "candidate-id",
stopAndRemoveContainer: async (_server, refs) => {
removed.push(refs);
},
dockerRename: async () => undefined,
dockerConnectNetwork: async () => undefined,
dockerInspect: async () => ({}),
waitForDockerHealth: async () => ({
healthy: true,
reason: "running",
status: "healthy",
attempts: 1,
durationMs: 0,
}),
resolveContainerUpstream: async () => ({
upstream: "http://127.0.0.1:49152",
selectedPort: 80,
}),
waitForHttpReadiness: async () => ({
ready: true,
reason: "ready",
attempts: 1,
durationMs: 0,
}),
findReachablePublishedHttpUpstream: async () => null,
provisionDomainProxyConfig: async ({ container }) => {
proxyTargets.push(container.dockerId ?? container.name);
if (container.dockerId === "candidate-id") {
candidateProxyWrites += 1;
if (candidateProxyWrites === 2) {
throw new Error("second proxy reload failed");
}
}
return { upstream: "", configPath: "", reloadTarget: "nginx" };
},
updateDeployment: async () => ({} as never),
},
),
(error: unknown) => {
assert.ok(error instanceof RollbackRuntimeError);
assert.equal(error.recoveryMode, "UNCHANGED");
return true;
},
);
assert.deepEqual(proxyTargets, [
"candidate-id",
"candidate-id",
"old-id",
"old-id",
]);
assert.deepEqual(removed, [["candidate-id", "app-redeploy"]]);
});
+17 -1
View File
@@ -125,7 +125,7 @@ test("deployment and rollback boundaries use the centralized sanitizer before pe
assert.match(
rollbackService,
/const message = sanitizeDeploymentError\(error,[\s\S]*?updateDeployment\(rollback\.id,[\s\S]*?error: message/,
/const message = sanitizeDeploymentError\(error,[\s\S]*?updateDeployment\(deployment\.id,[\s\S]*?error: message/,
);
assert.match(
containerRoutes,
@@ -138,3 +138,19 @@ test("deployment and rollback boundaries use the centralized sanitizer before pe
assert.match(containerHealth, /lastReason = sanitizeDeploymentError\(error/);
});
test("internal Docker inspect output is muted from streamed process-job logs", () => {
const dockerContainers = readFileSync(
"src/server/services/ssh-services/docker-containers.ts",
"utf8",
);
const commands = readFileSync(
"src/server/services/ssh-services/commands.ts",
"utf8",
);
assert.match(commands, /export function withMutedCommandLog/);
assert.match(
dockerContainers,
/dockerInspect[\s\S]*?withMutedCommandLog\(\(\) =>[\s\S]*?docker inspect/,
);
});
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
assertDeploymentTransition,
canTransitionDeployment,
isRollbackEligibleDeployment,
} from "../../src/server/services/deployment-state-machine";
test("deployment state machine supports the candidate validation lifecycle", () => {
assert.equal(canTransitionDeployment("QUEUED", "BUILDING"), true);
assert.equal(canTransitionDeployment("BUILDING", "VALIDATING"), true);
assert.equal(canTransitionDeployment("VALIDATING", "SWITCHING"), true);
assert.equal(canTransitionDeployment("SWITCHING", "ACTIVE"), true);
assert.equal(canTransitionDeployment("ACTIVE", "SUPERSEDED"), true);
});
test("deployment state machine preserves legacy running-success transitions", () => {
assert.equal(canTransitionDeployment("RUNNING", "SUCCESS"), true);
assert.equal(canTransitionDeployment("RUNNING", "FAILED"), true);
});
test("deployment state machine rejects transitions out of terminal failures", () => {
assert.equal(canTransitionDeployment("FAILED", "ACTIVE"), false);
assert.throws(
() => assertDeploymentTransition("FAILED_ROLLED_BACK", "SWITCHING"),
/Invalid deployment transition/,
);
});
test("only successful revision states are rollback eligible", () => {
assert.equal(isRollbackEligibleDeployment("ACTIVE"), true);
assert.equal(isRollbackEligibleDeployment("SUCCESS"), true);
assert.equal(isRollbackEligibleDeployment("SUPERSEDED"), true);
assert.equal(isRollbackEligibleDeployment("FAILED"), false);
assert.equal(isRollbackEligibleDeployment("FAILED_ROLLED_BACK"), false);
});
+95 -1
View File
@@ -1,8 +1,25 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { resolveDeploymentStrategy } from "../../src/server/services/deployment-strategy";
import {
resolveDeploymentStrategy,
resolveSafeRedeployStrategy,
} from "../../src/server/services/deployment-strategy";
import { buildDockerRunCommand } from "../../src/server/services/ssh-services/docker-containers";
describe("deployment strategy", () => {
it("preserves CPU and memory limits in Docker run commands", () => {
const command = buildDockerRunCommand({
name: "app",
image: "example/app:stable",
restartPolicy: "unless-stopped",
cpuLimit: 1.5,
memoryLimitMb: 512,
});
assert.match(command, /'--cpus' '1\.5'/);
assert.match(command, /'--memory' '512m'/);
});
it("uses atomic rename when no published ports are configured", () => {
assert.equal(resolveDeploymentStrategy(""), "ATOMIC_RENAME");
assert.equal(resolveDeploymentStrategy(" "), "ATOMIC_RENAME");
@@ -13,4 +30,81 @@ describe("deployment strategy", () => {
});
});
describe("safe redeploy strategy", () => {
it("allows Docker to allocate candidate ports on loopback only", () => {
const command = buildDockerRunCommand({
name: "app-candidate",
image: "example/app:revision",
ports: "127.0.0.1::80",
restartPolicy: "unless-stopped",
});
assert.match(command, /127\.0\.0\.1::80/);
assert.throws(() =>
buildDockerRunCommand({
name: "unsafe-candidate",
image: "example/app:revision",
ports: "0.0.0.0::80",
restartPolicy: "unless-stopped",
}),
);
});
it("uses a proxy candidate for isolated managed domains", () => {
assert.deepEqual(
resolveSafeRedeployStrategy({
ports: "8080:80",
volumes: "",
domains: [
{ proxy: "NGINX", configMode: "ISOLATED", targetPort: 80 },
],
}),
{
strategy: "PROXY_CANDIDATE_SWITCH",
proxyTrafficContinuous: true,
directPortInterruptionPossible: true,
reason:
"Managed isolated proxies can switch to a validated candidate before the previous runtime is removed.",
},
);
});
it("keeps an honest direct-port fallback when a shared proxy cannot switch", () => {
const plan = resolveSafeRedeployStrategy({
ports: "8080:80",
volumes: "",
domains: [
{ proxy: "NGINX", configMode: "SHARED", targetPort: 80 },
],
});
assert.equal(plan.strategy, "RECREATE_WITH_RECOVERY");
assert.equal(plan.proxyTrafficContinuous, false);
assert.equal(plan.directPortInterruptionPossible, true);
});
it("blocks an internal-IP rename when a linked proxy cannot be switched", () => {
const plan = resolveSafeRedeployStrategy({
ports: "",
volumes: "",
domains: [
{ proxy: "NGINX", configMode: "SHARED", targetPort: 80 },
],
});
assert.equal(plan.strategy, "BLOCKED_UNSUPPORTED_PROXY");
});
it("does not overlap a candidate with a persistent volume", () => {
const plan = resolveSafeRedeployStrategy({
ports: "8080:80",
volumes: "app-data:/data",
domains: [
{ proxy: "NGINX", configMode: "ISOLATED", targetPort: 80 },
],
});
assert.equal(plan.strategy, "RECREATE_WITH_RECOVERY");
assert.match(plan.reason, /persistent storage/);
});
});
+2 -1
View File
@@ -7,8 +7,9 @@ import {
writeCachedPageData,
storeServerSelection,
} from "../src/lib/page-state";
import { sensitiveStorageKeys } from "../src/lib/browser-storage";
const ORGANIZATION_STORAGE_KEY = "vps_active_organization";
const ORGANIZATION_STORAGE_KEY = sensitiveStorageKeys.organization;
class MemoryStorage implements Storage {
private store = new Map<string, string>();