Skip to content
This repository was archived by the owner on Jun 26, 2026. It is now read-only.

Commit 81c97aa

Browse files
committed
fix(backup): several fixes around backup-pages
Signed-off-by: Andrey Kolkov <[email protected]>
1 parent 4de877e commit 81c97aa

9 files changed

Lines changed: 382 additions & 471 deletions

‎apps/console/src/components/BackupClassWidget.tsx‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,34 @@ export function BackupClassWidget(props: WidgetProps) {
1919
})
2020

2121
const backupClasses = classList?.items || []
22+
const currentValue = typeof value === "string" ? value : ""
23+
const hasCurrentInList = backupClasses.some((bc) => bc.metadata.name === currentValue)
2224

2325
return (
2426
<select
25-
value={value || ""}
27+
value={currentValue}
2628
onChange={(e) => onChange(e.target.value || undefined)}
27-
disabled={disabled || readonly || isLoading}
29+
disabled={disabled || readonly}
2830
required={required}
2931
className="w-full rounded-lg border border-slate-300 bg-white pl-3 pr-8 py-2 text-sm text-slate-900 outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400 disabled:opacity-50 disabled:cursor-not-allowed"
3032
>
3133
{!required && <option value="">-- None --</option>}
32-
{isLoading ? (
33-
<option value="">Loading...</option>
34-
) : backupClasses.length === 0 ? (
34+
{/* Render the parent's value as a stable option even when the list is
35+
still loading or the value isn't present in the loaded results. This
36+
keeps the controlled <select> from losing the parent's selection on
37+
async re-renders of useK8sList (loading → loaded → refetch). */}
38+
{currentValue && !hasCurrentInList && (
39+
<option value={currentValue}>{currentValue}</option>
40+
)}
41+
{backupClasses.map((bc) => (
42+
<option key={bc.metadata.name} value={bc.metadata.name}>
43+
{bc.metadata.name}
44+
</option>
45+
))}
46+
{!isLoading && backupClasses.length === 0 && !currentValue && (
3547
<option value="" disabled>
3648
No backup classes available
3749
</option>
38-
) : (
39-
backupClasses.map((bc) => (
40-
<option key={bc.metadata.name} value={bc.metadata.name}>
41-
{bc.metadata.name}
42-
</option>
43-
))
4450
)}
4551
</select>
4652
)

‎apps/console/src/components/SchemaForm.tsx‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,14 @@ function addBackupClassWidgets(schema: RJSFSchema, uiSchema: UiSchema = {}): UiS
5151

5252
for (const [key, value] of Object.entries(properties)) {
5353
if (key === "backupClassName" && typeof value === "object" && (value as any).type === "string") {
54+
// Skip attaching the custom widget when an explicit enum is already
55+
// present — the parent supplies the option list, RJSF's native
56+
// SelectWidget handles binding correctly. Auto-attaching here would
57+
// override the select with our BackupClassWidget whose internal
58+
// useK8sList state can drop the user's selection on async re-renders.
59+
if (Array.isArray((value as any).enum)) {
60+
continue
61+
}
5462
// Found a backupClassName field - add widget
5563
result[key] = {
5664
...result[key],
@@ -169,18 +177,21 @@ export function SchemaForm({
169177

170178
const onChangeRef = useRef(onChange)
171179
onChangeRef.current = onChange
172-
const initialFormDataRef = useRef(formData)
180+
const formDataRef = useRef(formData)
181+
formDataRef.current = formData
173182
const emittedSchemaRef = useRef<RJSFSchema | null>(null)
174183

175184
// Emit defaults to parent once per schema so spec is never empty on first submit.
176-
// Uses initialFormDataRef so edit-mode existing values are preserved as base.
177-
// emittedSchemaRef prevents re-running on unrelated re-renders and avoids
178-
// overwriting user data if the schema object changes identity unexpectedly.
185+
// Uses formDataRef (current parent state, not the initial mount snapshot) so
186+
// user input is preserved when the parent recomputes openAPISchema due to
187+
// async sibling data (e.g. plansData/backupClassesData loading) — without
188+
// this, getDefaultFormState would re-emit defaults computed from the stale
189+
// initial formData and wipe whatever the user already typed.
179190
useEffect(() => {
180191
if (!schema || Object.keys(schema).length === 0) return
181192
if (emittedSchemaRef.current === schema) return
182193
emittedSchemaRef.current = schema
183-
const defaults = getDefaultFormState(validator, schema, initialFormDataRef.current ?? {}, schema)
194+
const defaults = getDefaultFormState(validator, schema, formDataRef.current ?? {}, schema)
184195
onChangeRef.current(defaults)
185196
// eslint-disable-next-line react-hooks/exhaustive-deps
186197
}, [schema])
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
import { useState, useMemo } from "react"
2+
import { useNavigate } from "react-router"
3+
import { Archive, Save } from "lucide-react"
4+
import { Button, Section, Spinner } from "@cozystack/ui"
5+
import { useK8sCreate, useK8sList } from "@cozystack/k8s-client"
6+
import { useTenantContext } from "../lib/tenant-context.tsx"
7+
import { useApplicationDefinitions } from "../lib/app-definitions.ts"
8+
import { useCRDSchema } from "../lib/use-crd-schema.ts"
9+
import { SchemaForm } from "../components/SchemaForm.tsx"
10+
import { enrichSchemaWithEnums } from "../lib/backup-utils.ts"
11+
12+
export function BackupJobCreatePage() {
13+
const navigate = useNavigate()
14+
const { tenantNamespace } = useTenantContext()
15+
const { data: appDefs } = useApplicationDefinitions()
16+
const [formData, setFormData] = useState<any>({})
17+
const [name, setName] = useState("")
18+
19+
// Get base schema from CRD
20+
const { schema: baseSchema, isLoading: schemaLoading } = useCRDSchema(
21+
"backupjobs.backups.cozystack.io"
22+
)
23+
24+
// Get BackupClasses (cluster-scoped)
25+
const { data: backupClassesData } = useK8sList<any>({
26+
apiGroup: "backups.cozystack.io",
27+
apiVersion: "v1alpha1",
28+
plural: "backupclasses",
29+
})
30+
31+
// Get Plans in the tenant namespace (optional reference)
32+
const { data: plansData } = useK8sList<any>({
33+
apiGroup: "backups.cozystack.io",
34+
apiVersion: "v1alpha1",
35+
plural: "plans",
36+
namespace: tenantNamespace ?? "",
37+
}, { enabled: !!tenantNamespace })
38+
39+
// Resolve instances for the selected application kind.
40+
// Mirrors BackupRestoreJobCreatePage: kind dropdown is gated to
41+
// apps.cozystack.io (the only apiGroup ApplicationDefinitions cover).
42+
// Strict undefined check so an explicit empty string from the user means
43+
// "no group" — clearing the field opts out of the cozystack defaults.
44+
const selectedKind = formData?.applicationRef?.kind
45+
const rawApiGroup = formData?.applicationRef?.apiGroup
46+
const selectedApiGroup = rawApiGroup === undefined ? "apps.cozystack.io" : rawApiGroup
47+
const selectedAppDef = useMemo(
48+
() => appDefs?.items.find(d => d.spec?.application.kind === selectedKind),
49+
[appDefs, selectedKind]
50+
)
51+
52+
const { data: instancesData } = useK8sList<any>({
53+
apiGroup: "apps.cozystack.io",
54+
apiVersion: "v1alpha1",
55+
plural: selectedAppDef?.spec?.application.plural ?? "",
56+
namespace: tenantNamespace ?? "",
57+
}, { enabled: !!selectedAppDef && !!tenantNamespace && selectedApiGroup === "apps.cozystack.io" })
58+
59+
const createMutation = useK8sCreate({
60+
apiGroup: "backups.cozystack.io",
61+
apiVersion: "v1alpha1",
62+
plural: "backupjobs",
63+
namespace: tenantNamespace ?? "",
64+
})
65+
66+
const schema = useMemo(() => {
67+
if (!baseSchema) return null
68+
69+
let base
70+
try {
71+
base = JSON.parse(baseSchema)
72+
} catch (e) {
73+
console.error("Failed to parse BackupJob schema:", e)
74+
return null
75+
}
76+
const kinds: string[] = selectedApiGroup === "apps.cozystack.io"
77+
? appDefs?.items.map(d => d.spec?.application.kind).filter((k): k is string => Boolean(k)) ?? []
78+
: []
79+
const instances = instancesData?.items.map((inst: any) => inst.metadata.name) ?? []
80+
const backupClasses = backupClassesData?.items.map((bc: any) => bc.metadata.name) ?? []
81+
const plans = plansData?.items.map((p: any) => p.metadata.name) ?? []
82+
83+
const enumMap: Record<string, string[]> = {}
84+
if (kinds.length > 0) {
85+
enumMap["applicationRef.kind"] = kinds
86+
}
87+
if (selectedApiGroup === "apps.cozystack.io" && selectedKind && instances.length > 0) {
88+
enumMap["applicationRef.name"] = instances
89+
}
90+
if (backupClasses.length > 0) {
91+
enumMap["backupClassName"] = backupClasses
92+
}
93+
if (plans.length > 0) {
94+
// planRef is optional in the CRD (default ""). Prepend an empty value
95+
// so the dropdown opens with no plan selected — matches the CRD default
96+
// and avoids accidentally pinning the BackupJob to the first listed Plan.
97+
enumMap["planRef.name"] = ["", ...plans]
98+
}
99+
100+
const enriched = enrichSchemaWithEnums(base, [], enumMap)
101+
102+
// Default the optional apiGroup to apps.cozystack.io so the cozystack-
103+
// managed kinds match without the user typing the group manually.
104+
if (enriched.properties?.applicationRef?.properties?.apiGroup) {
105+
enriched.properties.applicationRef.properties.apiGroup.default = "apps.cozystack.io"
106+
}
107+
108+
return JSON.stringify(enriched)
109+
}, [baseSchema, appDefs, backupClassesData, plansData, instancesData, selectedKind, selectedApiGroup])
110+
111+
const handleSubmit = async () => {
112+
if (!tenantNamespace) {
113+
alert("Tenant namespace is not available. Please refresh.")
114+
return
115+
}
116+
117+
if (!name.trim()) {
118+
alert("Name is required")
119+
return
120+
}
121+
122+
if (!formData.applicationRef?.kind || !formData.applicationRef?.name) {
123+
alert("Application reference is required")
124+
return
125+
}
126+
127+
if (!formData.backupClassName) {
128+
alert("Backup class name is required")
129+
return
130+
}
131+
132+
// planRef is optional metadata recording which Plan triggered the job. The
133+
// dropdown ships an empty sentinel; strip it so the API never receives
134+
// `planRef: { name: "" }`, which would otherwise round-trip as a malformed
135+
// LocalObjectReference.
136+
const spec = { ...formData }
137+
if (!spec.planRef?.name) {
138+
delete spec.planRef
139+
}
140+
141+
const resource = {
142+
apiVersion: "backups.cozystack.io/v1alpha1",
143+
kind: "BackupJob",
144+
metadata: {
145+
name: name.trim(),
146+
namespace: tenantNamespace ?? undefined,
147+
},
148+
spec,
149+
}
150+
151+
try {
152+
await createMutation.mutateAsync(resource)
153+
navigate("/console/backups/backupjobs")
154+
} catch (err) {
155+
alert(`Failed to create BackupJob: ${(err as Error).message}`)
156+
}
157+
}
158+
159+
const handleCancel = () => {
160+
navigate("/console/backups/backupjobs")
161+
}
162+
163+
if (schemaLoading) {
164+
return (
165+
<div className="flex items-center gap-2 p-8 text-slate-500">
166+
<Spinner /> Loading schema...
167+
</div>
168+
)
169+
}
170+
171+
if (!schema) {
172+
return (
173+
<div className="p-8 text-red-600">
174+
Failed to load BackupJob schema. Please refresh the page.
175+
</div>
176+
)
177+
}
178+
179+
return (
180+
<div className="p-6">
181+
<div className="mb-5 flex items-center gap-3">
182+
<div className="flex size-11 shrink-0 items-center justify-center rounded-md bg-slate-100">
183+
<Archive className="size-6 text-slate-600" />
184+
</div>
185+
<div>
186+
<h1 className="text-lg font-semibold text-slate-900">Create Backup Job</h1>
187+
<p className="text-xs text-slate-500">
188+
Trigger a backup of an application instance
189+
</p>
190+
</div>
191+
</div>
192+
193+
<div>
194+
<Section>
195+
<div className="space-y-4 p-5">
196+
<div>
197+
<label htmlFor="backup-job-name" className="block text-sm font-medium text-slate-700 mb-1">
198+
Backup Job Name <span className="text-red-500">*</span>
199+
</label>
200+
<input
201+
id="backup-job-name"
202+
type="text"
203+
value={name}
204+
onChange={(e) => setName(e.target.value)}
205+
placeholder="my-backup-job"
206+
className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400"
207+
required
208+
/>
209+
</div>
210+
211+
<div>
212+
<SchemaForm
213+
openAPISchema={schema}
214+
formData={formData}
215+
onChange={setFormData}
216+
>
217+
<div className="hidden" />
218+
</SchemaForm>
219+
</div>
220+
</div>
221+
222+
<div className="flex items-center gap-2 border-t border-slate-200 px-5 py-3">
223+
<Button
224+
type="button"
225+
variant="primary"
226+
size="sm"
227+
onClick={handleSubmit}
228+
disabled={createMutation.isPending}
229+
>
230+
{createMutation.isPending ? (
231+
<>
232+
<Spinner /> Creating...
233+
</>
234+
) : (
235+
<>
236+
<Save className="size-3.5" /> Create
237+
</>
238+
)}
239+
</Button>
240+
<Button
241+
type="button"
242+
variant="outline"
243+
size="sm"
244+
onClick={handleCancel}
245+
disabled={createMutation.isPending}
246+
>
247+
Cancel
248+
</Button>
249+
</div>
250+
</Section>
251+
</div>
252+
</div>
253+
)
254+
}

0 commit comments

Comments
 (0)