tatara_process/lib.rs
1//! Process CRD — the K8s-as-Unix-processes wire format.
2//!
3//! A `Process` is one element of the tatara convergence lattice.
4//! Clusters, HelmReleases, migrations, tests — all are Processes.
5//! The reconciliation loop *is* Unix: fork → exec → wait → exit → reap.
6
7pub mod allocation;
8pub mod attestation;
9pub mod boundary;
10pub mod classification;
11pub mod compliance;
12pub mod crd;
13pub mod encapsulates;
14pub mod env;
15pub mod ephemeral;
16pub mod export;
17pub mod hostname;
18pub mod identity;
19pub mod intent;
20pub mod lifetime;
21pub mod lifetime_clock;
22pub mod matrix;
23pub mod phase;
24pub mod pool;
25pub mod receipt;
26pub mod routing;
27pub mod signal;
28pub mod spec;
29pub mod status;
30pub mod table;
31pub mod tagged_union;
32
33pub mod prelude {
34 pub use crate::allocation::{
35 AllocationCondition, AllocationPhase, AllocationSpec, AllocationStatus,
36 EphemeralAllocation, Requestor,
37 };
38 pub use crate::attestation::ProcessAttestation;
39 pub use crate::boundary::{Boundary, Condition, ConditionKind, UnknownConditionKind};
40 pub use crate::classification::{
41 Arity, CalmClassification, Classification, ConvergencePointType, DataClassification,
42 Horizon, HorizonKind, OptimizationDirection, SubstrateType, UnknownCalmClassification,
43 UnknownConvergencePointType, UnknownDataClassification, UnknownHorizonKind,
44 UnknownOptimizationDirection, UnknownSubstrateType,
45 };
46 pub use crate::compliance::{
47 ComplianceBinding, ComplianceSpec, UnknownVerificationPhase, VerificationPhase,
48 };
49 pub use crate::crd::{Process, ProcessSpec, ProcessStatus};
50 pub use crate::encapsulates::{
51 BareWorkload, EncapsulatesSpec, EncapsulationKind, EncapsulationKindError,
52 EncapsulationKindVariant, EncapsulationMode, EncapsulationTarget, ExistingHelmRelease,
53 ExistingKustomization, UnknownEncapsulationMode, UnknownEncapsulationTarget,
54 };
55 pub use crate::ephemeral::{compile_ephemeral_source, EphemeralSpec};
56 pub use crate::export::{
57 ArtifactError, ArtifactKind, ArtifactSource, ArtifactVariant, ChannelError, ChannelKind,
58 ChannelVariant, ExportSpec, ExportTrigger, HttpEventChannel, NatsSubjectChannel,
59 ProcessSnapshotSource, ReceiptsSource, ReportFormat, ReportPayloadShape, RunMarkerSource,
60 StdoutChannel, TestReportSource, UnknownArtifactKind, UnknownChannelKind,
61 UnknownExportTrigger, UnknownReportFormat, VectorChannel, DEFAULT_NATS_URL,
62 DEFAULT_VECTOR_INGEST,
63 };
64 pub use crate::hostname::{
65 ephemeral_id_from_spec, fmt_fqdn, fmt_fqdn_stable, resolve_ephemeral_id, HostnameError,
66 EPHEMERAL_ID_HASH_LEN,
67 };
68 pub use crate::identity::{content_hash, derive_identity, format_process_address, Identity};
69 pub use crate::intent::{
70 AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, HelmLifecyclePolicy,
71 HelmRemediationPolicy, Intent, IntentError, IntentKind, IntentVariant, LispIntent,
72 NixIntent, UnknownWorkloadKind, WorkloadKind, FLUX_HELM_DEFAULT_INTERVAL,
73 HELM_LIFECYCLE_DEFAULT_RETRIES, HELM_LIFECYCLE_DEFAULT_TIMEOUT,
74 };
75 pub use crate::lifetime::{
76 EphemeralLifetime, Lifetime, LifetimeError, LifetimeKind, LifetimeVariant,
77 PermanentLifetime, TeardownPolicy, UnknownTeardownPolicy,
78 };
79 pub use crate::lifetime_clock::{
80 evaluate as lifetime_clock_evaluate, AutoTerminate, AutoTerminateKind, TerminateReason,
81 TerminateReasonKind, UnknownAutoTerminateKind, UnknownTerminateReasonKind,
82 };
83 pub use crate::matrix::{
84 compile_env_matrix_source, EnvMatrixSpec, MatrixAxis, MatrixBudget, NamedEphemeral,
85 SelectStrategy, SelectStrategyKind, UnknownSelectStrategyKind,
86 };
87 pub use crate::phase::{ProcessPhase, UnknownPhase};
88 pub use crate::pool::{
89 AllocationRef, EphemeralPool, MatchKey, MemberState, PoolCondition, PoolMember, PoolPhase,
90 PoolSelector, PoolSpec, PoolStatus, ReplacementPolicy, ReturnPolicy, UnknownMemberState,
91 UnknownPoolPhase, UnknownReplacementPolicy,
92 };
93 pub use crate::receipt::{
94 default_receipt_config_map_name, ReceiptEnvelope, ReceiptError, ReceiptKind,
95 RECEIPT_CM_SUFFIX, RECEIPT_VERSION,
96 };
97 pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
98 pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
99 pub use crate::spec::{
100 DependsOn, IdentitySpec, MustReachPhase, SignalPolicy, UnknownMustReachPhase,
101 };
102 pub use crate::status::{
103 BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
104 RenderedResourceCoords,
105 };
106 pub use crate::table::{
107 ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
108 };
109}
110
111/// CRD API group for every tatara CRD.
112pub const GROUP: &str = "tatara.pleme.io";
113/// CRD version for this module.
114pub const VERSION: &str = "v1alpha1";
115/// Kind spelling of the tatara Process CRD as it appears in a K8s
116/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
117/// [`VERSION`] — centralizes the ONE literal every SSA-time
118/// re-injection helper pre-lift restated by hand across
119/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
120///
121/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
122pub const PROCESS_KIND: &str = "Process";
123
124/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
125/// K8s `apiVersion` shape every tatara CRD stamps. Composed from
126/// [`GROUP`] + [`VERSION`] so a bump of either constant lands here
127/// exactly once; pre-lift, two `tatara-reconciler` sites hand-wrote
128/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
129/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
130/// opening a silent drift path if `VERSION` ever advances past
131/// `v1alpha1`.
132pub fn api_version() -> String {
133 format!("{GROUP}/{VERSION}")
134}
135
136/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
137/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
138/// [`api_version`]) with `controller: true` +
139/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
140/// re-injection site pre-lift restated three times across
141/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
142/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
143/// owners, `ssapply.rs::build_owner_reference` for the injected
144/// owner-ref stamped on every applied `DynamicObject`). Callers
145/// with a live `Process` value read `metadata.{name,uid}` and pass
146/// them through as `&str`.
147///
148/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
149/// both `true`); a Process-owned resource that wants a non-
150/// controller reference doesn't belong on this owner and can build
151/// its own `json!` inline — this primitive is the composer for the
152/// canonical "Process controls this resource, cascade-delete on
153/// GC" shape, not a general OwnerReference builder.
154///
155/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
156pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
157 serde_json::json!({
158 "apiVersion": api_version(),
159 "kind": PROCESS_KIND,
160 "name": name,
161 "uid": uid,
162 "controller": true,
163 "blockOwnerDeletion": true,
164 })
165}
166
167/// Substrate-primitive builder for a Process-owned resource's
168/// **`metadata.ownerReferences` array** — the empty-uid-gated,
169/// single-entry `Vec<Value>` every emit site that lacks a fully
170/// materialized [`crate::prelude::Process`] (i.e. every site that
171/// works from a bare `(name, uid)` pair rather than routing through
172/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
173/// anyhow-guarded unwrap) hand-composed by wrapping
174/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
175/// the `uid` slot.
176///
177/// The `uid.is_empty()` gate encodes the invariant every caller
178/// already enforced: a Process pre-metadata (fixtured in tests, or
179/// caught mid-Forking before the API server has stamped a `uid`) has
180/// no admissible owner reference to point at, so the emit site
181/// stamps `metadata.ownerReferences: []` rather than an
182/// owner-referenceless resource pointing at a placeholder uid the K8s
183/// GC would silently ignore. Post-lift the gate lives at ONE
184/// primitive so a regression that inlined an owner reference for
185/// an empty uid — which the API server accepts and quietly detaches
186/// from cascade-delete — surfaces at THIS primitive's pin rather
187/// than as an operator-visible ownerless resource after apply.
188///
189/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
190/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
191/// uid)); }` incantation was hand-authored at TWO sites past the
192/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
193/// `tatara-reconciler`, each restating the same gated composition:
194/// * `edges::build_owner_refs` — the shared owner-refs builder both
195/// `IngressEdge` + `DnsEndpointEdge` route through, sourcing
196/// `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
197/// * `render::one_export_job` — the export Job's owner-refs seed,
198/// sourcing `(name, uid)` from the [`crate::prelude::Process`]
199/// `render_export_jobs` threaded in.
200///
201/// Post-lift both callsites read `owner_references_json(name, uid)`.
202/// A future addition — e.g. a second owner-reference slot naming a
203/// controlling ProcessTable entry, a policy that stamps a stale-uid
204/// warning annotation before returning empty, or a normalization
205/// that strips a cluster-prefix off the uid — lands at ONE
206/// substrate function here and every emit site inherits the upgrade
207/// mechanically. The [`ssapply::build_owner_reference`] path (which
208/// works from a materialized [`crate::prelude::Process`] and errors
209/// on absent `metadata.uid`) is a peer, not a lift candidate: its
210/// contract is "the K8s API server assigned a uid, so refuse to
211/// SSA-apply resources whose owner cannot be materialized", while
212/// this primitive's contract is "the caller has an optional-uid
213/// posture; emit `[]` when the uid is absent". The two shapes
214/// partition the input space at the "is the enclosing scope
215/// obligated to produce a materialized Process reference" axis.
216///
217/// The 2-arg `(&str, &str)` signature accepts both the
218/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
219/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
220/// without widening — matches every current callsite.
221pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
222 if uid.is_empty() {
223 vec![]
224 } else {
225 vec![owner_reference_json(name, uid)]
226 }
227}
228
229/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
230pub mod annotations {
231 pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
232 pub const PROCESS: &str = "tatara.pleme.io/process";
233 pub const PID: &str = "tatara.pleme.io/pid";
234 pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
235 pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
236 pub const GENERATION: &str = "tatara.pleme.io/generation";
237 pub const SIGNAL: &str = "tatara.pleme.io/signal";
238 /// Stamped by the reconciler when transitioning into `Releasing`
239 /// — records which terminal-reached gate the Process came from
240 /// (`Attested` or `Failed`) so `handle_releasing` can pick the
241 /// matching `ExportTrigger` set + the correct post-Releasing
242 /// destination (`Exiting` from Attested, `Zombie` from Failed).
243 pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
244 /// Labels the export-worker Jobs the reconciler emits during
245 /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
246 pub const ROLE: &str = "tatara.pleme.io/role";
247 /// Index of an export inside `lifetime.ephemeral.exports`.
248 /// Stamped on the corresponding tatara-export-worker Job + its
249 /// receipt ConfigMap so the reconciler can correlate them
250 /// without re-parsing the spec JSON.
251 pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
252 /// Label / annotation key stamping which
253 /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
254 /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
255 /// a `label`-selector on this key slices every emitted edge
256 /// for a given `app` regardless of hostname form. Peer to
257 /// [`ROUTING_FORM`] on the routing-axis pair.
258 pub const APP: &str = "tatara.pleme.io/app";
259 /// Label / annotation key stamping the routing form
260 /// (`"stable"` | `"instance"`) on every emitted routing edge.
261 /// Value is a [`crate::routing::RoutingForm`] wire-form string;
262 /// consumers filtering the two forms compare to
263 /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
264 /// never to a bare literal.
265 pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
266}
267
268/// Standard finalizer for the Process reconciler.
269pub const PROCESS_FINALIZER: &str = "tatara.pleme.io/process-finalizer";
270
271/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
272/// Free-form `serde_json::Value` fields default to an *empty* schema
273/// in schemars, which the K8s API server rejects with "type: Required
274/// value: must not be empty for specified object fields". The typed
275/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
276/// fields: true}` — same shape kube-rs's own helpers produce.
277pub mod schema_helpers {
278 use schemars::{gen::SchemaGenerator, schema::Schema};
279 /// Schema for a free-form JSON object field. Apply via
280 /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
281 /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
282 /// field exposed through a CRD.
283 pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
284 serde_json::from_value(serde_json::json!({
285 "type": "object",
286 "x-kubernetes-preserve-unknown-fields": true
287 }))
288 .expect("static JSON literal parses as Schema")
289 }
290}
291
292#[cfg(test)]
293mod owner_reference_tests {
294 //! Pin the `owner_reference_json` composer at fail-before-pass-
295 //! after granularity. Every shape a pre-lift caller hand-authored
296 //! is re-asserted here so a regression that inlined any of the
297 //! six slots at a call site (breaking the primitive's role as
298 //! the ONE source of truth) fails HERE at the composer's shipped-
299 //! shape pin rather than as silent drift between the pre-lift
300 //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
301 //! already carried TWO different `apiVersion` spellings — a
302 //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
303 //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
304 use super::{
305 api_version, owner_reference_json, owner_references_json, GROUP, PROCESS_KIND, VERSION,
306 };
307 use serde_json::json;
308
309 #[test]
310 fn api_version_composes_group_and_version() {
311 // Any bump of GROUP or VERSION lands at ONE composer.
312 assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
313 }
314
315 #[test]
316 fn api_version_byte_matches_wire_form_pre_lift() {
317 // Byte-identity pin: the frozen wire-form literal
318 // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
319 // build_owner_reference` hand-wrote pre-lift must equal the
320 // composed shape now sourced through the ONE owner. A
321 // future VERSION bump that missed this test would land as
322 // an operator-visible reference-mismatch after apply.
323 assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
324 }
325
326 #[test]
327 fn process_kind_is_process_literal() {
328 // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
329 // pre-lift routes through this const post-lift.
330 assert_eq!(PROCESS_KIND, "Process");
331 }
332
333 #[test]
334 fn owner_reference_json_has_all_six_slots_present() {
335 let v = owner_reference_json("my-process", "abc-uid");
336 let obj = v.as_object().expect("owner reference is a JSON object");
337 for k in [
338 "apiVersion",
339 "kind",
340 "name",
341 "uid",
342 "controller",
343 "blockOwnerDeletion",
344 ] {
345 assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
346 }
347 assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
348 }
349
350 #[test]
351 fn owner_reference_json_apiversion_routes_through_api_version_owner() {
352 let v = owner_reference_json("x", "y");
353 assert_eq!(v["apiVersion"], api_version());
354 }
355
356 #[test]
357 fn owner_reference_json_kind_routes_through_process_kind_const() {
358 let v = owner_reference_json("x", "y");
359 assert_eq!(v["kind"], PROCESS_KIND);
360 }
361
362 #[test]
363 fn owner_reference_json_stamps_supplied_name_and_uid() {
364 let v = owner_reference_json("some-name", "some-uid");
365 assert_eq!(v["name"], "some-name");
366 assert_eq!(v["uid"], "some-uid");
367 }
368
369 #[test]
370 fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
371 // These are structural — a Process-owned resource always
372 // has a controlling reference that cascade-deletes with
373 // the owner. A regression that flipped either boolean
374 // would silently detach every emitted resource.
375 let v = owner_reference_json("x", "y");
376 assert_eq!(v["controller"], true);
377 assert_eq!(v["blockOwnerDeletion"], true);
378 }
379
380 #[test]
381 fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
382 // Byte-shape pin against the exact `json!({…})` incantation
383 // every pre-lift call site restated. A regression that
384 // reordered a slot, dropped one, or added a seventh here
385 // surfaces at THIS pin rather than as a subtle SSA-apply
386 // failure downstream when the K8s API server rejects the
387 // OwnerReference on schema mismatch.
388 let via_owner = owner_reference_json("p", "u");
389 let hand_authored = json!({
390 "apiVersion": "tatara.pleme.io/v1alpha1",
391 "kind": "Process",
392 "name": "p",
393 "uid": "u",
394 "controller": true,
395 "blockOwnerDeletion": true,
396 });
397 assert_eq!(via_owner, hand_authored);
398 }
399
400 #[test]
401 fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
402 // The primitive does not guard against empty inputs — its
403 // callers pre-lift did the empty-check upstream (both the
404 // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
405 // sites gated on `!uid.is_empty()` before calling this composer,
406 // and both now route through `owner_references_json` below;
407 // `ssapply.rs::build_owner_reference` unwraps a required
408 // `metadata.uid` via anyhow). The scalar composer owns
409 // shape composition, not admission control; a downstream
410 // rename that wants strict input validation lands as a
411 // peer, not a change to the composer's contract.
412 let v = owner_reference_json("", "");
413 assert_eq!(v["name"], "");
414 assert_eq!(v["uid"], "");
415 }
416
417 // ─── owner_references_json substrate pins ────────────────────────
418 //
419 // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
420 // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
421 // hand-authored at TWO sites in `tatara-reconciler`
422 // (`edges::build_owner_refs` + `render::one_export_job`) before
423 // this primitive existed, each restating the same optional-uid
424 // posture that emits `[]` when the caller lacks a K8s-assigned
425 // uid to point owners at. These pins bind the primitive at
426 // fail-before-pass-after granularity so a regression that
427 // inlined an owner reference for an empty uid — silently
428 // detaching the resource from cascade-delete — surfaces HERE
429 // rather than as an operator-visible ownerless resource after
430 // apply, and a regression that added an owner reference of the
431 // wrong SHAPE (a peer of `owner_reference_json` that swapped a
432 // slot) surfaces via the composed-shape pin below rather than
433 // as silent drift at every downstream emit site.
434
435 #[test]
436 fn owner_references_json_emits_single_entry_when_uid_present() {
437 // The primary shape: a caller with a materialized uid gets
438 // exactly one owner reference back — the pre-lift 3-line
439 // `vec![]` + `push` gate collapses to this ONE call, and
440 // the returned array is a direct-drop `ownerReferences`
441 // slot value at every callsite.
442 let refs = owner_references_json("demo-app", "abc-uid");
443 assert_eq!(refs.len(), 1);
444 assert_eq!(refs[0]["kind"], PROCESS_KIND);
445 assert_eq!(refs[0]["name"], "demo-app");
446 assert_eq!(refs[0]["uid"], "abc-uid");
447 // controller + blockOwnerDeletion routed through the scalar
448 // composer — a regression that hand-composed the vec entry
449 // rather than delegating would flip one of these booleans.
450 assert_eq!(refs[0]["controller"], true);
451 assert_eq!(refs[0]["blockOwnerDeletion"], true);
452 }
453
454 #[test]
455 fn owner_references_json_emits_empty_when_uid_empty() {
456 // The load-bearing gate — a pre-metadata Process (fixtured in
457 // tests, or caught mid-Forking) has no admissible owner
458 // reference to point at. Post-lift the gate lives at ONE
459 // primitive so every emit site stamps `[]` uniformly rather
460 // than one site accidentally emitting a placeholder-uid
461 // owner reference the K8s GC would quietly detach from
462 // cascade-delete.
463 let refs = owner_references_json("demo-app", "");
464 assert!(
465 refs.is_empty(),
466 "empty uid must produce zero owner references, not a placeholder-uid entry"
467 );
468 }
469
470 #[test]
471 fn owner_references_json_gates_on_uid_not_name() {
472 // The gate axis is `uid`, not `name` — a Process with a
473 // non-empty name but no uid still emits `[]` (the pre-metadata
474 // shape), while a Process with a non-empty uid emits ONE
475 // entry even when the name slot is empty (matching the
476 // scalar composer's admission-control-free contract). Pin
477 // both cross-diagonal combinations so a regression that
478 // swapped the gate axis surfaces HERE rather than at every
479 // downstream owner-refs consumer.
480 assert!(
481 owner_references_json("has-name", "").is_empty(),
482 "empty uid gates to []; name presence is irrelevant"
483 );
484 let refs = owner_references_json("", "has-uid");
485 assert_eq!(
486 refs.len(),
487 1,
488 "empty name but present uid still emits one entry (name is not the gate)"
489 );
490 assert_eq!(refs[0]["name"], "");
491 assert_eq!(refs[0]["uid"], "has-uid");
492 }
493
494 #[test]
495 fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
496 // Byte-identical parity with the exact pre-lift 3-line
497 // `let mut owner_refs = vec![]; if !uid.is_empty() {
498 // owner_refs.push(owner_reference_json(name, uid)); }` gate
499 // across the two axis combinations every callsite plausibly
500 // encounters. A regression that reordered the two branches,
501 // dropped the gate, or reshaped the vec composition surfaces
502 // HERE rather than at every downstream `ownerReferences`
503 // slot pinned across `edges.rs` + `render.rs` tests.
504 for (name, uid) in [
505 ("demo-app", "uid-abc"),
506 ("demo-app", ""),
507 ("", "uid-abc"),
508 ("", ""),
509 ] {
510 let via_primitive = owner_references_json(name, uid);
511
512 // The pre-lift 3-line block, byte-for-byte.
513 let mut hand_authored: Vec<serde_json::Value> = vec![];
514 if !uid.is_empty() {
515 hand_authored.push(owner_reference_json(name, uid));
516 }
517
518 assert_eq!(
519 via_primitive, hand_authored,
520 "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
521 );
522 }
523 }
524
525 #[test]
526 fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
527 // Both callsites drop the returned vec directly under a
528 // `"ownerReferences"` key inside a `json!({...})` block. Pin
529 // the interop shape: a JSON-macro-wrapped Value carries the
530 // primitive's output as a JSON array with the exact 6-slot
531 // entries at each index. A regression that returned a
532 // non-array (e.g. a single Value on the one-entry path,
533 // requiring per-site vec-wrapping) surfaces HERE rather than
534 // as a broken `metadata.ownerReferences` slot on every
535 // emitted Ingress / DNSEndpoint / export Job.
536 let refs = owner_references_json("demo-app", "abc-uid");
537 let wrapped = json!({
538 "metadata": {
539 "name": "resource",
540 "ownerReferences": refs,
541 },
542 });
543 let owner_refs = &wrapped["metadata"]["ownerReferences"];
544 assert!(
545 owner_refs.is_array(),
546 "ownerReferences must land as a JSON array"
547 );
548 assert_eq!(owner_refs.as_array().unwrap().len(), 1);
549 assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
550
551 // And the empty-uid path lands as an EMPTY array, not a
552 // missing key or a null — matches the K8s API server's
553 // expectation that the slot is either an array of entries
554 // or absent, never a null.
555 let empty_refs = owner_references_json("demo-app", "");
556 let wrapped_empty = json!({
557 "metadata": {
558 "name": "resource",
559 "ownerReferences": empty_refs,
560 },
561 });
562 let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
563 assert!(owner_refs_empty.is_array());
564 assert!(owner_refs_empty.as_array().unwrap().is_empty());
565 }
566}
567
568// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
569//
570// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
571// The derive on ProcessSpec handles every field via the serde Deserialize
572// fallthrough — no hand-rolled keyword parsing needed.
573
574/// A named ProcessSpec as produced by `compile_source`.
575pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
576
577/// Compile a Lisp source string into a list of named ProcessSpecs.
578/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
579pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
580 tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
581}
582
583/// Register every domain owned by this crate with the global Lisp
584/// dispatcher. Call once per binary, typically near the top of `main`.
585/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
586/// `lookup("defephemeral")` both resolve to the right typed compiler.
587///
588/// Idempotent — registering the same type twice is a no-op.
589pub fn register_all() {
590 tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
591 tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
592}
593
594#[cfg(test)]
595mod compile_tests {
596 use super::compile_source;
597 use crate::classification::{ConvergencePointType, SubstrateType};
598 use crate::compliance::VerificationPhase;
599 use crate::spec::MustReachPhase;
600
601 /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
602 /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
603 #[test]
604 fn full_processspec_round_trip_via_derive() {
605 let src = r#"
606 (defpoint observability-stack
607 :identity (:parent "seph.1")
608 :classification (:point-type Gate
609 :substrate Observability
610 :horizon (:kind Bounded)
611 :calm Monotone
612 :data-classification Internal)
613 :intent (:nix (:flake-ref "github:pleme-io/k8s"
614 :attribute "observability"
615 :attic-cache "main"))
616 :boundary (:postconditions
617 ((:kind KustomizationHealthy
618 :params (:name "observability-stack"
619 :namespace "flux-system"))
620 (:kind PromQL
621 :params (:query "up == 1")))
622 :timeout "15m")
623 :compliance (:baseline "fedramp-moderate"
624 :bindings ((:framework "nist-800-53"
625 :control-id "SC-7"
626 :phase AtBoundary)))
627 :depends-on ((:name "secret-injection" :must-reach Attested))
628 :signals (:sigterm-grace-seconds 480
629 :sighup-strategy Reconverge))
630 "#;
631 let defs = compile_source(src).expect("compile");
632 assert_eq!(defs.len(), 1);
633 let d = &defs[0];
634 assert_eq!(d.name, "observability-stack");
635
636 // identity
637 assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
638
639 // classification (enums deserialized via symbol → string)
640 assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
641 assert_eq!(
642 d.spec.classification.substrate,
643 SubstrateType::Observability
644 );
645
646 // intent (tagged-union with one of four options)
647 let nix = d.spec.intent.nix.as_ref().expect("nix intent");
648 assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
649 assert_eq!(nix.attribute, "observability");
650 assert_eq!(nix.attic_cache.as_deref(), Some("main"));
651
652 // boundary (Vec<nested struct with params object>)
653 assert_eq!(d.spec.boundary.postconditions.len(), 2);
654 assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
655
656 // compliance (Vec<binding with enum phase>)
657 assert_eq!(
658 d.spec.compliance.baseline.as_deref(),
659 Some("fedramp-moderate")
660 );
661 assert_eq!(d.spec.compliance.bindings.len(), 1);
662 assert_eq!(
663 d.spec.compliance.bindings[0].phase,
664 VerificationPhase::AtBoundary
665 );
666
667 // depends_on (Vec<struct with enum>)
668 assert_eq!(d.spec.depends_on.len(), 1);
669 assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
670
671 // signals (numeric + enum defaults)
672 assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
673 }
674
675 #[test]
676 fn missing_required_field_errors() {
677 // `:classification` has no #[serde(default)] — omit it and compile must fail.
678 let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
679 assert!(compile_source(src).is_err());
680 }
681
682 #[test]
683 fn serde_default_fields_are_optional() {
684 // Omit every #[serde(default)] field — compile must succeed because
685 // the derive honors serde defaults.
686 let src = r#"
687 (defpoint x
688 :classification (:point-type Transform :substrate Compute)
689 :intent (:flux (:git-repository "g" :path ".")))
690 "#;
691 let defs = compile_source(src).expect("compile");
692 assert_eq!(defs.len(), 1);
693 let d = &defs[0];
694 assert!(d.spec.depends_on.is_empty());
695 assert!(d.spec.boundary.postconditions.is_empty());
696 assert!(d.spec.compliance.bindings.is_empty());
697 assert!(!d.spec.suspended);
698 // Lifetime defaults to Permanent (no variant set, resolver still works).
699 assert!(d.spec.lifetime.is_default());
700 assert!(!d.spec.lifetime.is_ephemeral());
701 }
702
703 /// Registering all process-owned domains is idempotent and resolves
704 /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
705 #[test]
706 fn register_all_resolves_defpoint_and_defephemeral() {
707 use tatara_lisp::domain::lookup;
708 super::register_all();
709 super::register_all(); // idempotent
710 assert!(lookup("defpoint").is_some(), "defpoint must resolve");
711 assert!(
712 lookup("defephemeral").is_some(),
713 "defephemeral must resolve"
714 );
715 }
716
717 /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
718 /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
719 /// This is what the `(defephemeral …)` sugar lowers to via `From`.
720 #[test]
721 fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
722 use crate::intent::IntentVariant;
723 use crate::lifetime::{LifetimeVariant, TeardownPolicy};
724 let src = r#"
725 (defpoint closed-loop-attest
726 :classification (:point-type Gate :substrate Compute)
727 :intent (:aplicacao
728 (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
729 :version "0.5.5"
730 :profile "all-in-one"
731 :values-overlay (:cluster (:name "ephemeral-test-01"))
732 :target-namespace "demo-test"))
733 :boundary (:postconditions
734 ((:kind HelmReleaseReleased
735 :params (:name "demo-app-consolidated"
736 :namespace "demo-test"))
737 (:kind ClosedLoopAuth
738 :params (:issuer (:service "demo-app-issuer" :port 8080)
739 :consumer (:service "demo-app-gateway" :port 8000)
740 :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
741 :lifetime (:ephemeral (:ttl "1h"
742 :teardown-policy OnAttested
743 :max-concurrent 1)))
744 "#;
745 let defs = compile_source(src).expect("compile");
746 assert_eq!(defs.len(), 1);
747 let d = &defs[0];
748
749 // Aplicacao intent landed.
750 match d.spec.intent.variant().unwrap() {
751 IntentVariant::Aplicacao(a) => {
752 assert_eq!(a.profile, "all-in-one");
753 assert_eq!(a.version, "0.5.5");
754 assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
755 assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
756 }
757 other => panic!("expected Aplicacao, got {other:?}"),
758 }
759
760 // Ephemeral lifetime landed with the right teardown policy.
761 match d.spec.lifetime.variant().unwrap() {
762 LifetimeVariant::Ephemeral(e) => {
763 assert_eq!(e.ttl, "1h");
764 assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
765 assert_eq!(e.max_concurrent, 1);
766 }
767 other => panic!("expected ephemeral, got {other:?}"),
768 }
769
770 // Two typed postconditions including ClosedLoopAuth.
771 assert_eq!(d.spec.boundary.postconditions.len(), 2);
772 assert_eq!(
773 d.spec.boundary.postconditions[1].kind,
774 crate::boundary::ConditionKind::ClosedLoopAuth
775 );
776 }
777}