feat: rename restore targets and show the application next to them
- PUT /api/v1/restore-targets/:id changes only the display name (admin, validated, audited); ids, identity, relations and jobs are untouched - Relations console: Application column, inline rename, application in the target pickers - Refresh screen: the application on each card - registering a target suggests '<application> · <database>' Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -349,7 +349,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
}
|
||||
"/api/v1/refresh-runs/:id" => Uuid::parse_str(&w.run).unwrap(),
|
||||
"/api/v1/orbits/:id/environment" => a.orbit,
|
||||
"/api/v1/restore-targets/:id/environment" => a.target,
|
||||
"/api/v1/restore-targets/:id" | "/api/v1/restore-targets/:id/environment" => a.target,
|
||||
"/api/v1/relations/:id"
|
||||
| "/api/v1/relations/:id/access"
|
||||
| "/api/v1/relations/:id/access/:grant" => a.relation,
|
||||
@@ -374,6 +374,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
|
||||
("POST", "/api/v1/orbits") => Some(
|
||||
json!({"name": "created", "provider": "filesystem", "source": "filesystem", "provider_config": {"path": "/nonexistent"}}),
|
||||
),
|
||||
("PUT", "/api/v1/restore-targets/:id") => Some(json!({"name": "renamed"})),
|
||||
("PUT", "/api/v1/orbits/:id/retention") => Some(json!({"decay_preset": "week-of-dailies"})),
|
||||
("PUT", "/api/v1/orbits/:id/outpost") => Some(json!({"outpost_id": a.outpost})),
|
||||
("POST", "/api/v1/reconstitute") => {
|
||||
|
||||
@@ -1739,3 +1739,110 @@ async fn reconciling_a_job_that_needs_no_recovery_says_so() {
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
// ---- naming restore targets ----
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_administrator_can_rename_a_target_and_everything_that_points_at_it_keeps_working() {
|
||||
let lab = fresh().await;
|
||||
let admin = lab.admin();
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let uri = format!("/api/v1/restore-targets/{}", lab.target);
|
||||
let (status, _) = lab
|
||||
.send(
|
||||
&admin,
|
||||
"PUT",
|
||||
&uri,
|
||||
Some(json!({"name": "presensi · dev · app_dev"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
|
||||
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
|
||||
let target = &overview["targets"][0];
|
||||
assert_eq!(target["name"], "presensi · dev · app_dev");
|
||||
assert_eq!(target["id"], lab.target.to_string());
|
||||
assert_eq!(
|
||||
target["identity"]["database"], "staging_app",
|
||||
"identity is untouched"
|
||||
);
|
||||
let relation = &overview["relations"][0];
|
||||
assert_eq!(relation["target_name"], "presensi · dev · app_dev");
|
||||
assert_eq!(
|
||||
relation["id"], lab.relation,
|
||||
"the relation is the same relation"
|
||||
);
|
||||
assert!(relation["usable"].as_bool().unwrap());
|
||||
// the person who refreshes through it sees the new name, and a run through it still starts
|
||||
let (_, mine) = lab
|
||||
.send(&qa, "GET", "/api/v1/refresh-relations", None)
|
||||
.await;
|
||||
assert_eq!(mine[0]["target_name"], "presensi · dev · app_dev");
|
||||
let confirmation = format!(
|
||||
"REFRESH prod-db TO presensi · dev · app_dev v{}",
|
||||
lab.relation_version
|
||||
);
|
||||
let (status, body) = lab
|
||||
.send(&qa, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": lab.relation, "confirmation": confirmation, "idempotency_key": "after-rename"})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
|
||||
assert!(lab
|
||||
.audit_log()
|
||||
.iter()
|
||||
.any(|(event, detail)| event == "restore_target.renamed"
|
||||
&& detail.contains(&lab.target.to_string())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_target_name_is_validated_like_a_registration_and_only_administrators_set_it() {
|
||||
let lab = fresh().await;
|
||||
let admin = lab.admin();
|
||||
let uri = format!("/api/v1/restore-targets/{}", lab.target);
|
||||
for name in ["", " ", &"x".repeat(129), "bad\nname", "tab\tname"] {
|
||||
let (status, _) = lab
|
||||
.send(&admin, "PUT", &uri, Some(json!({"name": name})))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{name:?}");
|
||||
}
|
||||
let (status, _) = lab
|
||||
.send(
|
||||
&admin,
|
||||
"PUT",
|
||||
&uri,
|
||||
Some(json!({"name": "ok", "identity": {}})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
status,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"only the name is editable"
|
||||
);
|
||||
let unknown = format!("/api/v1/restore-targets/{}", Uuid::new_v4());
|
||||
assert_eq!(
|
||||
lab.send(&admin, "PUT", &unknown, Some(json!({"name": "ok"})))
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let status = lab
|
||||
.send(&qa, "PUT", &uri, Some(json!({"name": "mine"})))
|
||||
.await
|
||||
.0;
|
||||
assert!(
|
||||
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
|
||||
"{status}"
|
||||
);
|
||||
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
|
||||
assert_eq!(
|
||||
overview["targets"][0]["name"], "staging-db",
|
||||
"nothing above changed it"
|
||||
);
|
||||
// the longest allowed name is fine
|
||||
assert_eq!(
|
||||
lab.send(&admin, "PUT", &uri, Some(json!({"name": "y".repeat(128)})))
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use uuid::Uuid;
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route("/api/v1/restore-targets", post(register))
|
||||
.route("/api/v1/restore-targets/:id", axum::routing::put(rename))
|
||||
.route("/api/v1/capture-profiles/:id/restore-targets", get(targets))
|
||||
.route(
|
||||
"/api/v1/snapshots/:id/restore-targets",
|
||||
@@ -82,6 +83,43 @@ async fn register(
|
||||
Ok((StatusCode::CREATED, Json(target)))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Rename {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// Same rules as at registration: not blank, at most 128 characters, no control characters.
|
||||
fn valid_target_name(name: &str) -> bool {
|
||||
!name.trim().is_empty() && name.len() <= 128 && !name.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
async fn rename(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<Rename>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let actor = admin_write(&state, peer, &headers)?;
|
||||
let name = body.name.trim();
|
||||
if !valid_target_name(name) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if !state.db.rename_restore_target(id, name).map_err(internal)? {
|
||||
return Err(StatusCode::NOT_FOUND);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"restore_target.renamed",
|
||||
&format!("actor={actor} target={id}"),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn targets(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
|
||||
@@ -104,6 +104,17 @@ impl Db {
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
/// Change the display name of a restore target. Its id, identity and Outpost are not touched, so
|
||||
/// relations and jobs that refer to it stay valid. Returns false for an unknown target.
|
||||
pub fn rename_restore_target(&self, id: Uuid, name: &str) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"UPDATE restore_targets SET profile = json_set(profile, '$.name', ?2) WHERE id = ?1",
|
||||
params![id.to_string(), name],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
|
||||
Ok(self
|
||||
.restore_targets_with_activity(application)?
|
||||
|
||||
@@ -164,7 +164,9 @@ On the target agent, add a `targets` map under the application UUID, keyed by th
|
||||
}
|
||||
```
|
||||
|
||||
Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules.
|
||||
Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. A restore target can be renamed later with `PUT /api/v1/restore-targets/{id}` and `{"name": "..."}` (administrators only, 1 to 128 characters, no control characters, audited as `restore_target.renamed`). Only the display name changes: the id, the identity, the Outpost, relations and earlier jobs stay as they are. Since several applications can each have a target called `dev`, the Relations console shows the application next to every target and in its pickers, and the Refresh screen shows the application on each card. Registering a target suggests `<application> · <database>` until a name is typed.
|
||||
|
||||
Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules.
|
||||
|
||||
A custom-format archive must be readable by the `pg_restore` on the restore host. pg_restore refuses archives made by a newer pg_dump, so install a client at least as new as the one that captured. The check happens while the archive is being prepared, before the safety backup and before anything is touched, and the failure names both versions, for example `pg_restore 16.15 cannot read this archive (made by pg_dump 17.2, archive format 1.16): install a PostgreSQL client >= 17 on the restore host`. With `omit_pg_stat_statements`, the dump's own `pg_stat_statements` statements are skipped, but an extension the target already had is recreated in the schema it lived in (a target without it does not get it).
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
|
||||
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir |
|
||||
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 |
|
||||
| /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit |
|
||||
| /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | hanya name (1-128, tanpa karakter kontrol); id, identity, outpost, relasi, dan job lama tidak berubah; diaudit `restore_target.renamed` |
|
||||
| /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit |
|
||||
| /api/v1/relations | GET,POST | human | relation.manage | admin | daftar relasi, orbit dan target untuk wizard (dengan identity); POST membuat relasi atau menyebut aturan yang menolak |
|
||||
| /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit |
|
||||
|
||||
@@ -119,6 +119,7 @@ export const fetchRelations = () => api<RelationOverview>("/api/v1/relations");
|
||||
export const setOrbitEnvironment = (id: string, environment: Environment) => api<void>(`/api/v1/orbits/${id}/environment`, json("PUT", { environment }));
|
||||
export const setTargetEnvironment = (id: string, environment: Environment) =>
|
||||
api<{ ended_relations: string[] }>(`/api/v1/restore-targets/${id}/environment`, json("PUT", { environment }));
|
||||
export const renameTarget = (id: string, name: string) => api<void>(`/api/v1/restore-targets/${id}`, json("PUT", { name }));
|
||||
export const createRelation = (source_orbit_id: string, target_id: string) => api<RelationView>("/api/v1/relations", json("POST", { source_orbit_id, target_id }));
|
||||
export const retargetRelation = (id: string, target_id: string) => api<RelationView>(`/api/v1/relations/${id}`, json("PUT", { target_id }));
|
||||
export const endRelation = (id: string) => api<void>(`/api/v1/relations/${id}`, { method: "DELETE" });
|
||||
|
||||
@@ -22,8 +22,8 @@ const phases: Record<string, string> = {
|
||||
cancelled: "Cancelled",
|
||||
};
|
||||
|
||||
export function DatabaseRestore({ snapshot, application, engine }: {
|
||||
snapshot: string; application: string; engine: RestoreTarget["engine"];
|
||||
export function DatabaseRestore({ snapshot, application, applicationName, engine }: {
|
||||
snapshot: string; application: string; applicationName?: string; engine: RestoreTarget["engine"];
|
||||
}) {
|
||||
const fieldId = useId();
|
||||
const query = useQueryClient();
|
||||
@@ -112,7 +112,7 @@ export function DatabaseRestore({ snapshot, application, engine }: {
|
||||
</form>
|
||||
)}
|
||||
{registering
|
||||
? <RestoreTargetForm application={application} engine={engine} onClose={() => setRegistering(false)} />
|
||||
? <RestoreTargetForm application={application} applicationName={applicationName} engine={engine} onClose={() => setRegistering(false)} />
|
||||
: !targets.data?.length && <Button type="button" onClick={() => setRegistering(true)}>Register restore target</Button>}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ export function ReconstituteWizard({
|
||||
</div>
|
||||
|
||||
{managed && databaseMode ? (
|
||||
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id} engine={managed.engine} />
|
||||
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id} applicationName={snap?.orbit_name} engine={managed.engine} />
|
||||
) : <>
|
||||
<div className="restore-fields">
|
||||
<label className="block text-sm">
|
||||
|
||||
@@ -8,12 +8,16 @@ import { Hint } from "../ui/EmptyState";
|
||||
const field = "field";
|
||||
const uuidPattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
|
||||
|
||||
export function RestoreTargetForm({ application, engine, onClose }: {
|
||||
export function RestoreTargetForm({ application, applicationName, engine, onClose }: {
|
||||
application: string;
|
||||
/** Used to suggest a name that tells this target apart from the same environment of other applications. */
|
||||
applicationName?: string;
|
||||
engine: RestoreTarget["engine"];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [initialId] = useState(() => globalThis.crypto?.randomUUID?.() ?? "");
|
||||
const [name, setName] = useState("");
|
||||
const [named, setNamed] = useState(false);
|
||||
const qc = useQueryClient();
|
||||
const register = useMutation({
|
||||
mutationFn: registerRestoreTarget,
|
||||
@@ -42,7 +46,8 @@ export function RestoreTargetForm({ application, engine, onClose }: {
|
||||
<h4 className="font-medium text-star-100">Register a {engine === "postgres" ? "PostgreSQL" : "MySQL"} restore target</h4>
|
||||
<label className="block text-sm text-star-300">
|
||||
Target name
|
||||
<input name="name" required maxLength={128} className={field} />
|
||||
<input name="name" required maxLength={128} className={field} value={name}
|
||||
onChange={(event) => { setName(event.target.value); setNamed(true); }} />
|
||||
</label>
|
||||
<label className="block text-sm text-star-300">
|
||||
Target UUID
|
||||
@@ -55,7 +60,13 @@ export function RestoreTargetForm({ application, engine, onClose }: {
|
||||
</label>
|
||||
<label className="block text-sm text-star-300">
|
||||
Database name
|
||||
<input name="database" required maxLength={255} className={field} />
|
||||
<input name="database" required maxLength={255} className={field}
|
||||
onBlur={(event) => {
|
||||
// Suggest "<application> · <database>" until the person types their own name. The environment is
|
||||
// set afterwards in Relations, where the name can still be changed.
|
||||
const database = event.target.value.trim();
|
||||
if (!named && database && applicationName) setName(`${applicationName} · ${database}`.slice(0, 128));
|
||||
}} />
|
||||
</label>
|
||||
<Hint>Configure this target UUID under the application’s targets on the assigned agent. Keep the connection settings and credentials on that agent.</Hint>
|
||||
{register.isError && <p role="alert" className="text-sm text-orbit-red">Could not register the target. Verify its identity, UUID, and Outpost.</p>}
|
||||
|
||||
@@ -121,6 +121,7 @@ function RelationCard({ relation, runs, onChanged }: { relation: RefreshRelation
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-space-700 p-5" aria-label={`${relation.source_name} to ${relation.target_name}`}>
|
||||
<p className="text-xs uppercase tracking-wide text-star-300">Application: {relation.source_name}</p>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 className="text-lg font-semibold text-star-100">
|
||||
{relation.target_name}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, type FormEvent } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
createRelation, endRelation, fetchAccessUsers, fetchRelationAccess, fetchRelations, grantRelationAccess, refusalReason,
|
||||
retargetRelation, revokeRelationAccess, setOrbitEnvironment, setTargetEnvironment,
|
||||
renameTarget, retargetRelation, revokeRelationAccess, setOrbitEnvironment, setTargetEnvironment,
|
||||
type AccessUser, type Environment, type OrbitSetup, type RelationOverview, type RelationView, type TargetSetup,
|
||||
} from "../../api";
|
||||
import { Button } from "../ui/Button";
|
||||
@@ -50,6 +50,7 @@ export function RelationsView() {
|
||||
const orbitEnv = useMutation({ mutationFn: (v: { id: string; environment: Environment }) => setOrbitEnvironment(v.id, v.environment), onSuccess: refresh });
|
||||
const targetEnv = useMutation({ mutationFn: (v: { id: string; environment: Environment }) => setTargetEnvironment(v.id, v.environment), onSuccess: refresh });
|
||||
const create = useMutation({ mutationFn: (v: { source: string; target: string }) => createRelation(v.source, v.target), onSuccess: refresh });
|
||||
const rename = useMutation({ mutationFn: (v: { id: string; name: string }) => renameTarget(v.id, v.name), onSuccess: refresh });
|
||||
const end = useMutation({ mutationFn: endRelation, onSuccess: refresh });
|
||||
const [source, setSource] = useState("");
|
||||
|
||||
@@ -58,6 +59,10 @@ export function RelationsView() {
|
||||
return <p role="alert" className="p-6 text-star-300">Could not load relations. This hub may not support them.</p>;
|
||||
}
|
||||
|
||||
// Several applications can have a target called "dev": the application is what tells them apart.
|
||||
const appName = (t: TargetSetup) => data.orbits.find((o) => o.application_id === t.application_id)?.name ?? "Unknown application";
|
||||
// a name that already mentions the application (e.g. "presensi · dev") is not prefixed twice
|
||||
const targetLabel = (t: TargetSetup) => (t.name.toLowerCase().includes(appName(t).toLowerCase()) ? t.name : `${appName(t)} · ${t.name}`);
|
||||
const sources = data.orbits.filter((o) => o.ready);
|
||||
const chosen = data.orbits.find((o) => o.id === source);
|
||||
const targetsFor = (orbit?: OrbitSetup) =>
|
||||
@@ -109,11 +114,12 @@ export function RelationsView() {
|
||||
<h4 className="text-sm font-medium text-star-200">Restore targets</h4>
|
||||
{data.targets.length === 0 ? <p className="mt-2 text-sm text-star-300">No restore targets are registered yet. Register one from the Orbits console.</p> : (
|
||||
<table className="mt-2 w-full text-left text-sm">
|
||||
<thead className="text-star-300"><tr><th className="py-2 pr-3">Target</th><th className="pr-3">Database</th><th className="pr-3">Environment</th><th>Outpost</th></tr></thead>
|
||||
<thead className="text-star-300"><tr><th className="py-2 pr-3">Application</th><th className="pr-3">Target</th><th className="pr-3">Database</th><th className="pr-3">Environment</th><th>Outpost</th></tr></thead>
|
||||
<tbody>
|
||||
{data.targets.map((t: TargetSetup) => (
|
||||
<tr key={t.id} className="border-t border-space-700 text-star-100">
|
||||
<td className="py-2 pr-3">{t.name}</td>
|
||||
<td className="py-2 pr-3">{appName(t)}</td>
|
||||
<td className="pr-3"><TargetName target={t} pending={rename.isPending} onSave={(name) => rename.mutate({ id: t.id, name })} /></td>
|
||||
<td className="pr-3 text-star-300">{t.engine} · {t.identity.database}</td>
|
||||
<td className="pr-3" style={{ minWidth: 160 }}>
|
||||
<Select aria-label={`Environment of ${t.name}`} value={t.environment ?? ""} onChange={(e) => targetEnv.mutate({ id: t.id, environment: e.target.value as Environment })}>
|
||||
@@ -132,7 +138,7 @@ export function RelationsView() {
|
||||
{targetEnv.data && targetEnv.data.ended_relations.length > 0 && (
|
||||
<p role="status" className="mt-3 text-sm text-orbit-red">Relabelling that target ended {targetEnv.data.ended_relations.length} relation(s) into it.</p>
|
||||
)}
|
||||
{(orbitEnv.isError || targetEnv.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was refused.</p>}
|
||||
{(orbitEnv.isError || targetEnv.isError || rename.isError) && <p role="alert" className="mt-3 text-sm text-orbit-red">That change was refused.</p>}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="rel-new">
|
||||
@@ -152,7 +158,7 @@ export function RelationsView() {
|
||||
Target database
|
||||
<Select name="target" required key={source}>
|
||||
<option value="" disabled>{chosen ? "Choose…" : "Pick a source first"}</option>
|
||||
{targetsFor(chosen).map((t) => <option key={t.id} value={t.id}>{t.name} ({t.environment})</option>)}
|
||||
{targetsFor(chosen).map((t) => <option key={t.id} value={t.id}>{targetLabel(t)} ({t.environment})</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<div className="sm:col-span-2 flex items-center gap-4">
|
||||
@@ -172,7 +178,7 @@ export function RelationsView() {
|
||||
{active.length === 0 ? <p className="mt-2 text-sm text-star-300">No active relations.</p> : (
|
||||
<div className="mt-3 space-y-4">
|
||||
{active.map((relation) => (
|
||||
<RelationCard key={relation.id} relation={relation} targets={targetsFor({ id: relation.source_orbit_id, name: relation.source_name, application_id: data.targets.find((t) => t.id === relation.target_id)?.application_id ?? null, engine: relation.engine, environment: relation.source_environment, ready: true, reason: null })}
|
||||
<RelationCard key={relation.id} relation={relation} labelOf={targetLabel} targets={targetsFor({ id: relation.source_orbit_id, name: relation.source_name, application_id: data.targets.find((t) => t.id === relation.target_id)?.application_id ?? null, engine: relation.engine, environment: relation.source_environment, ready: true, reason: null })}
|
||||
onEnd={() => end.mutate(relation.id)} ending={end.isPending} onChanged={refresh} />
|
||||
))}
|
||||
</div>
|
||||
@@ -190,8 +196,8 @@ export function RelationsView() {
|
||||
);
|
||||
}
|
||||
|
||||
function RelationCard({ relation, targets, onEnd, ending, onChanged }: {
|
||||
relation: RelationView; targets: TargetSetup[]; onEnd: () => void; ending: boolean; onChanged: () => void;
|
||||
function RelationCard({ relation, targets, labelOf, onEnd, ending, onChanged }: {
|
||||
relation: RelationView; targets: TargetSetup[]; labelOf: (target: TargetSetup) => string; onEnd: () => void; ending: boolean; onChanged: () => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const retarget = useMutation({ mutationFn: (target: string) => retargetRelation(relation.id, target), onSuccess: onChanged });
|
||||
@@ -216,7 +222,7 @@ function RelationCard({ relation, targets, onEnd, ending, onChanged }: {
|
||||
Point at another target
|
||||
<Select name="target" key={relation.id}>
|
||||
<option value="" disabled>Choose…</option>
|
||||
{others.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
|
||||
{others.map((t) => <option key={t.id} value={t.id}>{labelOf(t)}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<Button type="submit" disabled={retarget.isPending}>Retarget</Button>
|
||||
@@ -288,3 +294,31 @@ function RelationAccess({ relationId, onChange }: { relationId: string; onChange
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A target's name with an inline rename. The id and the database it points at never change. */
|
||||
function TargetName({ target, pending, onSave }: { target: TargetSetup; pending: boolean; onSave: (name: string) => void }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
if (!editing) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
{target.name}
|
||||
<button type="button" className="console-control" aria-label={`Rename ${target.name}`} onClick={() => setEditing(true)}>Rename</button>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form
|
||||
className="flex items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const name = String(new FormData(event.currentTarget).get("name") ?? "").trim();
|
||||
if (name && name !== target.name) onSave(name);
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
<input name="name" aria-label={`New name for ${target.name}`} defaultValue={target.name} required maxLength={128} autoFocus className="field" />
|
||||
<Button type="submit" disabled={pending}>Save</Button>
|
||||
<Button type="button" onClick={() => setEditing(false)}>Cancel</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user