1use std::time::Duration;
57
58use crate::effect::Effect;
59use crate::node_lease::{find_ready_condition, project_ready_condition};
60use crate::status::resource_version_of;
61use engenho_store::{
62 ResourceKey, ResourceValue, StoreError, StoreMesh,
63 command::{Reason, ResourceCommand, ResourceOp},
64 revision::Revision,
65};
66use serde_json::Value;
67
68pub const REPORT_FREQUENCY: Duration = Duration::from_secs(5 * 60);
69
70#[derive(Debug, Clone)]
76pub struct ObservedNode {
77 value: ResourceValue,
78 revision: Revision,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Unobservable {
84 Absent,
87 Unversioned,
92}
93
94impl ObservedNode {
95 pub fn from_stored(value: ResourceValue) -> Result<Self, Unobservable> {
102 let revision = resource_version_of(&value).ok_or(Unobservable::Unversioned)?;
103 Ok(Self { value, revision })
104 }
105
106 pub async fn read(store: &StoreMesh, key: &ResourceKey) -> Result<Self, Unobservable> {
113 let value = store.get(key).await.ok_or(Unobservable::Absent)?;
114 Self::from_stored(value)
115 }
116}
117
118#[derive(Debug)]
121pub enum ReadinessPublish {
122 Published {
126 retried: bool,
128 condition: Value,
130 effect: Effect,
132 },
133 Unchanged,
138 NoNode,
141 Unversioned,
144 Malformed,
147 Contended,
150 Store(StoreError),
152}
153
154impl From<Unobservable> for ReadinessPublish {
155 fn from(why: Unobservable) -> Self {
156 match why {
157 Unobservable::Absent => Self::NoNode,
158 Unobservable::Unversioned => Self::Unversioned,
159 }
160 }
161}
162
163enum Attempt {
165 Written(Value, Effect),
166 Unchanged,
167 Malformed,
168 Lost,
169 Failed(StoreError),
170}
171
172impl Attempt {
173 fn settled(self, retried: bool) -> Option<ReadinessPublish> {
177 match self {
178 Self::Written(condition, effect) => Some(ReadinessPublish::Published {
179 retried,
180 condition,
181 effect,
182 }),
183 Self::Unchanged => Some(ReadinessPublish::Unchanged),
184 Self::Malformed => Some(ReadinessPublish::Malformed),
185 Self::Failed(e) => Some(ReadinessPublish::Store(e)),
186 Self::Lost => None,
187 }
188 }
189}
190
191pub async fn publish_ready(
200 store: &StoreMesh,
201 key: &ResourceKey,
202 lease: Option<&ResourceValue>,
203 now: &str,
204 refresh: Option<Duration>,
205) -> ReadinessPublish {
206 match ObservedNode::read(store, key).await {
207 Ok(observed) => publish_ready_onto(store, key, observed, lease, now, refresh).await,
208 Err(why) => why.into(),
209 }
210}
211
212pub async fn publish_ready_onto(
218 store: &StoreMesh,
219 key: &ResourceKey,
220 observed: ObservedNode,
221 lease: Option<&ResourceValue>,
222 now: &str,
223 refresh: Option<Duration>,
224) -> ReadinessPublish {
225 if let Some(done) = attempt(store, key, &observed, lease, now, refresh)
226 .await
227 .settled(false)
228 {
229 return done;
230 }
231 let fresh = match ObservedNode::read(store, key).await {
233 Ok(fresh) => fresh,
234 Err(why) => return why.into(),
235 };
236 attempt(store, key, &fresh, lease, now, refresh)
237 .await
238 .settled(true)
239 .unwrap_or(ReadinessPublish::Contended)
240}
241
242async fn attempt(
244 store: &StoreMesh,
245 key: &ResourceKey,
246 observed: &ObservedNode,
247 lease: Option<&ResourceValue>,
248 now: &str,
249 refresh: Option<Duration>,
250) -> Attempt {
251 let mut desired = observed.value.clone();
252 project_ready_condition(&mut desired, lease, now);
253 let Some(condition) = find_ready_condition(&desired).cloned() else {
256 return Attempt::Malformed;
257 };
258
259 let unchanged = find_ready_condition(&observed.value).is_some_and(|previous| {
260 previous.get("status") == condition.get("status")
261 && previous.get("reason") == condition.get("reason")
262 && !heartbeat_due(previous, refresh)
263 });
264 if unchanged {
265 return Attempt::Unchanged;
266 }
267
268 match store
269 .propose(ResourceCommand::Put {
270 key: key.clone(),
271 value: desired,
272 expected: Some(observed.revision),
273 reason: Reason::Controller,
274 })
275 .await
276 {
277 Ok(applied) if applied.op == ResourceOp::Conflict => Attempt::Lost,
278 Ok(applied) => Attempt::Written(condition, Effect::of(applied.op)),
279 Err(e) => Attempt::Failed(e),
280 }
281}
282
283fn heartbeat_due(previous: &Value, refresh: Option<Duration>) -> bool {
284 let Some(refresh) = refresh else {
285 return false;
286 };
287 previous
288 .get("lastHeartbeatTime")
289 .and_then(Value::as_str)
290 .and_then(engenho_types::time::age_since_rfc3339)
291 .is_none_or(|age| age >= refresh)
292}
293
294#[cfg(test)]
295mod tests {
296 use std::sync::Arc;
297 use std::time::Duration;
298
299 use crate::node_lease::lease_value;
300 use engenho_store::{InProcessRouter, default_config};
301 use serde_json::json;
302
303 use super::*;
304
305 async fn boot(name: &str) -> Arc<StoreMesh> {
306 let router = InProcessRouter::new();
307 let cfg = default_config(name).unwrap();
308 let store = Arc::new(
309 StoreMesh::start(1, "in-process://1".into(), router, cfg)
310 .await
311 .unwrap(),
312 );
313 store.initialize_singleton().await.unwrap();
314 assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
315 store
316 }
317
318 async fn shutdown(store: Arc<StoreMesh>) {
319 Arc::try_unwrap(store)
320 .ok()
321 .unwrap()
322 .terminate()
323 .await
324 .unwrap();
325 }
326
327 fn node_key() -> ResourceKey {
328 ResourceKey::cluster_scoped("", "v1", "Node", "node-A")
329 }
330
331 fn fresh_lease() -> ResourceValue {
333 lease_value("node-A", &engenho_types::time::now_rfc3339_utc(), 0)
334 }
335
336 async fn seed_node(store: &StoreMesh) {
339 store
340 .propose(ResourceCommand::Put {
341 key: node_key(),
342 value: json!({
343 "kind": "Node",
344 "apiVersion": "v1",
345 "metadata": { "name": "node-A" },
346 "status": { "conditions": [
347 { "type": "Ready", "status": "True" },
348 { "type": "MemoryPressure", "status": "False" }
349 ]}
350 }),
351 expected: None,
352 reason: Reason::Operator,
353 })
354 .await
355 .unwrap();
356 }
357
358 async fn cordon(store: &StoreMesh) {
361 let mut node = store.get(&node_key()).await.unwrap();
362 node["spec"] = json!({
363 "unschedulable": true,
364 "taints": [{
365 "key": "node.kubernetes.io/unschedulable",
366 "effect": "NoSchedule"
367 }]
368 });
369 node["metadata"]["labels"] = json!({ "drain": "in-progress" });
370 store
371 .propose(ResourceCommand::Put {
372 key: node_key(),
373 value: node,
374 expected: None,
375 reason: Reason::Operator,
376 })
377 .await
378 .unwrap();
379 }
380
381 #[tokio::test]
382 async fn a_cordon_committed_between_read_and_write_survives() {
383 let store = boot("readiness-cordon-race").await;
384 seed_node(&store).await;
385
386 let stale = ObservedNode::read(&store, &node_key()).await.unwrap();
388 cordon(&store).await;
390 let lease = fresh_lease();
392 let outcome = publish_ready_onto(
393 &store,
394 &node_key(),
395 stale,
396 Some(&lease),
397 &engenho_types::time::now_rfc3339_utc(),
398 None,
399 )
400 .await;
401
402 let node = store.get(&node_key()).await.unwrap();
403 assert_eq!(
404 node["spec"]["unschedulable"], true,
405 "a readiness publish must never undo a cordon that committed after its read: {node}"
406 );
407 assert_eq!(
408 node["spec"]["taints"][0]["key"], "node.kubernetes.io/unschedulable",
409 "nor the taint that came with it: {node}"
410 );
411 assert_eq!(
412 node["metadata"]["labels"]["drain"], "in-progress",
413 "nor a label: {node}"
414 );
415
416 assert!(
419 matches!(outcome, ReadinessPublish::Published { retried: true, .. }),
420 "the first write loses, the re-read write commits: {outcome:?}"
421 );
422 let ready = find_ready_condition(&node).expect("Ready was published");
423 assert_eq!(ready["status"], "True", "{node}");
424 assert_eq!(ready["reason"], "KubeletReady", "{node}");
425 assert!(
426 node["status"]["conditions"]
427 .as_array()
428 .is_some_and(|cs| cs.iter().any(|c| c["type"] == "MemoryPressure")),
429 "a condition this kubelet does not own survives the merge: {node}"
430 );
431
432 shutdown(store).await;
433 }
434
435 #[tokio::test]
436 async fn a_node_deleted_between_read_and_write_is_not_recreated() {
437 let store = boot("readiness-delete-race").await;
438 seed_node(&store).await;
439
440 let stale = ObservedNode::read(&store, &node_key()).await.unwrap();
441 store
442 .propose(ResourceCommand::delete(node_key(), Reason::Operator))
443 .await
444 .unwrap();
445
446 let lease = fresh_lease();
447 let outcome = publish_ready_onto(
448 &store,
449 &node_key(),
450 stale,
451 Some(&lease),
452 &engenho_types::time::now_rfc3339_utc(),
453 None,
454 )
455 .await;
456
457 assert!(
458 store.get(&node_key()).await.is_none(),
459 "a readiness publish must not resurrect a deleted Node"
460 );
461 assert!(
462 matches!(outcome, ReadinessPublish::NoNode),
463 "the re-read finds nothing and says so: {outcome:?}"
464 );
465
466 shutdown(store).await;
467 }
468
469 #[tokio::test]
470 async fn an_uncontended_publish_commits_first_time_then_holds() {
471 let store = boot("readiness-uncontended").await;
472 seed_node(&store).await;
473 let lease = fresh_lease();
474
475 let first = publish_ready(
476 &store,
477 &node_key(),
478 Some(&lease),
479 &engenho_types::time::now_rfc3339_utc(),
480 None,
481 )
482 .await;
483 assert!(
484 matches!(first, ReadinessPublish::Published { retried: false, .. }),
485 "nothing raced it, so the first write commits: {first:?}"
486 );
487
488 let before = store.current_revision().await;
491 let second = publish_ready(
492 &store,
493 &node_key(),
494 Some(&lease),
495 &engenho_types::time::now_rfc3339_utc(),
496 None,
497 )
498 .await;
499 assert!(matches!(second, ReadinessPublish::Unchanged), "{second:?}");
500 assert_eq!(store.current_revision().await, before);
501
502 shutdown(store).await;
503 }
504
505 #[tokio::test]
506 async fn no_node_means_nothing_is_written() {
507 let store = boot("readiness-no-node").await;
508 let lease = fresh_lease();
509 let outcome = publish_ready(
510 &store,
511 &node_key(),
512 Some(&lease),
513 &engenho_types::time::now_rfc3339_utc(),
514 None,
515 )
516 .await;
517 assert!(matches!(outcome, ReadinessPublish::NoNode), "{outcome:?}");
518 assert!(
519 store.get(&node_key()).await.is_none(),
520 "registration creates Nodes; a readiness publish never does"
521 );
522 shutdown(store).await;
523 }
524
525 #[tokio::test]
526 async fn an_unchanged_condition_is_written_again_once_its_heartbeat_is_due() {
527 let store = boot("readiness-heartbeat-refresh").await;
528 seed_node(&store).await;
529 let lease = fresh_lease();
530 let now = engenho_types::time::now_rfc3339_utc();
531 let first = publish_ready(&store, &node_key(), Some(&lease), &now, None).await;
532 assert!(
533 matches!(first, ReadinessPublish::Published { .. }),
534 "{first:?}"
535 );
536
537 let held = store.current_revision().await;
538 let young = publish_ready(
539 &store,
540 &node_key(),
541 Some(&lease),
542 &now,
543 Some(REPORT_FREQUENCY),
544 )
545 .await;
546 assert!(matches!(young, ReadinessPublish::Unchanged), "{young:?}");
547 assert_eq!(store.current_revision().await, held);
548
549 let mut node = store.get(&node_key()).await.unwrap();
550 for c in node["status"]["conditions"].as_array_mut().unwrap() {
551 if c["type"] == "Ready" {
552 c["lastHeartbeatTime"] = serde_json::json!("2020-01-01T00:00:00Z");
553 }
554 }
555 store
556 .propose(ResourceCommand::Put {
557 key: node_key(),
558 value: node,
559 expected: None,
560 reason: Reason::Operator,
561 })
562 .await
563 .unwrap();
564 let stale_rv = resource_version_of(&store.get(&node_key()).await.unwrap()).unwrap();
565
566 let due = publish_ready(
567 &store,
568 &node_key(),
569 Some(&lease),
570 &now,
571 Some(REPORT_FREQUENCY),
572 )
573 .await;
574 assert!(matches!(due, ReadinessPublish::Published { .. }), "{due:?}");
575 let node = store.get(&node_key()).await.unwrap();
576 let ready = find_ready_condition(&node).unwrap();
577 assert_eq!(ready["lastHeartbeatTime"], now.as_str(), "{node}");
578 assert_ne!(
579 resource_version_of(&node).unwrap(),
580 stale_rv,
581 "a moved heartbeat is a new revision: {node}"
582 );
583
584 shutdown(store).await;
585 }
586
587 #[test]
588 fn a_node_without_a_revision_cannot_be_observed() {
589 let unversioned = json!({ "kind": "Node", "metadata": { "name": "node-A" } });
592 assert_eq!(
593 ObservedNode::from_stored(unversioned).err(),
594 Some(Unobservable::Unversioned)
595 );
596 let garbage = json!({ "metadata": { "resourceVersion": "not-a-number" } });
597 assert_eq!(
598 ObservedNode::from_stored(garbage).err(),
599 Some(Unobservable::Unversioned)
600 );
601 }
602}