Skip to main content

engenho_controllers/
pv_binder.rs

1//! `PvBinderController` — the `PersistentVolume` / `PersistentVolumeClaim`
2//! binder PLUS a minimal local-path dynamic provisioner.
3//!
4//! ## What it does (the Storage CNCF brick)
5//!
6//! Each tick, for every `PersistentVolumeClaim` in `status.phase == Pending`
7//! (or unset) it tries, in order:
8//!
9//!   1. **Static bind** — find an `Available` `PersistentVolume` that
10//!      *matches* the claim (capacity ≥ request, accessModes ⊇ requested,
11//!      storageClassName equal incl. `""`/nil semantics, and — if the PVC
12//!      pre-binds via `spec.volumeName` — exactly that PV). On a match it
13//!      **bidirectionally binds**: `PVC.spec.volumeName = PV.name`,
14//!      `PVC.status.phase = Bound`, `PV.status.phase = Bound`, and
15//!      `PV.spec.claimRef → {namespace,name,uid}` of the PVC.
16//!   2. **Dynamic provision** — if no static PV matches AND the PVC's
17//!      effective `StorageClass` uses the local-path provisioner (or is the
18//!      cluster default SC), it CREATES a `PersistentVolume` named
19//!      `pvc-<uid>` with a node-local `hostPath` source under
20//!      `<data_dir>/local-path/pvc-<uid>_<ns>_<name>`, `capacity = request`,
21//!      the SC's `reclaimPolicy`, and a `claimRef` pre-pointing at the PVC,
22//!      then binds it.
23//!
24//! ## Identity is the claim's uid
25//!
26//! A claim's name is reusable; its `metadata.uid` is not. Every volume a
27//! claim is given is tied to its uid ([`ClaimUid`]):
28//!
29//!   * a dynamic PV's name and directory come from [`PvName::for_claim`],
30//!     so a claim deleted and recreated under the same name gets a new PV
31//!     and a new, empty directory — never the deleted claim's data;
32//!   * a PV whose `claimRef` carries a different uid belongs to an earlier
33//!     claim of the same name and is never bound to this one;
34//!   * the PV is written create-if-absent, so a provision never overwrites
35//!     a PV that already holds its name;
36//!   * a claim with no usable uid stays Pending with a typed reason
37//!     ([`NoVolumeIdentity`]).
38//!
39//! PVs provisioned before this rule keep their names (`pvc-<ns>-<name>`):
40//! nothing renames a bound volume, and a claim whose PV was written but not
41//! yet bound finds it again through its `claimRef` uid.
42//!
43//! ## Released, then reclaimed
44//!
45//! Each tick also walks the PVs, after the claims ([`lifecycle`]): a PV
46//! whose claim is gone goes `Released`, and its reclaim policy decides the
47//! rest — `Delete` removes the backing storage and then the PV, `Retain`
48//! keeps it `Released` until an operator clears its `claimRef`. A claim
49//! that pvc-protection still holds is not gone
50//! ([`crate::pvc_protection`]).
51//!
52//! Every claim write is at the revision the claim was read at, so a bind
53//! never overwrites what another writer did since the list: the
54//! pvc-protection finalizer, a `deletionTimestamp`, or the claim's delete.
55//!
56//! ## volumeBindingMode
57//!
58//! `Immediate` (the default + only mode this brick provisions in) provisions
59//! as soon as the PVC is seen. `WaitForFirstConsumer` is **typed-deferred**:
60//! the binder leaves such a PVC Pending (it does NOT provision until a Pod
61//! references it) and records that in the report — a named follow-up rather
62//! than a silent wrong behavior.
63//!
64//! ## The filesystem seam (Environment-trait discipline)
65//!
66//! The ONLY host effect this controller performs is creating the local-path
67//! data directory at provision time. That sits behind the
68//! [`ProvisionerEnv`] trait so the whole binder is unit-testable WITHOUT
69//! touching the real filesystem (the [`FakeProvisionerEnv`]). The real
70//! [`HostProvisionerEnv`] `mkdir -p`s the dir. The directory is created here
71//! at *provision* time (the provisioner's job) so the PV's `hostPath` exists
72//! before any kubelet tries to bind-mount it — the clean seam, documented.
73//!
74//! ## No silent wrong answers
75//!
76//! Every store write goes through `ResourceCommand::Put` with
77//! `Reason::Controller`. A PVC that matches nothing AND can't be dynamically
78//! provisioned is left Pending (the K8s behavior) — never fake-Bound. There
79//! is no `todo!()` / `unimplemented!()` / `panic!()` anywhere in the path.
80
81mod identity;
82mod lifecycle;
83
84use std::sync::Arc;
85
86use async_trait::async_trait;
87use engenho_store::{
88    StoreMesh,
89    command::{Reason, ResourceCommand, TxnCompare, TxnOp},
90    resource::ResourceKey,
91};
92use engenho_types::primitives::quantity::Quantity;
93use serde_json::{Value, json};
94use std::str::FromStr;
95use tracing::debug;
96
97use crate::controller::{Controller, ReconcileOutcome};
98use crate::csi_provisioner::{CsiCreateRequest, CsiProvisioner, NoCsiProvisioner, parse_quantity};
99use crate::effect::Effect;
100use crate::error::ControllerError;
101use crate::event_recorder::Reason as EventReason;
102use crate::reads::{DeclaresReads, Reads, gvk};
103use crate::status::resource_version_of;
104use crate::sweep::{ObjectOutcome, Sweep, impl_sweep_event_sink};
105use crate::volume_snapshot::{SNAPSHOT_GROUP, SNAPSHOT_VERSION};
106
107pub use identity::{ClaimUid, LocalPathDir, NoVolumeIdentity, PvName};
108use lifecycle::PROVISIONED_BY;
109pub use lifecycle::{ReclaimError, ReclaimPolicy, Unreclaimable};
110
111/// The local-path provisioner identifier. A `StorageClass` whose
112/// `provisioner` is this string (the rancher.io/local-path de-facto
113/// standard) OR engenho's own alias triggers dynamic provisioning.
114pub const LOCAL_PATH_PROVISIONER: &str = "rancher.io/local-path";
115/// engenho's own alias for the same node-local-hostPath provisioner.
116pub const ENGENHO_LOCAL_PATH_PROVISIONER: &str = "engenho.io/local-path";
117
118/// The annotation marking a `StorageClass` as the cluster default.
119const DEFAULT_SC_ANNOTATION: &str = "storageclass.kubernetes.io/is-default-class";
120
121/// Upstream's `source.component` for the PV controller, which signs the
122/// binder's Events.
123const COMPONENT: &str = "persistentvolume-controller";
124
125/// Why a local-path claim with no usable size cannot be provisioned.
126///
127/// Upstream's apiserver refuses such a claim at create time; engenho's does
128/// not, and the binder used to provision it anyway — a local-path PV whose
129/// `capacity.storage` was `null` or the unparseable string, bound as if it
130/// were real. Now it is an Item failure on the claim: the claim stays
131/// Pending and a `ProvisioningFailed` Event on it says why.
132const UNUSABLE_REQUEST: &str = "spec.resources.requests.storage is missing or is not a quantity, \
133     so the local-path provisioner has no size to give the volume; the claim stays Pending \
134     until it names one";
135
136/// The report note for a claim that restores from a snapshot not yet ready.
137const SNAPSHOT_NOT_READY: &str = "PVC names a VolumeSnapshot dataSource that is not ready; left \
138     Pending rather than provisioned empty";
139
140/// The report note for a `WaitForFirstConsumer` claim.
141const WAIT_FOR_FIRST_CONSUMER: &str = "WaitForFirstConsumer PVC left Pending (deferred)";
142
143/// The report note for a claim that cannot be written at a known revision.
144const CLAIM_NO_REVISION: &str = "PVC carries no resourceVersion, so a bind cannot be written at \
145     the revision it was read at; left for the next pass";
146
147/// The report note for a claim whose derived PV name is already held by a
148/// PV that is not bound to it. Nothing is overwritten and nothing is
149/// provisioned into that PV's directory; the claim stays Pending.
150const PV_NAME_TAKEN: &str = "a PersistentVolume already holds the name derived from this \
151     claim's uid and is not bound to it; nothing was overwritten and the claim stays Pending";
152
153/// One claim, as a PV's `claimRef` names it.
154#[derive(Debug, Clone, Copy)]
155struct ClaimId<'a> {
156    namespace: &'a str,
157    name: &'a str,
158    uid: &'a ClaimUid,
159}
160
161/// Where a PV's `spec.claimRef` points, seen from one claim.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum ClaimRefTo {
164    /// No claimRef: free for any claim it matches.
165    Nobody,
166    /// This claim's namespace and name, with no uid: reserved for the claim
167    /// by name, the way an operator pre-binds a PV.
168    ThisName,
169    /// This claim's namespace, name and uid: already this claim's volume.
170    ThisClaim,
171    /// Some other claim — including an earlier claim of the same namespace
172    /// and name, told apart by its uid.
173    Other,
174}
175
176/// Everything a sweep reads once and matches each claim against.
177struct TickView {
178    pvs: Vec<(ResourceKey, Value)>,
179    storage_classes: Vec<(ResourceKey, Value)>,
180    snapshots: Vec<(ResourceKey, Value)>,
181    snapshot_contents: Vec<(ResourceKey, Value)>,
182}
183
184/// The host-effect seam — the side-effecting half of the provisioner behind
185/// a trait so binding + provisioning is unit-testable WITHOUT a real
186/// filesystem. The real [`HostProvisionerEnv`] creates the local-path dir;
187/// the [`FakeProvisionerEnv`] records the request + returns success.
188pub trait ProvisionerEnv: Send + Sync {
189    /// Idempotently ensure the host directory `path` exists (the local-path
190    /// PV's `hostPath` backing dir). Created at provision time so the kubelet
191    /// can bind-mount it.
192    ///
193    /// # Errors
194    ///
195    /// Returns a human-readable error string on mkdir failure — surfaced as a
196    /// [`ControllerError`] so provisioning fails loudly (the PVC stays Pending),
197    /// never a silent fake-Bound.
198    fn ensure_dir(&self, path: &str) -> Result<(), String>;
199
200    /// Hydrate a freshly-provisioned backing dir FROM a snapshot directory.
201    ///
202    /// Added to this trait rather than to a second env so restore stays the
203    /// same seam as provision: a PV whose data came from a snapshot is still
204    /// just a local-path PV, and splitting the two would let a cluster
205    /// provision without being able to restore.
206    ///
207    /// # Errors
208    ///
209    /// A human-readable message. A failed restore must leave the claim
210    /// Pending — an EMPTY volume presented as a restored one is the silent
211    /// wrong answer this whole controller refuses to give.
212    fn restore_tree(&self, src: &str, dst: &str) -> Result<(), String>;
213
214    /// Remove a Released local-path volume's backing directory, and
215    /// everything in it. Already absent is success: a retry after a PV
216    /// delete that did not land removes nothing twice.
217    ///
218    /// Takes a [`LocalPathDir`], whose only constructor derives it from a
219    /// validated claim uid, namespace and name under the provisioner's
220    /// root, so this seam cannot be asked to remove any other path.
221    ///
222    /// # Errors
223    ///
224    /// The I/O error. The volume stays Released and the removal is retried.
225    fn remove_dir(&self, dir: &LocalPathDir<'_>) -> std::io::Result<()>;
226}
227
228/// Production [`ProvisionerEnv`] — `std::fs::create_dir_all` rooted under the
229/// configured `data_dir/local-path`.
230pub struct HostProvisionerEnv;
231
232impl ProvisionerEnv for HostProvisionerEnv {
233    fn ensure_dir(&self, path: &str) -> Result<(), String> {
234        std::fs::create_dir_all(path).map_err(|e| format!("mkdir {path}: {e}"))
235    }
236
237    /// Delegates to the snapshot controller's copy, so provision-side restore
238    /// and snapshot-side capture are ONE implementation. Two copies of a
239    /// recursive directory copy would be free to disagree about symlinks,
240    /// permissions or partial failure — and only one of them would be tested.
241    fn restore_tree(&self, src: &str, dst: &str) -> Result<(), String> {
242        crate::volume_snapshot::SnapshotEnv::copy_tree(
243            &crate::volume_snapshot::HostSnapshotEnv,
244            src,
245            dst,
246        )
247    }
248
249    /// `remove_dir_all` does not follow a symlink it meets, the directory
250    /// itself included: a link is removed, never its target.
251    fn remove_dir(&self, dir: &LocalPathDir<'_>) -> std::io::Result<()> {
252        match std::fs::remove_dir_all(dir.to_string()) {
253            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
254            done => done,
255        }
256    }
257}
258
259/// The PV/PVC binder controller + local-path dynamic provisioner.
260pub struct PvBinderController {
261    store: Arc<StoreMesh>,
262    namespace: Option<String>,
263    /// Host data root under which dynamically-provisioned local-path PVs are
264    /// backed: each PV's hostPath is
265    /// `<local_path_root>/pvc-<uid>_<pvc-ns>_<pvc-name>` ([`PvName::local_path_dir`]).
266    local_path_root: String,
267    /// The filesystem seam (mockable).
268    env: Arc<dyn ProvisionerEnv>,
269    /// The CSI provisioning seam. Defaults to [`NoCsiProvisioner`], under
270    /// which every CSI `StorageClass` stays Pending exactly as it did before
271    /// this branch existed — so wiring it is opt-in and its absence is not
272    /// a behaviour change.
273    csi: Arc<dyn CsiProvisioner>,
274    /// Per-claim isolation: one claim's failure costs only that claim.
275    sweep: Sweep,
276    /// Per-volume isolation for the lifecycle walk. Its own sweep, because
277    /// a sweep forgets the failures of every object it did not see: one
278    /// sweep over both kinds would forget the claims' each time it walked
279    /// the volumes.
280    volume_sweep: Sweep,
281}
282
283impl_sweep_event_sink!(PvBinderController: sweep, volume_sweep);
284
285impl PvBinderController {
286    /// New binder with the production [`HostProvisionerEnv`]. `local_path_root`
287    /// is typically `<data_dir>/local-path`.
288    #[must_use]
289    pub fn new(
290        store: Arc<StoreMesh>,
291        namespace: Option<String>,
292        local_path_root: impl Into<String>,
293    ) -> Self {
294        Self {
295            store,
296            namespace,
297            local_path_root: local_path_root.into(),
298            env: Arc::new(HostProvisionerEnv),
299            csi: Arc::new(NoCsiProvisioner),
300            sweep: Sweep::new(COMPONENT, EventReason::ProvisioningFailed),
301            volume_sweep: Sweep::new(COMPONENT, EventReason::VolumeFailedDelete),
302        }
303    }
304
305    /// Construct with an explicit [`ProvisionerEnv`] — the unit-test seam so
306    /// the provisioner never touches the real filesystem.
307    #[must_use]
308    pub fn with_env(
309        store: Arc<StoreMesh>,
310        namespace: Option<String>,
311        local_path_root: impl Into<String>,
312        env: Arc<dyn ProvisionerEnv>,
313    ) -> Self {
314        Self {
315            store,
316            namespace,
317            local_path_root: local_path_root.into(),
318            env,
319            csi: Arc::new(NoCsiProvisioner),
320            sweep: Sweep::new(COMPONENT, EventReason::ProvisioningFailed),
321            volume_sweep: Sweep::new(COMPONENT, EventReason::VolumeFailedDelete),
322        }
323    }
324
325    /// Builder: wire the CSI provisioning seam.
326    #[must_use]
327    pub fn with_csi(mut self, csi: Arc<dyn CsiProvisioner>) -> Self {
328        self.csi = csi;
329        self
330    }
331
332    /// A PVC's `status.phase`, defaulting to `"Pending"` when unset or empty (a freshly
333    /// created PVC has no status yet — it is Pending by definition).
334    fn pvc_phase(pvc: &Value) -> &str {
335        pvc.get("status")
336            .and_then(|s| s.get("phase"))
337            .and_then(|p| p.as_str())
338            .filter(|p| !p.is_empty())
339            .unwrap_or("Pending")
340    }
341
342    /// A PV's `status.phase`, defaulting to `"Available"` when unset or empty (a fresh
343    /// PV with no status is available to bind).
344    fn pv_phase(pv: &Value) -> &str {
345        pv.get("status")
346            .and_then(|s| s.get("phase"))
347            .and_then(|p| p.as_str())
348            .filter(|p| !p.is_empty())
349            .unwrap_or("Available")
350    }
351
352    /// The PVC's requested storage as a canonical byte count, or `None` when
353    /// absent/unparseable (an unparseable request never matches — surfaced by
354    /// leaving the PVC Pending rather than guessing).
355    fn pvc_request_bytes(pvc: &Value) -> Option<i128> {
356        let s = pvc
357            .get("spec")
358            .and_then(|sp| sp.get("resources"))
359            .and_then(|r| r.get("requests"))
360            .and_then(|r| r.get("storage"))
361            .and_then(|q| q.as_str())?;
362        Quantity::from_str(s).ok()?.milli_value()
363    }
364
365    /// A PV's `spec.capacity.storage` as a canonical byte count.
366    fn pv_capacity_bytes(pv: &Value) -> Option<i128> {
367        let s = pv
368            .get("spec")
369            .and_then(|sp| sp.get("capacity"))
370            .and_then(|c| c.get("storage"))
371            .and_then(|q| q.as_str())?;
372        Quantity::from_str(s).ok()?.milli_value()
373    }
374
375    /// The requested access modes of a PVC (`spec.accessModes`), as a sorted
376    /// owned vec. Empty when unset.
377    fn access_modes(spec_obj: &Value) -> Vec<String> {
378        spec_obj
379            .get("spec")
380            .and_then(|sp| sp.get("accessModes"))
381            .and_then(|a| a.as_array())
382            .map(|arr| {
383                let mut v: Vec<String> = arr
384                    .iter()
385                    .filter_map(|m| m.as_str().map(str::to_string))
386                    .collect();
387                v.sort();
388                v
389            })
390            .unwrap_or_default()
391    }
392
393    /// A resource's `spec.storageClassName` as `Option<&str>`. `None` (nil) and
394    /// `Some("")` are distinct in K8s but bind-compatible only with each other;
395    /// this returns the raw value (nil → `None`, `""` → `Some("")`).
396    fn storage_class(spec_obj: &Value) -> Option<&str> {
397        spec_obj
398            .get("spec")
399            .and_then(|sp| sp.get("storageClassName"))
400            .and_then(|s| s.as_str())
401    }
402
403    /// K8s storageClassName matching: nil and `""` are treated as equal (both
404    /// mean "no class"); otherwise an exact string match.
405    fn storage_class_matches(pvc: &Value, pv: &Value) -> bool {
406        let norm = |o: Option<&str>| o.unwrap_or("").to_string();
407        norm(Self::storage_class(pvc)) == norm(Self::storage_class(pv))
408    }
409
410    /// The PVC's `spec.volumeName` (a pre-bind to a named PV), if set + non-empty.
411    fn pre_bound_volume(pvc: &Value) -> Option<&str> {
412        pvc.get("spec")
413            .and_then(|sp| sp.get("volumeName"))
414            .and_then(|v| v.as_str())
415            .filter(|s| !s.is_empty())
416    }
417
418    /// Where `pv`'s `spec.claimRef` points, seen from `claim`.
419    ///
420    /// The namespace and name must both match for the claimRef to be this
421    /// claim's. When it also carries a uid, that uid decides: a different
422    /// one is an earlier claim that happened to have the same name
423    /// (upstream's `IsVolumeBoundToClaim`). An empty uid is no uid.
424    fn claim_ref_to(pv: &Value, claim: &ClaimId<'_>) -> ClaimRefTo {
425        let Some(cr) = pv
426            .get("spec")
427            .and_then(|s| s.get("claimRef"))
428            .filter(|cr| !cr.is_null())
429        else {
430            return ClaimRefTo::Nobody;
431        };
432        let field = |k: &str| cr.get(k).and_then(Value::as_str).unwrap_or("");
433        if field("namespace") != claim.namespace || field("name") != claim.name {
434            return ClaimRefTo::Other;
435        }
436        match cr.get("uid") {
437            None | Some(Value::Null) => ClaimRefTo::ThisName,
438            Some(Value::String(uid)) if uid.is_empty() => ClaimRefTo::ThisName,
439            Some(uid) if claim.uid.is(uid) => ClaimRefTo::ThisClaim,
440            Some(_) => ClaimRefTo::Other,
441        }
442    }
443
444    /// A PV is *available to bind to this PVC* iff it's `Available` AND (if it
445    /// carries a `spec.claimRef`) that claimRef already points at THIS PVC
446    /// (a pre-provisioned PV reserved for the claim). A PV claimRef'd to a
447    /// DIFFERENT claim is not available, and neither is one claimRef'd to an
448    /// earlier claim of the same namespace and name: the uid tells them apart.
449    fn pv_claimref_compatible(pv: &Value, claim: &ClaimId<'_>) -> bool {
450        match Self::claim_ref_to(pv, claim) {
451            ClaimRefTo::Nobody | ClaimRefTo::ThisName | ClaimRefTo::ThisClaim => true,
452            ClaimRefTo::Other => false,
453        }
454    }
455
456    /// Is `pv` big enough for `pvc`'s request? A claim with no parseable
457    /// request asks for nothing in particular (a CSI driver chose the
458    /// size); a PV with no parseable capacity satisfies no request.
459    fn holds_request(pv: &Value, pvc: &Value) -> bool {
460        Self::pvc_request_bytes(pvc)
461            .is_none_or(|req| Self::pv_capacity_bytes(pv).is_some_and(|cap| cap >= req))
462    }
463
464    /// Does `pv` satisfy `pvc`'s static-bind requirements? Capacity ≥ request,
465    /// accessModes ⊇ requested, storageClassName equal, claimRef compatible.
466    /// (volumeName pre-bind is checked by the caller — it narrows the candidate
467    /// set to exactly one PV before this predicate runs.)
468    fn pv_matches_pvc(pv: &Value, pvc: &Value, claim: &ClaimId<'_>) -> bool {
469        // Capacity: PV must offer ≥ the request. A PVC with no parseable
470        // request matches nothing (left Pending).
471        let Some(req) = Self::pvc_request_bytes(pvc) else {
472            return false;
473        };
474        let Some(cap) = Self::pv_capacity_bytes(pv) else {
475            return false;
476        };
477        if cap < req {
478            return false;
479        }
480        // Access modes: the PV must support every mode the PVC requests.
481        let want = Self::access_modes(pvc);
482        let have = Self::access_modes(pv);
483        if !want.iter().all(|m| have.contains(m)) {
484            return false;
485        }
486        // StorageClass equality (nil/"" normalized).
487        if !Self::storage_class_matches(pvc, pv) {
488            return false;
489        }
490        // claimRef must be unset or already point at this PVC.
491        Self::pv_claimref_compatible(pv, claim)
492    }
493
494    /// The PVC's `volumeBindingMode` — resolved from its effective
495    /// `StorageClass`. Returns `true` for `WaitForFirstConsumer` (provisioning
496    /// deferred), `false` (default) for `Immediate` / absent.
497    fn is_wait_for_first_consumer(sc: Option<&Value>) -> bool {
498        sc.and_then(|c| c.get("volumeBindingMode"))
499            .and_then(|m| m.as_str())
500            .is_some_and(|m| m == "WaitForFirstConsumer")
501    }
502
503    /// Find the `StorageClass` object for a PVC: its explicit
504    /// `spec.storageClassName`, else the cluster default SC (annotation).
505    /// Returns the SC `Value` if one applies, `None` when the PVC has an
506    /// empty/nil class and there is no default SC.
507    fn effective_storage_class<'a>(
508        pvc: &Value,
509        storage_classes: &'a [(ResourceKey, Value)],
510    ) -> Option<&'a Value> {
511        match Self::storage_class(pvc) {
512            Some(name) if !name.is_empty() => storage_classes
513                .iter()
514                .find(|(k, _)| k.name == name)
515                .map(|(_, v)| v),
516            // nil or "" → cluster default SC (if any).
517            _ => storage_classes
518                .iter()
519                .find(|(_, v)| is_default_sc(v))
520                .map(|(_, v)| v),
521        }
522    }
523
524    /// Build the bound PVC value: stamp `spec.volumeName` + `status.phase=Bound`.
525    fn bind_pvc(mut pvc: Value, pv_name: &str) -> Value {
526        if let Some(spec) = pvc.get_mut("spec").and_then(Value::as_object_mut) {
527            spec.insert("volumeName".into(), json!(pv_name));
528        } else if let Some(obj) = pvc.as_object_mut() {
529            obj.insert("spec".into(), json!({ "volumeName": pv_name }));
530        }
531        set_phase(&mut pvc, "Bound");
532        pvc
533    }
534
535    /// The `spec.claimRef` naming `claim` — always with its uid, so the PV
536    /// can never be mistaken for a later claim of the same name.
537    fn claim_ref(claim: &ClaimId<'_>) -> Value {
538        json!({
539            "apiVersion": "v1",
540            "kind": "PersistentVolumeClaim",
541            "namespace": claim.namespace,
542            "name": claim.name,
543            "uid": claim.uid.as_str(),
544        })
545    }
546
547    /// Build the bound PV value: stamp `spec.claimRef` → the PVC +
548    /// `status.phase=Bound`.
549    fn bind_pv(mut pv: Value, claim: &ClaimId<'_>) -> Value {
550        let claim_ref = Self::claim_ref(claim);
551        if let Some(spec) = pv.get_mut("spec").and_then(Value::as_object_mut) {
552            spec.insert("claimRef".into(), claim_ref);
553        } else if let Some(obj) = pv.as_object_mut() {
554            obj.insert("spec".into(), json!({ "claimRef": claim_ref }));
555        }
556        set_phase(&mut pv, "Bound");
557        pv
558    }
559
560    /// Build a dynamically-provisioned local-path PV body for `pvc`, named
561    /// `pv_name` and backed by `host_path` (both from [`PvName`]); capacity =
562    /// the request; reclaimPolicy from the SC (default `Delete`); accessModes
563    /// copied from the PVC; storageClassName from the PVC's effective class;
564    /// claimRef pre-pointing at the PVC.
565    fn build_dynamic_pv(
566        pvc: &Value,
567        claim: &ClaimId<'_>,
568        pv_name: &str,
569        host_path: &str,
570        sc: &Value,
571    ) -> Value {
572        let capacity = pvc
573            .get("spec")
574            .and_then(|s| s.get("resources"))
575            .and_then(|r| r.get("requests"))
576            .and_then(|r| r.get("storage"))
577            .cloned()
578            .unwrap_or(Value::Null);
579        let reclaim = sc
580            .get("reclaimPolicy")
581            .and_then(|r| r.as_str())
582            .unwrap_or("Delete");
583        let access_modes = pvc
584            .get("spec")
585            .and_then(|s| s.get("accessModes"))
586            .cloned()
587            .unwrap_or_else(|| json!(["ReadWriteOnce"]));
588        let sc_name = sc
589            .get("metadata")
590            .and_then(|m| m.get("name"))
591            .and_then(|n| n.as_str())
592            .unwrap_or("");
593        json!({
594            "apiVersion": "v1",
595            "kind": "PersistentVolume",
596            "metadata": {
597                "name": pv_name,
598                "annotations": {
599                    PROVISIONED_BY: ENGENHO_LOCAL_PATH_PROVISIONER
600                }
601            },
602            "spec": {
603                "capacity": { "storage": capacity },
604                "accessModes": access_modes,
605                "persistentVolumeReclaimPolicy": reclaim,
606                "storageClassName": sc_name,
607                "hostPath": { "path": host_path },
608                "claimRef": Self::claim_ref(claim)
609            },
610            "status": { "phase": "Bound" }
611        })
612    }
613
614    /// The `VolumeSnapshot` name a PVC restores from, if any.
615    ///
616    /// Reads `spec.dataSource` (and accepts `spec.dataSourceRef`, which
617    /// upstream added as the general form). The apiGroup is CHECKED: a
618    /// dataSource naming a PVC clone or some other kind is not a snapshot and
619    /// must not be silently treated as one.
620    fn snapshot_data_source(pvc: &Value) -> Option<String> {
621        let spec = pvc.get("spec")?;
622        let ds = spec
623            .get("dataSource")
624            .or_else(|| spec.get("dataSourceRef"))?;
625        if ds.get("kind").and_then(Value::as_str)? != "VolumeSnapshot" {
626            return None;
627        }
628        let group = ds.get("apiGroup").and_then(Value::as_str).unwrap_or("");
629        if group != crate::volume_snapshot::SNAPSHOT_GROUP {
630            return None;
631        }
632        ds.get("name").and_then(Value::as_str).map(str::to_string)
633    }
634
635    /// Resolve a `VolumeSnapshot` to the directory holding its data.
636    ///
637    /// Returns `None` unless the snapshot is READY and its bound content
638    /// carries a `snapshotHandle`. Every other outcome — missing snapshot,
639    /// not-yet-ready, missing content — is `None` on purpose, and the caller
640    /// leaves the claim Pending. A restore that silently produced an empty
641    /// volume would pass every liveness check while losing all the data,
642    /// which is the failure mode a drill is supposed to detect, not cause.
643    fn resolve_snapshot_path(
644        &self,
645        namespace: &str,
646        snapshot_name: &str,
647        snapshots: &[(ResourceKey, Value)],
648        contents: &[(ResourceKey, Value)],
649    ) -> Option<String> {
650        let (_, snap) = snapshots
651            .iter()
652            .find(|(k, _)| k.namespace.as_deref() == Some(namespace) && k.name == snapshot_name)?;
653        let status = snap.get("status")?;
654        if !status
655            .get("readyToUse")
656            .and_then(Value::as_bool)
657            .unwrap_or(false)
658        {
659            return None;
660        }
661        let content_name = status
662            .get("boundVolumeSnapshotContentName")
663            .and_then(Value::as_str)?;
664        let (_, content) = contents.iter().find(|(k, _)| k.name == content_name)?;
665        content
666            .get("status")
667            .and_then(|s| s.get("snapshotHandle"))
668            .and_then(Value::as_str)
669            .map(str::to_string)
670    }
671
672    /// Provision one PVC through a registered CSI driver, then bind it.
673    ///
674    /// ★ THE ORDER IS CREATE-THEN-WRITE, AND IT MATTERS. The driver call
675    /// happens first; only on success is a PV written. The reverse — write
676    /// the PV, then create — leaves a PV referencing a volume handle that
677    /// does not exist if the driver call fails, and a pod that mounts it
678    /// gets a mount error rather than a Pending claim.
679    ///
680    /// The idempotency key is the PV NAME, derived from the claim's UID, so
681    /// a retry after a transient failure returns the SAME volume instead of
682    /// provisioning a second disk nobody will ever delete — and a claim
683    /// recreated under the same name is a different key, so a driver that
684    /// answers `CreateVolume` idempotently by name cannot hand it the deleted
685    /// claim's disk.
686    async fn provision_csi(
687        &self,
688        pvc_key: &ResourceKey,
689        pvc: &Value,
690        claim: &ClaimId<'_>,
691        pv_name: &str,
692        sc: &Value,
693        provisioner: &str,
694    ) -> Result<ObjectOutcome, ControllerError> {
695        let requested = pvc
696            .get("spec")
697            .and_then(|s| s.get("resources"))
698            .and_then(|r| r.get("requests"))
699            .and_then(|r| r.get("storage"))
700            .and_then(Value::as_str)
701            .and_then(parse_quantity)
702            .unwrap_or(0);
703
704        let mut parameters = std::collections::BTreeMap::new();
705        if let Some(params) = sc.get("parameters").and_then(Value::as_object) {
706            for (k, v) in params {
707                if let Some(v) = v.as_str() {
708                    parameters.insert(k.clone(), v.to_string());
709                }
710            }
711        }
712
713        let access_modes = pvc
714            .get("spec")
715            .and_then(|s| s.get("accessModes"))
716            .and_then(Value::as_array)
717            .cloned()
718            .unwrap_or_default();
719        let multi_node = access_modes
720            .iter()
721            .filter_map(Value::as_str)
722            .any(|m| m == "ReadWriteMany" || m == "ReadOnlyMany");
723
724        // A driver's refusal is this claim's alone: Item scope, retried on
725        // the claim's own curve. Never a fake Bound — a claim bound to a
726        // volume that was never created is worse than one honestly Pending.
727        let created = self
728            .csi
729            .create_volume(&CsiCreateRequest {
730                driver: provisioner.to_string(),
731                name: pv_name.to_string(),
732                capacity_bytes: requested,
733                parameters,
734                multi_node,
735            })
736            .await
737            .map_err(|e| {
738                ControllerError::Internal(
739                    ["CSI CreateVolume through ", provisioner, " failed: ", &e].concat(),
740                )
741            })?;
742
743        let sc_name = sc
744            .get("metadata")
745            .and_then(|m| m.get("name"))
746            .and_then(Value::as_str)
747            .unwrap_or_default();
748        let reclaim = sc
749            .get("reclaimPolicy")
750            .and_then(Value::as_str)
751            .unwrap_or("Delete");
752        let attributes: serde_json::Map<String, Value> = created
753            .volume_attributes
754            .iter()
755            .map(|(k, v)| (k.clone(), json!(v)))
756            .collect();
757
758        let pv = json!({
759            "apiVersion": "v1",
760            "kind": "PersistentVolume",
761            "metadata": {
762                "name": pv_name,
763                "annotations": { PROVISIONED_BY: provisioner }
764            },
765            "spec": {
766                // The DRIVER's capacity, which may exceed the request: a
767                // driver rounds up to its allocation unit, and recording the
768                // request instead would make a later binding check compare
769                // against a size that does not exist.
770                "capacity": { "storage": format!("{}", created.capacity_bytes) },
771                "accessModes": if access_modes.is_empty() {
772                    json!(["ReadWriteOnce"])
773                } else {
774                    json!(access_modes)
775                },
776                "persistentVolumeReclaimPolicy": reclaim,
777                "storageClassName": sc_name,
778                "csi": {
779                    "driver": provisioner,
780                    "volumeHandle": created.volume_handle,
781                    "volumeAttributes": Value::Object(attributes),
782                },
783                "claimRef": Self::claim_ref(claim)
784            },
785            "status": { "phase": "Bound" }
786        });
787
788        // Store writes keep their own error, so they keep its Sweep scope.
789        // They used to be flattened to a String with the driver's refusal,
790        // which made a store that could not commit look like one claim's
791        // problem and let the sweep carry on writing into it.
792        self.create_and_bind(pvc_key, pvc, pv_name, pv).await
793    }
794
795    /// Write a freshly provisioned PV only if nothing holds its name, then
796    /// bind the claim to it.
797    ///
798    /// ★ CREATE-IF-ABSENT, NEVER PUT. The PV is written by a transaction
799    /// whose one compare is "this key does not exist" — the compare
800    /// kube-apiserver uses for every create — with an empty failure branch.
801    /// An unconditional Put here is how a recreated claim used to take over
802    /// the deleted claim's PV: same name, overwritten claimRef, same
803    /// directory underneath. A PV that already holds the name is left as it
804    /// is, and the claim is not bound this pass; a PV that is this claim's
805    /// is found on the next pass through its `claimRef` uid.
806    async fn create_and_bind(
807        &self,
808        pvc_key: &ResourceKey,
809        pvc: &Value,
810        pv_name: &str,
811        pv: Value,
812    ) -> Result<ObjectOutcome, ControllerError> {
813        let Some(claim_revision) = resource_version_of(pvc) else {
814            return Ok(ObjectOutcome::skipped_because(CLAIM_NO_REVISION));
815        };
816        let volume_key = ResourceKey::cluster_scoped("", "v1", "PersistentVolume", pv_name);
817        let applied = self
818            .store
819            .propose(ResourceCommand::Txn {
820                compares: vec![TxnCompare::NotExists {
821                    key: volume_key.clone(),
822                }],
823                success: vec![TxnOp::Put {
824                    key: volume_key,
825                    value: pv,
826                }],
827                failure: Vec::new(),
828                reason: Reason::Controller,
829            })
830            .await?;
831        let volume = match Effect::of(applied.op) {
832            written @ Effect::Written(_) => written,
833            // The failure branch is empty, so a transaction that changed
834            // nothing took it: the key was already there.
835            Effect::Unchanged => return Ok(ObjectOutcome::skipped_because(PV_NAME_TAKEN)),
836            refused @ Effect::Rejected(_) => return Ok(ObjectOutcome::from(refused)),
837        };
838        // At the claim's revision: a claim that moved since it was read
839        // finds this PV through its claimRef uid on the next pass.
840        let claim = self
841            .put(
842                pvc_key.clone(),
843                Self::bind_pvc(pvc.clone(), pv_name),
844                Some(claim_revision),
845            )
846            .await?;
847        Ok(ObjectOutcome::from(volume.and(claim)))
848    }
849
850    /// Bind the listed claim to the existing PV `volume`: the claim first,
851    /// at the revision it was listed at, then the volume. A claim that
852    /// moved since is refused and nothing is bound; the next pass binds it
853    /// as it now stands.
854    async fn bind_existing(
855        &self,
856        (claim_key, listed): (&ResourceKey, &Value),
857        claim_revision: engenho_store::revision::Revision,
858        (volume_key, volume): (&ResourceKey, &Value),
859        claim: &ClaimId<'_>,
860    ) -> Result<Effect, ControllerError> {
861        let bound_claim = Self::bind_pvc(listed.clone(), &volume_key.name);
862        let written = self
863            .put(claim_key.clone(), bound_claim, Some(claim_revision))
864            .await?;
865        if let Effect::Rejected(_) = written {
866            return Ok(written);
867        }
868        let bound_volume = self
869            .put(
870                volume_key.clone(),
871                Self::bind_pv(volume.clone(), claim),
872                None,
873            )
874            .await?;
875        debug!(pvc = %claim_key.label(), pv = %volume_key.name, "bound PVC to existing PV");
876        Ok(written.and(bound_volume))
877    }
878
879    /// Write a Put for a resource value (Controller reason) at `expected`
880    /// (unconditional when `None`), and say what the store did with it.
881    async fn put(
882        &self,
883        key: ResourceKey,
884        value: Value,
885        expected: Option<engenho_store::revision::Revision>,
886    ) -> Result<Effect, ControllerError> {
887        let applied = self
888            .store
889            .propose(ResourceCommand::Put {
890                key,
891                value,
892                expected,
893                reason: Reason::Controller,
894            })
895            .await?;
896        Ok(Effect::of(applied.op))
897    }
898}
899
900/// Set `status.phase` on a resource value, creating `status` if absent.
901fn set_phase(v: &mut Value, phase: &str) {
902    if let Some(status) = v.get_mut("status").and_then(Value::as_object_mut) {
903        status.insert("phase".into(), json!(phase));
904    } else if let Some(obj) = v.as_object_mut() {
905        obj.insert("status".into(), json!({ "phase": phase }));
906    }
907}
908
909/// Is this `StorageClass` the cluster default (`...is-default-class: "true"`)?
910fn is_default_sc(sc: &Value) -> bool {
911    sc.get("metadata")
912        .and_then(|m| m.get("annotations"))
913        .and_then(|a| a.get(DEFAULT_SC_ANNOTATION))
914        .and_then(|v| v.as_str())
915        .is_some_and(|s| s == "true")
916}
917
918/// Does a `StorageClass` use the local-path provisioner (either the
919/// rancher.io standard or engenho's alias)?
920fn sc_is_local_path(sc: &Value) -> bool {
921    matches!(
922        sc.get("provisioner").and_then(|p| p.as_str()),
923        Some(LOCAL_PATH_PROVISIONER | ENGENHO_LOCAL_PATH_PROVISIONER)
924    )
925}
926
927impl PvBinderController {
928    /// The existing PV `pvc` binds to, if any. Candidates are the PVs not
929    /// already claimed this tick; a pre-bound claim (`spec.volumeName`)
930    /// narrows them to exactly that PV.
931    ///
932    /// First a PV whose claimRef carries this claim's uid, whatever its
933    /// phase: it is already this claim's volume — a provision whose PV write
934    /// landed and whose claim write did not, or an operator pre-bind by uid
935    /// (upstream's `IsVolumeBoundToClaim` arm). Then any Available PV that
936    /// matches.
937    fn static_candidate<'v>(
938        pvs: &'v [(ResourceKey, Value)],
939        pvc: &Value,
940        claim: &ClaimId<'_>,
941        pre_bound: Option<&str>,
942        claimed_this_tick: &[String],
943    ) -> Option<&'v (ResourceKey, Value)> {
944        let eligible = |key: &ResourceKey| {
945            !claimed_this_tick.contains(&key.name) && pre_bound.is_none_or(|n| key.name == n)
946        };
947        pvs.iter()
948            .find(|(key, pv)| {
949                eligible(key)
950                    && Self::claim_ref_to(pv, claim) == ClaimRefTo::ThisClaim
951                    && Self::holds_request(pv, pvc)
952            })
953            .or_else(|| {
954                pvs.iter().find(|(key, pv)| {
955                    eligible(key)
956                        && Self::pv_phase(pv) == "Available"
957                        && Self::pv_matches_pvc(pv, pvc, claim)
958                })
959            })
960    }
961
962    /// Reconcile ONE claim. `?` in here leaves this claim only; whether the
963    /// error then ends the sweep is decided by its scope in
964    /// [`ObjectOutcome::settle`], never here.
965    ///
966    /// `claimed_this_tick` is shared across the sweep so two Pending claims
967    /// do not bind the same available PV in one pass.
968    async fn reconcile_claim(
969        &self,
970        pvc_key: &ResourceKey,
971        pvc: &Value,
972        view: &TickView,
973        claimed_this_tick: &tokio::sync::Mutex<Vec<String>>,
974    ) -> Result<ObjectOutcome, ControllerError> {
975        // Held for this claim's whole reconcile. Claims are reconciled one
976        // at a time, so this never waits; it is how the one list is shared
977        // by per-claim futures that each outlive a single borrow.
978        let mut claimed_this_tick = claimed_this_tick.lock().await;
979        // Only Pending (or status-less) PVCs need binding. Already-Bound
980        // PVCs are converged: idempotent no-ops.
981        if Self::pvc_phase(pvc) != "Pending" {
982            return Ok(ObjectOutcome::Unchanged);
983        }
984        let pvc_ns = pvc_key.namespace.as_deref().unwrap_or("default");
985        let pvc_name = &pvc_key.name;
986        // Every write to the claim is at the revision it was listed at. A
987        // Put of the listed copy made blind would overwrite whatever landed
988        // since: the pvc-protection finalizer, a deletionTimestamp — or the
989        // claim's delete itself, which a blind Put undoes by creating it
990        // again.
991        let Some(claim_revision) = resource_version_of(pvc) else {
992            return Ok(ObjectOutcome::skipped_because(CLAIM_NO_REVISION));
993        };
994
995        // 0. IDENTITY. Every volume this claim is given — found or made —
996        //    is tied to it by uid, so a claim with no usable uid has nothing
997        //    to be matched by and stays Pending, saying why.
998        let uid = match ClaimUid::of(pvc) {
999            Ok(uid) => uid,
1000            Err(gap) => return Ok(ObjectOutcome::skipped_because(gap.note())),
1001        };
1002        let claim = ClaimId {
1003            namespace: pvc_ns,
1004            name: pvc_name,
1005            uid: &uid,
1006        };
1007
1008        // 1. STATIC BIND.
1009        let pre_bound = Self::pre_bound_volume(pvc);
1010        let candidate =
1011            Self::static_candidate(&view.pvs, pvc, &claim, pre_bound, &claimed_this_tick);
1012        if let Some((pv_key, pv)) = candidate {
1013            let bound = self
1014                .bind_existing((pvc_key, pvc), claim_revision, (pv_key, pv), &claim)
1015                .await?;
1016            if !matches!(bound, Effect::Rejected(_)) {
1017                claimed_this_tick.push(pv_key.name.clone());
1018            }
1019            return Ok(ObjectOutcome::from(bound));
1020        }
1021
1022        // A pre-bound PVC whose named PV isn't available this pass waits;
1023        // we never dynamically provision over an explicit volumeName.
1024        if pre_bound.is_some() {
1025            return Ok(ObjectOutcome::SKIPPED);
1026        }
1027
1028        // 2. DYNAMIC PROVISION via the local-path provisioner / default SC.
1029        let Some(sc) = Self::effective_storage_class(pvc, &view.storage_classes) else {
1030            // No class + no default SC → stay Pending (no provisioner).
1031            return Ok(ObjectOutcome::SKIPPED);
1032        };
1033        // The name this claim's volume gets, from its uid. If a PV already
1034        // holds it and was not bound to this claim above, it is not this
1035        // claim's to take: nothing is created over it, and nothing is
1036        // provisioned into what may be its directory.
1037        let volume = PvName::for_claim(&uid);
1038        let name_taken = view.pvs.iter().any(|(k, _)| volume.names(&k.name));
1039        let volume_name = volume.to_string();
1040        if !sc_is_local_path(sc) {
1041            // 2b. CSI DYNAMIC PROVISION. The class names some other
1042            // provisioner; if a registered CSI driver answers to that
1043            // name, engenho provisions through it.
1044            let provisioner = sc
1045                .get("provisioner")
1046                .and_then(Value::as_str)
1047                .unwrap_or_default();
1048            // Asked BEFORE creating: an absent driver must leave the PVC
1049            // Pending ("waiting for your driver"), not fail a provision
1050            // ("your storage is broken"). Also what keeps a cluster with
1051            // an external provisioner working unchanged.
1052            if provisioner.is_empty() || !self.csi.can_provision(provisioner).await {
1053                return Ok(ObjectOutcome::SKIPPED);
1054            }
1055            if Self::is_wait_for_first_consumer(Some(sc)) {
1056                return Ok(ObjectOutcome::SKIPPED);
1057            }
1058            // Before the driver is asked: a CreateVolume idempotent by name
1059            // would hand back whatever volume holds it.
1060            if name_taken {
1061                return Ok(ObjectOutcome::skipped_because(PV_NAME_TAKEN));
1062            }
1063            return self
1064                .provision_csi(pvc_key, pvc, &claim, &volume_name, sc, provisioner)
1065                .await;
1066        }
1067        if Self::is_wait_for_first_consumer(Some(sc)) {
1068            // WaitForFirstConsumer: leave Pending until a Pod references the
1069            // PVC. TYPED-DEFERRED (named follow-up) — never provision early.
1070            return Ok(ObjectOutcome::skipped_because(WAIT_FOR_FIRST_CONSUMER));
1071        }
1072
1073        // Immediate binding mode: provision now. The local-path PV copies
1074        // the claim's request as its capacity, so a claim with no usable
1075        // size has nothing to provision. That is its declaration being
1076        // unusable, not the world being unready: Declarative, reported on
1077        // the claim. (A CSI claim with no size is different: the driver
1078        // picks one and the PV records the driver's answer.)
1079        if Self::pvc_request_bytes(pvc).is_none() {
1080            return Err(ControllerError::InvalidResource(
1081                UNUSABLE_REQUEST.to_string(),
1082            ));
1083        }
1084        let host_path = match volume.local_path_dir(&self.local_path_root, pvc_ns, pvc_name) {
1085            Ok(dir) => dir.to_string(),
1086            Err(gap) => return Ok(ObjectOutcome::skipped_because(gap.note())),
1087        };
1088        // Before any host effect: the directory is named by the same uid,
1089        // so a PV holding the name may be using it.
1090        if name_taken {
1091            return Ok(ObjectOutcome::skipped_because(PV_NAME_TAKEN));
1092        }
1093        // The ONE host effect — create the backing dir before the PV is
1094        // visible so the kubelet can bind-mount it. A failure is this
1095        // claim's alone: the claims after it in the list still bind.
1096        self.env
1097            .ensure_dir(&host_path)
1098            .map_err(|e| ControllerError::Internal(["provision local-path dir: ", &e].concat()))?;
1099        // ── RESTORE-FROM-SNAPSHOT ────────────────────────────────────
1100        // A PVC whose `spec.dataSource` names a VolumeSnapshot is a
1101        // RESTORE, and this is the PITR drill's whole restore vector. The
1102        // hydrate happens AFTER the dir exists and BEFORE the PV is
1103        // visible, so a pod can never observe a half-filled volume.
1104        //
1105        // A named-but-unresolvable snapshot leaves the claim Pending
1106        // rather than provisioning an empty volume: presenting an empty
1107        // restore as a successful one is exactly the "clean receipt, no
1108        // data underneath" failure a drill exists to catch.
1109        if let Some(snap_name) = Self::snapshot_data_source(pvc) {
1110            let Some(src) = self.resolve_snapshot_path(
1111                pvc_ns,
1112                &snap_name,
1113                &view.snapshots,
1114                &view.snapshot_contents,
1115            ) else {
1116                return Ok(ObjectOutcome::skipped_because(SNAPSHOT_NOT_READY));
1117            };
1118            self.env
1119                .restore_tree(&src, &host_path)
1120                .map_err(|e| ControllerError::Internal(["restore from snapshot: ", &e].concat()))?;
1121            debug!(pvc = %pvc_key.label(), snapshot = %snap_name, "restored PV data from snapshot");
1122        }
1123        let dyn_pv = Self::build_dynamic_pv(pvc, &claim, &volume_name, &host_path, sc);
1124        let outcome = self
1125            .create_and_bind(pvc_key, pvc, &volume_name, dyn_pv)
1126            .await?;
1127        debug!(pvc = %pvc_key.label(), pv = %volume_name, ?outcome, "local-path provision");
1128        claimed_this_tick.push(volume_name);
1129        Ok(outcome)
1130    }
1131}
1132
1133/// Claims, the volumes and classes that satisfy them, and the snapshots a
1134/// claim with a `dataSource` is restored from. A snapshot turning
1135/// `readyToUse` wakes the binder, so the claim waiting on it binds then.
1136impl DeclaresReads for PvBinderController {
1137    fn reads(&self) -> Reads {
1138        Reads::of(&[
1139            gvk("", "v1", "PersistentVolumeClaim"),
1140            gvk("", "v1", "PersistentVolume"),
1141            gvk("storage.k8s.io", "v1", "StorageClass"),
1142            gvk(SNAPSHOT_GROUP, SNAPSHOT_VERSION, "VolumeSnapshot"),
1143            gvk(SNAPSHOT_GROUP, SNAPSHOT_VERSION, "VolumeSnapshotContent"),
1144        ])
1145    }
1146}
1147
1148#[async_trait]
1149impl Controller for PvBinderController {
1150    fn name(&self) -> &'static str {
1151        "pv-binder"
1152    }
1153
1154    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
1155        // PVCs are namespaced; PVs + StorageClasses are cluster-scoped.
1156        let pvcs = self
1157            .store
1158            .list("", "v1", "PersistentVolumeClaim", self.namespace.as_deref())
1159            .await;
1160        let view = TickView {
1161            pvs: self.store.list("", "v1", "PersistentVolume", None).await,
1162            storage_classes: self
1163                .store
1164                .list("storage.k8s.io", "v1", "StorageClass", None)
1165                .await,
1166            // Snapshot kinds, for `spec.dataSource` restores. Listing them
1167            // unconditionally costs one store read per tick and keeps the
1168            // restore path from needing a second controller.
1169            snapshots: self
1170                .store
1171                .list(
1172                    crate::volume_snapshot::SNAPSHOT_GROUP,
1173                    crate::volume_snapshot::SNAPSHOT_VERSION,
1174                    "VolumeSnapshot",
1175                    None,
1176                )
1177                .await,
1178            snapshot_contents: self
1179                .store
1180                .list(
1181                    crate::volume_snapshot::SNAPSHOT_GROUP,
1182                    crate::volume_snapshot::SNAPSHOT_VERSION,
1183                    "VolumeSnapshotContent",
1184                    None,
1185                )
1186                .await,
1187        };
1188
1189        // Track PVs claimed THIS tick so two Pending PVCs don't bind the same
1190        // available PV in one pass.
1191        let claimed_this_tick = tokio::sync::Mutex::new(Vec::new());
1192
1193        let (this, view, claimed) = (self, &view, &claimed_this_tick);
1194        let claims = self
1195            .sweep
1196            .run(&pvcs, |pvc_key, pvc| async move {
1197                ObjectOutcome::settle(this.reconcile_claim(pvc_key, pvc, view, claimed).await)
1198            })
1199            .await?;
1200        // Then the volumes, as listed at the top of the tick. A PV bound or
1201        // provisioned above is not among them; it is walked next tick.
1202        let listed_claims = &pvcs;
1203        let volumes = self
1204            .volume_sweep
1205            .run(&view.pvs, |pv_key, pv| async move {
1206                ObjectOutcome::settle(this.reconcile_volume(pv_key, pv, listed_claims).await)
1207            })
1208            .await?;
1209        Ok(claims.then(volumes).into())
1210    }
1211}
1212
1213/// Deterministic mock [`ProvisionerEnv`] — records every dir it was asked to
1214/// ensure + always succeeds. The trait IS the testability contract: binding +
1215/// provisioning is fully exercised with ZERO host filesystem.
1216#[derive(Default)]
1217pub struct FakeProvisionerEnv {
1218    ensured: std::sync::Mutex<Vec<String>>,
1219    restored: std::sync::Mutex<Vec<(String, String)>>,
1220    removed: std::sync::Mutex<Vec<String>>,
1221}
1222
1223impl FakeProvisionerEnv {
1224    /// Fresh empty mock.
1225    #[must_use]
1226    pub fn new() -> Self {
1227        Self::default()
1228    }
1229
1230    /// The dirs the mock was asked to ensure (in call order).
1231    #[must_use]
1232    pub fn ensured_dirs(&self) -> Vec<String> {
1233        self.ensured.lock().unwrap().clone()
1234    }
1235
1236    /// The `(src, dst)` restores the mock was asked to perform, in call order.
1237    #[must_use]
1238    pub fn restored_trees(&self) -> Vec<(String, String)> {
1239        self.restored.lock().unwrap().clone()
1240    }
1241
1242    /// The directories the mock was asked to remove, in call order.
1243    #[must_use]
1244    pub fn removed_dirs(&self) -> Vec<String> {
1245        self.removed
1246            .lock()
1247            .unwrap_or_else(std::sync::PoisonError::into_inner)
1248            .clone()
1249    }
1250}
1251
1252impl ProvisionerEnv for FakeProvisionerEnv {
1253    fn ensure_dir(&self, path: &str) -> Result<(), String> {
1254        self.ensured.lock().unwrap().push(path.to_string());
1255        Ok(())
1256    }
1257
1258    /// Records `(src, dst)` instead of copying, so a test can assert that a
1259    /// restore was attempted FROM THE RIGHT SNAPSHOT — the pair is the whole
1260    /// claim, and a mock that only recorded "a restore happened" could not
1261    /// catch a restore from the wrong snapshot.
1262    fn restore_tree(&self, src: &str, dst: &str) -> Result<(), String> {
1263        self.restored
1264            .lock()
1265            .unwrap()
1266            .push((src.to_string(), dst.to_string()));
1267        Ok(())
1268    }
1269
1270    fn remove_dir(&self, dir: &LocalPathDir<'_>) -> std::io::Result<()> {
1271        self.removed
1272            .lock()
1273            .unwrap_or_else(std::sync::PoisonError::into_inner)
1274            .push(dir.to_string());
1275        Ok(())
1276    }
1277}
1278
1279#[cfg(test)]
1280mod tests {
1281    use super::*;
1282    use std::time::Duration;
1283
1284    async fn live_store() -> Arc<StoreMesh> {
1285        use engenho_store::{InProcessRouter, default_config};
1286        let router = InProcessRouter::new();
1287        let cfg = default_config("controllers-pv-binder").unwrap();
1288        let store = Arc::new(
1289            StoreMesh::start(1, "in-process://1".into(), router, cfg)
1290                .await
1291                .unwrap(),
1292        );
1293        store.initialize_singleton().await.unwrap();
1294        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
1295        store
1296    }
1297
1298    async fn put_op(store: &StoreMesh, key: ResourceKey, value: Value) {
1299        store
1300            .propose(ResourceCommand::put(key, value, Reason::Operator))
1301            .await
1302            .unwrap();
1303    }
1304
1305    fn pvc_key(ns: &str, name: &str) -> ResourceKey {
1306        ResourceKey::namespaced("", "v1", "PersistentVolumeClaim", ns, name)
1307    }
1308    fn pv_key(name: &str) -> ResourceKey {
1309        ResourceKey::cluster_scoped("", "v1", "PersistentVolume", name)
1310    }
1311    fn sc_key(name: &str) -> ResourceKey {
1312        ResourceKey::cluster_scoped("storage.k8s.io", "v1", "StorageClass", name)
1313    }
1314
1315    fn uid(s: &str) -> ClaimUid {
1316        ClaimUid::of(&json!({"metadata": {"uid": s}})).unwrap()
1317    }
1318
1319    /// The claim `ns/c` with uid `u-c`, as the pure predicates see it.
1320    fn with_claim<R>(f: impl FnOnce(&ClaimId<'_>) -> R) -> R {
1321        let u = uid("u-c");
1322        f(&ClaimId {
1323            namespace: "ns",
1324            name: "c",
1325            uid: &u,
1326        })
1327    }
1328
1329    fn binder(store: Arc<StoreMesh>) -> PvBinderController {
1330        PvBinderController::with_env(
1331            store,
1332            None,
1333            "/data/local-path",
1334            Arc::new(FakeProvisionerEnv::new()),
1335        )
1336    }
1337
1338    // ── pure-predicate tests (no store) ──────────────────────────────
1339
1340    #[test]
1341    fn capacity_must_be_at_least_request() {
1342        let pvc = json!({"spec": {"resources": {"requests": {"storage": "1Gi"}},
1343                                  "accessModes": ["ReadWriteOnce"]}});
1344        let big = json!({"spec": {"capacity": {"storage": "2Gi"},
1345                                  "accessModes": ["ReadWriteOnce"]}});
1346        let small = json!({"spec": {"capacity": {"storage": "512Mi"},
1347                                    "accessModes": ["ReadWriteOnce"]}});
1348        with_claim(|c| {
1349            assert!(PvBinderController::pv_matches_pvc(&big, &pvc, c));
1350            assert!(!PvBinderController::pv_matches_pvc(&small, &pvc, c));
1351        });
1352    }
1353
1354    #[test]
1355    fn access_modes_must_be_superset() {
1356        let pvc = json!({"spec": {"resources": {"requests": {"storage": "1Gi"}},
1357                                  "accessModes": ["ReadWriteMany"]}});
1358        // PV offers only RWO → cannot satisfy a RWX request.
1359        let rwo = json!({"spec": {"capacity": {"storage": "1Gi"},
1360                                  "accessModes": ["ReadWriteOnce"]}});
1361        let rwx = json!({"spec": {"capacity": {"storage": "1Gi"},
1362                                  "accessModes": ["ReadWriteOnce", "ReadWriteMany"]}});
1363        with_claim(|c| {
1364            assert!(!PvBinderController::pv_matches_pvc(&rwo, &pvc, c));
1365            assert!(PvBinderController::pv_matches_pvc(&rwx, &pvc, c));
1366        });
1367    }
1368
1369    #[test]
1370    fn storage_class_must_match_nil_eq_empty() {
1371        let pvc_nil = json!({"spec": {}});
1372        let pv_empty = json!({"spec": {"storageClassName": ""}});
1373        assert!(PvBinderController::storage_class_matches(
1374            &pvc_nil, &pv_empty
1375        ));
1376        let pvc_fast = json!({"spec": {"storageClassName": "fast"}});
1377        let pv_slow = json!({"spec": {"storageClassName": "slow"}});
1378        assert!(!PvBinderController::storage_class_matches(
1379            &pvc_fast, &pv_slow
1380        ));
1381        let pv_fast = json!({"spec": {"storageClassName": "fast"}});
1382        assert!(PvBinderController::storage_class_matches(
1383            &pvc_fast, &pv_fast
1384        ));
1385    }
1386
1387    #[test]
1388    fn claimref_to_other_claim_blocks_match() {
1389        let pvc = json!({"spec": {"resources": {"requests": {"storage": "1Gi"}}}});
1390        let pv = json!({"spec": {"capacity": {"storage": "1Gi"},
1391                                 "claimRef": {"namespace": "other", "name": "x"}}});
1392        // claimRef to THIS pvc is fine.
1393        let pv2 = json!({"spec": {"capacity": {"storage": "1Gi"},
1394                                  "claimRef": {"namespace": "ns", "name": "c"}}});
1395        with_claim(|c| {
1396            assert!(!PvBinderController::pv_matches_pvc(&pv, &pvc, c));
1397            assert!(PvBinderController::pv_matches_pvc(&pv2, &pvc, c));
1398        });
1399    }
1400
1401    /// A claimRef naming this namespace and name but ANOTHER uid is an
1402    /// earlier claim of the same name: never compatible. With this claim's
1403    /// uid, or with none (a reservation by name), it is.
1404    #[test]
1405    fn a_claim_ref_uid_tells_two_claims_of_one_name_apart() {
1406        let pvc = json!({"spec": {"resources": {"requests": {"storage": "1Gi"}}}});
1407        let reserved = |uid: Value| {
1408            json!({"spec": {"capacity": {"storage": "1Gi"},
1409                            "claimRef": {"namespace": "ns", "name": "c", "uid": uid}}})
1410        };
1411        with_claim(|c| {
1412            let earlier = reserved(json!("u-earlier"));
1413            assert_eq!(
1414                PvBinderController::claim_ref_to(&earlier, c),
1415                ClaimRefTo::Other
1416            );
1417            assert!(!PvBinderController::pv_claimref_compatible(&earlier, c));
1418            assert!(!PvBinderController::pv_matches_pvc(&earlier, &pvc, c));
1419
1420            let this = reserved(json!("u-c"));
1421            assert_eq!(
1422                PvBinderController::claim_ref_to(&this, c),
1423                ClaimRefTo::ThisClaim
1424            );
1425            assert!(PvBinderController::pv_matches_pvc(&this, &pvc, c));
1426
1427            for by_name in [reserved(Value::Null), reserved(json!(""))] {
1428                assert_eq!(
1429                    PvBinderController::claim_ref_to(&by_name, c),
1430                    ClaimRefTo::ThisName
1431                );
1432                assert!(PvBinderController::pv_matches_pvc(&by_name, &pvc, c));
1433            }
1434            // A uid that is not a string cannot be checked, so it is not
1435            // this claim's.
1436            assert_eq!(
1437                PvBinderController::claim_ref_to(&reserved(json!(7)), c),
1438                ClaimRefTo::Other
1439            );
1440        });
1441    }
1442
1443    #[test]
1444    fn an_empty_phase_is_the_unset_phase() {
1445        let empty = json!({"status": {"phase": ""}});
1446        assert_eq!(PvBinderController::pvc_phase(&empty), "Pending");
1447        assert_eq!(PvBinderController::pv_phase(&empty), "Available");
1448    }
1449
1450    // ── live-store binding tests ─────────────────────────────────────
1451
1452    #[tokio::test]
1453    async fn a_claim_created_with_an_empty_phase_binds() {
1454        let store = live_store().await;
1455        put_op(
1456            &store,
1457            pvc_key("ns1", "claim"),
1458            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1459                   "metadata": {"name": "claim", "namespace": "ns1", "uid": "claim-uid"},
1460                   "spec": {"accessModes": ["ReadWriteOnce"],
1461                            "resources": {"requests": {"storage": "1Gi"}},
1462                            "storageClassName": "manual"},
1463                   "status": {"phase": ""}}),
1464        )
1465        .await;
1466        put_op(
1467            &store,
1468            pv_key("vol-a"),
1469            json!({"apiVersion": "v1", "kind": "PersistentVolume",
1470                   "metadata": {"name": "vol-a"},
1471                   "spec": {"capacity": {"storage": "5Gi"},
1472                            "accessModes": ["ReadWriteOnce"],
1473                            "storageClassName": "manual",
1474                            "hostPath": {"path": "/mnt/a"}},
1475                   "status": {"phase": ""}}),
1476        )
1477        .await;
1478
1479        binder(store.clone()).tick().await.unwrap();
1480
1481        assert_eq!(phase(&store, "claim").await, "Bound");
1482        let pv = store.get(&pv_key("vol-a")).await.unwrap();
1483        assert_eq!(pv["status"]["phase"], "Bound");
1484    }
1485
1486    #[tokio::test]
1487    async fn pending_pvc_binds_to_matching_pv_bidirectionally() {
1488        let store = live_store().await;
1489        put_op(
1490            &store,
1491            pvc_key("ns1", "claim"),
1492            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1493                   "metadata": {"name": "claim", "namespace": "ns1", "uid": "claim-uid"},
1494                   "spec": {"accessModes": ["ReadWriteOnce"],
1495                            "resources": {"requests": {"storage": "1Gi"}},
1496                            "storageClassName": "manual"}}),
1497        )
1498        .await;
1499        put_op(
1500            &store,
1501            pv_key("vol-a"),
1502            json!({"apiVersion": "v1", "kind": "PersistentVolume",
1503                   "metadata": {"name": "vol-a"},
1504                   "spec": {"capacity": {"storage": "5Gi"},
1505                            "accessModes": ["ReadWriteOnce"],
1506                            "storageClassName": "manual",
1507                            "hostPath": {"path": "/mnt/a"}},
1508                   "status": {"phase": "Available"}}),
1509        )
1510        .await;
1511
1512        binder(store.clone()).tick().await.unwrap();
1513
1514        let pvc = store.get(&pvc_key("ns1", "claim")).await.unwrap();
1515        assert_eq!(pvc["spec"]["volumeName"], "vol-a");
1516        assert_eq!(pvc["status"]["phase"], "Bound");
1517        let pv = store.get(&pv_key("vol-a")).await.unwrap();
1518        assert_eq!(pv["status"]["phase"], "Bound");
1519        assert_eq!(pv["spec"]["claimRef"]["name"], "claim");
1520        assert_eq!(pv["spec"]["claimRef"]["namespace"], "ns1");
1521        assert_eq!(pv["spec"]["claimRef"]["uid"], "claim-uid");
1522    }
1523
1524    #[tokio::test]
1525    async fn mismatched_pvs_do_not_bind() {
1526        let store = live_store().await;
1527        put_op(
1528            &store,
1529            pvc_key("ns1", "claim"),
1530            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1531                   "metadata": {"name": "claim", "namespace": "ns1"},
1532                   "spec": {"accessModes": ["ReadWriteMany"],
1533                            "resources": {"requests": {"storage": "10Gi"}},
1534                            "storageClassName": "manual"}}),
1535        )
1536        .await;
1537        // Too small.
1538        put_op(
1539            &store,
1540            pv_key("small"),
1541            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"small"},
1542                   "spec":{"capacity":{"storage":"1Gi"},"accessModes":["ReadWriteMany"],
1543                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1544        )
1545        .await;
1546        // Wrong class.
1547        put_op(
1548            &store,
1549            pv_key("wrongclass"),
1550            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"wrongclass"},
1551                   "spec":{"capacity":{"storage":"100Gi"},"accessModes":["ReadWriteMany"],
1552                           "storageClassName":"other"},"status":{"phase":"Available"}}),
1553        )
1554        .await;
1555        // Wrong access mode (RWO can't serve RWX).
1556        put_op(
1557            &store,
1558            pv_key("wrongmode"),
1559            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"wrongmode"},
1560                   "spec":{"capacity":{"storage":"100Gi"},"accessModes":["ReadWriteOnce"],
1561                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1562        )
1563        .await;
1564
1565        binder(store.clone()).tick().await.unwrap();
1566
1567        let pvc = store.get(&pvc_key("ns1", "claim")).await.unwrap();
1568        // Left untouched: phase never advanced to Bound (a Pending PVC the
1569        // binder can't satisfy is not re-stamped — phase stays unset).
1570        assert_ne!(pvc["status"]["phase"], "Bound");
1571        assert!(pvc["spec"].get("volumeName").is_none() || pvc["spec"]["volumeName"].is_null());
1572        // No PV was claimed.
1573        for n in ["small", "wrongclass", "wrongmode"] {
1574            let pv = store.get(&pv_key(n)).await.unwrap();
1575            assert_eq!(
1576                pv["status"]["phase"], "Available",
1577                "{n} must stay available"
1578            );
1579        }
1580    }
1581
1582    #[tokio::test]
1583    async fn pvc_with_default_local_path_sc_dynamically_provisions() {
1584        let store = live_store().await;
1585        put_op(
1586            &store,
1587            sc_key("local-path"),
1588            json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass",
1589                   "metadata": {"name": "local-path",
1590                                "annotations": {"storageclass.kubernetes.io/is-default-class": "true"}},
1591                   "provisioner": "rancher.io/local-path",
1592                   "reclaimPolicy": "Delete",
1593                   "volumeBindingMode": "Immediate"}),
1594        )
1595        .await;
1596        // PVC omits storageClassName → uses the default SC.
1597        put_op(
1598            &store,
1599            pvc_key("ns1", "dyn"),
1600            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1601                   "metadata": {"name": "dyn", "namespace": "ns1", "uid": "dyn-uid"},
1602                   "spec": {"accessModes": ["ReadWriteOnce"],
1603                            "resources": {"requests": {"storage": "2Gi"}}}}),
1604        )
1605        .await;
1606
1607        let env = Arc::new(FakeProvisionerEnv::new());
1608        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
1609        c.tick().await.unwrap();
1610
1611        // A PV was provisioned + the PVC bound to it.
1612        let pvc = store.get(&pvc_key("ns1", "dyn")).await.unwrap();
1613        assert_eq!(pvc["status"]["phase"], "Bound");
1614        let pv_name = pvc["spec"]["volumeName"].as_str().unwrap().to_string();
1615        let pv = store.get(&pv_key(&pv_name)).await.unwrap();
1616        assert_eq!(pv["status"]["phase"], "Bound");
1617        assert_eq!(pv["spec"]["capacity"]["storage"], "2Gi");
1618        assert_eq!(pv_name, "pvc-dyn-uid", "the PV is named by the claim's uid");
1619        assert_eq!(
1620            pv["spec"]["hostPath"]["path"],
1621            "/data/local-path/pvc-dyn-uid_ns1_dyn"
1622        );
1623        assert_eq!(pv["spec"]["claimRef"]["name"], "dyn");
1624        assert_eq!(pv["spec"]["claimRef"]["uid"], "dyn-uid");
1625        assert_eq!(pv["spec"]["persistentVolumeReclaimPolicy"], "Delete");
1626        // The host effect: the backing dir was ensured.
1627        assert_eq!(
1628            env.ensured_dirs(),
1629            vec!["/data/local-path/pvc-dyn-uid_ns1_dyn".to_string()]
1630        );
1631    }
1632
1633    #[tokio::test]
1634    async fn wait_for_first_consumer_pvc_stays_pending() {
1635        let store = live_store().await;
1636        put_op(
1637            &store,
1638            sc_key("local-path-wfc"),
1639            json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass",
1640                   "metadata": {"name": "local-path-wfc",
1641                                "annotations": {"storageclass.kubernetes.io/is-default-class": "true"}},
1642                   "provisioner": "rancher.io/local-path",
1643                   "volumeBindingMode": "WaitForFirstConsumer"}),
1644        )
1645        .await;
1646        put_op(
1647            &store,
1648            pvc_key("ns1", "wfc"),
1649            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1650                   "metadata": {"name": "wfc", "namespace": "ns1"},
1651                   "spec": {"accessModes": ["ReadWriteOnce"],
1652                            "resources": {"requests": {"storage": "1Gi"}}}}),
1653        )
1654        .await;
1655
1656        binder(store.clone()).tick().await.unwrap();
1657        let pvc = store.get(&pvc_key("ns1", "wfc")).await.unwrap();
1658        // WaitForFirstConsumer: never provisioned/bound — phase stays unset
1659        // (i.e. still Pending), and no volumeName was stamped.
1660        assert_ne!(
1661            pvc["status"]["phase"], "Bound",
1662            "WaitForFirstConsumer PVC must NOT be bound (no early provision)"
1663        );
1664        assert!(pvc["spec"].get("volumeName").is_none() || pvc["spec"]["volumeName"].is_null());
1665        // No PV was dynamically provisioned for it.
1666        let pvs = store.list("", "v1", "PersistentVolume", None).await;
1667        assert!(pvs.is_empty(), "no PV provisioned for a WFC claim");
1668    }
1669
1670    #[tokio::test]
1671    async fn pre_bound_pvc_binds_only_to_named_pv() {
1672        let store = live_store().await;
1673        // PVC pre-binds to vol-named via spec.volumeName.
1674        put_op(
1675            &store,
1676            pvc_key("ns1", "claim"),
1677            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1678                   "metadata": {"name": "claim", "namespace": "ns1"},
1679                   "spec": {"accessModes": ["ReadWriteOnce"],
1680                            "resources": {"requests": {"storage": "1Gi"}},
1681                            "storageClassName": "manual",
1682                            "volumeName": "vol-named"}}),
1683        )
1684        .await;
1685        // A different available PV that ALSO matches on capacity/class —
1686        // must NOT be chosen.
1687        put_op(
1688            &store,
1689            pv_key("vol-other"),
1690            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"vol-other"},
1691                   "spec":{"capacity":{"storage":"1Gi"},"accessModes":["ReadWriteOnce"],
1692                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1693        )
1694        .await;
1695        put_op(
1696            &store,
1697            pv_key("vol-named"),
1698            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"vol-named"},
1699                   "spec":{"capacity":{"storage":"1Gi"},"accessModes":["ReadWriteOnce"],
1700                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1701        )
1702        .await;
1703
1704        binder(store.clone()).tick().await.unwrap();
1705
1706        let pvc = store.get(&pvc_key("ns1", "claim")).await.unwrap();
1707        assert_eq!(pvc["spec"]["volumeName"], "vol-named");
1708        assert_eq!(pvc["status"]["phase"], "Bound");
1709        // The other PV was left untouched.
1710        let other = store.get(&pv_key("vol-other")).await.unwrap();
1711        assert_eq!(other["status"]["phase"], "Available");
1712    }
1713
1714    #[tokio::test]
1715    async fn already_bound_pvc_is_idempotent_noop() {
1716        let store = live_store().await;
1717        put_op(
1718            &store,
1719            pvc_key("ns1", "bound"),
1720            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1721                   "metadata": {"name": "bound", "namespace": "ns1"},
1722                   "spec": {"accessModes": ["ReadWriteOnce"],
1723                            "resources": {"requests": {"storage": "1Gi"}},
1724                            "storageClassName": "manual",
1725                            "volumeName": "vol-x"},
1726                   "status": {"phase": "Bound"}}),
1727        )
1728        .await;
1729        // An Available PV that WOULD match if the PVC were Pending.
1730        put_op(
1731            &store,
1732            pv_key("vol-free"),
1733            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"vol-free"},
1734                   "spec":{"capacity":{"storage":"1Gi"},"accessModes":["ReadWriteOnce"],
1735                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1736        )
1737        .await;
1738
1739        let outcome = binder(store.clone()).tick().await.unwrap();
1740        assert_eq!(
1741            outcome.objects_changed, 0,
1742            "no re-bind on an already-Bound PVC"
1743        );
1744        // The PVC's volumeName is unchanged; the free PV is untouched.
1745        let pvc = store.get(&pvc_key("ns1", "bound")).await.unwrap();
1746        assert_eq!(pvc["spec"]["volumeName"], "vol-x");
1747        let free = store.get(&pv_key("vol-free")).await.unwrap();
1748        assert_eq!(free["status"]["phase"], "Available");
1749    }
1750
1751    #[tokio::test]
1752    async fn two_pending_pvcs_do_not_share_one_pv() {
1753        let store = live_store().await;
1754        for name in ["a", "b"] {
1755            put_op(
1756                &store,
1757                pvc_key("ns1", name),
1758                json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1759                       "metadata": {"name": name, "namespace": "ns1"},
1760                       "spec": {"accessModes": ["ReadWriteOnce"],
1761                                "resources": {"requests": {"storage": "1Gi"}},
1762                                "storageClassName": "manual"}}),
1763            )
1764            .await;
1765        }
1766        // Only ONE available PV.
1767        put_op(
1768            &store,
1769            pv_key("only"),
1770            json!({"apiVersion":"v1","kind":"PersistentVolume","metadata":{"name":"only"},
1771                   "spec":{"capacity":{"storage":"1Gi"},"accessModes":["ReadWriteOnce"],
1772                           "storageClassName":"manual"},"status":{"phase":"Available"}}),
1773        )
1774        .await;
1775
1776        binder(store.clone()).tick().await.unwrap();
1777
1778        let mut bound_count = 0;
1779        for n in ["a", "b"] {
1780            let pvc = store.get(&pvc_key("ns1", n)).await.unwrap();
1781            if pvc["status"]["phase"] == "Bound" {
1782                bound_count += 1;
1783            }
1784        }
1785        assert_eq!(bound_count, 1, "exactly one PVC binds the single PV");
1786    }
1787
1788    // ── per-claim isolation (T2.3) ───────────────────────────────────
1789
1790    /// A host seam whose directory creation fails for exactly one claim.
1791    struct PoisonedEnv {
1792        poisoned_dir: &'static str,
1793    }
1794
1795    impl ProvisionerEnv for PoisonedEnv {
1796        fn ensure_dir(&self, path: &str) -> Result<(), String> {
1797            if path.ends_with(self.poisoned_dir) {
1798                Err("mkdir: permission denied".into())
1799            } else {
1800                Ok(())
1801            }
1802        }
1803        fn restore_tree(&self, _src: &str, _dst: &str) -> Result<(), String> {
1804            Ok(())
1805        }
1806        fn remove_dir(&self, _dir: &LocalPathDir<'_>) -> std::io::Result<()> {
1807            Ok(())
1808        }
1809    }
1810
1811    async fn default_local_path_class(store: &StoreMesh) {
1812        put_op(
1813            store,
1814            sc_key("local-path"),
1815            json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass",
1816                   "metadata": {"name": "local-path",
1817                                "annotations": {"storageclass.kubernetes.io/is-default-class": "true"}},
1818                   "provisioner": "rancher.io/local-path",
1819                   "volumeBindingMode": "Immediate"}),
1820        )
1821        .await;
1822    }
1823
1824    async fn put_claim(store: &StoreMesh, name: &str, spec: Value) {
1825        put_claim_as(store, name, json!(["uid-", name].concat()), spec).await;
1826    }
1827
1828    /// A claim `ns1/<name>` carrying exactly `uid` (which may be null or
1829    /// malformed — the store keeps whatever the body says).
1830    async fn put_claim_as(store: &StoreMesh, name: &str, uid: Value, spec: Value) {
1831        put_op(
1832            store,
1833            pvc_key("ns1", name),
1834            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1835                   "metadata": {"name": name, "namespace": "ns1", "uid": uid},
1836                   "spec": spec}),
1837        )
1838        .await;
1839    }
1840
1841    fn sized() -> Value {
1842        json!({"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "1Gi"}}})
1843    }
1844
1845    async fn phase(store: &StoreMesh, name: &str) -> Value {
1846        store.get(&pvc_key("ns1", name)).await.unwrap()["status"]["phase"].clone()
1847    }
1848
1849    /// The claim listed FIRST cannot get its directory. Before T2.3 its
1850    /// `?` ended the tick, so the two healthy claims after it were never
1851    /// reached — on that tick or any later one while the directory failed.
1852    #[tokio::test]
1853    async fn one_poisoned_claim_does_not_stop_the_others() {
1854        let store = live_store().await;
1855        default_local_path_class(&store).await;
1856        for name in ["aaa-poisoned", "bbb", "ccc"] {
1857            put_claim(&store, name, sized()).await;
1858        }
1859        let listed = store.list("", "v1", "PersistentVolumeClaim", None).await;
1860        assert_eq!(
1861            listed[0].0.name, "aaa-poisoned",
1862            "precondition: listed first"
1863        );
1864
1865        let c = PvBinderController::with_env(
1866            store.clone(),
1867            None,
1868            "/data/local-path",
1869            Arc::new(PoisonedEnv {
1870                poisoned_dir: "_ns1_aaa-poisoned",
1871            }),
1872        );
1873        let outcome = c
1874            .tick()
1875            .await
1876            .expect("one claim's directory is not the whole sweep's failure");
1877
1878        for name in ["bbb", "ccc"] {
1879            assert_eq!(phase(&store, name).await, "Bound", "{name} was reconciled");
1880        }
1881        assert_ne!(phase(&store, "aaa-poisoned").await, "Bound");
1882        assert!(
1883            store.get(&pv_key("pvc-uid-aaa-poisoned")).await.is_none(),
1884            "no PV is written for a claim whose directory does not exist"
1885        );
1886        let sweep = outcome.sweep.expect("the binder reports through its sweep");
1887        assert_eq!((sweep.changed(), sweep.failed()), (2, 1));
1888        // A mkdir failure is Transient: isolated, but still retried on the
1889        // claim's own curve rather than left to the fallback timer.
1890        assert_eq!(
1891            outcome.result,
1892            crate::ReconcileResult::Requeue(crate::TRANSIENT_RETRY.base())
1893        );
1894    }
1895
1896    /// examined = changed + unchanged + skipped + failed, on a real tick
1897    /// that produces every outcome.
1898    #[tokio::test]
1899    async fn the_report_identity_holds_on_a_real_sweep() {
1900        let store = live_store().await;
1901        default_local_path_class(&store).await;
1902        // Changed: provisioned.
1903        put_claim(&store, "fresh", sized()).await;
1904        // Unchanged: already Bound.
1905        put_op(
1906            &store,
1907            pvc_key("ns1", "settled"),
1908            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
1909                   "metadata": {"name": "settled", "namespace": "ns1"},
1910                   "spec": {"volumeName": "elsewhere"}, "status": {"phase": "Bound"}}),
1911        )
1912        .await;
1913        // Skipped: pre-bound to a PV that is not there.
1914        put_claim(
1915            &store,
1916            "waiting",
1917            json!({"accessModes": ["ReadWriteOnce"], "volumeName": "absent",
1918                   "resources": {"requests": {"storage": "1Gi"}}}),
1919        )
1920        .await;
1921        // Failed, Transient: its directory cannot be made.
1922        put_claim(&store, "poisoned", sized()).await;
1923        // Failed, Declarative: no size to provision.
1924        put_claim(
1925            &store,
1926            "sizeless",
1927            json!({"accessModes": ["ReadWriteOnce"]}),
1928        )
1929        .await;
1930
1931        let c = PvBinderController::with_env(
1932            store.clone(),
1933            None,
1934            "/data/local-path",
1935            Arc::new(PoisonedEnv {
1936                poisoned_dir: "_ns1_poisoned",
1937            }),
1938        );
1939        let outcome = c.tick().await.unwrap();
1940        let sweep = outcome.sweep.unwrap();
1941        assert_eq!(
1942            (
1943                sweep.changed(),
1944                sweep.unchanged(),
1945                sweep.skipped(),
1946                sweep.failed()
1947            ),
1948            (1, 1, 1, 2)
1949        );
1950        assert_eq!(sweep.examined(), 5, "every listed claim was examined");
1951        assert_eq!(outcome.objects_examined, 5);
1952        assert_eq!(outcome.objects_changed, 1);
1953        assert_eq!(outcome.objects_skipped, 1);
1954    }
1955
1956    /// A claim with no usable size is a broken declaration: it stays
1957    /// Pending, gets no PV, and says why on itself — once, not once per
1958    /// sweep. The claim beside it still provisions.
1959    #[tokio::test]
1960    async fn a_sizeless_claim_fails_on_itself_with_one_event() {
1961        let store = live_store().await;
1962        default_local_path_class(&store).await;
1963        put_claim(
1964            &store,
1965            "sizeless",
1966            json!({"accessModes": ["ReadWriteOnce"]}),
1967        )
1968        .await;
1969        put_claim(&store, "sized", sized()).await;
1970
1971        let events = Arc::new(crate::event_recorder::CollectingEventSink::new());
1972        let c = binder(store.clone()).with_event_sink(events.clone());
1973        let outcome = c.tick().await.unwrap();
1974        c.tick().await.unwrap();
1975
1976        assert_eq!(phase(&store, "sized").await, "Bound");
1977        assert_ne!(phase(&store, "sizeless").await, "Bound");
1978        assert!(
1979            store.get(&pv_key("pvc-uid-sizeless")).await.is_none(),
1980            "no PV with a null or unparseable capacity"
1981        );
1982        let recorded = events.drain();
1983        assert_eq!(
1984            recorded.len(),
1985            1,
1986            "one Event across two sweeps: {recorded:?}"
1987        );
1988        let e = &recorded[0];
1989        assert_eq!(e.reason, crate::event_recorder::Reason::ProvisioningFailed);
1990        assert_eq!(e.involved.kind, "PersistentVolumeClaim");
1991        assert_eq!(e.involved.name, "sizeless");
1992        assert_eq!(e.involved.uid.as_deref(), Some("uid-sizeless"));
1993        assert_eq!(e.component, "persistentvolume-controller");
1994        // Declarative: no targeted retry; the Event is the answer.
1995        assert_eq!(outcome.result, crate::ReconcileResult::Done);
1996    }
1997
1998    // ── identity is the claim's uid (T1.4) ───────────────────────────
1999
2000    async fn delete_claim(store: &StoreMesh, name: &str) {
2001        store
2002            .propose(ResourceCommand::delete(
2003                pvc_key("ns1", name),
2004                Reason::Operator,
2005            ))
2006            .await
2007            .unwrap();
2008        assert!(store.get(&pvc_key("ns1", name)).await.is_none());
2009    }
2010
2011    /// ★ THE DEFECT. A claim is provisioned, deleted, and created again
2012    /// under the same namespace and name. Its PV goes Released on the tick
2013    /// that notices, and is still in the store on that tick. The new claim is a new
2014    /// object with a new uid, and must get a new volume: on HEAD it was
2015    /// handed the same `pvc-<ns>-<name>` PV, re-Put over itself, and the
2016    /// same directory with the deleted claim's data in it.
2017    #[tokio::test]
2018    async fn a_recreated_claim_does_not_inherit_the_deleted_claims_volume() {
2019        let store = live_store().await;
2020        default_local_path_class(&store).await;
2021        let env = Arc::new(FakeProvisionerEnv::new());
2022        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2023
2024        put_claim_as(&store, "data", json!("uid-first"), sized()).await;
2025        c.tick().await.unwrap();
2026        let first = store.get(&pvc_key("ns1", "data")).await.unwrap();
2027        assert_eq!(first["status"]["phase"], "Bound");
2028        let first_pv_name = first["spec"]["volumeName"].as_str().unwrap().to_string();
2029        let first_pv = store.get(&pv_key(&first_pv_name)).await.unwrap();
2030
2031        delete_claim(&store, "data").await;
2032        put_claim_as(&store, "data", json!("uid-second"), sized()).await;
2033        c.tick().await.unwrap();
2034
2035        let second = store.get(&pvc_key("ns1", "data")).await.unwrap();
2036        assert_eq!(second["metadata"]["uid"], "uid-second", "a new incarnation");
2037        assert_eq!(second["status"]["phase"], "Bound");
2038        let second_pv_name = second["spec"]["volumeName"].as_str().unwrap();
2039        assert_ne!(
2040            second_pv_name, first_pv_name,
2041            "the recreated claim must not bind the deleted claim's PV"
2042        );
2043        let second_pv = store.get(&pv_key(second_pv_name)).await.unwrap();
2044        assert_ne!(
2045            second_pv["spec"]["hostPath"]["path"], first_pv["spec"]["hostPath"]["path"],
2046            "the recreated claim must not mount the deleted claim's directory"
2047        );
2048        assert_eq!(second_pv["spec"]["claimRef"]["uid"], "uid-second");
2049        let first_after = store.get(&pv_key(&first_pv_name)).await.unwrap();
2050        assert_eq!(
2051            first_after["spec"], first_pv["spec"],
2052            "the deleted claim's PV is not taken over: its claimRef and directory are its own"
2053        );
2054        assert_eq!(
2055            first_after["status"]["phase"], "Released",
2056            "its claim is gone, so it is Released"
2057        );
2058        let dirs = env.ensured_dirs();
2059        assert_eq!(dirs.len(), 2, "{dirs:?}");
2060        assert_ne!(dirs[0], dirs[1], "two claims, two directories");
2061    }
2062
2063    /// An Available PV whose claimRef names this namespace and name but an
2064    /// EARLIER uid is the earlier claim's, and that claim is gone: the PV is
2065    /// Released (upstream's call too). A new claim of the same name must
2066    /// not bind it — on HEAD the claimRef was compared by namespace and
2067    /// name only.
2068    #[tokio::test]
2069    async fn a_pv_reserved_for_an_earlier_claim_of_the_same_name_is_not_bound() {
2070        let store = live_store().await;
2071        put_op(
2072            &store,
2073            pv_key("vol-old"),
2074            json!({"apiVersion": "v1", "kind": "PersistentVolume",
2075                   "metadata": {"name": "vol-old"},
2076                   "spec": {"capacity": {"storage": "1Gi"}, "accessModes": ["ReadWriteOnce"],
2077                            "storageClassName": "manual",
2078                            "claimRef": {"namespace": "ns1", "name": "data", "uid": "uid-old"}},
2079                   "status": {"phase": "Available"}}),
2080        )
2081        .await;
2082        put_claim_as(
2083            &store,
2084            "data",
2085            json!("uid-new"),
2086            json!({"accessModes": ["ReadWriteOnce"], "storageClassName": "manual",
2087                   "resources": {"requests": {"storage": "1Gi"}}}),
2088        )
2089        .await;
2090
2091        binder(store.clone()).tick().await.unwrap();
2092
2093        assert_ne!(phase(&store, "data").await, "Bound");
2094        let pv = store.get(&pv_key("vol-old")).await.unwrap();
2095        assert_eq!(pv["status"]["phase"], "Released");
2096        assert_eq!(pv["spec"]["claimRef"]["uid"], "uid-old");
2097    }
2098
2099    /// A PV reserved by namespace and name alone — no uid, the way an
2100    /// operator pre-binds one — still binds, and the bind records the uid.
2101    #[tokio::test]
2102    async fn a_pv_reserved_by_name_alone_binds_and_records_the_uid() {
2103        let store = live_store().await;
2104        put_op(
2105            &store,
2106            pv_key("vol-reserved"),
2107            json!({"apiVersion": "v1", "kind": "PersistentVolume",
2108                   "metadata": {"name": "vol-reserved"},
2109                   "spec": {"capacity": {"storage": "1Gi"}, "accessModes": ["ReadWriteOnce"],
2110                            "storageClassName": "manual",
2111                            "claimRef": {"namespace": "ns1", "name": "data"}},
2112                   "status": {"phase": "Available"}}),
2113        )
2114        .await;
2115        put_claim_as(
2116            &store,
2117            "data",
2118            json!("uid-data"),
2119            json!({"accessModes": ["ReadWriteOnce"], "storageClassName": "manual",
2120                   "resources": {"requests": {"storage": "1Gi"}}}),
2121        )
2122        .await;
2123
2124        binder(store.clone()).tick().await.unwrap();
2125
2126        assert_eq!(phase(&store, "data").await, "Bound");
2127        let pv = store.get(&pv_key("vol-reserved")).await.unwrap();
2128        assert_eq!(pv["status"]["phase"], "Bound");
2129        assert_eq!(pv["spec"]["claimRef"]["uid"], "uid-data");
2130    }
2131
2132    /// A claim whose uid cannot name a volume or a directory stays Pending:
2133    /// no PV, no directory, and the sweep's note says which. A null uid
2134    /// cannot reach the store (it mints one), so `UidAbsent` is
2135    /// `ClaimUid::of`'s own case.
2136    #[tokio::test]
2137    async fn a_claim_with_no_usable_uid_stays_pending_with_a_typed_reason() {
2138        for (uid, gap) in [
2139            (json!("../../escape"), NoVolumeIdentity::UidMalformed),
2140            (json!(12), NoVolumeIdentity::UidMalformed),
2141        ] {
2142            let store = live_store().await;
2143            default_local_path_class(&store).await;
2144            put_claim_as(&store, "data", uid.clone(), sized()).await;
2145            let env = Arc::new(FakeProvisionerEnv::new());
2146            let c =
2147                PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2148
2149            let outcome = c.tick().await.unwrap();
2150
2151            assert_ne!(phase(&store, "data").await, "Bound", "{uid}");
2152            assert!(
2153                store
2154                    .list("", "v1", "PersistentVolume", None)
2155                    .await
2156                    .is_empty(),
2157                "no PV for a claim with uid {uid}"
2158            );
2159            assert!(env.ensured_dirs().is_empty(), "no directory for uid {uid}");
2160            let sweep = outcome.sweep.unwrap();
2161            assert_eq!((sweep.skipped(), sweep.failed()), (1, 0), "{uid}");
2162            assert_eq!(sweep.note(), Some(gap.note()), "{uid}");
2163        }
2164    }
2165
2166    /// A provision whose PV write landed and whose claim write did not
2167    /// leaves a PV bound to the claim by uid and the claim Pending. The next
2168    /// pass binds the claim to THAT PV — it does not provision a second one
2169    /// or touch the directory again. The same holds for a PV provisioned
2170    /// under the old `pvc-<ns>-<name>` scheme: existing PVs keep their names.
2171    #[tokio::test]
2172    async fn a_pv_already_bound_to_the_claim_by_uid_is_found_not_reprovisioned() {
2173        let store = live_store().await;
2174        default_local_path_class(&store).await;
2175        for (claim, pv_name) in [("data", "pvc-uid-data"), ("legacy", "pvc-ns1-legacy")] {
2176            put_claim(&store, claim, sized()).await;
2177            put_op(
2178                &store,
2179                pv_key(pv_name),
2180                json!({"apiVersion": "v1", "kind": "PersistentVolume",
2181                       "metadata": {"name": pv_name},
2182                       "spec": {"capacity": {"storage": "1Gi"},
2183                                "accessModes": ["ReadWriteOnce"],
2184                                "storageClassName": "local-path",
2185                                "hostPath": {"path": (["/data/local-path/", claim].concat())},
2186                                "claimRef": {"namespace": "ns1", "name": claim,
2187                                             "uid": (["uid-", claim].concat())}},
2188                       "status": {"phase": "Bound"}}),
2189            )
2190            .await;
2191        }
2192        let env = Arc::new(FakeProvisionerEnv::new());
2193        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2194
2195        c.tick().await.unwrap();
2196
2197        for (claim, pv_name) in [("data", "pvc-uid-data"), ("legacy", "pvc-ns1-legacy")] {
2198            let pvc = store.get(&pvc_key("ns1", claim)).await.unwrap();
2199            assert_eq!(pvc["status"]["phase"], "Bound", "{claim}");
2200            assert_eq!(pvc["spec"]["volumeName"], pv_name, "{claim}");
2201        }
2202        assert_eq!(
2203            store.list("", "v1", "PersistentVolume", None).await.len(),
2204            2,
2205            "no second PV was provisioned"
2206        );
2207        assert!(
2208            env.ensured_dirs().is_empty(),
2209            "no directory was provisioned again: {:?}",
2210            env.ensured_dirs()
2211        );
2212    }
2213
2214    /// A PV that already holds the name derived from this claim's uid but is
2215    /// bound to some other claim is never overwritten, and nothing is
2216    /// provisioned into what may be its directory.
2217    #[tokio::test]
2218    async fn a_pv_holding_the_derived_name_for_another_claim_is_left_alone() {
2219        let store = live_store().await;
2220        default_local_path_class(&store).await;
2221        let foreign = json!({"apiVersion": "v1", "kind": "PersistentVolume",
2222            "metadata": {"name": "pvc-uid-data"},
2223            "spec": {"capacity": {"storage": "1Gi"}, "accessModes": ["ReadWriteOnce"],
2224                     "storageClassName": "local-path",
2225                     "hostPath": {"path": "/foreign"},
2226                     "claimRef": {"namespace": "ns1", "name": "other", "uid": "uid-other"}},
2227            "status": {"phase": "Bound"}});
2228        put_op(&store, pv_key("pvc-uid-data"), foreign).await;
2229        // The other claim exists and holds it, so the PV is Bound for real.
2230        put_op(
2231            &store,
2232            pvc_key("ns1", "other"),
2233            json!({"apiVersion": "v1", "kind": "PersistentVolumeClaim",
2234                   "metadata": {"name": "other", "namespace": "ns1", "uid": "uid-other"},
2235                   "spec": {"volumeName": "pvc-uid-data"}, "status": {"phase": "Bound"}}),
2236        )
2237        .await;
2238        let before = store.get(&pv_key("pvc-uid-data")).await.unwrap();
2239        put_claim(&store, "data", sized()).await;
2240        let env = Arc::new(FakeProvisionerEnv::new());
2241        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2242
2243        let outcome = c.tick().await.unwrap();
2244
2245        assert_ne!(phase(&store, "data").await, "Bound");
2246        assert_eq!(store.get(&pv_key("pvc-uid-data")).await.unwrap(), before);
2247        assert!(env.ensured_dirs().is_empty(), "{:?}", env.ensured_dirs());
2248        assert_eq!(outcome.sweep.unwrap().note(), Some(PV_NAME_TAKEN));
2249    }
2250
2251    /// The PV write itself is create-if-absent: a second create of the same
2252    /// name — a writer that raced this one between list and write — neither
2253    /// overwrites the PV nor binds the claim.
2254    #[tokio::test]
2255    async fn the_pv_write_is_create_if_absent() {
2256        let store = live_store().await;
2257        put_claim(&store, "data", sized()).await;
2258        let pvc = store.get(&pvc_key("ns1", "data")).await.unwrap();
2259        let c = binder(store.clone());
2260        let pv = |path: &str| {
2261            json!({"apiVersion": "v1", "kind": "PersistentVolume",
2262                   "metadata": {"name": "pvc-uid-data"},
2263                   "spec": {"hostPath": {"path": path}}})
2264        };
2265
2266        let created = c
2267            .create_and_bind(&pvc_key("ns1", "data"), &pvc, "pvc-uid-data", pv("/first"))
2268            .await
2269            .unwrap();
2270        assert!(matches!(created, ObjectOutcome::Changed(_)), "{created:?}");
2271        let written = store.get(&pv_key("pvc-uid-data")).await.unwrap();
2272
2273        // Unbind the claim, so only the create can say whether it binds.
2274        put_claim(&store, "data", sized()).await;
2275        let again = c
2276            .create_and_bind(&pvc_key("ns1", "data"), &pvc, "pvc-uid-data", pv("/second"))
2277            .await
2278            .unwrap();
2279
2280        assert!(
2281            matches!(
2282                again,
2283                ObjectOutcome::Skipped {
2284                    note: Some(PV_NAME_TAKEN)
2285                }
2286            ),
2287            "{again:?}"
2288        );
2289        assert_eq!(
2290            store.get(&pv_key("pvc-uid-data")).await.unwrap(),
2291            written,
2292            "the existing PV is not overwritten"
2293        );
2294        assert_ne!(phase(&store, "data").await, "Bound");
2295    }
2296
2297    /// A CSI driver that records every name it is asked to create under,
2298    /// and every volume it is asked to delete.
2299    #[derive(Default)]
2300    struct RecordingDriver {
2301        names: std::sync::Mutex<Vec<String>>,
2302        deleted: std::sync::Mutex<Vec<(String, String)>>,
2303        refuse_deletes: bool,
2304    }
2305
2306    #[async_trait]
2307    impl CsiProvisioner for RecordingDriver {
2308        async fn can_provision(&self, _driver: &str) -> bool {
2309            true
2310        }
2311        async fn create_volume(
2312            &self,
2313            req: &CsiCreateRequest,
2314        ) -> Result<crate::csi_provisioner::CsiCreatedVolume, String> {
2315            self.names.lock().unwrap().push(req.name.clone());
2316            Ok(crate::csi_provisioner::CsiCreatedVolume {
2317                volume_handle: ["vol-", &req.name].concat(),
2318                capacity_bytes: req.capacity_bytes,
2319                volume_attributes: std::collections::BTreeMap::new(),
2320            })
2321        }
2322        async fn delete_volume(&self, driver: &str, handle: &str) -> Result<(), String> {
2323            if self.refuse_deletes {
2324                return Err("volume is attached".into());
2325            }
2326            self.deleted
2327                .lock()
2328                .unwrap()
2329                .push((driver.to_string(), handle.to_string()));
2330            Ok(())
2331        }
2332    }
2333
2334    async fn csi_class(store: &StoreMesh) {
2335        put_op(
2336            store,
2337            sc_key("csi-sc"),
2338            json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass",
2339                   "metadata": {"name": "csi-sc"}, "provisioner": "csi.example.com"}),
2340        )
2341        .await;
2342    }
2343
2344    fn csi_claim_spec() -> Value {
2345        json!({"accessModes": ["ReadWriteOnce"], "storageClassName": "csi-sc",
2346               "resources": {"requests": {"storage": "1Gi"}}})
2347    }
2348
2349    /// A PV holding the name derived from a CSI claim's uid, bound to some
2350    /// other claim: the driver is never asked, because a `CreateVolume`
2351    /// idempotent by name would answer with whatever volume holds it.
2352    #[tokio::test]
2353    async fn a_csi_claim_whose_name_is_taken_never_reaches_the_driver() {
2354        let store = live_store().await;
2355        csi_class(&store).await;
2356        put_op(
2357            &store,
2358            pv_key("pvc-uid-db"),
2359            json!({"apiVersion": "v1", "kind": "PersistentVolume",
2360                   "metadata": {"name": "pvc-uid-db"},
2361                   "spec": {"capacity": {"storage": "1Gi"},
2362                            "csi": {"driver": "csi.example.com", "volumeHandle": "theirs"},
2363                            "claimRef": {"namespace": "ns1", "name": "other", "uid": "uid-other"}},
2364                   "status": {"phase": "Bound"}}),
2365        )
2366        .await;
2367        put_claim(&store, "db", csi_claim_spec()).await;
2368        let driver = Arc::new(RecordingDriver::default());
2369
2370        let outcome = binder(store.clone())
2371            .with_csi(driver.clone())
2372            .tick()
2373            .await
2374            .unwrap();
2375
2376        assert!(driver.names.lock().unwrap().is_empty());
2377        assert_ne!(phase(&store, "db").await, "Bound");
2378        assert_eq!(outcome.sweep.unwrap().note(), Some(PV_NAME_TAKEN));
2379    }
2380
2381    /// A CSI driver keys `CreateVolume` idempotency on the name it is given.
2382    /// A recreated claim must ask under a new name, or the driver hands it
2383    /// the deleted claim's disk.
2384    #[tokio::test]
2385    async fn a_recreated_csi_claim_asks_the_driver_for_a_new_volume() {
2386        let store = live_store().await;
2387        csi_class(&store).await;
2388        let csi_claim = csi_claim_spec();
2389        let driver = Arc::new(RecordingDriver::default());
2390        let c = binder(store.clone()).with_csi(driver.clone());
2391
2392        put_claim_as(&store, "db", json!("uid-db-1"), csi_claim.clone()).await;
2393        c.tick().await.unwrap();
2394        delete_claim(&store, "db").await;
2395        put_claim_as(&store, "db", json!("uid-db-2"), csi_claim).await;
2396        c.tick().await.unwrap();
2397
2398        assert_eq!(
2399            *driver.names.lock().unwrap(),
2400            vec!["pvc-uid-db-1".to_string(), "pvc-uid-db-2".to_string()]
2401        );
2402        let pvc = store.get(&pvc_key("ns1", "db")).await.unwrap();
2403        assert_eq!(pvc["status"]["phase"], "Bound");
2404        assert_eq!(pvc["spec"]["volumeName"], "pvc-uid-db-2");
2405        let pv = store.get(&pv_key("pvc-uid-db-2")).await.unwrap();
2406        assert_eq!(pv["spec"]["csi"]["volumeHandle"], "vol-pvc-uid-db-2");
2407        assert_eq!(pv["spec"]["claimRef"]["uid"], "uid-db-2");
2408    }
2409
2410    // ── Released, then reclaimed (W9) ────────────────────────────────
2411
2412    /// The directory the binder derives for claim `ns1/<name>` (uid
2413    /// `uid-<name>`) under the test root.
2414    fn local_dir(name: &str) -> String {
2415        ["/data/local-path/pvc-uid-", name, "_ns1_", name].concat()
2416    }
2417
2418    /// The default local-path class, reclaiming by `policy`.
2419    async fn local_path_class_reclaiming(store: &StoreMesh, policy: &str) {
2420        put_op(
2421            store,
2422            sc_key("local-path"),
2423            json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass",
2424                   "metadata": {"name": "local-path",
2425                                "annotations": {"storageclass.kubernetes.io/is-default-class": "true"}},
2426                   "provisioner": "rancher.io/local-path",
2427                   "reclaimPolicy": policy,
2428                   "volumeBindingMode": "Immediate"}),
2429        )
2430        .await;
2431    }
2432
2433    async fn volume(store: &StoreMesh, name: &str) -> Option<Value> {
2434        store.get(&pv_key(name)).await
2435    }
2436
2437    /// Provision `ns1/<name>` and bind it, then delete the claim.
2438    async fn provision_then_delete_claim(store: &StoreMesh, c: &PvBinderController, name: &str) {
2439        put_claim(store, name, sized()).await;
2440        c.tick().await.unwrap();
2441        assert_eq!(
2442            phase(store, name).await,
2443            "Bound",
2444            "precondition: {name} bound"
2445        );
2446        delete_claim(store, name).await;
2447    }
2448
2449    /// A PV standing Bound to claim `ns1/<claim>` (uid `uid-<claim>`),
2450    /// which does not exist: `extra` is merged over its body.
2451    async fn put_orphan_volume(store: &StoreMesh, name: &str, claim: &str, extra: &Value) {
2452        let mut pv = json!({"apiVersion": "v1", "kind": "PersistentVolume",
2453            "metadata": {"name": name},
2454            "spec": {"capacity": {"storage": "1Gi"}, "accessModes": ["ReadWriteOnce"],
2455                     "persistentVolumeReclaimPolicy": "Delete",
2456                     "claimRef": {"namespace": "ns1", "name": claim,
2457                                  "uid": (["uid-", claim].concat())}},
2458            "status": {"phase": "Bound"}});
2459        json_patch_merge(&mut pv, extra);
2460        put_op(store, pv_key(name), pv).await;
2461    }
2462
2463    /// RFC 7396, enough for fixtures.
2464    fn json_patch_merge(target: &mut Value, patch: &Value) {
2465        if let (Some(t), Some(p)) = (target.as_object_mut(), patch.as_object()) {
2466            for (k, v) in p {
2467                if v.is_null() {
2468                    t.remove(k);
2469                } else if v.is_object() && t.get(k).is_some_and(Value::is_object) {
2470                    json_patch_merge(t.get_mut(k).unwrap(), v);
2471                } else {
2472                    t.insert(k.clone(), v.clone());
2473                }
2474            }
2475        }
2476    }
2477
2478    /// ★ Bound → Released → deleted. Under `Delete` the volume is first
2479    /// Released with its directory still there, then its directory is
2480    /// removed and the PV with it — the one directory derived for the
2481    /// claim, and nothing else.
2482    #[tokio::test]
2483    async fn a_deleted_claims_volume_is_released_then_deleted_with_its_directory() {
2484        let store = live_store().await;
2485        local_path_class_reclaiming(&store, "Delete").await;
2486        let env = Arc::new(FakeProvisionerEnv::new());
2487        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2488        provision_then_delete_claim(&store, &c, "data").await;
2489
2490        c.tick().await.unwrap();
2491        let released = volume(&store, "pvc-uid-data")
2492            .await
2493            .expect("Released is a state the volume is seen in");
2494        assert_eq!(released["status"]["phase"], "Released");
2495        assert!(env.removed_dirs().is_empty(), "{:?}", env.removed_dirs());
2496
2497        for _ in 0..2 {
2498            c.tick().await.unwrap();
2499        }
2500        assert!(volume(&store, "pvc-uid-data").await.is_none(), "PV deleted");
2501        assert_eq!(env.removed_dirs(), vec![local_dir("data")]);
2502    }
2503
2504    /// Bound → Released, and `Retain` keeps it there: the PV, its claimRef
2505    /// and its directory all stay.
2506    #[tokio::test]
2507    async fn a_retained_volume_stays_released_with_its_directory() {
2508        let store = live_store().await;
2509        local_path_class_reclaiming(&store, "Retain").await;
2510        let env = Arc::new(FakeProvisionerEnv::new());
2511        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2512        provision_then_delete_claim(&store, &c, "data").await;
2513
2514        for _ in 0..3 {
2515            c.tick().await.unwrap();
2516        }
2517
2518        let pv = volume(&store, "pvc-uid-data").await.expect("retained");
2519        assert_eq!(pv["status"]["phase"], "Released");
2520        assert_eq!(pv["spec"]["claimRef"]["uid"], "uid-data");
2521        assert!(env.removed_dirs().is_empty(), "{:?}", env.removed_dirs());
2522    }
2523
2524    /// Released → Available: an operator frees a retained volume by
2525    /// clearing its claimRef's uid, and a claim can then bind it.
2526    #[tokio::test]
2527    async fn a_freed_retained_volume_becomes_available_and_binds_again() {
2528        let store = live_store().await;
2529        local_path_class_reclaiming(&store, "Retain").await;
2530        let c = binder(store.clone());
2531        provision_then_delete_claim(&store, &c, "data").await;
2532        c.tick().await.unwrap();
2533        let mut pv = volume(&store, "pvc-uid-data").await.unwrap();
2534        assert_eq!(pv["status"]["phase"], "Released");
2535
2536        pv["spec"]["claimRef"]["uid"] = Value::Null;
2537        put_op(&store, pv_key("pvc-uid-data"), pv).await;
2538        c.tick().await.unwrap();
2539        assert_eq!(
2540            volume(&store, "pvc-uid-data").await.unwrap()["status"]["phase"],
2541            "Available"
2542        );
2543
2544        put_claim_as(
2545            &store,
2546            "data",
2547            json!("uid-again"),
2548            json!({"accessModes": ["ReadWriteOnce"], "storageClassName": "local-path",
2549                   "volumeName": "pvc-uid-data",
2550                   "resources": {"requests": {"storage": "1Gi"}}}),
2551        )
2552        .await;
2553        c.tick().await.unwrap();
2554        assert_eq!(phase(&store, "data").await, "Bound");
2555        let rebound = volume(&store, "pvc-uid-data").await.unwrap();
2556        assert_eq!(rebound["status"]["phase"], "Bound");
2557        assert_eq!(rebound["spec"]["claimRef"]["uid"], "uid-again");
2558    }
2559
2560    /// A claim that is Terminating still exists: pvc-protection is holding
2561    /// it for a pod, and its volume stays Bound with its directory.
2562    #[tokio::test]
2563    async fn a_terminating_claim_keeps_its_volume_bound() {
2564        let store = live_store().await;
2565        local_path_class_reclaiming(&store, "Delete").await;
2566        let env = Arc::new(FakeProvisionerEnv::new());
2567        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2568        put_claim(&store, "data", sized()).await;
2569        c.tick().await.unwrap();
2570        let mut held = store.get(&pvc_key("ns1", "data")).await.unwrap();
2571        held["metadata"]["finalizers"] = json!([crate::pvc_protection::PVC_PROTECTION_FINALIZER]);
2572        put_op(&store, pvc_key("ns1", "data"), held).await;
2573        store
2574            .propose(ResourceCommand::delete(
2575                pvc_key("ns1", "data"),
2576                Reason::Operator,
2577            ))
2578            .await
2579            .unwrap();
2580
2581        for _ in 0..3 {
2582            c.tick().await.unwrap();
2583        }
2584
2585        let pv = volume(&store, "pvc-uid-data").await.expect("kept");
2586        assert_eq!(pv["status"]["phase"], "Bound");
2587        assert!(env.removed_dirs().is_empty(), "{:?}", env.removed_dirs());
2588    }
2589
2590    /// The tick's list is not the judge of a claim being gone: a claim the
2591    /// list missed, the store still has, and its volume is left Bound.
2592    #[tokio::test]
2593    async fn a_claim_missing_from_the_list_is_asked_for_again() {
2594        let store = live_store().await;
2595        put_claim(&store, "data", sized()).await;
2596        put_orphan_volume(&store, "vol", "data", &json!({})).await;
2597        let pv = volume(&store, "vol").await.unwrap();
2598
2599        let outcome = binder(store.clone())
2600            .reconcile_volume(&pv_key("vol"), &pv, &[])
2601            .await
2602            .unwrap();
2603
2604        assert!(matches!(outcome, ObjectOutcome::Unchanged), "{outcome:?}");
2605        assert_eq!(volume(&store, "vol").await.unwrap(), pv);
2606    }
2607
2608    /// A binder scoped to one namespace did not list another's claims, so
2609    /// it never judges a volume whose claim lives there.
2610    #[tokio::test]
2611    async fn a_scoped_binder_leaves_another_namespaces_volume_alone() {
2612        let store = live_store().await;
2613        put_orphan_volume(
2614            &store,
2615            "vol",
2616            "gone",
2617            &json!({"spec": {"claimRef": {"namespace": "ns2"}}}),
2618        )
2619        .await;
2620        let before = volume(&store, "vol").await.unwrap();
2621        let env = Arc::new(FakeProvisionerEnv::new());
2622        let c = PvBinderController::with_env(
2623            store.clone(),
2624            Some("ns1".into()),
2625            "/data/local-path",
2626            env.clone(),
2627        );
2628
2629        for _ in 0..3 {
2630            c.tick().await.unwrap();
2631        }
2632
2633        assert_eq!(volume(&store, "vol").await.unwrap(), before);
2634        assert!(env.removed_dirs().is_empty());
2635    }
2636
2637    /// A volume that cannot be reclaimed goes Failed, says why, keeps its
2638    /// storage, and is announced once — not once per sweep.
2639    #[tokio::test]
2640    async fn an_unreclaimable_volume_fails_once_and_keeps_its_storage() {
2641        let local = json!({"metadata": {"annotations":
2642            {"pv.kubernetes.io/provisioned-by": ENGENHO_LOCAL_PATH_PROVISIONER}}});
2643        let cases = [
2644            // A local-path PV pointing somewhere the provisioner never made.
2645            (
2646                "pvc-uid-a",
2647                "a",
2648                {
2649                    let mut v = local.clone();
2650                    json_patch_merge(&mut v, &json!({"spec": {"hostPath": {"path": "/"}}}));
2651                    v
2652                },
2653                Unreclaimable::ForeignDirectory,
2654            ),
2655            // A legacy name: not derived from the uid.
2656            (
2657                "pvc-ns1-b",
2658                "b",
2659                {
2660                    let mut v = local.clone();
2661                    json_patch_merge(
2662                        &mut v,
2663                        &json!({"spec": {"hostPath": {"path": "/data/local-path/ns1-b"}}}),
2664                    );
2665                    v
2666                },
2667                Unreclaimable::ForeignDirectory,
2668            ),
2669            // Nobody provisioned it.
2670            (
2671                "vol-c",
2672                "c",
2673                json!({"spec": {"hostPath": {"path": "/srv/c"}}}),
2674                Unreclaimable::NoDeleter,
2675            ),
2676            // A policy engenho does not run.
2677            (
2678                "vol-d",
2679                "d",
2680                json!({"spec": {"persistentVolumeReclaimPolicy": "Recycle",
2681                                "hostPath": {"path": "/srv/d"}}}),
2682                Unreclaimable::UnsupportedPolicy,
2683            ),
2684        ];
2685        for (pv_name, claim, extra, why) in cases {
2686            let store = live_store().await;
2687            put_orphan_volume(&store, pv_name, claim, &extra).await;
2688            let env = Arc::new(FakeProvisionerEnv::new());
2689            let events = Arc::new(crate::event_recorder::CollectingEventSink::new());
2690            let c =
2691                PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone())
2692                    .with_event_sink(events.clone());
2693
2694            for _ in 0..4 {
2695                c.tick().await.unwrap();
2696            }
2697
2698            let pv = volume(&store, pv_name).await.expect("kept");
2699            assert_eq!(pv["status"]["phase"], "Failed", "{pv_name}");
2700            assert_eq!(pv["status"]["message"], why.message(), "{pv_name}");
2701            assert!(
2702                env.removed_dirs().is_empty(),
2703                "{pv_name}: {:?}",
2704                env.removed_dirs()
2705            );
2706            let recorded = events.drain();
2707            assert_eq!(recorded.len(), 1, "{pv_name}: {recorded:?}");
2708            assert_eq!(
2709                recorded[0].reason,
2710                crate::event_recorder::Reason::VolumeFailedDelete
2711            );
2712            assert_eq!(recorded[0].involved.name, pv_name);
2713        }
2714    }
2715
2716    /// Another provisioner's volume stays Released for that provisioner to
2717    /// delete; engenho touches neither it nor its storage.
2718    #[tokio::test]
2719    async fn another_provisioners_volume_stays_released() {
2720        let store = live_store().await;
2721        put_orphan_volume(
2722            &store,
2723            "pvc-uid-data",
2724            "data",
2725            &json!({"metadata": {"annotations":
2726                       {"pv.kubernetes.io/provisioned-by": "rancher.io/local-path"}},
2727                   "spec": {"hostPath": {"path": local_dir("data")}}}),
2728        )
2729        .await;
2730        let env = Arc::new(FakeProvisionerEnv::new());
2731        let c = PvBinderController::with_env(store.clone(), None, "/data/local-path", env.clone());
2732
2733        for _ in 0..3 {
2734            c.tick().await.unwrap();
2735        }
2736
2737        let pv = volume(&store, "pvc-uid-data").await.expect("kept");
2738        assert_eq!(pv["status"]["phase"], "Released");
2739        assert!(env.removed_dirs().is_empty());
2740    }
2741
2742    /// A CSI volume under `Delete` is deleted through the driver that
2743    /// provisioned it, then the PV goes.
2744    #[tokio::test]
2745    async fn a_csi_volume_is_deleted_through_its_driver() {
2746        let store = live_store().await;
2747        csi_class(&store).await;
2748        let driver = Arc::new(RecordingDriver::default());
2749        let c = binder(store.clone()).with_csi(driver.clone());
2750        put_claim(&store, "db", csi_claim_spec()).await;
2751        c.tick().await.unwrap();
2752        assert_eq!(phase(&store, "db").await, "Bound");
2753        delete_claim(&store, "db").await;
2754
2755        for _ in 0..3 {
2756            c.tick().await.unwrap();
2757        }
2758
2759        assert_eq!(
2760            *driver.deleted.lock().unwrap(),
2761            vec![("csi.example.com".to_string(), "vol-pvc-uid-db".to_string())]
2762        );
2763        assert!(volume(&store, "pvc-uid-db").await.is_none());
2764    }
2765
2766    /// A deleter that fails leaves the volume Released, with its PV, and
2767    /// the sweep owes it a retry rather than waiting for the fallback.
2768    #[tokio::test]
2769    async fn a_failed_delete_keeps_the_volume_and_is_retried() {
2770        let store = live_store().await;
2771        csi_class(&store).await;
2772        let driver = Arc::new(RecordingDriver {
2773            refuse_deletes: true,
2774            ..RecordingDriver::default()
2775        });
2776        let c = binder(store.clone()).with_csi(driver.clone());
2777        put_claim(&store, "db", csi_claim_spec()).await;
2778        c.tick().await.unwrap();
2779        delete_claim(&store, "db").await;
2780        c.tick().await.unwrap();
2781
2782        let outcome = c.tick().await.unwrap();
2783
2784        let pv = volume(&store, "pvc-uid-db").await.expect("kept");
2785        assert_eq!(pv["status"]["phase"], "Released");
2786        assert_eq!(outcome.sweep.unwrap().failed(), 1);
2787        assert_eq!(
2788            outcome.result,
2789            crate::ReconcileResult::Requeue(crate::TRANSIENT_RETRY.base())
2790        );
2791    }
2792
2793    // ── a bind never overwrites what landed since the list ───────────
2794
2795    /// A claim deleted after the binder listed it stays deleted: the bind
2796    /// is written at the revision read, so it cannot create the claim again.
2797    #[tokio::test]
2798    async fn a_bind_never_resurrects_a_deleted_claim() {
2799        let store = live_store().await;
2800        put_claim(
2801            &store,
2802            "data",
2803            json!({"accessModes": ["ReadWriteOnce"], "storageClassName": "manual",
2804                   "resources": {"requests": {"storage": "1Gi"}}}),
2805        )
2806        .await;
2807        put_op(
2808            &store,
2809            pv_key("vol-a"),
2810            json!({"apiVersion": "v1", "kind": "PersistentVolume",
2811                   "metadata": {"name": "vol-a"},
2812                   "spec": {"capacity": {"storage": "1Gi"}, "accessModes": ["ReadWriteOnce"],
2813                            "storageClassName": "manual"},
2814                   "status": {"phase": "Available"}}),
2815        )
2816        .await;
2817        let listed = store.get(&pvc_key("ns1", "data")).await.unwrap();
2818        let view = TickView {
2819            pvs: store.list("", "v1", "PersistentVolume", None).await,
2820            storage_classes: Vec::new(),
2821            snapshots: Vec::new(),
2822            snapshot_contents: Vec::new(),
2823        };
2824        delete_claim(&store, "data").await;
2825
2826        binder(store.clone())
2827            .reconcile_claim(
2828                &pvc_key("ns1", "data"),
2829                &listed,
2830                &view,
2831                &tokio::sync::Mutex::new(Vec::new()),
2832            )
2833            .await
2834            .unwrap();
2835
2836        assert!(store.get(&pvc_key("ns1", "data")).await.is_none());
2837        let pv = volume(&store, "vol-a").await.unwrap();
2838        assert!(pv["spec"].get("claimRef").is_none(), "{pv}");
2839    }
2840
2841    /// A finalizer that landed after the binder listed the claim survives
2842    /// the bind: the stale bind is refused, and the next pass binds the
2843    /// claim as it now stands.
2844    #[tokio::test]
2845    async fn a_bind_never_erases_a_finalizer_written_since_the_list() {
2846        let store = live_store().await;
2847        default_local_path_class(&store).await;
2848        put_claim(&store, "data", sized()).await;
2849        let listed = store.get(&pvc_key("ns1", "data")).await.unwrap();
2850        let mut protected = listed.clone();
2851        protected["metadata"]["finalizers"] =
2852            json!([crate::pvc_protection::PVC_PROTECTION_FINALIZER]);
2853        put_op(&store, pvc_key("ns1", "data"), protected).await;
2854        let view = TickView {
2855            pvs: Vec::new(),
2856            storage_classes: store
2857                .list("storage.k8s.io", "v1", "StorageClass", None)
2858                .await,
2859            snapshots: Vec::new(),
2860            snapshot_contents: Vec::new(),
2861        };
2862        let c = binder(store.clone());
2863
2864        c.reconcile_claim(
2865            &pvc_key("ns1", "data"),
2866            &listed,
2867            &view,
2868            &tokio::sync::Mutex::new(Vec::new()),
2869        )
2870        .await
2871        .unwrap();
2872        let after_stale = store.get(&pvc_key("ns1", "data")).await.unwrap();
2873        assert_eq!(
2874            after_stale["metadata"]["finalizers"],
2875            json!([crate::pvc_protection::PVC_PROTECTION_FINALIZER])
2876        );
2877
2878        c.tick().await.unwrap();
2879        let bound = store.get(&pvc_key("ns1", "data")).await.unwrap();
2880        assert_eq!(bound["status"]["phase"], "Bound");
2881        assert_eq!(
2882            bound["metadata"]["finalizers"],
2883            json!([crate::pvc_protection::PVC_PROTECTION_FINALIZER])
2884        );
2885    }
2886}
2887
2888#[cfg(test)]
2889mod snapshot_restore_source {
2890    use super::PvBinderController;
2891    use serde_json::json;
2892
2893    fn pvc_with(ds: serde_json::Value) -> serde_json::Value {
2894        json!({ "spec": { "dataSource": ds } })
2895    }
2896
2897    #[test]
2898    fn a_volume_snapshot_data_source_is_recognised() {
2899        let pvc = pvc_with(json!({
2900            "apiGroup": "snapshot.storage.k8s.io",
2901            "kind": "VolumeSnapshot",
2902            "name": "db-snap"
2903        }));
2904        assert_eq!(
2905            PvBinderController::snapshot_data_source(&pvc).as_deref(),
2906            Some("db-snap")
2907        );
2908    }
2909
2910    #[test]
2911    fn data_source_ref_is_accepted_too() {
2912        // Upstream added `dataSourceRef` as the general form; a cluster that
2913        // only read `dataSource` would silently provision an EMPTY volume for
2914        // a restore written the modern way.
2915        let pvc = json!({ "spec": { "dataSourceRef": {
2916            "apiGroup": "snapshot.storage.k8s.io",
2917            "kind": "VolumeSnapshot",
2918            "name": "db-snap"
2919        }}});
2920        assert_eq!(
2921            PvBinderController::snapshot_data_source(&pvc).as_deref(),
2922            Some("db-snap")
2923        );
2924    }
2925
2926    /// ★ NEGATIVE CONTROL — the group is CHECKED. A same-named kind in some
2927    /// other group is not our snapshot, and treating it as one would restore
2928    /// from a directory that has nothing to do with it.
2929    #[test]
2930    fn a_foreign_api_group_is_not_our_snapshot() {
2931        let pvc = pvc_with(json!({
2932            "apiGroup": "example.com",
2933            "kind": "VolumeSnapshot",
2934            "name": "db-snap"
2935        }));
2936        assert_eq!(PvBinderController::snapshot_data_source(&pvc), None);
2937    }
2938
2939    /// ★ NEGATIVE CONTROL — a PVC CLONE (`kind: PersistentVolumeClaim`) is a
2940    /// different feature. Silently treating it as a snapshot restore would
2941    /// look up a snapshot that does not exist and leave the claim Pending
2942    /// with a misleading note.
2943    #[test]
2944    fn a_pvc_clone_data_source_is_not_a_snapshot() {
2945        let pvc = pvc_with(json!({
2946            "apiGroup": "",
2947            "kind": "PersistentVolumeClaim",
2948            "name": "other"
2949        }));
2950        assert_eq!(PvBinderController::snapshot_data_source(&pvc), None);
2951    }
2952
2953    #[test]
2954    fn a_plain_pvc_has_no_data_source() {
2955        assert_eq!(
2956            PvBinderController::snapshot_data_source(&json!({"spec": {}})),
2957            None
2958        );
2959        assert_eq!(PvBinderController::snapshot_data_source(&json!({})), None);
2960    }
2961}