kopiur_api/maintenance.rs
1//! The `Maintenance` CRD — schedules `kopia maintenance run` quick + full and
2//! manages the ownership lease. At most one per repository. ADR-0001 §3.7.
3
4use crate::common::{CredentialProjection, CronSpec, FailurePolicy, MoverSpec, RepositoryRef};
5use k8s_openapi::apimachinery::pkg::apis::meta::v1::Condition;
6use kube::CustomResource;
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10/// The schedule an operator-managed `Maintenance` uses when the owning
11/// `Repository`/`ClusterRepository` does not override it: quick every 6h (30m
12/// jitter), full daily at 03:00 (1h jitter). Shared by the webhook (defaulting),
13/// the controller (projection), and tests, so the default lives in exactly one
14/// place. ADR §3.7.
15///
16/// ```
17/// use kopiur_api::default_maintenance_schedule;
18///
19/// let s = default_maintenance_schedule();
20/// assert_eq!(s.quick.cron, "0 */6 * * *");
21/// assert_eq!(s.quick.jitter.as_deref(), Some("30m"));
22/// assert_eq!(s.full.cron, "0 3 * * *");
23/// assert_eq!(s.full.jitter.as_deref(), Some("1h"));
24/// assert!(s.timezone.is_none());
25/// ```
26pub fn default_maintenance_schedule() -> MaintenanceSchedule {
27 MaintenanceSchedule {
28 quick: CronSpec {
29 cron: "0 */6 * * *".to_string(),
30 jitter: Some("30m".to_string()),
31 timezone: None,
32 },
33 full: CronSpec {
34 cron: "0 3 * * *".to_string(),
35 jitter: Some("1h".to_string()),
36 timezone: None,
37 },
38 timezone: None,
39 }
40}
41
42/// Maintenance schedule and ownership lease for one `Repository`/`ClusterRepository`.
43///
44/// Not `Eq`: `mover` transitively embeds k8s-openapi types.
45#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
46#[kube(
47 group = "kopiur.home-operations.com",
48 version = "v1alpha1",
49 kind = "Maintenance",
50 namespaced,
51 status = "MaintenanceStatus",
52 shortname = "kopiamaint",
53 category = "kopiur",
54 printcolumn = r#"{"name":"Repository","type":"string","jsonPath":".spec.repository.name"}"#,
55 printcolumn = r#"{"name":"Owner","type":"string","jsonPath":".status.ownership.owner"}"#,
56 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
57)]
58#[serde(rename_all = "camelCase")]
59pub struct MaintenanceSpec {
60 /// Reference to the `Repository` or `ClusterRepository` to maintain.
61 pub repository: RepositoryRef,
62 /// quick (cheap) and full (`--full`, reclamation) maintenance crons.
63 pub schedule: MaintenanceSchedule,
64 /// Maintenance ownership lease holder and takeover policy.
65 pub ownership: Ownership,
66 /// Mover (Job pod) overrides for the maintenance run.
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub mover: Option<MoverSpec>,
69 /// How a failed maintenance run is retried and bounded (backoff, deadline).
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub failure_policy: Option<FailurePolicy>,
72 /// Opt-in projection of the repository's credential Secret(s) into this run's namespace (default off).
73 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub credential_projection: Option<CredentialProjection>,
75}
76
77/// quick (cheap) and full (`--full`, reclamation) maintenance crons and a shared timezone.
78#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
79#[serde(rename_all = "camelCase")]
80pub struct MaintenanceSchedule {
81 /// Cron and jitter for `kopia maintenance run` (quick, cheap index/log work).
82 pub quick: CronSpec,
83 /// Cron and jitter for `kopia maintenance run --full` (content reclamation).
84 pub full: CronSpec,
85 /// IANA timezone both crons are evaluated in; absent means the controller default.
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub timezone: Option<String>,
88}
89
90/// Maintenance ownership lease holder and takeover policy.
91#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
92#[serde(rename_all = "camelCase")]
93pub struct Ownership {
94 /// Stable lease holder identity (e.g. `kopia-operator/nas-primary`).
95 pub owner: String,
96 /// Previous lease strings still recognized as SELF (a migration path):
97 /// when kopia's currently-recorded maintenance owner matches the owner
98 /// derived from one of these aliases, a run treats the lease as its own —
99 /// it claims it and re-stamps `owner`, upgrading the recorded owner to the
100 /// current format. The operator populates this when a repository's managed
101 /// Maintenance moves to a cluster-qualified lease (identityDefaults.cluster),
102 /// so the transition never yields the lease to what merely looks like a
103 /// foreign owner.
104 #[serde(default, skip_serializing_if = "Vec::is_empty")]
105 pub owner_aliases: Vec<String>,
106 /// What to do when the lease is already held by a different `owner`.
107 #[serde(default)]
108 pub takeover_policy: TakeoverPolicy,
109}
110
111/// What to do when another owner already holds the lease. Defaults to `Never`
112/// (the safest: never seize a lease another owner holds).
113#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default, JsonSchema)]
114pub enum TakeoverPolicy {
115 /// Never take over a lease another owner holds (default, safest).
116 #[default]
117 Never,
118 /// Surface a condition prompting an operator to decide.
119 PromptCondition,
120 /// Forcibly claim the lease.
121 Force,
122}
123
124/// What to do about the ownership lease, decided from the takeover policy and
125/// whether another owner currently holds it (ADR §3.7). Exhaustive over
126/// [`TakeoverPolicy`].
127///
128/// Lives in `kopiur-api` (not the controller) because the lease decision is made
129/// in the mover for object-store repositories — only something with repo access
130/// can read `kopia maintenance info` to learn the current holder. Keeping the
131/// pure decision here gives the controller (filesystem) and the mover
132/// (object-store) one shared, exhaustively-matched source of truth.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum LeaseAction {
135 /// Claim the lease (we hold it or it is free).
136 Claim,
137 /// Forcibly take the lease from the current holder.
138 Takeover,
139 /// Surface a condition prompting a human to decide; do not claim.
140 Prompt,
141 /// Another owner holds it and policy is `Never`: do nothing, requeue.
142 Yield,
143}
144
145/// Decide the lease action. `held_by_other` is true when a *different* owner
146/// currently holds the maintenance lease for this repository.
147///
148/// ```
149/// use kopiur_api::{lease_action, LeaseAction, TakeoverPolicy};
150///
151/// // Free (or already ours) → always claim, regardless of policy.
152/// assert_eq!(lease_action(TakeoverPolicy::Never, false), LeaseAction::Claim);
153/// // Held by another → dispatch on policy.
154/// assert_eq!(lease_action(TakeoverPolicy::Never, true), LeaseAction::Yield);
155/// assert_eq!(lease_action(TakeoverPolicy::Force, true), LeaseAction::Takeover);
156/// ```
157pub fn lease_action(policy: TakeoverPolicy, held_by_other: bool) -> LeaseAction {
158 if !held_by_other {
159 // Free or already ours → just (re)claim.
160 return LeaseAction::Claim;
161 }
162 match policy {
163 TakeoverPolicy::Never => LeaseAction::Yield,
164 TakeoverPolicy::PromptCondition => LeaseAction::Prompt,
165 TakeoverPolicy::Force => LeaseAction::Takeover,
166 }
167}
168
169/// The logical maintenance-lease string the operator uses for a repository's
170/// DEFAULT-MANAGED `Maintenance` (ADR §3.7). Single derivation, shared by the
171/// managed-Maintenance projection and the bootstrap mover's initial kopia
172/// owner stamp, so they cannot drift.
173///
174/// `cluster` is `Repository`/`ClusterRepository.spec.identityDefaults.cluster`
175/// (M1/M5): `None` keeps the original, pre-multi-cluster format (a same-named
176/// `ClusterRepository`/`Repository` in two clusters would otherwise derive the
177/// SAME lease and race each other's maintenance on a shared repo — kopia has no
178/// cross-host maintenance lock of its own, only this owner lease); `Some(c)`
179/// inserts the cluster as the second path segment so each cluster claims a
180/// distinct lease (and, via [`kopia_lease_identity`], a distinct kopia owner)
181/// for what is otherwise the same repository name.
182///
183/// ```
184/// use kopiur_api::common::RepositoryKind;
185/// use kopiur_api::maintenance::managed_lease;
186///
187/// assert_eq!(
188/// managed_lease(RepositoryKind::Repository, "media", "nas", None),
189/// "kopiur/media/nas"
190/// );
191/// assert_eq!(
192/// managed_lease(RepositoryKind::Repository, "media", "nas", Some("east")),
193/// "kopiur/east/media/nas"
194/// );
195/// assert_eq!(
196/// managed_lease(RepositoryKind::ClusterRepository, "ignored", "shared", None),
197/// "kopiur/clusterrepository/shared"
198/// );
199/// assert_eq!(
200/// managed_lease(RepositoryKind::ClusterRepository, "ignored", "shared", Some("east")),
201/// "kopiur/east/clusterrepository/shared"
202/// );
203/// ```
204pub fn managed_lease(
205 kind: crate::common::RepositoryKind,
206 namespace: &str,
207 name: &str,
208 cluster: Option<&str>,
209) -> String {
210 use crate::common::RepositoryKind;
211 match (kind, cluster) {
212 (RepositoryKind::Repository, None) => format!("kopiur/{namespace}/{name}"),
213 (RepositoryKind::Repository, Some(c)) => format!("kopiur/{c}/{namespace}/{name}"),
214 (RepositoryKind::ClusterRepository, None) => {
215 format!("kopiur/clusterrepository/{name}")
216 }
217 (RepositoryKind::ClusterRepository, Some(c)) => {
218 format!("kopiur/{c}/clusterrepository/{name}")
219 }
220 }
221}
222
223/// The mover-owned condition recording lease state on `Maintenance.status`:
224/// `True` (lease claimed, run proceeded) or `False` with one of the reasons
225/// below. Written by the mover, matched by the controller (Ready degradation)
226/// and the kubectl plugin — one definition so the producers and readers cannot
227/// drift.
228pub const LEASE_OWNED_CONDITION: &str = "LeaseOwned";
229/// `LeaseOwned=False` reason: a foreign owner holds the lease and
230/// `takeoverPolicy: Never` — the run yielded.
231pub const LEASE_HELD_BY_OTHER_REASON: &str = "LeaseHeldByOther";
232/// `LeaseOwned=False` reason: a foreign owner holds the lease and
233/// `takeoverPolicy: PromptCondition` — the run yielded, prompting the operator
234/// to set `Force`.
235pub const LEASE_TAKEOVER_PROMPT_REASON: &str = "LeaseTakeoverPrompt";
236
237/// Hostname-unsafe-character rule shared by every `kopia_lease_identity` path:
238/// lowercase, `[a-z0-9-]` kept, everything else collapses to `-`, repeated `-`
239/// collapsed, then trimmed from both ends. Pulled out so the character class
240/// itself can never drift between the legacy (whole-string) and
241/// cluster-qualified (per-segment) sanitizers below.
242fn sanitize_lease_fragment(s: &str) -> String {
243 let mut out: String = s
244 .to_ascii_lowercase()
245 .chars()
246 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
247 .collect();
248 while out.contains("--") {
249 out = out.replace("--", "-");
250 }
251 out.trim_matches('-').to_string()
252}
253
254/// A single DNS label's worth of cap for the legacy (pre-multi-cluster)
255/// hostname derivation. Unchanged from the original implementation — every
256/// existing doctest/behavior for a non-cluster-qualified lease must stay
257/// byte-identical.
258const LEGACY_HOSTNAME_MAX: usize = 63;
259
260/// Cap for the cluster-qualified (dot-joined) hostname derivation below —
261/// kopia's identity hostname has no real limit, but this mirrors DNS's overall
262/// name ceiling as a defensive backstop (see [`kopia_lease_identity`] doc).
263const CLUSTER_HOSTNAME_MAX: usize = 253;
264
265/// The STABLE kopia client identity a maintenance mover assumes for `lease`
266/// (`(username, hostname)`); the mover sets it with `kopia repository
267/// set-client` so kopia's designated-owner check compares something stable —
268/// the pod's own identity is ephemeral (a new hostname every run), which is
269/// why comparing kopia's recorded owner against it can never work.
270///
271/// The derivation forks on the lease's own shape (the mover only ever sees the
272/// lease STRING, never the CR it came from, so the rule must be derivable from
273/// the string alone):
274///
275/// * **Exactly 4 `/`-separated segments, AND the first is literally `"kopiur"`**
276/// — [`managed_lease`]'s two cluster-qualified formats
277/// (`kopiur/{cluster}/{namespace}/{name}`,
278/// `kopiur/{cluster}/clusterrepository/{name}`) — sanitize each segment
279/// INDEPENDENTLY (the same character rule, but with no per-segment cap and
280/// without ever crossing a segment boundary) and join with `.`. Every
281/// generated segment is already a lowercase, dot-free RFC 1123 label (the
282/// cluster name is validated as such; Kubernetes namespace/resource names
283/// are too), so for a generated lease this is verbatim
284/// `kopiur.{cluster}.{namespace}.{name}` — and CRITICALLY, injective: two
285/// leases can only produce the same hostname if they were `/`-split
286/// identically, because a `-` inside one segment can no longer be forged
287/// into a fake `.` boundary the way collapsing everything to `-` allowed
288/// (`kopiur/east-prod/db/x` and `kopiur/east/prod-db/x` used to collide).
289/// No per-segment cap also means a long cluster/namespace/name no longer
290/// collides via truncation — capped defensively only on the TOTAL, at
291/// [`CLUSTER_HOSTNAME_MAX`] (253, the identity-hostname byte cap enforced by
292/// [`crate::validate::validate_identity_component`]), which cluster (≤32) +
293/// two Kubernetes names + `"kopiur"` cannot reach in practice.
294///
295/// The `"kopiur"`-first-segment check matters because [`managed_lease`] is
296/// NOT the only source of lease strings: `Ownership.owner` is a free-form
297/// field a user can hand-author, and a hand-authored value that HAPPENS to
298/// have 4 `/`-separated segments (e.g. `a/b/c/d`) is not one of our
299/// generated formats at all. Gating the dot-join on the reserved `"kopiur"`
300/// prefix — which [`managed_lease`] always emits and a user has no reason to
301/// — guarantees a hand-authored owner's derivation can never change across
302/// an operator upgrade merely because it happens to split into 4 segments;
303/// it always falls to the legacy whole-string sanitizer below, exactly as it
304/// did pre-M6. Without this gate, such an owner would silently switch from
305/// its `a-b-c-d` identity to `a.b.c.d`, and with `takeoverPolicy: Never` the
306/// repository's maintenance would then yield forever.
307/// * **Any other shape** (the legacy 3-segment formats, a 4-segment lease NOT
308/// `"kopiur"`-prefixed, or any other hand-authored `Ownership.owner`/alias)
309/// — the ORIGINAL whole-string sanitizer: collapse the entire lease through
310/// the same character rule and cap at [`LEGACY_HOSTNAME_MAX`] (63, a DNS
311/// label). Byte-identical to every pre-M6 lease this function has ever
312/// produced.
313///
314/// ```
315/// use kopiur_api::maintenance::kopia_lease_identity;
316///
317/// // Legacy (3-segment / hand-authored): unchanged.
318/// assert_eq!(
319/// kopia_lease_identity("kopiur/media/nas"),
320/// ("kopiur".to_string(), "kopiur-media-nas".to_string())
321/// );
322///
323/// // Cluster-qualified (4-segment, "kopiur"-prefixed): dot-joined, segment-preserving.
324/// assert_eq!(
325/// kopia_lease_identity("kopiur/east/media/nas"),
326/// ("kopiur".to_string(), "kopiur.east.media.nas".to_string())
327/// );
328///
329/// // A hand-authored 4-segment owner that is NOT "kopiur"-prefixed: legacy
330/// // sanitization, byte-identical to pre-M6 — never dot-joined.
331/// assert_eq!(
332/// kopia_lease_identity("a/b/c/d"),
333/// ("kopiur".to_string(), "a-b-c-d".to_string())
334/// );
335///
336/// // Injective: a '-' inside a segment can no longer masquerade as a boundary.
337/// assert_ne!(
338/// kopia_lease_identity("kopiur/east-prod/db/x").1,
339/// kopia_lease_identity("kopiur/east/prod-db/x").1
340/// );
341/// ```
342pub fn kopia_lease_identity(lease: &str) -> (String, String) {
343 let segments: Vec<&str> = lease.split('/').collect();
344 let host = match segments.as_slice() {
345 [a, b, c, d] if *a == "kopiur" => {
346 let joined = [a, b, c, d]
347 .iter()
348 .map(|s| sanitize_lease_fragment(s))
349 .collect::<Vec<_>>()
350 .join(".");
351 let capped: String = joined.chars().take(CLUSTER_HOSTNAME_MAX).collect();
352 capped.trim_end_matches(['.', '-']).to_string()
353 }
354 _ => {
355 let host = sanitize_lease_fragment(lease);
356 let capped: String = host.chars().take(LEGACY_HOSTNAME_MAX).collect();
357 capped.trim_end_matches('-').to_string()
358 }
359 };
360 ("kopiur".to_string(), host)
361}
362
363/// The full `user@hostname` owner string kopia records for `lease` — what the
364/// mover compares `maintenance info`'s owner against, and what the bootstrap
365/// stamps on a repository it CREATES.
366///
367/// ```
368/// use kopiur_api::maintenance::kopia_owner_for_lease;
369///
370/// assert_eq!(kopia_owner_for_lease("kopiur/media/nas"), "kopiur@kopiur-media-nas");
371/// ```
372pub fn kopia_owner_for_lease(lease: &str) -> String {
373 let (user, host) = kopia_lease_identity(lease);
374 format!("{user}@{host}")
375}
376
377/// Whether kopia's currently-recorded maintenance owner is a DIFFERENT owner
378/// than us — i.e. neither our own lease's owner nor one of our recognized
379/// [`Ownership::owner_aliases`] (the migration path: a repo whose managed
380/// `Maintenance` moved to a new lease format still recognizes the owner it
381/// used to stamp as itself, so the transition claims and re-stamps rather than
382/// yielding to what would otherwise look like a foreign owner).
383///
384/// `current` is empty for a never-run repository (kopia's own "no owner set"
385/// state) — never "held by another".
386///
387/// ```
388/// use kopiur_api::maintenance::{kopia_owner_for_lease, lease_held_by_other};
389///
390/// let lease = "kopiur/east/media/nas";
391/// let alias = "kopiur/media/nas"; // the pre-cluster lease this repo used to use
392/// let mine = kopia_owner_for_lease(lease);
393/// let legacy = kopia_owner_for_lease(alias);
394///
395/// // Never-run repository: empty owner is never "held by another".
396/// assert!(!lease_held_by_other("", lease, &[]));
397/// // Already ours: not held by another.
398/// assert!(!lease_held_by_other(&mine, lease, &[]));
399/// // The recognized alias's owner: treated as self (migration path).
400/// assert!(!lease_held_by_other(&legacy, lease, &[alias.to_string()]));
401/// // The SAME string but the alias isn't registered: a genuine foreign owner.
402/// assert!(lease_held_by_other(&legacy, lease, &[]));
403/// // Any other owner: foreign.
404/// assert!(lease_held_by_other("someone@else", lease, &[alias.to_string()]));
405/// ```
406pub fn lease_held_by_other(current: &str, lease: &str, aliases: &[String]) -> bool {
407 if current.is_empty() {
408 return false;
409 }
410 if current == kopia_owner_for_lease(lease) {
411 return false;
412 }
413 !aliases
414 .iter()
415 .any(|alias| current == kopia_owner_for_lease(alias))
416}
417
418/// The `kubectl kopiur` invocation that stamps a `Maintenance` run request,
419/// quoted in the fix hint when the annotation does not parse.
420const MAINTENANCE_RUN_COMMAND: &str = "kubectl kopiur maintenance run";
421
422/// Parse the `run-requested`/`run-mode` annotations into a manual-run request.
423/// `Ok(None)` = no request; `Err` = the annotations are present but malformed
424/// (the messages say how to fix). Shared by the admission webhook and the
425/// controller so validation cannot fork (SKILL "one validator, two callers").
426///
427/// The timestamp half is [`crate::common::parse_run_requested_at`] — the one
428/// parser every "run it now" surface shares (both replication kinds call it
429/// directly); only the `run-mode` companion is maintenance-specific.
430pub fn parse_run_annotations(
431 annotations: Option<&std::collections::BTreeMap<String, String>>,
432) -> Result<Option<(chrono::DateTime<chrono::Utc>, ManualRunMode)>, String> {
433 let Some(at) = crate::common::parse_run_requested_at(annotations, MAINTENANCE_RUN_COMMAND)?
434 else {
435 return Ok(None);
436 };
437 let mode = match annotations.and_then(|a| a.get(crate::consts::RUN_MODE_ANNOTATION)) {
438 None => ManualRunMode::Quick,
439 Some(raw_mode) => ManualRunMode::parse(raw_mode).ok_or_else(|| {
440 format!(
441 "annotation {} must be `quick` or `full` (got {raw_mode:?}). \
442 Fix: re-annotate with a valid mode",
443 crate::consts::RUN_MODE_ANNOTATION
444 )
445 })?,
446 };
447 Ok(Some((at, mode)))
448}
449
450/// Inline maintenance control on a `Repository`/`ClusterRepository` (`spec.maintenance`).
451///
452/// Not `Eq`: `mover` transitively embeds k8s-openapi types.
453#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
454#[serde(rename_all = "camelCase")]
455pub struct RepositoryMaintenanceSpec {
456 /// Whether the operator manages a `Maintenance` CR for this repository (default `true`).
457 #[serde(default = "crate::common::default_true")]
458 pub enabled: bool,
459 /// Schedule override; absent uses the default quick-6h / full-daily schedule.
460 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub schedule: Option<MaintenanceSchedule>,
462 /// Mover overrides for the managed `Maintenance`.
463 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub mover: Option<MoverSpec>,
465 /// Failure handling (backoff/deadline) for the managed `Maintenance` run.
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub failure_policy: Option<FailurePolicy>,
468 /// Lease takeover policy for the managed `Maintenance` (default `Never`).
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub takeover_policy: Option<TakeoverPolicy>,
471 /// ClusterRepository only: namespace the managed `Maintenance` CR is created in (default the operator's namespace).
472 #[serde(default, skip_serializing_if = "Option::is_none")]
473 pub namespace: Option<String>,
474}
475
476impl Default for RepositoryMaintenanceSpec {
477 /// Default-on with no overrides. `enabled` is `true` here to match the serde
478 /// `default_true` so a constructed default and a deserialized `{}` agree.
479 fn default() -> Self {
480 Self {
481 enabled: true,
482 schedule: None,
483 mover: None,
484 failure_policy: None,
485 takeover_policy: None,
486 namespace: None,
487 }
488 }
489}
490
491/// Observed maintenance state: lease holder and per-kind run results.
492#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default, JsonSchema)]
493#[serde(rename_all = "camelCase")]
494pub struct MaintenanceStatus {
495 /// The `metadata.generation` this status reflects, for staleness detection.
496 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub observed_generation: Option<i64>,
498 /// Current lease holder, if the lease has been claimed.
499 #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub ownership: Option<OwnershipStatus>,
501 /// Last/next-run state for the quick maintenance schedule.
502 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub quick: Option<RunStatus>,
504 /// Last/next-run state for the full maintenance schedule.
505 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub full: Option<RunStatus>,
507 /// Standard Kubernetes conditions surfacing maintenance health.
508 #[serde(default, skip_serializing_if = "Vec::is_empty")]
509 pub conditions: Vec<Condition>,
510 /// State of the most recent annotation-requested out-of-band run; absent until one is requested.
511 #[serde(default, skip_serializing_if = "Option::is_none")]
512 pub manual_run: Option<ManualRunStatus>,
513}
514
515/// Which maintenance kind a manual (annotation-requested) run performs; the wire
516/// values are the `run-mode` annotation values. Defaults to `quick`.
517#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default, JsonSchema)]
518#[serde(rename_all = "camelCase")]
519pub enum ManualRunMode {
520 /// `kopia maintenance run` (quick); the default when `run-mode` is absent.
521 #[default]
522 Quick,
523 /// `kopia maintenance run --full`.
524 Full,
525}
526
527impl ManualRunMode {
528 /// Parse a `run-mode` annotation value. Exact-match, lowercase — the same
529 /// strings serde uses on the wire.
530 pub fn parse(s: &str) -> Option<Self> {
531 match s {
532 "quick" => Some(Self::Quick),
533 "full" => Some(Self::Full),
534 _ => None,
535 }
536 }
537
538 /// The stable wire/annotation string.
539 pub fn label(self) -> &'static str {
540 match self {
541 Self::Quick => "quick",
542 Self::Full => "full",
543 }
544 }
545}
546
547/// Lifecycle of a manual run.
548///
549/// **Closed on the wire, open on decode.** The CRD schema still admits exactly
550/// `Running`/`Succeeded`/`Failed` — the apiserver rejects anything else on
551/// every write — but [`Self::Unknown`] exists so a value written by a NEWER
552/// kopiur decodes instead of failing the typed watch for the whole Kind. The
553/// schema `description` this type publishes deliberately still reads "Closed
554/// enum." and is frozen there; see `phase_serde!` on why the rustdoc and the
555/// schema text diverge.
556///
557/// ```
558/// use kopiur_api::maintenance::ManualRunPhase;
559///
560/// assert_eq!(serde_json::to_value(ManualRunPhase::Running).unwrap(), "Running");
561/// // An unrecognized phase from a newer operator decodes instead of erroring.
562/// let p: ManualRunPhase = serde_json::from_value(serde_json::json!("Queued")).unwrap();
563/// assert_eq!(p, ManualRunPhase::Unknown("Queued".into()));
564/// assert_eq!(serde_json::to_value(&p).unwrap(), "Queued");
565/// ```
566#[derive(Clone, Debug, PartialEq, Eq)]
567pub enum ManualRunPhase {
568 /// The mover Job for this request is in flight.
569 Running,
570 /// The run finished successfully or yielded the lease cleanly (see the `LeaseOwned` condition).
571 Succeeded,
572 /// The run's Job failed; conditions carry the detail.
573 Failed,
574 /// A phase string this build does not recognize (newer operator, or legacy
575 /// stored data). Decode-compat only — hidden from the CRD schema, never
576 /// produced by this build. Never counted as a finished run, so a
577 /// re-run request is never deduped against it.
578 Unknown(String),
579}
580
581crate::common::phase_serde!(ManualRunPhase, "Lifecycle of a manual run. Closed enum.");
582
583impl crate::common::PhaseLabel for ManualRunPhase {
584 const ALL: &'static [Self] = &[Self::Running, Self::Succeeded, Self::Failed];
585 fn label(&self) -> &str {
586 match self {
587 Self::Running => "Running",
588 Self::Succeeded => "Succeeded",
589 Self::Failed => "Failed",
590 Self::Unknown(s) => s,
591 }
592 }
593 fn unknown(raw: String) -> Self {
594 Self::Unknown(raw)
595 }
596}
597
598/// Bookkeeping for the most recent annotation-requested run.
599#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default, JsonSchema)]
600#[serde(rename_all = "camelCase")]
601pub struct ManualRunStatus {
602 /// The `run-requested` annotation value this status reflects (RFC3339).
603 #[serde(default, skip_serializing_if = "Option::is_none")]
604 pub requested_at: Option<String>,
605 /// The run kind that was performed.
606 #[serde(default, skip_serializing_if = "Option::is_none")]
607 pub mode: Option<ManualRunMode>,
608 /// Where the run is in its lifecycle.
609 #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub phase: Option<ManualRunPhase>,
611 /// RFC3339 instant the run reached a terminal phase.
612 // Deliberately serialized EVEN WHEN `None` (no `skip_serializing_if`), for
613 // the same reason as `common::ReplicationManualRunStatus::completed_at`: a
614 // non-terminal phase emits `"completedAt": null` so the merge-patch CLEARS
615 // the previous run's stamp instead of leaving it standing over a fresh
616 // `Running` (#394). The apiserver answers that null by deleting the key
617 // (plain RFC-7386) or by storing the null verbatim — a nullable CRD field on
618 // k8s 1.33 was observed doing the latter — and both decode back to `None`,
619 // so no stale timestamp survives either way. Maintenance patches `manualRun`
620 // unconditionally (no noop guard), so here the stake is a truthful status
621 // rather than a non-converging write loop.
622 //
623 // This depends on `patch_status` sending `kube::api::Patch::Merge`
624 // (`crates/controller/src/io/apply.rs`). Under `Patch::Apply` an explicit
625 // null does NOT clear the field, and this contract silently breaks.
626 //
627 // Kept a plain comment rather than rustdoc on purpose: doc comments become
628 // the CRD `description` (`kubectl explain`, docs/field-reference.md).
629 #[serde(default)]
630 pub completed_at: Option<String>,
631}
632
633/// Observed ownership-lease state: who holds it and since when.
634#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default, JsonSchema)]
635#[serde(rename_all = "camelCase")]
636pub struct OwnershipStatus {
637 /// The current lease holder's identity (matches `Ownership.owner`).
638 #[serde(default, skip_serializing_if = "Option::is_none")]
639 pub owner: Option<String>,
640 /// RFC3339 instant the lease was claimed.
641 #[serde(default, skip_serializing_if = "Option::is_none")]
642 pub claimed_at: Option<String>,
643}
644
645/// Per-kind (quick/full) run status.
646#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default, JsonSchema)]
647#[serde(rename_all = "camelCase")]
648pub struct RunStatus {
649 /// RFC3339 instant of the most recent run of this kind.
650 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub last_run_at: Option<String>,
652 /// RFC3339 instant of the next scheduled run of this kind (cron + jitter, pinned).
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub next_scheduled_at: Option<String>,
655 /// RFC3339 instant the controller last observed this kind's per-slot Job reach terminal success.
656 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub last_handled_at: Option<String>,
658 /// Count of back-to-back failed runs of this kind; resets on success.
659 #[serde(default, skip_serializing_if = "Option::is_none")]
660 pub consecutive_failures: Option<i64>,
661 /// Bytes of storage reclaimed by the most recent run of this kind.
662 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub last_content_reclaimed_bytes: Option<i64>,
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use crate::common::{PhaseLabel, RepositoryKind};
670 use crate::testutil::from_yaml;
671 use kube::core::CustomResourceExt;
672
673 #[test]
674 fn manual_run_phase_all_covers_every_variant_uniquely() {
675 // `ManualRunPhase` was the one phase enum with no `PhaseLabel` impl, so
676 // nothing could enumerate it. Same tripwire as the other phases: every
677 // variant in ALL, unique non-empty labels, and the label string equal to
678 // the serde encoding (this phase is written to `status.manualRun.phase`,
679 // so a label that drifts from the wire value would mislabel metrics and
680 // any CLI rendering).
681 let labels: Vec<&str> = ManualRunPhase::ALL.iter().map(|p| p.label()).collect();
682 assert_eq!(ManualRunPhase::ALL.len(), 3);
683 assert!(labels.iter().all(|l| !l.is_empty()));
684 let mut sorted = labels.clone();
685 sorted.sort_unstable();
686 sorted.dedup();
687 assert_eq!(sorted.len(), labels.len(), "phase labels must be unique");
688 for p in ManualRunPhase::ALL {
689 assert_eq!(
690 serde_json::to_value(p).expect("serialize"),
691 p.label(),
692 "{p:?}"
693 );
694 }
695 }
696
697 #[test]
698 fn manual_run_status_roundtrips_camel_case_and_nulls_a_missing_completion() {
699 // Parsed the cluster's way (YAML -> serde_json::Value -> typed), which
700 // is the only path that proves the camelCase wire names land.
701 let status: MaintenanceStatus = from_yaml(
702 "manualRun:\n requestedAt: 2026-06-11T12:00:00Z\n mode: full\n phase: Succeeded\n completedAt: 2026-06-11T12:01:42Z\n",
703 );
704 let manual = status.manual_run.expect("manualRun decodes");
705 assert_eq!(manual.requested_at.as_deref(), Some("2026-06-11T12:00:00Z"));
706 assert_eq!(manual.mode, Some(ManualRunMode::Full));
707 assert_eq!(manual.phase, Some(ManualRunPhase::Succeeded));
708 assert_eq!(manual.completed_at.as_deref(), Some("2026-06-11T12:01:42Z"));
709 let json = serde_json::to_value(&manual).unwrap();
710 assert_eq!(json["requestedAt"], "2026-06-11T12:00:00Z");
711 assert_eq!(json["mode"], "full");
712 assert_eq!(json["phase"], "Succeeded");
713 assert_eq!(json["completedAt"], "2026-06-11T12:01:42Z");
714
715 // #394: a non-terminal run emits an EXPLICIT null completedAt, so the
716 // merge-patch clears the previous run's stamp rather than leaving it
717 // standing over a fresh `Running`. Whether the apiserver deletes the key
718 // or stores the null, it decodes back to `None`.
719 let running = serde_json::to_value(ManualRunStatus {
720 requested_at: Some("2026-06-11T13:00:00Z".into()),
721 mode: Some(ManualRunMode::Quick),
722 phase: Some(ManualRunPhase::Running),
723 completed_at: None,
724 })
725 .unwrap();
726 assert_eq!(
727 running,
728 serde_json::json!({
729 "requestedAt": "2026-06-11T13:00:00Z",
730 "mode": "quick",
731 "phase": "Running",
732 "completedAt": null,
733 })
734 );
735 // The explicit null reads back as "no completion instant".
736 let back: ManualRunStatus = serde_json::from_value(running).unwrap();
737 assert!(back.completed_at.is_none());
738 assert_eq!(
739 serde_json::to_value(ManualRunStatus::default()).unwrap(),
740 serde_json::json!({ "completedAt": null })
741 );
742
743 // A status that never requested a run still has NO manualRun key —
744 // the parent field keeps its own skip_serializing_if.
745 let never: MaintenanceStatus = from_yaml("observedGeneration: 3\n");
746 assert!(never.manual_run.is_none());
747 assert!(
748 serde_json::to_value(&never)
749 .unwrap()
750 .get("manualRun")
751 .is_none()
752 );
753 }
754
755 #[test]
756 fn lease_identity_is_hostname_safe_and_stable() {
757 let (user, host) = kopia_lease_identity("kopiur/media/My_App.x");
758 assert_eq!(user, "kopiur");
759 assert_eq!(host, "kopiur-media-my-app-x");
760 // Long leases cap at a DNS label and never end with '-'.
761 let (_, host) = kopia_lease_identity(&format!("kopiur/{}/x", "n".repeat(100)));
762 assert!(host.len() <= 63, "{host}");
763 assert!(!host.ends_with('-'), "{host}");
764 // Deterministic.
765 assert_eq!(
766 kopia_owner_for_lease("kopiur/media/nas"),
767 kopia_owner_for_lease("kopiur/media/nas")
768 );
769 }
770
771 #[test]
772 fn parse_run_annotations_covers_ok_default_and_garbage() {
773 use std::collections::BTreeMap;
774 assert_eq!(parse_run_annotations(None), Ok(None));
775 let mut a = BTreeMap::new();
776 a.insert(
777 crate::consts::RUN_REQUESTED_ANNOTATION.to_string(),
778 "2026-06-11T12:00:00Z".to_string(),
779 );
780 let (_, mode) = parse_run_annotations(Some(&a)).unwrap().unwrap();
781 assert_eq!(mode, ManualRunMode::Quick, "mode defaults to quick");
782 a.insert(
783 crate::consts::RUN_MODE_ANNOTATION.to_string(),
784 "full".to_string(),
785 );
786 let (_, mode) = parse_run_annotations(Some(&a)).unwrap().unwrap();
787 assert_eq!(mode, ManualRunMode::Full);
788 a.insert(
789 crate::consts::RUN_REQUESTED_ANNOTATION.to_string(),
790 "yesterday".to_string(),
791 );
792 let err = parse_run_annotations(Some(&a)).unwrap_err();
793 assert!(err.contains("must be an RFC3339 timestamp"), "{err}");
794 assert!(err.contains("kubectl kopiur maintenance run"), "{err}");
795 }
796
797 #[test]
798 fn maintenance_crd_metadata_is_correct() {
799 let crd = Maintenance::crd();
800 assert_eq!(crd.spec.group, "kopiur.home-operations.com");
801 assert_eq!(crd.spec.names.kind, "Maintenance");
802 assert_eq!(crd.spec.scope, "Namespaced");
803 assert_eq!(crd.spec.versions[0].name, "v1alpha1");
804 }
805
806 #[test]
807 fn maintenance_roundtrip_matches_adr_shape() {
808 // Mirrors ADR-0001 §3.7.
809 let yaml = r#"
810repository:
811 kind: Repository
812 name: nas-primary
813schedule:
814 quick: { cron: "0 */6 * * *", jitter: 30m }
815 full: { cron: "0 3 * * 0", jitter: 1h }
816 timezone: UTC
817ownership:
818 owner: "kopia-operator/nas-primary"
819 takeoverPolicy: PromptCondition
820mover:
821 resources: { requests: { cpu: 250m, memory: 1Gi }, limits: { cpu: "2", memory: 4Gi } }
822 securityContext: { runAsUser: 1000, runAsNonRoot: true }
823 podSecurityContext: { fsGroup: 1000 }
824failurePolicy:
825 backoffLimit: 1
826 activeDeadlineSeconds: 14400
827"#;
828 let spec: MaintenanceSpec = from_yaml(yaml);
829 assert_eq!(spec.repository.kind, RepositoryKind::Repository);
830 // The mover security contexts (container + pod) round-trip on Maintenance too.
831 let mover = spec.mover.as_ref().expect("mover");
832 assert_eq!(
833 mover.security_context.as_ref().and_then(|s| s.run_as_user),
834 Some(1000)
835 );
836 assert_eq!(
837 mover.pod_security_context.as_ref().and_then(|p| p.fs_group),
838 Some(1000)
839 );
840 assert_eq!(spec.schedule.quick.cron, "0 */6 * * *");
841 assert_eq!(spec.schedule.quick.jitter.as_deref(), Some("30m"));
842 assert_eq!(spec.schedule.full.cron, "0 3 * * 0");
843 assert_eq!(spec.schedule.timezone.as_deref(), Some("UTC"));
844 assert_eq!(spec.ownership.owner, "kopia-operator/nas-primary");
845 assert_eq!(
846 spec.ownership.takeover_policy,
847 TakeoverPolicy::PromptCondition
848 );
849 assert_eq!(
850 spec.failure_policy
851 .as_ref()
852 .unwrap()
853 .active_deadline_seconds,
854 Some(14400)
855 );
856
857 let json = serde_json::to_value(&spec).expect("serialize");
858 let reparsed: MaintenanceSpec = serde_json::from_value(json).expect("reparse");
859 assert_eq!(spec, reparsed);
860 }
861
862 #[test]
863 fn maintenance_status_roundtrips() {
864 // Mirrors ADR-0001 §3.7 status block.
865 let yaml = r#"
866ownership:
867 owner: "kopia-operator/nas-primary"
868 claimedAt: 2026-05-12T08:14:02Z
869quick:
870 lastRunAt: 2026-05-24T12:00:11Z
871 nextScheduledAt: 2026-05-24T18:00:00Z
872 consecutiveFailures: 0
873 lastContentReclaimedBytes: 1234567
874full:
875 lastRunAt: 2026-05-19T03:01:42Z
876 nextScheduledAt: 2026-05-26T03:00:00Z
877 consecutiveFailures: 0
878 lastContentReclaimedBytes: 89456789012
879"#;
880 let status: MaintenanceStatus = from_yaml(yaml);
881 assert_eq!(
882 status.ownership.as_ref().unwrap().owner.as_deref(),
883 Some("kopia-operator/nas-primary")
884 );
885 assert_eq!(
886 status.quick.as_ref().unwrap().last_content_reclaimed_bytes,
887 Some(1234567)
888 );
889 assert_eq!(
890 status.full.as_ref().unwrap().last_content_reclaimed_bytes,
891 Some(89456789012)
892 );
893
894 let json = serde_json::to_value(&status).unwrap();
895 let reparsed: MaintenanceStatus = serde_json::from_value(json).unwrap();
896 assert_eq!(status, reparsed);
897 }
898
899 #[test]
900 fn repository_maintenance_defaults_to_enabled() {
901 // An empty `spec.maintenance: {}` is default-on with no overrides.
902 let m: RepositoryMaintenanceSpec = from_yaml("{}\n");
903 assert!(
904 m.enabled,
905 "absent `enabled` must default to true (default-on)"
906 );
907 assert!(m.schedule.is_none());
908 assert!(m.namespace.is_none());
909 assert!(m.takeover_policy.is_none());
910 // The constructed Default agrees with the deserialized `{}`.
911 assert_eq!(m, RepositoryMaintenanceSpec::default());
912 }
913
914 #[test]
915 fn repository_maintenance_roundtrip_with_overrides() {
916 let yaml = r#"
917enabled: false
918schedule:
919 quick: { cron: "0 */4 * * *", jitter: 20m }
920 full: { cron: "30 2 * * *", jitter: 45m }
921 timezone: America/Chicago
922takeoverPolicy: Force
923namespace: kopia-system
924failurePolicy:
925 backoffLimit: 2
926"#;
927 let m: RepositoryMaintenanceSpec = from_yaml(yaml);
928 assert!(!m.enabled);
929 let s = m.schedule.as_ref().expect("schedule");
930 assert_eq!(s.quick.cron, "0 */4 * * *");
931 assert_eq!(s.full.jitter.as_deref(), Some("45m"));
932 assert_eq!(s.timezone.as_deref(), Some("America/Chicago"));
933 assert_eq!(m.takeover_policy, Some(TakeoverPolicy::Force));
934 assert_eq!(m.namespace.as_deref(), Some("kopia-system"));
935 assert_eq!(m.failure_policy.as_ref().unwrap().backoff_limit, Some(2));
936
937 let json = serde_json::to_value(&m).expect("serialize");
938 let reparsed: RepositoryMaintenanceSpec = serde_json::from_value(json).expect("reparse");
939 assert_eq!(m, reparsed);
940 }
941
942 #[test]
943 fn default_maintenance_schedule_is_quick_6h_full_daily() {
944 let s = default_maintenance_schedule();
945 assert_eq!(s.quick.cron, "0 */6 * * *");
946 assert_eq!(s.quick.jitter.as_deref(), Some("30m"));
947 assert_eq!(s.full.cron, "0 3 * * *");
948 assert_eq!(s.full.jitter.as_deref(), Some("1h"));
949 assert!(s.timezone.is_none());
950 }
951
952 #[test]
953 fn free_lease_is_claimed_regardless_of_policy() {
954 for p in [
955 TakeoverPolicy::Never,
956 TakeoverPolicy::PromptCondition,
957 TakeoverPolicy::Force,
958 ] {
959 assert_eq!(lease_action(p, false), LeaseAction::Claim);
960 }
961 }
962
963 #[test]
964 fn held_lease_dispatches_by_policy() {
965 assert_eq!(
966 lease_action(TakeoverPolicy::Never, true),
967 LeaseAction::Yield
968 );
969 assert_eq!(
970 lease_action(TakeoverPolicy::PromptCondition, true),
971 LeaseAction::Prompt
972 );
973 assert_eq!(
974 lease_action(TakeoverPolicy::Force, true),
975 LeaseAction::Takeover
976 );
977 }
978
979 #[test]
980 fn takeover_policy_serializes_to_expected_strings() {
981 assert_eq!(
982 serde_json::to_value(TakeoverPolicy::Never).unwrap(),
983 "Never"
984 );
985 assert_eq!(
986 serde_json::to_value(TakeoverPolicy::PromptCondition).unwrap(),
987 "PromptCondition"
988 );
989 assert_eq!(
990 serde_json::to_value(TakeoverPolicy::Force).unwrap(),
991 "Force"
992 );
993 assert_eq!(TakeoverPolicy::default(), TakeoverPolicy::Never);
994 }
995
996 #[test]
997 fn manual_run_mode_parses_exact_lowercase_and_defaults_to_quick() {
998 assert_eq!(ManualRunMode::default(), ManualRunMode::Quick);
999 assert_eq!(ManualRunMode::parse("quick"), Some(ManualRunMode::Quick));
1000 assert_eq!(ManualRunMode::parse("full"), Some(ManualRunMode::Full));
1001 assert_eq!(ManualRunMode::parse("FULL"), None); // exact, lowercase only
1002 assert_eq!(serde_json::to_value(ManualRunMode::Quick).unwrap(), "quick");
1003 }
1004
1005 // --- M6: cluster-qualified maintenance lease -----------------------------
1006
1007 #[test]
1008 fn managed_lease_covers_all_four_arms() {
1009 assert_eq!(
1010 managed_lease(RepositoryKind::Repository, "media", "nas", None),
1011 "kopiur/media/nas"
1012 );
1013 assert_eq!(
1014 managed_lease(RepositoryKind::Repository, "media", "nas", Some("east")),
1015 "kopiur/east/media/nas"
1016 );
1017 assert_eq!(
1018 managed_lease(RepositoryKind::ClusterRepository, "ignored", "shared", None),
1019 "kopiur/clusterrepository/shared"
1020 );
1021 assert_eq!(
1022 managed_lease(
1023 RepositoryKind::ClusterRepository,
1024 "ignored",
1025 "shared",
1026 Some("east")
1027 ),
1028 "kopiur/east/clusterrepository/shared"
1029 );
1030 }
1031
1032 #[test]
1033 fn legacy_lease_shapes_are_byte_identical_to_pre_m6() {
1034 // 3-segment namespaced-Repository format: unchanged.
1035 assert_eq!(
1036 kopia_lease_identity("kopiur/media/nas"),
1037 ("kopiur".to_string(), "kopiur-media-nas".to_string())
1038 );
1039 // 3-segment ClusterRepository format: unchanged.
1040 assert_eq!(
1041 kopia_lease_identity("kopiur/clusterrepository/shared"),
1042 (
1043 "kopiur".to_string(),
1044 "kopiur-clusterrepository-shared".to_string()
1045 )
1046 );
1047 // 2-segment hand-authored owner: unchanged (falls through to legacy).
1048 assert_eq!(
1049 kopia_lease_identity("kopia-operator/nas-primary"),
1050 (
1051 "kopiur".to_string(),
1052 "kopia-operator-nas-primary".to_string()
1053 )
1054 );
1055 // Mixed-case/punctuation whole-string sanitization: unchanged.
1056 let (user, host) = kopia_lease_identity("kopiur/media/My_App.x");
1057 assert_eq!(user, "kopiur");
1058 assert_eq!(host, "kopiur-media-my-app-x");
1059 // Long legacy leases still cap at a DNS label and never end with '-'.
1060 let (_, host) = kopia_lease_identity(&format!("kopiur/{}/x", "n".repeat(100)));
1061 assert!(host.len() <= 63, "{host}");
1062 assert!(!host.ends_with('-'), "{host}");
1063 }
1064
1065 /// Hardening (fix round 1): a hand-authored `Ownership.owner` that HAPPENS
1066 /// to be 4 `/`-separated segments must NOT be mistaken for one of
1067 /// `managed_lease`'s generated cluster-qualified formats — those are always
1068 /// `"kopiur"`-first-segment. Without this gate, an owner like `a/b/c/d`
1069 /// would silently change derivation from the legacy `a-b-c-d` to the
1070 /// dot-joined `a.b.c.d` across an operator upgrade, and with
1071 /// `takeoverPolicy: Never` maintenance would then yield forever.
1072 #[test]
1073 fn four_segment_non_kopiur_lease_is_legacy_byte_identical_to_pre_m6() {
1074 assert_eq!(
1075 kopia_lease_identity("a/b/c/d"),
1076 ("kopiur".to_string(), "a-b-c-d".to_string())
1077 );
1078 // Still legacy even when the segments individually look plausible.
1079 assert_eq!(
1080 kopia_lease_identity("east/media/nas/extra"),
1081 ("kopiur".to_string(), "east-media-nas-extra".to_string())
1082 );
1083 }
1084
1085 #[test]
1086 fn cluster_qualified_lease_is_dot_joined_and_injective() {
1087 // Verbatim dot-join for already-clean generated segments.
1088 assert_eq!(
1089 kopia_lease_identity("kopiur/east/media/nas"),
1090 ("kopiur".to_string(), "kopiur.east.media.nas".to_string())
1091 );
1092 assert_eq!(
1093 kopia_lease_identity("kopiur/east/clusterrepository/shared"),
1094 (
1095 "kopiur".to_string(),
1096 "kopiur.east.clusterrepository.shared".to_string()
1097 )
1098 );
1099
1100 // Adversarial: a '-' inside a segment must not be forgeable into a
1101 // fake '.' boundary (the whole-string collapse this replaces would
1102 // make these two leases collide).
1103 assert_ne!(
1104 kopia_lease_identity("kopiur/east-prod/db/x").1,
1105 kopia_lease_identity("kopiur/east/prod-db/x").1
1106 );
1107
1108 // Two 32-char clusters sharing a 31-char prefix must stay distinct —
1109 // the old cap-at-63 truncation would have collided these.
1110 let cluster_a = format!("{}x", "a".repeat(31));
1111 let cluster_b = format!("{}y", "a".repeat(31));
1112 assert_eq!(cluster_a.len(), 32);
1113 assert_eq!(cluster_b.len(), 32);
1114 let lease_a = format!("kopiur/{cluster_a}/media/nas");
1115 let lease_b = format!("kopiur/{cluster_b}/media/nas");
1116 assert_ne!(
1117 kopia_lease_identity(&lease_a).1,
1118 kopia_lease_identity(&lease_b).1
1119 );
1120
1121 // Dots land in the hostname, and the shared identity-shape validator
1122 // (kopia's username/hostname contract) accepts them: dots are
1123 // explicitly permitted, only '@'/':'/whitespace/control chars/length
1124 // are rejected.
1125 let (_, host) = kopia_lease_identity("kopiur/east/media/nas");
1126 assert!(host.contains('.'));
1127 assert!(crate::validate::validate_identity_component("hostname", &host).is_ok());
1128 }
1129
1130 #[test]
1131 fn lease_held_by_other_table() {
1132 let lease = "kopiur/east/media/nas";
1133 let alias = "kopiur/media/nas";
1134 let mine = kopia_owner_for_lease(lease);
1135 let alias_owner = kopia_owner_for_lease(alias);
1136
1137 // empty current: never-run repo, never "held by another".
1138 assert!(!lease_held_by_other("", lease, &[]));
1139 assert!(!lease_held_by_other("", lease, &[alias.to_string()]));
1140 // own owner: not held by another, with or without aliases configured.
1141 assert!(!lease_held_by_other(&mine, lease, &[]));
1142 assert!(!lease_held_by_other(&mine, lease, &[alias.to_string()]));
1143 // a registered alias's owner: treated as self (migration path).
1144 assert!(!lease_held_by_other(
1145 &alias_owner,
1146 lease,
1147 &[alias.to_string()]
1148 ));
1149 // the SAME owner string, but the alias isn't registered: foreign.
1150 assert!(lease_held_by_other(&alias_owner, lease, &[]));
1151 // a genuinely foreign owner, with an unrelated alias configured: foreign.
1152 assert!(lease_held_by_other(
1153 "someone@else",
1154 lease,
1155 &[alias.to_string()]
1156 ));
1157 }
1158}