diff --git a/landing-zone-configurator/app/apps/api/src/assistant/knowledge-topics.generated.ts b/landing-zone-configurator/app/apps/api/src/assistant/knowledge-topics.generated.ts index 3c50e935..78d3af2f 100644 --- a/landing-zone-configurator/app/apps/api/src/assistant/knowledge-topics.generated.ts +++ b/landing-zone-configurator/app/apps/api/src/assistant/knowledge-topics.generated.ts @@ -774,7 +774,7 @@ export const assistantKnowledgeTopics = { { path: "landing-zone-configurator/app/apps/api/src/deployments/preparations.ts", sha256: - "178669b42f85549db9e2f09c32e9c657a6a801c012bbd4a317f473549eec8879", + "14eba29818e560a51d155a11b5e692fb5df135161029d34d862b4fff62e1dcc7", }, { path: "landing-zone-configurator/app/packages/domain/src/initial-plan.ts", diff --git a/landing-zone-configurator/app/apps/api/src/credentials/profiles.ts b/landing-zone-configurator/app/apps/api/src/credentials/profiles.ts index 4255432c..952a55a0 100644 --- a/landing-zone-configurator/app/apps/api/src/credentials/profiles.ts +++ b/landing-zone-configurator/app/apps/api/src/credentials/profiles.ts @@ -42,7 +42,7 @@ export interface CredentialProfiles { name: string, key: ServiceAccountKey, firewallAdministration?: FirewallAdministration, - ): Promise; + ): Promise; remove(session: Session, id: string): Promise; } export class PostgresCredentialProfiles implements CredentialProfiles { @@ -119,6 +119,7 @@ export class PostgresCredentialProfiles implements CredentialProfiles { [id], ); }); + return id; } async check(session: Session, id: string, organizationId: string) { return (await this.verifyForPreparation(session, id, organizationId)).check; diff --git a/landing-zone-configurator/app/apps/api/src/credentials/routes.ts b/landing-zone-configurator/app/apps/api/src/credentials/routes.ts index de1e9021..286a99f9 100644 --- a/landing-zone-configurator/app/apps/api/src/credentials/routes.ts +++ b/landing-zone-configurator/app/apps/api/src/credentials/routes.ts @@ -65,15 +65,18 @@ export function registerCredentials( } catch { return reply.code(400).send({ error: "invalid_service_account_key" }); } - if (input.firewallAdministration) - await profiles.create( - session, - input.name, - key, - input.firewallAdministration, - ); - else await profiles.create(session, input.name, key); - return reply.code(201).send({ stored: true }); + const profileId = input.firewallAdministration + ? await profiles.create( + session, + input.name, + key, + input.firewallAdministration, + ) + : await profiles.create(session, input.name, key); + return reply.code(201).send({ + stored: true, + ...(typeof profileId === "string" ? { profileId } : {}), + }); }, ); routes.post("/api/v1/credentials/:id/check", async (request, reply) => { diff --git a/landing-zone-configurator/app/apps/api/src/deployments/preparations.ts b/landing-zone-configurator/app/apps/api/src/deployments/preparations.ts index 06b50d52..24a21ed1 100644 --- a/landing-zone-configurator/app/apps/api/src/deployments/preparations.ts +++ b/landing-zone-configurator/app/apps/api/src/deployments/preparations.ts @@ -329,7 +329,7 @@ export class Preparations { `preparations:${session.userId}`, ]); const count = await c.query( - "SELECT count(*)::int AS count FROM lzc.deployment_preparations", + "SELECT count(*)::int AS count FROM lzc.deployment_preparations p WHERE NOT EXISTS (SELECT 1 FROM lzc.plan_runs r WHERE r.preparation_id=p.id)", ); if (count.rows[0].count >= 100) throw new CredentialError(409, "preparation_limit_reached"); diff --git a/landing-zone-configurator/app/apps/api/src/plans/service.ts b/landing-zone-configurator/app/apps/api/src/plans/service.ts index 53da4e80..7108f2f6 100644 --- a/landing-zone-configurator/app/apps/api/src/plans/service.ts +++ b/landing-zone-configurator/app/apps/api/src/plans/service.ts @@ -100,7 +100,7 @@ export class Plans { async (client) => ( await client.query( - 'SELECT r.id,r.preparation_id AS "preparationId",r.status,r.summary,r.error_code AS "errorCode",r.created_at AS "createdAt",r.finished_at AS "finishedAt",r.operation,r.plan_id AS "planId",r.artifact_sha256 AS "artifactSha256",a.expires_at AS "expiresAt",b.descriptor AS "stateBackend",lzc_auth.platform_run_retired(r.id) AS "retirementBlocked" FROM lzc.plan_runs r LEFT JOIN lzc.plan_artifacts a ON a.run_id=r.id LEFT JOIN lzc.platform_states s ON s.state_key=r.state_key LEFT JOIN lzc.state_backends b ON b.id=s.backend_id ORDER BY r.created_at DESC LIMIT 100', + 'SELECT r.id,r.preparation_id AS "preparationId",r.status,r.summary,r.error_code AS "errorCode",r.created_at AS "createdAt",r.finished_at AS "finishedAt",r.operation,r.plan_id AS "planId",r.artifact_sha256 AS "artifactSha256",a.expires_at AS "expiresAt",b.descriptor AS "stateBackend",(s.lock_run_id IS NOT NULL OR s.pending_backend_id IS NOT NULL OR s.migration_run_id IS NOT NULL OR r.status=\'recovery_required\') AS "retryCheckpointRequired",lzc_auth.platform_run_retired(r.id) AS "retirementBlocked" FROM lzc.plan_runs r LEFT JOIN lzc.plan_artifacts a ON a.run_id=r.id LEFT JOIN lzc.platform_states s ON s.state_key=r.state_key LEFT JOIN lzc.state_backends b ON b.id=s.backend_id ORDER BY r.created_at DESC LIMIT 100', ) ).rows, ); diff --git a/landing-zone-configurator/app/apps/web/src/components/Configurations.tsx b/landing-zone-configurator/app/apps/web/src/components/Configurations.tsx index 82e8ffa1..4bc028bc 100644 --- a/landing-zone-configurator/app/apps/web/src/components/Configurations.tsx +++ b/landing-zone-configurator/app/apps/web/src/components/Configurations.tsx @@ -81,6 +81,8 @@ export function Configurations({ onSaved, onLoad, onPrepare, + onPlanCurrent, + onAdviceChange, compact = false, dirty = true, }: { @@ -90,6 +92,10 @@ export function Configurations({ onSaved: (binding: ConfigurationBinding | null) => void; onLoad: (draft: EditorDraft, binding: ConfigurationBinding) => void; onPrepare: (selection: DeploymentSelection) => void; + onPlanCurrent?: () => void; + onAdviceChange?: + | ((advice: { id: string; revision: number } | null) => void) + | undefined; compact?: boolean; dirty?: boolean; }) { @@ -106,6 +112,9 @@ export function Configurations({ string, string > | null>(null); + useEffect(() => { + onAdviceChange?.(!binding && includeAdvice ? templateAdvice : null); + }, [binding, includeAdvice, templateAdvice, onAdviceChange]); const currentDraft = useRef({ draft, dirty }); currentDraft.current = { draft, dirty }; const active = useRef(false); @@ -291,9 +300,11 @@ export function Configurations({ type="button" className="button primary" disabled={busy || !session || !draft} - onClick={() => void save(false, true)} + onClick={() => + onPlanCurrent ? onPlanCurrent() : void save(false, true) + } > - {t("Speichern und zur Bereitstellung")} + {t(dirty ? "Speichern und Plan erstellen" : "Plan erstellen")} -

{t("Deine gespeicherten Zugänge")}

- - {!profiles.length && ( -

{t("Noch keine persönlichen Zugänge geladen.")}

- )} - {profiles.map((profile) => ( -
-

{profile.name}

-

{profile.serviceAccount}

- {profile.state === "stored" && - profile.firewallAdministrationConfigured && ( -

{t("OPNsense-Administrationszugang sicher hinterlegt")}

- )} -

- {profile.state === "stored" - ? profile.lastCheck - ? t("Sicher gespeichert · letzte Prüfung siehe unten") - : t( - "Sicher gespeichert · Berechtigungen noch nicht geprüft", - ) - : t( - "Speicherung unvollständig · bitte löschen und neu anlegen", + {!createOnly && ( + <> +

{t("Deine gespeicherten Zugänge")}

+ + {!profiles.length && ( +

{t("Noch keine persönlichen Zugänge geladen.")}

+ )} + {profiles.map((profile) => ( +
+

{profile.name}

+

{profile.serviceAccount}

+ {profile.state === "stored" && + profile.firewallAdministrationConfigured && ( +

+ {t("OPNsense-Administrationszugang sicher hinterlegt")} +

)} -

- {profile.lastCheck && } - {profile.state === "stored" && ( - <> - - setOrganizations((previous) => ({ - ...previous, - [profile.id]: value, - })) - } - hint="Die Organisations-ID findest du im STACKIT Portal oder in deiner Konfiguration. Diese Prüfung verändert keine Cloud-Ressourcen." - /> +

+ {profile.state === "stored" + ? profile.lastCheck + ? t("Sicher gespeichert · letzte Prüfung siehe unten") + : t( + "Sicher gespeichert · Berechtigungen noch nicht geprüft", + ) + : t( + "Speicherung unvollständig · bitte löschen und neu anlegen", + )} +

+ {profile.lastCheck && ( + + )} + {profile.state === "stored" && ( + <> + + setOrganizations((previous) => ({ + ...previous, + [profile.id]: value, + })) + } + hint="Die Organisations-ID findest du im STACKIT Portal oder in deiner Konfiguration. Diese Prüfung verändert keine Cloud-Ressourcen." + /> + + + )} - - )} - -
- ))} +
+ ))} + + )}

{t(error)}

diff --git a/landing-zone-configurator/app/apps/web/src/components/Deployments.tsx b/landing-zone-configurator/app/apps/web/src/components/Deployments.tsx index 7c219e40..943d2b92 100644 --- a/landing-zone-configurator/app/apps/web/src/components/Deployments.tsx +++ b/landing-zone-configurator/app/apps/web/src/components/Deployments.tsx @@ -1,12 +1,10 @@ -import { platformUpgradeAcceleratorCommit } from "@lzc/contracts"; -import { useEffect, useRef, useState } from "react"; -import { currentLanguage, t } from "../i18n"; +import { useEffect, useState } from "react"; +import { t } from "../i18n"; import type { DeploymentStep } from "../navigation"; import type { Session } from "./Account"; -import { type AccessCheck, CheckSummary, checkMessages } from "./CheckSummary"; +import { type AccessCheck, checkMessages } from "./CheckSummary"; import { configurationDeploymentSelection } from "./Configurations"; import { PlanRuns } from "./PlanRuns"; -import { StateBackends } from "./StateBackends"; export type DeploymentSelection = | { target: { id: number; owner: string; name: string }; @@ -30,7 +28,7 @@ type Preparation = { manifest: { source: | { - repository: { owner: string; name: string }; + repository: { id: number; owner: string; name: string }; commit: string; configurationId: string; } @@ -46,11 +44,11 @@ type Preparation = { check: AccessCheck; }; }; -const errors: Record = { +export const deploymentErrors: Record = { observability_plan_incompatible: "Der gewählte Observability-Tarif und seine Einstellungen passen nicht zusammen oder konnten nicht verifiziert werden. Prüfe Tarif und Aufbewahrung im Editor. Gespeicherte Werte bleiben erhalten.", firewall_administration_required: - "Für Firewall-HA fehlt ein gebundener OPNsense-Administrationszugang. Erstelle unter Zugänge ein Profil mit Service-Account und OPNsense-Zugang und danach eine neue Vorbereitung und einen neuen Plan. Bestehende Nachweise bleiben erhalten.", + "Für Firewall-HA fehlt ein OPNsense-Administrationszugang. Ergänze im Plan-Dialog ein passendes Zugangsprofil und erstelle einen neuen Plan.", configuration_execution_not_supported: "Diese Konfiguration enthält Komponenten, die der Erstbereitstellungsplan noch nicht unterstützt. Prüfe die Ausführungshinweise bei der Konfigurationsauswahl.", preparation_has_plans: @@ -58,7 +56,7 @@ const errors: Record = { ...checkMessages, authentication_required: "Bitte melde dich an.", configuration_changed: - "Die gespeicherte Konfiguration wurde geändert. Wähle sie erneut aus und erstelle eine neue Vorbereitung.", + "Die gespeicherte Konfiguration wurde geändert. Öffne den aktuellen Stand und erstelle einen neuen Plan.", configuration_not_found: "Die Konfiguration wurde entfernt oder ist nicht zugänglich.", configuration_incomplete: @@ -75,9 +73,9 @@ const errors: Record = { repository_access_denied: "Der Zugriff auf den Fork wurde abgelehnt. Prüfe die GitHub-App-Installation.", preparation_limit_reached: - "Maximal 100 Vorbereitungen. Entferne zuerst nicht mehr benötigte Einträge.", + "Zu viele offene Plan-Anfragen. Lass nicht verwendete Ausführungsnachweise durch den Betreiber prüfen.", platform_upgrade_unavailable: - "Der aktuelle Accelerator-Stand ist für neue Vorbereitungen nicht freigegeben. Bitte die Runner-Konfiguration prüfen lassen.", + "Der aktuelle Ausführungsstand ist für neue Pläne nicht freigegeben. Bitte die Runner-Konfiguration prüfen lassen.", platform_upgrade_state_unavailable: "Für den Accelerator-Wechsel ist der vorhandene S3-State oder ein ausdrücklich geprüfter, unterstützter Bootstrap-Checkpoint erforderlich. Prüfe den Checkpoint und offene Ausführungen; deine Konfiguration bleibt erhalten.", state_backend_already_managed: @@ -93,535 +91,127 @@ const errors: Record = { invalid_request_origin_or_csrf: "Die Sicherheitsbestätigung deiner Sitzung ist nicht mehr aktuell. Lade die Seite neu und melde dich gegebenenfalls erneut an.", invalid_preparation_request: - "Die Vorbereitung enthält ungültige oder zur aktuellen API-Version unpassende Angaben. Lade die Seite neu und wähle die gespeicherte Konfiguration erneut aus.", + "Der Plan-Auftrag enthält ungültige oder zur aktuellen API-Version unpassende Angaben. Lade die Seite neu und öffne die gespeicherte Konfiguration erneut.", github_connection_required: "Für eine im GitHub-Fork gespeicherte Konfiguration ist eine GitHub-Verbindung erforderlich. Verbinde GitHub oder wähle eine in der Datenbank gespeicherte Konfiguration.", }; export function Deployments({ session, selection, - onSelect, onChoose, - onCredentials, + onSelect, historyOnly = false, configurationId, - step = "preparation", + step = "plan", onStep, + onNewPlan, + onRetryApply, + refreshKey = 0, }: { session: Session | null; selection: DeploymentSelection | null; - onSelect: (selection: DeploymentSelection | null) => void; onChoose: () => void; - onCredentials: () => void; + onSelect: (selection: DeploymentSelection) => void; historyOnly?: boolean; configurationId?: string | undefined; step?: DeploymentStep; onStep?: (step: DeploymentStep) => void; + onNewPlan: () => void; + onRetryApply: ( + id: string, + credentialId: string | null, + repository?: { id: number; owner: string; name: string }, + ) => void; + refreshKey?: number; }) { const [preparations, setPreparations] = useState([]); - const [configurations, setConfigurations] = useState< - { id: string; name: string; revision: number }[] - >([]); - const [profiles, setProfiles] = useState< - { id: string; name: string; state: string }[] - >([]); - const [credentialId, setCredentialId] = useState(""); - const [backendId, setBackendId] = useState(""); - const [backendReady, setBackendReady] = useState(false); - const [busy, setBusy] = useState(false); const [error, setError] = useState(""); - const [notice, setNotice] = useState(""); - const [chosenPreparation, setChosenPreparation] = useState(""); - const [upgradeAvailable, setUpgradeAvailable] = useState(false); - const [upgradeRequired, setUpgradeRequired] = useState(false); - const [upgradeConfirmed, setUpgradeConfirmed] = useState(false); + const [selectionChecked, setSelectionChecked] = useState(false); + // biome-ignore lint/correctness/useExhaustiveDependencies: refresh the internal evidence after a new plan is started. useEffect(() => { - if (selection?.configurationId) setUpgradeConfirmed(false); - }, [selection?.configurationId]); - const preparationScope = useRef(configurationId); - useEffect(() => { - if (preparationScope.current !== configurationId) { - preparationScope.current = configurationId; - setChosenPreparation(""); - } - }, [configurationId]); - const active = useRef(false); - const lifetime = useRef(null); - async function api(url: string, init?: RequestInit) { - const response = await fetch(url, { + if (!session) return; + const controller = new AbortController(); + void fetch("/api/v1/preparations", { credentials: "same-origin", - signal: lifetime.current?.signal ?? null, - ...init, - }); - if (response.status === 204) return null; - const data = await response.json(); - if (!response.ok) { - const code = - typeof data.error === "string" && - /^[a-z][a-z0-9_]{0,79}$/.test(data.error) - ? data.error - : "unexpected_response"; - throw new Error( - errors[code] ?? - `${t("Die Anfrage ist fehlgeschlagen.")} (HTTP ${response.status}, ${t("Fehlercode:")} ${code}).`, - ); - } - return data; - } - async function refresh(signal = lifetime.current?.signal) { - const options = signal ? { signal } : {}; - const [records, credentials, saved] = await Promise.all([ - api("/api/v1/preparations", options), - api("/api/v1/credentials", options), - api("/api/v1/configurations", options), - ]); - if (signal?.aborted) return; - setPreparations(records.preparations); - setUpgradeAvailable(records.capabilities?.platformUpgradeEnabled === true); - setUpgradeRequired( - records.capabilities?.runnerAcceleratorCommit === - platformUpgradeAcceleratorCommit, - ); - setProfiles(credentials.profiles); - setConfigurations(saved.configurations); - const stored = credentials.profiles.filter( - (profile: { state: string }) => profile.state === "stored", - ); - setCredentialId((current) => - stored.some((profile: { id: string }) => profile.id === current) - ? current - : stored.length === 1 - ? stored[0].id - : "", - ); - if (!historyOnly && !selection && saved.configurations.length === 1) { - const { configuration } = await api( - `/api/v1/configurations/${saved.configurations[0].id}`, - options, - ); - if (!signal?.aborted) - onSelect(configurationDeploymentSelection(configuration)); - } - } - // biome-ignore lint/correctness/useExhaustiveDependencies: reload lists on session changes, not configuration selection. + signal: controller.signal, + }) + .then(async (response) => { + if (!response.ok) + throw Error("Ausführungsnachweise konnten nicht geladen werden."); + const data = await response.json(); + if (!controller.signal.aborted) { + setPreparations(data.preparations); + setError(""); + } + }) + .catch(() => { + if (!controller.signal.aborted) + setError("Ausführungsnachweise konnten nicht geladen werden."); + }); + return () => controller.abort(); + }, [session, refreshKey]); + // biome-ignore lint/correctness/useExhaustiveDependencies: choose the sole saved configuration only when no draft or explicit selection is active. useEffect(() => { - if (!session) return; + if (!session || selection || configurationId || historyOnly) return; + setSelectionChecked(false); const controller = new AbortController(); - lifetime.current = controller; - void refresh(controller.signal).catch((failure) => { - if (!controller.signal.aborted) - setError( - failure instanceof Error - ? failure.message - : "Vorbereitungen konnten nicht geladen werden.", + void fetch("/api/v1/configurations", { + credentials: "same-origin", + signal: controller.signal, + }) + .then(async (response) => { + if (!response.ok) return; + const body = await response.json(); + if (body.configurations?.length !== 1) return; + const saved = await fetch( + `/api/v1/configurations/${body.configurations[0].id}`, + { credentials: "same-origin", signal: controller.signal }, ); - }); + if (!saved.ok) return; + const data = await saved.json(); + if (!controller.signal.aborted) + onSelect(configurationDeploymentSelection(data.configuration)); + }) + .catch(() => {}) + .finally(() => { + if (!controller.signal.aborted) setSelectionChecked(true); + }); return () => controller.abort(); - }, [session]); - async function perform(action: () => Promise) { - if (active.current) return; - active.current = true; - setBusy(true); - setError(""); - setNotice(""); - try { - await action(); - } catch (error) { - setError( - error instanceof Error ? error.message : "Aktion fehlgeschlagen.", - ); - } finally { - setBusy(false); - active.current = false; - } - } - const headers = { - "Content-Type": "application/json", - "X-LZC-CSRF": session?.csrfToken ?? "", - }; - const scopedPreparations = configurationId + }, [session, selection, configurationId, historyOnly]); + const scoped = configurationId ? preparations.filter( - (preparation) => - preparation.manifest.source.configurationId === configurationId, + (p) => p.manifest.source.configurationId === configurationId, ) : preparations; return (
-

- {historyOnly - ? t("Ausführungsverlauf") - : step === "plan" - ? t("Plan") - : step === "apply" - ? t("Apply") - : t("Deployment vorbereiten")} -

- - {!session ? ( -

- {t( - "Melde dich oben an, um Deployments vorzubereiten. GitHub ist dafür nicht erforderlich.", - )} -

- ) : ( - <> + {!selection && !historyOnly && ( +
+

{t("Öffne eine Konfiguration, um einen Plan zu erstellen.")}

+ +
+ )} + {error &&

{t(error)}

} + {session && + (selection || configurationId || historyOnly || selectionChecked) && ( - - {busy &&

{t("Prüfung läuft …")}

} - {!busy && notice && ( -

- {t(notice)} -

- )} - {error && ( -

- {t(error)} -

- )} - - )} + )}
); } diff --git a/landing-zone-configurator/app/apps/web/src/components/ForkWorkspace.tsx b/landing-zone-configurator/app/apps/web/src/components/ForkWorkspace.tsx index ea38af22..651b1598 100644 --- a/landing-zone-configurator/app/apps/web/src/components/ForkWorkspace.tsx +++ b/landing-zone-configurator/app/apps/web/src/components/ForkWorkspace.tsx @@ -547,7 +547,7 @@ export function ForkWorkspace({ }) } > - {t("Deployment vorbereiten")} + {t("Plan erstellen")} : {config.name} diff --git a/landing-zone-configurator/app/apps/web/src/components/PlanDialog.tsx b/landing-zone-configurator/app/apps/web/src/components/PlanDialog.tsx new file mode 100644 index 00000000..01854978 --- /dev/null +++ b/landing-zone-configurator/app/apps/web/src/components/PlanDialog.tsx @@ -0,0 +1,353 @@ +import { platformUpgradeAcceleratorCommit } from "@lzc/contracts"; +import { useEffect, useRef, useState } from "react"; +import { t } from "../i18n"; +import type { Session } from "./Account"; +import { Credentials } from "./Credentials"; +import { type DeploymentSelection, deploymentErrors } from "./Deployments"; +import { PeopleDialog } from "./PeopleDialog"; +import { StateBackends } from "./StateBackends"; + +type Profile = { id: string; name: string; state: string }; +export function PlanDialog({ + session, + selection, + name, + configurationId, + onSave, + onClose, + onStarted, + preferredCredentialId, + retry = false, +}: { + session: Session; + selection: DeploymentSelection | null; + name: string; + configurationId: string | null; + onSave?: (signal: AbortSignal) => Promise; + onClose: () => void; + onStarted: (selection: DeploymentSelection) => void; + preferredCredentialId?: string | undefined; + retry?: boolean; +}) { + const [profiles, setProfiles] = useState([]); + const [credentialId, setCredentialId] = useState(""); + const [backendId, setBackendId] = useState(""); + const [backendReady, setBackendReady] = useState(false); + const [capabilities, setCapabilities] = useState<{ + platformUpgradeEnabled?: boolean; + runnerAcceleratorCommit?: string; + } | null>(null); + const [adding, setAdding] = useState(false), + [credentialBusy, setCredentialBusy] = useState(false); + const [busy, setBusy] = useState(false), + [confirmed, setConfirmed] = useState(false), + [error, setError] = useState(""); + const [stage, setStage] = useState(""); + const [profilesLoaded, setProfilesLoaded] = useState(false); + const active = useRef(false), + lifetime = useRef(null); + async function api(path: string, init?: RequestInit) { + const response = await fetch(path, { + credentials: "same-origin", + signal: lifetime.current?.signal ?? null, + ...init, + }); + const body = await response.json(); + if (!response.ok) + throw Error( + deploymentErrors[body.error] ?? + ( + { + plan_already_running: + "Es läuft bereits ein Plan in deinem Arbeitsbereich.", + plan_daily_limit: "Das Tageslimit von 20 Plänen ist erreicht.", + configuration_changed: + "Die Konfiguration wurde geändert. Öffne den aktuellen Stand und erstelle einen neuen Plan.", + state_locked: + "Der Plattform-State ist durch eine laufende Ausführung gesperrt. Prüfe den Ausführungsstatus und warte auf deren Abschluss.", + } as Record + )[body.error] ?? + `${t("Die Anfrage ist fehlgeschlagen.")} (HTTP ${response.status}, ${t("Fehlercode:")} ${typeof body.error === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(body.error) ? body.error : "unexpected_response"}).`, + ); + return body; + } + async function loadProfiles(preferred?: string) { + const body = await api("/api/v1/credentials"); + if (lifetime.current?.signal.aborted) return; + const stored = body.profiles.filter( + (p: Profile) => p.state === "stored", + ) as Profile[]; + setProfiles(stored); + setProfilesLoaded(true); + setCredentialId((previous) => + stored.some((p) => p.id === (preferred ?? previous)) + ? (preferred ?? previous) + : retry || preferred + ? "" + : stored.length === 1 + ? (stored[0]?.id ?? "") + : "", + ); + } + // biome-ignore lint/correctness/useExhaustiveDependencies: the dialog is remounted for each workspace/configuration context. + useEffect(() => { + const controller = new AbortController(); + lifetime.current = controller; + void Promise.all([ + loadProfiles(preferredCredentialId), + api("/api/v1/preparations").then((body) => { + if (!controller.signal.aborted) + setCapabilities(body.capabilities ?? {}); + }), + ]).catch((failure) => { + if (!controller.signal.aborted) setError(failure.message); + }); + return () => controller.abort(); + }, []); + async function start() { + if ( + active.current || + !credentialId || + !confirmed || + !backendReady || + !capabilities || + !lifetime.current + ) + return; + active.current = true; + setBusy(true); + setError(""); + const controller = lifetime.current; + try { + setStage("Konfiguration wird gespeichert und geprüft …"); + const chosen = onSave ? await onSave(controller.signal) : selection; + if (controller.signal.aborted) return; + if (!chosen) + throw Error("Öffne eine Konfiguration, um einen Plan zu erstellen."); + const currentEngine = + capabilities.runnerAcceleratorCommit === + platformUpgradeAcceleratorCommit; + if (currentEngine && !capabilities.platformUpgradeEnabled) + throw Error(deploymentErrors.platform_upgrade_unavailable); + setStage("Zugang und Ziel werden geprüft …"); + const prepared = await api("/api/v1/preparations", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-LZC-CSRF": session.csrfToken, + }, + body: JSON.stringify({ + configurationId: chosen.configurationId, + ...("target" in chosen + ? { target: chosen.target, head: chosen.head } + : { source: "database", revision: chosen.revision }), + credentialId, + ...(backendId ? { backendId } : {}), + ...(currentEngine + ? { + platformUpgrade: { + confirm: true, + acceleratorCommit: platformUpgradeAcceleratorCommit, + }, + } + : {}), + }), + }); + if (controller.signal.aborted) return; + setStage("Plan wird gestartet …"); + await api("/api/v1/plans", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-LZC-CSRF": session.csrfToken, + }, + body: JSON.stringify({ + preparationId: prepared.id, + confirmStateBinding: true, + }), + }); + if (!controller.signal.aborted) onStarted(chosen); + } catch (failure) { + if (!controller.signal.aborted) + setError( + failure instanceof Error + ? failure.message + : "Der Plan konnte nicht gestartet werden. Prüfe den Ausführungsverlauf und versuche es erneut.", + ); + } finally { + if (!controller.signal.aborted) { + setBusy(false); + setStage(""); + active.current = false; + } + } + } + return ( + + {retry && ( +

+ {t( + "Die Wiederholung berechnet einen neuen Plan auf dem aktuellen State. Prüfe ihn und gib Apply anschließend erneut frei. Bereits ausgeführte Änderungen bleiben berücksichtigt.", + )} +

+ )} +
+
{t("Konfiguration")}
+
{name}
+
{t("Stand")}
+
+ {onSave + ? t("Aktueller Entwurf · wird vor dem Plan gespeichert") + : t("Aktueller gespeicherter Stand")} +
+ {selection && ( + <> +
{t("Zielorganisation")}
+
{selection.organizationId}
+ + )} +
{t("State-Backend")}
+
+ {!backendReady + ? t("wird geprüft") + : backendId + ? t("Zugeordnetes S3-Backend") + : t("Accelerator-Standard")} +
+
+ {adding ? ( +
+ { + setAdding(false); + void loadProfiles(id).catch((failure) => + setError(failure.message), + ); + }} + /> + +
+ ) : ( + <> +
+ + +
+ + {retry && + profilesLoaded && + !profiles.some((p) => p.id === preferredCredentialId) && ( +

+ {t( + "Der bisherige Zugang ist nicht mehr verfügbar. Wähle einen Zugang oder lege ihn hier an.", + )} +

+ )} + {!profiles.length && ( +

+ {t( + "Lege hier einen Deployment-Zugang an. Danach kannst du den Plan direkt starten.", + )} +

+ )} +
+ {t("State-Zuordnung und Ausführungsdetails")} +

+ {t( + "Verwendet den aktuell freigegebenen Ausführungsstand. Apply übernimmt den geprüften Zugang und die State-Zuordnung aus diesem Plan.", + )} +

+

+ {t("Konfigurationsstand:")}{" "} + {onSave + ? t("Nach dem Speichern") + : selection && + ("target" in selection + ? selection.head.slice(0, 12) + : selection.revision)} +

+ +
+

+ {t( + "Die bestehende State-Zuordnung wird geprüft. Apply benötigt anschließend deine separate Freigabe.", + )} +

+ +
+ +
+ + )} + {stage &&

{t(stage)}

} + {error && ( +

+ {t(error)} +

+ )} +
+ ); +} diff --git a/landing-zone-configurator/app/apps/web/src/components/PlanRuns.tsx b/landing-zone-configurator/app/apps/web/src/components/PlanRuns.tsx index d8321174..dc2a57b1 100644 --- a/landing-zone-configurator/app/apps/web/src/components/PlanRuns.tsx +++ b/landing-zone-configurator/app/apps/web/src/components/PlanRuns.tsx @@ -30,6 +30,7 @@ type Run = { applyBlocker?: PlatformApplyBlocker | null; expiresAt?: string | null; stateBackend?: S3BackendDescriptor | null; + retryCheckpointRequired?: boolean; }; const active = new Set([ "starting", @@ -60,13 +61,13 @@ const failures: Record = { "Diese Landing Zone wird stillgelegt. Neue Bestellungen, Erweiterungen und alte Ausführungsfreigaben sind gesperrt. Prüfe den Rückbaustatus.", firewall_administration_required: - "Für Firewall-HA fehlt ein gebundener OPNsense-Administrationszugang. Erstelle unter Zugänge ein Profil mit Service-Account und OPNsense-Zugang und danach eine neue Vorbereitung und einen neuen Plan. Bestehende Nachweise bleiben erhalten.", + "Für Firewall-HA fehlt ein OPNsense-Administrationszugang. Ergänze im Plan-Dialog ein passendes Zugangsprofil und erstelle einen neuen Plan.", configuration_execution_not_supported: "Diese Konfiguration enthält Komponenten, die der Erstbereitstellungsplan noch nicht unterstützt. Wähle eine unterstützte Standalone-Konfiguration.", configuration_apply_not_supported: "Diese Konfiguration kann geplant, aber mit den enthaltenen Komponenten noch nicht angewendet werden. Die gesperrten Felder sind unten aufgeführt. Ein neuer Plan allein hebt diese Sperre nicht auf.", configuration_changed: - "Die Konfiguration wurde seit der Vorbereitung geändert. Erstelle eine neue Vorbereitung und einen neuen Plan.", + "Die Konfiguration wurde seit dem Planstart geändert. Erstelle einen neuen Plan.", configuration_not_found: "Die gespeicherte Konfiguration ist nicht mehr verfügbar.", github_connection_required: @@ -75,15 +76,15 @@ const failures: Record = { "Deine aktuelle Rolle erlaubt keine Apply-Freigabe.", runner_unavailable: "Der Runner konnte nicht gestartet werden.", credential_changed: - "Der Zugang wurde geändert. Erstelle eine neue Vorbereitung.", + "Der Zugang wurde geändert. Wähle den aktuellen Zugang und erstelle einen neuen Plan.", access_check_failed: "Der Zugang zur Zielorganisation konnte nicht bestätigt werden.", input_invalid: "Die festgehaltene Konfiguration konnte nicht bestätigt werden.", preparation_accelerator_mismatch: - "Die Vorbereitung verwendet einen anderen Accelerator-Stand als der installierte Runner. Erstelle eine neue Vorbereitung und bestätige dort den aktuellen Accelerator-Stand. Bestehende States und Nachweise bleiben erhalten.", + "Der Plan verwendet einen anderen Ausführungsstand als der installierte Runner. Erstelle einen neuen Plan mit dem aktuell freigegebenen Stand. Bestehende States und Nachweise bleiben erhalten.", preparation_organization_mismatch: - "Die Zielorganisation der Vorbereitung passt nicht zur gespeicherten Konfiguration. Prüfe die Organisationsauswahl und erstelle eine neue Vorbereitung.", + "Die Zielorganisation des Plans passt nicht zur gespeicherten Konfiguration. Prüfe die Organisation und erstelle einen neuen Plan.", init_failed: "OpenTofu konnte die Provider nicht initialisieren.", validate_failed: "OpenTofu hat die Konfiguration abgewiesen.", plan_failed: @@ -93,7 +94,7 @@ const failures: Record = { plan_already_running: "Es läuft bereits ein Plan in deinem Arbeitsbereich.", plan_daily_limit: "Das Tageslimit von 20 Plänen ist erreicht.", repository_changed: - "Der Fork wurde geändert. Erstelle eine neue Vorbereitung.", + "Der Fork wurde geändert. Öffne den aktuellen Stand und erstelle einen neuen Plan.", credential_not_found: "Der persönliche Zugang ist nicht mehr verfügbar.", stale_plan: "Der Plan ist nicht mehr aktuell. Erstelle und prüfe einen neuen Plan.", @@ -108,7 +109,7 @@ const failures: Record = { backend_read_failed: "Der S3-State ist nicht lesbar. Prüfe den Backend-Zugang.", backend_binding_changed: - "Die Backend-Zuordnung stimmt nicht mehr. Erstelle eine neue Vorbereitung.", + "Die Backend-Zuordnung stimmt nicht mehr. Prüfe sie im Plan-Dialog und erstelle einen neuen Plan.", legacy_state_migration_required: "Ein bisheriger Konfigurator-State muss zuerst explizit übernommen werden. Es wird kein neuer State angelegt.", state_failed: @@ -134,7 +135,7 @@ const failures: Record = { plan_not_approvable: "Der Plan ist nicht mehr freigabefähig: abgelaufen, geändert oder bereits verwendet. Prüfe den Ausführungsstatus und erstelle bei Bedarf einen neuen Plan.", organization_mismatch: - "Die Zielorganisation stimmt nicht mit der gespeicherten Vorbereitung überein. Prüfe die exakte Organisations-ID.", + "Die Zielorganisation stimmt nicht mit dem geprüften Plan überein. Prüfe die exakte Organisations-ID.", artifact_invalid: "Das gespeicherte Plan-Artefakt konnte nicht bestätigt werden. Erstelle und prüfe einen neuen Plan.", runner_package_changed: @@ -150,7 +151,7 @@ const failures: Record = { apply_failed: "Apply ist fehlgeschlagen. Ressourcen können bereits verändert worden sein. Prüfe den Ausführungsstatus vor weiteren Aktionen.", recovery_required: - "Die Ausführung benötigt Wiederherstellung. Ressourcen können bereits verändert worden sein. Kein erneutes Apply starten.", + "Die Ausführung benötigt Wiederherstellung. Prüfe zuerst den Checkpoint. Bereits ausgeführte Änderungen werden bei einem neuen Plan berücksichtigt.", }; function ApplyBlocker({ run }: { run: Run }) { @@ -187,6 +188,7 @@ type Preparation = { configurationId?: string; revision?: number; commit?: string; + repository?: { id: number; owner: string; name: string }; }; }; }; @@ -341,10 +343,12 @@ function CheckpointReview({ runId, session, onReconciled, + retry = false, }: { runId: string; session: Session; onReconciled: () => Promise; + retry?: boolean; }) { const [checkpoint, setCheckpoint] = useState(null); const [confirmed, setConfirmed] = useState(false); @@ -435,6 +439,10 @@ function CheckpointReview({ pending.current = null; } } + // biome-ignore lint/correctness/useExhaustiveDependencies: retry inspection runs once for this immutable run/session mount. + useEffect(() => { + if (retry) void perform("checkpoint"); + }, []); return (
{t("Recovery-Abgleich")}
@@ -762,8 +770,10 @@ export function PlanRuns({ readOnly = false, scopeToPreparations = false, phase = "plan", - preparationId = "", - onPreparationChange, + onNewPlan, + onRetryApply, + canCreatePlan = false, + refreshKey = 0, onStep, }: { session: Session; @@ -772,18 +782,23 @@ export function PlanRuns({ readOnly?: boolean; scopeToPreparations?: boolean; phase?: DeploymentStep; - preparationId?: string; - onPreparationChange?: (id: string) => void; + onNewPlan: () => void; + onRetryApply?: ( + configurationId: string, + credentialId: string | null, + repository?: { id: number; owner: string; name: string }, + ) => void; + canCreatePlan?: boolean; + refreshKey?: number; onStep?: ((step: DeploymentStep) => void) | undefined; }) { const [runs, setRuns] = useState([]), [enabled, setEnabled] = useState(false), - [selected, setSelected] = useState(""), - [confirmed, setConfirmed] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState(""), [blocked, setBlocked] = useState([]); const pending = useRef(false); + const [retryRun, setRetryRun] = useState(null); const [now, setNow] = useState(Date.now); const [historyOpen, setHistoryOpen] = useState(false); const [expanded, setExpanded] = useState([]); @@ -794,7 +809,7 @@ export function PlanRuns({ const preparation = preparations.find( (item) => item.id === run.preparationId, ); - return `${scope}:${selected}:${run.id}:${run.artifactSha256 ?? ""}:${run.expiresAt ?? ""}:${run.applyAllowed}:${preparation?.credentialId}:${preparation?.manifest.organization.id}:${JSON.stringify(run.stateBackend)}`; + return `${scope}:${run.id}:${run.artifactSha256 ?? ""}:${run.expiresAt ?? ""}:${run.applyAllowed}:${preparation?.credentialId}:${preparation?.manifest.organization.id}:${JSON.stringify(run.stateBackend)}`; } async function refresh(signal?: AbortSignal) { const requestScope = scope; @@ -832,8 +847,6 @@ export function PlanRuns({ const controller = new AbortController(); setRuns([]); setEnabled(false); - setConfirmed(false); - setSelected(""); setError(""); setBlocked([]); setHistoryOpen(false); @@ -843,11 +856,7 @@ export function PlanRuns({ setError("Pläne konnten nicht geladen werden."); }); return () => controller.abort(); - }, [scope]); - useEffect(() => { - setSelected(preparationId); - setConfirmed(false); - }, [preparationId]); + }, [scope, refreshKey]); useEffect(() => { const deadlines = runs .map((run) => Date.parse(run.expiresAt ?? "")) @@ -914,7 +923,6 @@ export function PlanRuns({ ); } await refresh(); - setConfirmed(false); } catch (e) { if (currentScope.current === requestScope) { setError(e instanceof Error ? e.message : "Aktion fehlgeschlagen."); @@ -1132,6 +1140,50 @@ export function PlanRuns({ {failures.recovery_required}

)} + {!readOnly && + !historical && + onRetryApply && + run.operation === "apply" && + ["failed", "recovery_required"].includes(run.status) && + (() => { + const prepared = preparations.find( + (p) => p.id === run.preparationId, + ); + const configurationId = + prepared?.manifest.source?.configurationId; + return ( +
+
{t("Apply erneut versuchen")}
+

+ {t( + "Die Wiederholung berechnet einen neuen Plan auf dem aktuellen State. Prüfe ihn und gib Apply anschließend erneut frei. Bereits ausgeführte Änderungen bleiben berücksichtigt.", + )} +

+ +
+ ); + })()} {run.operation === "apply" && (
@@ -1170,16 +1222,27 @@ export function PlanRuns({ )} {!readOnly && !historical && - phase === "apply" && - run.status === "recovery_required" && ( + (phase === "apply" || retryRun === run.id) && + (run.status === "recovery_required" || retryRun === run.id) && ( { - setConfirmed(false); await refresh(); - onStep?.("plan"); + const prepared = preparations.find( + (p) => p.id === run.preparationId, + ); + const id = prepared?.manifest.source?.configurationId; + if (retryRun === run.id && id && onRetryApply) { + setRetryRun(null); + onRetryApply( + id, + prepared?.credentialId ?? null, + prepared?.manifest.source?.repository, + ); + } else onStep?.("plan"); }} /> )} @@ -1343,11 +1406,6 @@ export function PlanRuns({ return (
- - {t("Vorbereitung:")}{" "} - {preparations.filter((item) => item.credentialId).length}{" "} - {t("gespeichert")} - {t("Plan:")} {(() => { const run = scopedRuns.find((item) => item.operation !== "apply"); @@ -1397,102 +1455,34 @@ export function PlanRuns({ {t("Weiter zu Apply")} )} - +
+ )} ) : ( <> @@ -1016,7 +1170,6 @@ function App() { {( [ - ["preparation", "Vorbereitung"], ["plan", "Plan"], ["apply", "Apply"], ["history", "Verlauf"], @@ -1089,6 +1242,35 @@ function App() { standalone={view === "retire"} /> )} + {planDialogOpen && session && platformAccess && ( + setPlanDialogOpen(false)} + onStarted={(selected) => { + setDeploymentSelection(selected); + setPlanDialogOpen(false); + setPlanRefresh((value) => value + 1); + setView("deployments", "plan"); + }} + /> + )} @@ -1130,7 +1312,16 @@ function App() { compact onSaved={saveConfigurationBinding} onLoad={loadConfiguration} + onAdviceChange={(advice) => { + planAdvice.current = advice; + }} onPrepare={openDeployment} + onPlanCurrent={() => { + setPlanFromDraft(true); + setRetryApply(false); + setRetryCredential(undefined); + setPlanDialogOpen(true); + }} /> ) : undefined @@ -1164,9 +1355,24 @@ function App() { configurationBinding?.id ?? (draft ? "unsaved" : undefined) } - onSelect={(selection) => openDeployment(selection, false)} onChoose={() => setView("repositories")} - onCredentials={() => setView("credentials")} + onSelect={(selection) => openDeployment(selection, false)} + onNewPlan={() => { + setPlanFromDraft( + Boolean( + draft && + configurationBinding?.id === + deploymentSelection?.configurationId, + ), + ); + setRetryApply(false); + setRetryCredential(undefined); + setPlanDialogOpen(true); + }} + onRetryApply={(id, credential, repository) => + void retryFromPlan(id, credential, repository) + } + refreshKey={planRefresh} /> )} {view === "credentials" && ( @@ -1355,7 +1561,20 @@ function App() { dirty={draftDirty} compact={view === "editor"} onSaved={saveConfigurationBinding} + onAdviceChange={ + view === "editor" + ? (advice) => { + planAdvice.current = advice; + } + : undefined + } onPrepare={openDeployment} + onPlanCurrent={() => { + setPlanFromDraft(true); + setRetryApply(false); + setRetryCredential(undefined); + setPlanDialogOpen(true); + }} onLoad={loadConfiguration} />