416 lines
19 KiB
TypeScript
416 lines
19 KiB
TypeScript
import { useEffect, useMemo, useState } from 'react';
|
|
import { ChevronLeft, ChevronRight, MoreHorizontal, Play } from 'lucide-react';
|
|
import { Button, Card, CardHeader, Modal } from '../../components/ui';
|
|
import { useToast } from '../../components/toast';
|
|
import { PageTitle } from '../../layout/AppLayout';
|
|
import type { AppRelease, RuntimeControlJob } from '../../types/application';
|
|
import { LoadingModal, useMinimumLoading } from '../operations/operation-utils';
|
|
import { StatusBadge, formatDate, useApps } from './ApplicationControls';
|
|
import { createMigration, listMigrationsPage, listReleases } from './application-api';
|
|
|
|
type ImageTags = {
|
|
images?: Record<string, string>;
|
|
artifacts?: Record<string, string>;
|
|
};
|
|
|
|
function imageMap(imageTags: unknown) {
|
|
if (!imageTags || typeof imageTags !== 'object') return {};
|
|
const tags = imageTags as ImageTags;
|
|
return tags.images ?? tags.artifacts ?? {};
|
|
}
|
|
|
|
function imageEntries(imageTags: unknown) {
|
|
return Object.entries(imageMap(imageTags));
|
|
}
|
|
|
|
function selectedImageTag(release: AppRelease | undefined, imageName: string) {
|
|
if (!release || !imageName) return '-';
|
|
return imageMap(release.imageTags)[imageName] ?? '-';
|
|
}
|
|
|
|
function requestText(job: RuntimeControlJob, key: string, fallback = '-') {
|
|
const value = job.request?.[key];
|
|
return typeof value === 'string' && value.trim() ? value : fallback;
|
|
}
|
|
|
|
function sanitizeK8sName(value: string) {
|
|
return value
|
|
.trim()
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9-]+/g, '-')
|
|
.replace(/^-+|-+$/g, '');
|
|
}
|
|
|
|
function uniqueValues(values: string[]) {
|
|
return [...new Set(values.filter(Boolean))];
|
|
}
|
|
|
|
const migrationPageSize = 3;
|
|
type MigrationRange = 'week' | 'month' | 'all';
|
|
|
|
const migrationRangeLabels: Record<MigrationRange, string> = {
|
|
week: '일주일',
|
|
month: '한달',
|
|
all: '전체'
|
|
};
|
|
|
|
function migrationRangeSince(range: MigrationRange) {
|
|
if (range === 'all') return undefined;
|
|
const date = new Date();
|
|
date.setDate(date.getDate() - (range === 'week' ? 7 : 30));
|
|
return date.toISOString();
|
|
}
|
|
|
|
export function MigrationManagementPage() {
|
|
const { apps, selectedApp, selectedAppId, selectApp, loading: appsLoading } = useApps();
|
|
const { toast } = useToast();
|
|
const [jobs, setJobs] = useState<RuntimeControlJob[]>([]);
|
|
const [releases, setReleases] = useState<AppRelease[]>([]);
|
|
const [releaseId, setReleaseId] = useState('');
|
|
const [migrationComponentId, setMigrationComponentId] = useState('');
|
|
const [imageComponentName, setImageComponentName] = useState('');
|
|
const [namespace, setNamespace] = useState('');
|
|
const [command, setCommand] = useState('npx prisma migrate deploy --schema=prisma/schema.prisma');
|
|
const [envSecretName, setEnvSecretName] = useState('');
|
|
const [selectedJob, setSelectedJob] = useState<RuntimeControlJob | null>(null);
|
|
const [confirmOpen, setConfirmOpen] = useState(false);
|
|
const [loading, setLoading] = useState(false);
|
|
const [runningMigration, setRunningMigration] = useState(false);
|
|
const [page, setPage] = useState(1);
|
|
const [range, setRange] = useState<MigrationRange>('week');
|
|
const [totalJobs, setTotalJobs] = useState(0);
|
|
const loadingVisible = useMinimumLoading(appsLoading || loading);
|
|
|
|
const selectedRelease = releases.find((release) => release.id === releaseId);
|
|
const migrationComponents = selectedApp?.components?.filter((component) => component.type === 'MIGRATION') ?? [];
|
|
const images = imageEntries(selectedRelease?.imageTags);
|
|
const namespaceOptions = useMemo(
|
|
() => uniqueValues([selectedApp?.namespace || '', namespace]),
|
|
[namespace, selectedApp?.namespace]
|
|
);
|
|
const envSecretOptions = useMemo(
|
|
() => uniqueValues([
|
|
...images.map(([name]) => `${sanitizeK8sName(name)}-secret`),
|
|
`${sanitizeK8sName(selectedApp?.key ?? 'app')}-be-secret`,
|
|
envSecretName
|
|
]),
|
|
[envSecretName, images, selectedApp?.key]
|
|
);
|
|
const selectedImage = selectedImageTag(selectedRelease, imageComponentName);
|
|
const totalPages = Math.max(1, Math.ceil(totalJobs / migrationPageSize));
|
|
const currentPage = page;
|
|
const pagedJobs = jobs;
|
|
|
|
const refresh = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const [nextJobs, nextReleases] = await Promise.all([
|
|
listMigrationsPage({
|
|
appId: selectedAppId,
|
|
page,
|
|
limit: migrationPageSize,
|
|
since: migrationRangeSince(range)
|
|
}),
|
|
listReleases(selectedApp?.key)
|
|
]);
|
|
const succeededReleases = nextReleases.filter((release) => release.status === 'SUCCEEDED');
|
|
setJobs(nextJobs.jobs);
|
|
setTotalJobs(nextJobs.total);
|
|
setReleases(succeededReleases);
|
|
setReleaseId((prev) => (succeededReleases.some((release) => release.id === prev) ? prev : succeededReleases[0]?.id || ''));
|
|
setNamespace((prev) => prev || selectedApp?.namespace || '');
|
|
setMigrationComponentId((prev) => (
|
|
migrationComponents.some((component) => component.id === prev) ? prev : migrationComponents[0]?.id || ''
|
|
));
|
|
setEnvSecretName((prev) => prev || `${sanitizeK8sName(selectedApp?.key ?? 'app')}-be-secret`);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
void refresh();
|
|
}, [selectedApp?.key, selectedApp?.namespace, selectedAppId, page, range]);
|
|
|
|
useEffect(() => {
|
|
const nextImages = imageEntries(selectedRelease?.imageTags);
|
|
setImageComponentName((prev) => (nextImages.some(([name]) => name === prev) ? prev : nextImages[0]?.[0] || ''));
|
|
}, [selectedRelease?.id]);
|
|
|
|
useEffect(() => {
|
|
if (imageComponentName) setEnvSecretName(`${sanitizeK8sName(imageComponentName)}-secret`);
|
|
}, [imageComponentName]);
|
|
|
|
useEffect(() => {
|
|
setNamespace(selectedApp?.namespace || '');
|
|
setMigrationComponentId(migrationComponents[0]?.id || '');
|
|
setEnvSecretName(`${sanitizeK8sName(selectedApp?.key ?? 'app')}-be-secret`);
|
|
setPage(1);
|
|
}, [selectedAppId]);
|
|
|
|
useEffect(() => {
|
|
setPage(1);
|
|
}, [range]);
|
|
|
|
const runMigration = async () => {
|
|
if (runningMigration) return;
|
|
setRunningMigration(true);
|
|
try {
|
|
setConfirmOpen(false);
|
|
const result = await createMigration({ releaseId, migrationComponentId, imageComponentName, namespace, command, envSecretName });
|
|
toast({ type: 'success', message: '마이그레이션 작업이 실행되었습니다.' });
|
|
setSelectedJob(result.migrationJob);
|
|
await refresh();
|
|
} catch (error) {
|
|
toast({ type: 'error', message: error instanceof Error ? error.message : '마이그레이션 실행에 실패했습니다.' });
|
|
} finally {
|
|
setRunningMigration(false);
|
|
}
|
|
};
|
|
|
|
const canRun = Boolean(releaseId && migrationComponentId && imageComponentName && namespace && envSecretName && command.trim());
|
|
|
|
return (
|
|
<>
|
|
<PageTitle
|
|
eyebrow="어플리케이션"
|
|
title="마이그레이션"
|
|
description="마이그레이션 구성요소를 선택하고 릴리즈 기준으로 데이터 변경 작업을 실행합니다."
|
|
actions={(
|
|
<Button disabled={!canRun || loading} onClick={() => setConfirmOpen(true)}>
|
|
<Play className="size-4" />
|
|
실행
|
|
</Button>
|
|
)}
|
|
/>
|
|
|
|
<Card className="mb-4">
|
|
<div className="grid gap-4 p-5 lg:grid-cols-3">
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">앱</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={selectedAppId}
|
|
disabled={appsLoading || apps.length === 0}
|
|
onChange={(event) => selectApp(event.target.value)}
|
|
>
|
|
{apps.length === 0 ? <option value="">등록된 앱 없음</option> : null}
|
|
{apps.map((app) => <option key={app.id} value={app.id}>{app.name}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">릴리즈</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={releaseId}
|
|
onChange={(event) => setReleaseId(event.target.value)}
|
|
>
|
|
{releases.length === 0 ? <option value="">릴리즈 없음</option> : null}
|
|
{releases.map((release) => <option key={release.id} value={release.id}>{release.version}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">마이그레이션 구성요소</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={migrationComponentId}
|
|
onChange={(event) => setMigrationComponentId(event.target.value)}
|
|
>
|
|
{migrationComponents.length === 0 ? <option value="">구성요소 없음</option> : null}
|
|
{migrationComponents.map((component) => <option key={component.id} value={component.id}>{component.name}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">실행 이미지</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={imageComponentName}
|
|
onChange={(event) => setImageComponentName(event.target.value)}
|
|
>
|
|
{images.length === 0 ? <option value="">이미지 없음</option> : null}
|
|
{images.map(([name]) => <option key={name} value={name}>{name}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">네임스페이스</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={namespace}
|
|
onChange={(event) => setNamespace(event.target.value)}
|
|
>
|
|
{namespaceOptions.length === 0 ? <option value="">네임스페이스 없음</option> : null}
|
|
{namespaceOptions.map((item) => <option key={item} value={item}>{item}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block">
|
|
<span className="text-xs font-medium text-muted-foreground">envFrom Secret</span>
|
|
<select
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={envSecretName}
|
|
onChange={(event) => setEnvSecretName(event.target.value)}
|
|
>
|
|
{envSecretOptions.length === 0 ? <option value="">Secret 없음</option> : null}
|
|
{envSecretOptions.map((item) => <option key={item} value={item}>{item}</option>)}
|
|
</select>
|
|
</label>
|
|
<label className="block lg:col-span-3">
|
|
<span className="text-xs font-medium text-muted-foreground">명령</span>
|
|
<input
|
|
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 font-mono text-xs text-foreground outline-none focus:ring-2 focus:ring-ring"
|
|
value={command}
|
|
onChange={(event) => setCommand(event.target.value)}
|
|
/>
|
|
</label>
|
|
<div className="rounded-md border border-border bg-muted/20 p-4 lg:col-span-3">
|
|
<p className="text-xs font-medium text-muted-foreground">선택 이미지</p>
|
|
<p className="mt-2 break-all font-mono text-sm font-medium text-foreground">{selectedImage}</p>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Card className="min-w-0 overflow-hidden">
|
|
<CardHeader
|
|
title="마이그레이션 작업"
|
|
description="선택한 기간의 마이그레이션 실행 이력과 로그를 최신순으로 표시합니다."
|
|
action={
|
|
<div className="flex items-center gap-2">
|
|
{(Object.keys(migrationRangeLabels) as MigrationRange[]).map((item) => (
|
|
<Button
|
|
key={item}
|
|
variant={range === item ? 'default' : 'outline'}
|
|
className="h-8 px-3 text-[13px]"
|
|
onClick={() => setRange(item)}
|
|
>
|
|
{migrationRangeLabels[item]}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
}
|
|
/>
|
|
|
|
<div className="min-h-[410px] space-y-3 p-5">
|
|
{!loading && jobs.length === 0 ? (
|
|
<div className="flex min-h-44 items-center justify-center text-center text-sm text-muted-foreground">
|
|
등록된 마이그레이션 작업이 없습니다.
|
|
</div>
|
|
) : pagedJobs.map((job, index) => {
|
|
const releaseVersion = requestText(job, 'releaseVersion');
|
|
const imageName = requestText(job, 'imageComponentName', requestText(job, 'image'));
|
|
const commandText = requestText(job, 'command', command);
|
|
|
|
return (
|
|
<div key={job.id} className="rounded-md border border-border bg-background/70 p-4">
|
|
<div className="flex items-start justify-between gap-4">
|
|
<div className="min-w-0 flex-1">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<span className="text-xs font-medium text-muted-foreground">No. {totalJobs - ((currentPage - 1) * migrationPageSize + index)}</span>
|
|
<StatusBadge status={job.status} />
|
|
<span className="truncate text-base font-medium text-foreground">
|
|
{selectedApp?.name ?? '앱'} {job.name}
|
|
</span>
|
|
</div>
|
|
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs">
|
|
<span className="text-muted-foreground">릴리즈 <b className="text-foreground">{releaseVersion}</b></span>
|
|
<span className="text-muted-foreground">네임스페이스 <b className="text-foreground">{job.namespace}</b></span>
|
|
<span className="text-muted-foreground">이미지 <b className="text-foreground">{imageName}</b></span>
|
|
<span className="text-muted-foreground">시작 <b className="text-foreground">{formatDate(job.startedAt || job.createdAt)}</b></span>
|
|
</div>
|
|
</div>
|
|
<Button variant="outline" className="size-8 shrink-0 px-0" onClick={() => setSelectedJob(job)} title="로그" aria-label="로그">
|
|
<MoreHorizontal className="size-4" />
|
|
</Button>
|
|
</div>
|
|
<div className="mt-3 rounded-md border border-border bg-card p-3">
|
|
<p className="text-xs text-muted-foreground">명령</p>
|
|
<p className="mt-2 break-all font-mono text-xs text-foreground">{commandText}</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
<div className="flex items-center justify-between gap-4 border-t border-border px-5 py-3 text-sm">
|
|
<span className="text-xs text-muted-foreground">
|
|
{loading ? '불러오는 중' : `총 ${totalJobs}건 · ${currentPage} / ${totalPages}`}
|
|
</span>
|
|
<div className="flex gap-2">
|
|
<Button
|
|
variant="outline"
|
|
className="h-8 px-3 text-[13px]"
|
|
disabled={currentPage <= 1}
|
|
onClick={() => setPage((prev) => Math.max(1, prev - 1))}
|
|
>
|
|
<ChevronLeft className="size-4" />
|
|
이전
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
className="h-8 px-3 text-[13px]"
|
|
disabled={currentPage >= totalPages}
|
|
onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))}
|
|
>
|
|
다음
|
|
<ChevronRight className="size-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<Modal open={Boolean(selectedJob)} title="마이그레이션 로그" onClose={() => setSelectedJob(null)} className="log-modal-shell">
|
|
{selectedJob?.logs ? (
|
|
<pre className="whitespace-pre-wrap rounded-md border border-border bg-background p-4 font-mono text-xs leading-5 text-muted-foreground">
|
|
{selectedJob.logs}
|
|
</pre>
|
|
) : (
|
|
<div className="flex min-h-44 items-center justify-center text-center text-sm text-muted-foreground">
|
|
작업을 선택하면 로그가 표시됩니다.
|
|
</div>
|
|
)}
|
|
</Modal>
|
|
<Modal
|
|
open={confirmOpen}
|
|
title="마이그레이션 실행"
|
|
onClose={() => {
|
|
if (!runningMigration) setConfirmOpen(false);
|
|
}}
|
|
footer={(
|
|
<>
|
|
<Button variant="outline" disabled={runningMigration} onClick={() => setConfirmOpen(false)}>취소</Button>
|
|
<Button disabled={!canRun || loading || runningMigration} onClick={runMigration}>{runningMigration ? '실행 중' : '실행'}</Button>
|
|
</>
|
|
)}
|
|
>
|
|
<div className="space-y-4 text-sm">
|
|
<p className="text-muted-foreground">
|
|
선택한 릴리즈 기준으로 데이터베이스 변경 작업을 실행합니다. 적용 전 대상 정보를 확인하세요.
|
|
</p>
|
|
<div className="rounded-md border border-border bg-background/70 p-4">
|
|
<div className="grid gap-3 text-xs md:grid-cols-2">
|
|
<div>
|
|
<p className="text-muted-foreground">앱</p>
|
|
<p className="mt-1 font-medium text-foreground">{selectedApp?.name ?? '-'}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-muted-foreground">릴리즈</p>
|
|
<p className="mt-1 font-medium text-foreground">{selectedRelease?.version ?? '-'}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-muted-foreground">네임스페이스</p>
|
|
<p className="mt-1 font-medium text-foreground">{namespace || '-'}</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-muted-foreground">이미지</p>
|
|
<p className="mt-1 break-all font-mono font-medium text-foreground">{selectedImage}</p>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4">
|
|
<p className="text-xs text-muted-foreground">명령</p>
|
|
<p className="mt-1 break-all font-mono text-xs font-medium text-foreground">{command}</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
<LoadingModal open={loadingVisible} />
|
|
</>
|
|
);
|
|
}
|