Files
studio-admin-fe/src/pages/launcher/LauncherBuildPage.tsx
T
chyoo a48055bf65
ci/woodpecker/push/woodpecker Pipeline was successful
improve launcher history and runtime config UX
2026-07-07 09:43:18 +09:00

524 lines
23 KiB
TypeScript

import { ChevronLeft, ChevronRight, MoreHorizontal, Play, Plus, RotateCcw, Trash2 } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Badge, Button, Card, CardHeader, Modal } from '../../components/ui';
import { useToast } from '../../components/toast';
import { PageTitle } from '../../layout/AppLayout';
import { formatDateTime } from '../../lib/date-format';
import { LoadingModal, useMinimumLoading } from '../operations/operation-utils';
import {
createLauncherBuildJob,
getLauncherSource,
listLauncherBuildEnv,
listLauncherBuildJobs,
listLauncherBuildJobsPage,
listLauncherVersions,
saveLauncherBuildEnv,
type LauncherSource,
type LauncherBuildJob,
type LauncherBuildEnvVariable,
type LauncherVersion
} from './launcher-api';
const r2PublicBaseUrl = import.meta.env.VITE_R2_PUBLIC_BASE_URL ?? '';
const r2ArtifactPrefix = import.meta.env.VITE_R2_ARTIFACT_PREFIX ?? 'studio-artifacts';
function formatDate(value: string) {
return formatDateTime(value);
}
function statusText(status: LauncherBuildJob['status']) {
if (status === 'SUCCEEDED') return '성공';
if (status === 'RUNNING') return '실행 중';
if (status === 'PENDING') return '대기';
if (status === 'FAILED') return '실패';
if (status === 'CANCELED') return '취소';
return status;
}
function statusTone(status: LauncherBuildJob['status']): 'neutral' | 'green' | 'amber' | 'red' | 'blue' {
if (status === 'SUCCEEDED') return 'green';
if (status === 'RUNNING') return 'blue';
if (status === 'PENDING') return 'amber';
if (status === 'FAILED') return 'red';
return 'neutral';
}
function jobTime(job: LauncherBuildJob) {
const value = new Date(job.createdAt || job.startedAt || job.finishedAt || 0).getTime();
return Number.isNaN(value) ? 0 : value;
}
const launcherBuildJobPageSize = 5;
type BuildTarget = 'launcher-client' | 'launcher-backend';
type BuildRange = 'week' | 'month' | 'all';
const buildRangeLabels: Record<BuildRange, string> = {
week: '일주일',
month: '한달',
all: '전체'
};
function buildRangeSince(range: BuildRange) {
if (range === 'all') return undefined;
const date = new Date();
date.setDate(date.getDate() - (range === 'week' ? 7 : 30));
return date.toISOString();
}
function sanitizeObjectKeyPart(value: string) {
return value
.trim()
.replace(/^\/+|\/+$/g, '')
.replace(/[^a-zA-Z0-9._@+=-]+/g, '-')
|| 'unknown';
}
function encodeObjectKey(key: string) {
return key.split('/').map(encodeURIComponent).join('/');
}
function launcherArtifactKey(version: string, branch: string, commitSha: string, artifactName: string) {
const revision = commitSha.trim().slice(0, 7) || 'latest';
return [
r2ArtifactPrefix,
'launcher',
version || '0.0.0',
branch || 'release',
revision,
artifactName,
].map(sanitizeObjectKeyPart).join('/');
}
export function LauncherBuildPage() {
const { toast } = useToast();
const [target, setTarget] = useState<BuildTarget>('launcher-client');
const [versions, setVersions] = useState<LauncherVersion[]>([]);
const [source, setSource] = useState<LauncherSource | null>(null);
const [version, setVersion] = useState('');
const [branch, setBranch] = useState('release');
const [commitSha, setCommitSha] = useState('');
const [jobs, setJobs] = useState<LauncherBuildJob[]>([]);
const [buildEnv, setBuildEnv] = useState<LauncherBuildEnvVariable[]>([]);
const [buildEnvSaving, setBuildEnvSaving] = useState(false);
const [selectedJob, setSelectedJob] = useState<LauncherBuildJob | null>(null);
const [confirmOpen, setConfirmOpen] = useState(false);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [range, setRange] = useState<BuildRange>('week');
const [totalJobs, setTotalJobs] = useState(0);
const loadingVisible = useMinimumLoading(loading);
const activeVersion = useMemo(() => versions.find((item) => item.isActive) ?? versions[0], [versions]);
const isBackend = target === 'launcher-backend';
const backendSource = source?.backend;
const clientSource = source?.client;
const artifactName = `autonomy-studio-launcher-${version || activeVersion?.version || '0.0.0'}.deb`;
const backendImageName = backendSource?.image || 'localhost:5000/studio-launcher-be';
const backendDockerfile = backendSource?.dockerfile || 'Dockerfile';
const uploadPath = launcherArtifactKey(version || activeVersion?.version || '0.0.0', branch, commitSha, artifactName);
const downloadUrl = r2PublicBaseUrl ? `${r2PublicBaseUrl.replace(/\/$/, '')}/${encodeObjectKey(uploadPath)}` : '백엔드 R2 설정 기준으로 생성됩니다.';
const currentPage = page;
const totalPages = Math.max(1, Math.ceil(totalJobs / launcherBuildJobPageSize));
const pagedJobs = jobs;
const hasActiveJob = jobs.some((job) => job.status === 'PENDING' || job.status === 'RUNNING');
const loadBuildJobs = (nextPage = page, nextTarget = target, nextRange = range) => (
listLauncherBuildJobsPage({
target: nextTarget,
page: nextPage,
limit: launcherBuildJobPageSize,
since: buildRangeSince(nextRange)
}).then((result) => {
setJobs(result.jobs);
setTotalJobs(result.total);
})
);
const refresh = () => {
setLoading(true);
Promise.all([
listLauncherVersions(),
listLauncherBuildJobsPage({
target,
page,
limit: launcherBuildJobPageSize,
since: buildRangeSince(range)
}),
getLauncherSource(),
listLauncherBuildEnv()
])
.then(([nextVersions, nextJobs, nextSource, nextBuildEnv]) => {
setVersions(nextVersions);
setJobs(nextJobs.jobs);
setTotalJobs(nextJobs.total);
setSource(nextSource.source);
setBuildEnv(nextBuildEnv.variables ?? []);
const nextVersion = nextVersions.find((item) => item.isActive) ?? nextVersions[0];
setVersion(nextVersion?.version ?? '');
setBranch('release');
setCommitSha(target === 'launcher-backend' ? nextSource.source.backend?.commitSha ?? '' : nextSource.source.client?.commitSha ?? nextVersion?.commitSha ?? '');
})
.catch((error: Error) => {
toast({ type: 'error', title: '런처 버전 조회 실패', message: error.message });
})
.finally(() => setLoading(false));
};
useEffect(() => {
refresh();
}, []);
useEffect(() => {
setPage(1);
}, [target, range]);
useEffect(() => {
loadBuildJobs().catch((error: Error) => {
setJobs([]);
setTotalJobs(0);
toast({ type: 'error', title: '빌드 작업 조회 실패', message: error.message });
});
}, [target, page, range]);
useEffect(() => {
if (!source) return;
if (target === 'launcher-backend') {
setBranch('release');
setCommitSha(source.backend?.commitSha ?? '');
return;
}
setBranch('release');
setCommitSha(source.client?.commitSha ?? activeVersion?.commitSha ?? '');
}, [activeVersion?.branch, activeVersion?.commitSha, source, target]);
useEffect(() => {
if (!hasActiveJob) return;
const timer = window.setInterval(() => {
loadBuildJobs()
.catch((error: Error) => {
toast({ type: 'error', title: '빌드 작업 갱신 실패', message: error.message });
});
}, 2000);
return () => window.clearInterval(timer);
}, [hasActiveJob, toast, target, page, range]);
useEffect(() => {
if (!selectedJob) return;
const nextSelectedJob = jobs.find((job) => job.id === selectedJob.id);
if (nextSelectedJob && nextSelectedJob !== selectedJob) {
setSelectedJob(nextSelectedJob);
}
}, [jobs, selectedJob]);
const createJob = () => {
setConfirmOpen(false);
setLoading(true);
createLauncherBuildJob({
target,
repository: isBackend ? backendSource?.repository ?? undefined : clientSource?.repository ?? activeVersion?.repository ?? undefined,
branch,
commitSha: commitSha.trim() || undefined,
version: undefined,
uploadPath: isBackend ? backendDockerfile : uploadPath,
artifact: isBackend ? backendImageName.replace(/^localhost:5000\//, '') : undefined,
downloadUrl: isBackend ? undefined : r2PublicBaseUrl ? downloadUrl : undefined
})
.then(({ job }) => {
setPage(1);
setRange('week');
setJobs((prev) => [job, ...prev].slice(0, launcherBuildJobPageSize));
setTotalJobs((prev) => prev + 1);
setSelectedJob(job);
toast({ type: 'success', title: '빌드 작업', message: '런처 빌드 작업이 생성되었습니다.' });
})
.catch((error: Error) => {
toast({ type: 'error', title: '빌드 작업 실패', message: error.message });
})
.finally(() => setLoading(false));
};
const updateBuildEnv = (index: number, patch: Partial<LauncherBuildEnvVariable>) => {
setBuildEnv((prev) => prev.map((variable, variableIndex) => (
variableIndex === index ? { ...variable, ...patch } : variable
)));
};
const removeBuildEnv = (index: number) => {
setBuildEnv((prev) => prev.filter((_, variableIndex) => variableIndex !== index));
};
const persistBuildEnv = () => {
setBuildEnvSaving(true);
saveLauncherBuildEnv(
buildEnv
.map((variable) => ({ ...variable, key: variable.key.trim() }))
.filter((variable) => variable.key)
)
.then((result) => {
setBuildEnv(result.variables ?? []);
toast({ type: 'success', title: '빌드 환경변수 저장', message: '런처 클라이언트 빌드 환경변수를 저장했습니다.' });
})
.catch((error: Error) => {
toast({ type: 'error', title: '빌드 환경변수 저장 실패', message: error.message });
})
.finally(() => setBuildEnvSaving(false));
};
return (
<>
<PageTitle
eyebrow="런처 운영"
title="빌드 관리"
description="런처 클라이언트 설치 파일과 백엔드 컨테이너 이미지를 구성요소별로 빌드합니다."
actions={
<div className="flex items-center gap-2">
<Button variant="outline" className="h-8 px-3 text-[13px]" onClick={refresh} disabled={loading}>
<RotateCcw className={loading ? 'size-4 animate-spin' : 'size-4'} />
새로고침
</Button>
<Button className="h-8 px-3 text-[13px]" onClick={() => setConfirmOpen(true)}>
<Play className="size-4" />
실행
</Button>
</div>
}
/>
<div className="mb-4 flex flex-wrap gap-2">
<Button variant={target === 'launcher-client' ? 'default' : 'outline'} onClick={() => setTarget('launcher-client')}>
클라이언트
</Button>
<Button variant={target === 'launcher-backend' ? 'default' : 'outline'} onClick={() => setTarget('launcher-backend')}>
백엔드
</Button>
</div>
<div className="grid gap-4 xl:grid-cols-[420px_minmax(0,1fr)]">
<Card className="min-w-0 overflow-hidden">
<CardHeader title="빌드 요청" description={isBackend ? '브랜치와 커밋 기준으로 런처 백엔드 이미지를 빌드하고 레지스트리에 푸시합니다.' : '브랜치와 커밋 기준으로 런처 설치 파일을 생성합니다.'} />
<div className="space-y-4 p-5">
<div className="rounded-md border border-border bg-muted/20 px-3 py-2">
<p className="text-xs font-medium text-muted-foreground">버전</p>
<p className="mt-1 text-sm font-medium text-foreground">빌드 후 package.json 기준으로 자동 확정</p>
</div>
<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={branch} onChange={(event) => setBranch(event.target.value)}>
<option value="develop">develop</option>
<option value="release">release</option>
<option value="main">main</option>
</select>
</label>
<label className="block">
<span className="text-xs font-medium text-muted-foreground">Commit SHA</span>
<input className="mt-2 h-9 w-full rounded-md border border-input bg-background px-3 font-mono text-sm text-foreground outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-ring" value={commitSha} onChange={(event) => setCommitSha(event.target.value)} placeholder="비워두면 브랜치 최신 커밋" />
</label>
{isBackend ? (
<div className="rounded-md border border-border bg-background p-3">
<p className="text-xs text-muted-foreground">이미지 이름</p>
<p className="mt-2 break-all font-mono text-xs text-foreground">{backendImageName}</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">태그는 빌드 후 package.json 버전으로 자동 확정됩니다.</p>
<p className="mt-2 text-xs text-muted-foreground">Repository</p>
<p className="mt-1 break-all font-mono text-xs text-foreground">{backendSource?.repository || '-'}</p>
</div>
) : (
<div className="rounded-md border border-border bg-background p-3">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-xs font-medium text-foreground">클라이언트 빌드 환경변수</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">저장 후 실행한 빌드부터 반영됩니다.</p>
</div>
<Button variant="outline" className="h-8 px-3 text-[13px]" onClick={persistBuildEnv} disabled={buildEnvSaving}>
{buildEnvSaving ? '저장 중' : '저장'}
</Button>
</div>
<div className="mt-3 space-y-2">
{buildEnv.map((variable, index) => (
<div key={`${variable.key}-${index}`} className="grid gap-2 md:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)_auto]">
<input
className="h-9 rounded-md border border-input bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"
value={variable.key}
onChange={(event) => updateBuildEnv(index, { key: event.target.value })}
placeholder="VITE_ATNMY_STDO_API_BASE_URL"
/>
<input
className="h-9 rounded-md border border-input bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"
value={variable.value}
onChange={(event) => updateBuildEnv(index, { value: event.target.value })}
placeholder="https://portal-api.autonomystudio.net"
/>
<Button variant="outline" className="size-9 px-0" title="삭제" aria-label="삭제" onClick={() => removeBuildEnv(index)}>
<Trash2 className="size-4" />
</Button>
</div>
))}
{buildEnv.length === 0 ? <p className="rounded-md border border-dashed border-border px-3 py-4 text-center text-xs text-muted-foreground">등록된 빌드 환경변수가 없습니다.</p> : null}
</div>
<Button
variant="outline"
className="mt-3 h-8 px-3 text-[13px]"
onClick={() => setBuildEnv((prev) => [...prev, { key: '', value: '', isSecret: false }])}
>
<Plus className="size-4" />
추가
</Button>
</div>
)}
</div>
</Card>
<Card className="min-w-0 overflow-hidden">
<CardHeader
title="빌드 작업 목록"
description={isBackend ? '런처 백엔드 이미지 빌드 작업입니다.' : '생성된 런처 클라이언트 빌드 작업과 업로드 계획입니다.'}
action={
<div className="flex items-center gap-2">
{(Object.keys(buildRangeLabels) as BuildRange[]).map((item) => (
<Button
key={item}
variant={range === item ? 'default' : 'outline'}
className="h-8 px-3 text-[13px]"
onClick={() => setRange(item)}
>
{buildRangeLabels[item]}
</Button>
))}
</div>
}
/>
<div className="min-h-[638px] space-y-3 p-4">
{jobs.length === 0 ? (
<div className="flex min-h-44 items-center justify-center text-center text-sm text-muted-foreground">
빌드 작업이 없습니다.
</div>
) : null}
{pagedJobs.map((job, index) => (
<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">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-muted-foreground">No. {(currentPage - 1) * launcherBuildJobPageSize + index + 1}</span>
<Badge tone={statusTone(job.status)}>{statusText(job.status)}</Badge>
<span className="font-medium">{job.target}</span>
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span>브랜치 <b className="text-foreground">{job.branch}</b></span>
<span>커밋 <b className="font-mono text-foreground">{job.commitSha || '-'}</b></span>
<span>생성 <b className="text-foreground">{formatDate(job.createdAt)}</b></span>
</div>
</div>
<Button variant="outline" className="size-8 px-0" title="로그" aria-label="로그" onClick={() => setSelectedJob(job)}>
<MoreHorizontal className="size-4" />
</Button>
</div>
<div className="mt-3 grid gap-3 rounded-md border border-border bg-card px-3 py-2 text-xs md:grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)]">
<div className="min-w-0">
<p className="text-muted-foreground">산출물</p>
<p className="mt-1 truncate font-mono font-medium">{job.artifact}</p>
</div>
<div className="min-w-0">
<p className="text-muted-foreground">다운로드 URL</p>
<p className="mt-1 truncate font-mono font-medium">{job.downloadUrl || '-'}</p>
</div>
<div className="min-w-0 md:col-span-2">
<p className="text-muted-foreground">R2 Object Key</p>
<p className="mt-1 truncate font-mono font-medium">{job.uploadPath}</p>
</div>
</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>
</div>
<Modal
open={Boolean(selectedJob)}
title="런처 빌드 로그"
onClose={() => setSelectedJob(null)}
className="log-modal-shell"
footer={<Button variant="outline" onClick={() => setSelectedJob(null)}>닫기</Button>}
>
<pre className="whitespace-pre-wrap bg-background p-4 font-mono text-xs leading-6 text-muted-foreground">
{selectedJob?.logs || '작업을 선택하면 로그가 표시됩니다.'}
</pre>
</Modal>
<Modal
open={confirmOpen}
title="빌드 실행 확인"
onClose={() => setConfirmOpen(false)}
footer={
<>
<Button variant="outline" onClick={() => setConfirmOpen(false)}>취소</Button>
<Button onClick={createJob} disabled={loading}>
<Play className="size-4" />
실행
</Button>
</>
}
>
<div className="space-y-3 text-sm">
<div className="rounded-md border border-border bg-muted/20 px-4 py-3">
<p className="font-medium">{isBackend ? '런처 백엔드 이미지 빌드' : '런처 클라이언트 설치 파일 빌드'}를 실행합니다.</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">
실행 후 빌드 작업이 생성되고, 작업 목록에서 진행 상태와 로그를 확인할 수 있습니다.
</p>
</div>
<div className="grid gap-2 rounded-md border border-border bg-background p-4">
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">대상</span>
<span className="font-medium">{isBackend ? '백엔드' : '클라이언트'}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">저장소</span>
<span className="truncate font-medium">
{isBackend ? backendSource?.repository || '-' : clientSource?.repository || activeVersion?.repository || '-'}
</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">브랜치</span>
<span className="font-medium">{branch}</span>
</div>
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">커밋</span>
<span className="font-mono text-xs font-medium">{commitSha.trim() || '브랜치 최신'}</span>
</div>
{isBackend ? (
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">이미지 이름</span>
<span className="truncate font-mono text-xs font-medium">{backendImageName}</span>
</div>
) : null}
</div>
</div>
</Modal>
<LoadingModal open={loadingVisible} />
</>
);
}