cloud/reconciler/mod.rs
1//! Reconciler abstraction — bring a workload up against a mirror's
2//! provider slots.
3//!
4//! A reconciler is the kind-specific code that knows how to deploy one
5//! workload kind (`mesofact-static`, `container`, future `almanac`, …) to a
6//! mirror. Selection: a [`ServiceComponent`](crate::ServiceComponent)'s
7//! `kind` field picks which reconciler runs; the reconciler then dispatches
8//! on the mirror's provider slot (e.g. `mesofact-static` →
9//! `providers.static` slot → `local-static` inline or `cloudflare` ref).
10//!
11//! T3 ships [`MesofactStaticReconciler`] with the `local-static` path
12//! wired (spawn `mesofact-dev` as a child process). The Cloudflare path is
13//! a stub — the production reconciler lands once `mesofact-publisher`
14//! integration is on the roadmap.
15//!
16//!
17//! @yah:ticket(R419-F2, "Implement CloudflareWorkerReconciler (kind=cloudflare-worker)")
18//! @yah:assignee(agent:claude)
19//! @yah:at(2026-06-03T08:02:49Z)
20//! @yah:status(review)
21//! @yah:parent(R419)
22//! @yah:handoff("Landed CloudflareWorkerReconciler in crates/yah/cloud/src/reconciler/cloudflare_worker.rs and re-exported it through reconciler/mod.rs + cloud/src/lib.rs. up() validates the registry slot (must be `use = \"cloudflare\"` with non-empty `zone` + `domain`), reads workload.toml's `[build]` + `[[bindings]]`, matches each binding against a sibling mirror slot by `binding` field, runs build, reads the bundled entrypoint (default dist/index.js), idempotently lists+creates R2 buckets, deploys via deploy_worker_script with WorkerBinding::R2Bucket entries (R419-F1 surface), then attaches the custom domain via the new upsert_worker_custom_domain method on CloudflareClient. Returns RunningWorkload::adopted with public_url=https://<domain>. All config validation runs BEFORE any CF API call (R330-B5 fail-fast discipline).")
23//! @yah:handoff("Added CloudflareClient::upsert_worker_custom_domain (cloudflare.rs) — separate from upsert_worker_route because Worker Routes are zone-scoped pattern matches and Custom Domains are account-scoped hostname attachments. List-first idempotency: skips PUT when the (hostname, service, zone_id) tuple is already bound.")
24//! @yah:verify("cargo check -p cloud --lib — clean")
25//! @yah:depends_on(R419-F1)
26//!
27//! @yah:ticket(R419-F3, "Register cloudflare-worker reconciler in CLI + desktop dispatch")
28//! @yah:assignee(agent:claude)
29//! @yah:at(2026-06-03T08:02:58Z)
30//! @yah:status(review)
31//! @yah:parent(R419)
32//! @yah:handoff("Added match arm `\"cloudflare-worker\" => CloudflareWorkerReconciler::new().up(ctx)` in both dispatchers: app/yah/cli/src/cloud.rs:reconcile_component and app/yah/desktop/src/mirror_run.rs's component.kind.as_str() match. Imported CloudflareWorkerReconciler at the top of each file. Updated the desktop file-level docstring to list the new kind. Pre-existing fallback arm still produces a clean error for unknown kinds.")
33//! @yah:verify("cargo check -p cloud --lib — clean")
34//! @yah:verify("cargo check -p yah --lib --bins — clean (warnings unchanged from baseline)")
35//! @yah:verify("cargo check -p desktop --lib — clean (warnings unchanged from baseline)")
36//! @yah:depends_on(R419-F2)
37//!
38//! @yah:ticket(R419-F4, "Regression tests: misconfig fail-fast for cloudflare-worker reconciler")
39//! @yah:assignee(agent:claude)
40//! @yah:at(2026-06-03T08:03:09Z)
41//! @yah:status(review)
42//! @yah:parent(R419)
43//! @yah:handoff("Three fail-fast tests in reconciler::cloudflare_worker::tests — Fixture builds an in-tempdir yah-cr-shaped workspace (writes workload.toml + .yah/infra/providers/cloudflare.toml). up_bails_on_registry_missing_domain (case 3) drops domain off the registry slot. up_bails_on_binding_name_drift (case 2) puts binding=\"STORAGE\" in the cache slot while workload.toml binds CACHE. up_bails_on_cache_slot_missing_bucket (case 1) keeps binding=\"CACHE\" but omits bucket. Each test asserts the error message names the offending field, the slot role, the service, and the env — no CF HTTP call is made because validation runs before any client construction.")
44//! @yah:verify("cargo test -p cloud --lib reconciler::cloudflare_worker — 3 passed")
45//! @yah:verify("cargo test -p cloud --lib — 246 passed (1 pre-existing failure cloud_init::tests::embedded_template_matches_workspace_canonical is unrelated R092-F2 template drift, not caused by R419)")
46//! @yah:depends_on(R419-F2)
47//!
48//! @yah:relay(R458, "Cloud reconciler for .yah/domains/*.toml — R2 custom-domain shape")
49//! @yah:at(2026-06-05T08:40:57Z)
50//! @yah:status(open)
51//! @yah:next("F1: implement ensure_r2_custom_domain (mirror of ensure_r2_bucket) + wire into yah cloud apply as a post-services pass. Scope: domains with cdn_bucket set and no [[routes]] (today: cdn-yah-dev.toml). Worker-routed shape (yah-dev, app-yah-dev) is a separate surface.")
52//! @arch:see(.yah/domains/cdn-yah-dev.toml)
53//!
54//! @yah:ticket(R458-F1, "ensure_r2_custom_domain (CF API) + apply-time orchestration")
55//! @yah:at(2026-06-05T08:41:07Z)
56//! @yah:status(review)
57//! @yah:assignee(agent:claude)
58//! @yah:parent(R458)
59//! @arch:see(.yah/domains/cdn-yah-dev.toml)
60//! @yah:next("R458 can be archived once F1 is signed off, unless we want to keep it open for the routed-domain (Worker) reconciler shape — that's a much larger surface (DNS + Worker route management + bundle deploy) than this F1's bucket-binding.")
61//! @yah:handoff("Live-verified end-to-end. cdn.yah.dev now resolves to CF anycast IPs (104.21.43.100, 172.67.178.4) and curl HTTP/2 200s against https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin (content-length 584567555 = the q5_1 bytes R422-F11 published). Second apply is idempotent — the list-first path skips the POST when the binding is already present. Files touched: (1) crates/yah/cloud/src/provider/cloudflare.rs — new R2CustomDomain output type + CloudflareClient::list_r2_custom_domains and CloudflareClient::add_r2_custom_domain methods (GET / POST /accounts/{id}/r2/buckets/{bucket}/domains/custom). The POST body needs zone_id even though the endpoint is bucket-scoped (CF rejects with 'JSON not well formed' otherwise — caught live and added on the second iteration). Re-exported through provider/mod.rs + cloud/src/lib.rs. (2) crates/yah/cloud/src/reconciler/domain.rs — new module with ensure_r2_custom_domain(account_id, bucket, domain) mirroring static_asset::ensure_r2_bucket's list-first idempotency. Resolves the parent zone id via the existing CloudflareClient::zone_id_for_name and a parent_zone_name(domain) heuristic that takes the last two labels (correct for every yah-owned zone today; the doc comment names the longest-suffix-match upgrade path for future three-label-apex zones). 3 unit tests cover apex / subdomain / deeper-subdomain. (3) crates/yah/cloud/src/reconciler/mod.rs — declared `pub mod domain` + re-exported ensure_r2_custom_domain. (4) app/yah/cli/src/cloud.rs — new DomainOutcome enum + a post-services domain pass in handle_apply that walks cfg.domains, dispatches the R2-custom-domain shape (cdn_bucket set, no [[routes]]), and routes routed-shape domains (yah-dev, app-yah-dev) into a Skipped row labelled 'has [[routes]] — Worker-routed shape'. Gated on a cloudflare provider being declared (pond-only setups print 'skip domain pass: no cloudflare provider declared'). Originally also gated on empty --service filter; that gate dropped on review — domains are workspace-scoped and the operator wants them reconciled even when narrowing services. New print_domain_summary mirrors print_apply_summary's table + JSON output. Required CF token scopes (verified live): Workers R2 Storage: Edit + Zone: Read. The existing cloudflare-api-token slot carries both.\n\nLive verification command + transcript:\n\n $ ./target/debug/yah cloud apply --env cloud --service yah-desktop\n ==> yah-desktop/cloud: reconciling 2 component(s)\n component desktop (kind=binary)\n component whisper-models (kind=static-asset)\n ==> domain cdn-yah-dev (cdn.yah.dev): ensuring R2 custom-domain binding on bucket yah-dev\n apply summary (cloud):\n yah-desktop ok 2 component(s) reconciled\n domain summary (cloud):\n cdn-yah-dev ok R2 custom domain bound\n $ dig +short cdn.yah.dev\n 104.21.43.100\n 172.67.178.4\n $ curl -sI https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin | head -4\n HTTP/2 200\n content-length: 584567555\n\nUnblocks R422-T13's client-side `cdn_fallback = \"https://cdn.yah.dev/yah-desktop/whisper/{blake3}\"` — the URL now actually resolves and serves the bytes.")
62//! @yah:verify("cargo test -p cloud --lib reconciler::domain --locked # 3 pass")
63//! @yah:verify("cargo check --workspace --locked # clean")
64//! @yah:verify("./target/debug/yah cloud apply --env cloud --service yah-desktop # domain summary shows cdn-yah-dev=ok, yah-dev/app-yah-dev=skipped (routed)")
65//! @yah:verify("curl -sI https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin # HTTP/2 200, content-length 584567555")
66
67use std::collections::{BTreeMap, VecDeque};
68use std::path::{Path, PathBuf};
69use std::sync::Arc;
70
71use anyhow::{Context, Result};
72use async_trait::async_trait;
73use serde::{Deserialize, Serialize};
74use tokio::sync::{oneshot, Mutex as AsyncMutex};
75
76use workload_spec::{NamespaceId, TenantId};
77
78use crate::{GitSource, MirrorConfig, MirrorProviderSlot, ServiceComponent, ServiceConfig};
79
80pub mod bundle_store;
81pub(crate) mod cf_creds;
82pub mod cloudflare_worker;
83pub mod container;
84pub mod derive_cache_prune;
85pub mod domain;
86pub mod ingress;
87pub mod local_process;
88pub mod mesofact_bundle;
89pub mod mesofact_static;
90mod native_support;
91pub mod pg_driver;
92pub mod pond;
93pub mod pond_door;
94pub mod pond_publish;
95pub mod publish_beacon;
96pub mod r2_publish;
97pub mod service_discovery;
98pub mod static_asset;
99pub mod static_asset_prune;
100pub mod sync_status;
101
102#[cfg(test)]
103mod lowering_golden;
104
105pub use bundle_store::{publish_bundle_to_r2, PublishReport as BundlePublishReport};
106pub use cloudflare_worker::CloudflareWorkerReconciler;
107pub use container::{ContainerOptions, ContainerReconciler};
108pub use derive_cache_prune::{
109 collect_live_derive_hashes, compute_derive_cache_candidates, execute_derive_cache_prune,
110 DeriveCacheLiveHashes, DerivePruneCandidate,
111};
112pub use domain::ensure_r2_custom_domain;
113pub use ingress::{
114 collate_front_doors, declared as ingress_declared, ensure_tunnel_ingress, plan_ingress,
115 publish_tunnel_ingress, resolve_ingress_placements, Collation, IngressPlan, IngressRule,
116 NodeFrontDoor, PlannedEdge, TunnelIngressOutcome,
117};
118pub use local_process::LocalProcessReconciler;
119pub use mesofact_bundle::{
120 resolve_bundle_machines, BundleSlot, MesofactBundleReconciler, RevalidateSlot,
121 SLOT_ROLE as BUNDLE_SLOT_ROLE,
122};
123pub use mesofact_static::{LocalStaticOptions, MesofactStaticReconciler};
124pub use pond::{PondOptions, PondState};
125pub use pond_door::{
126 door_env, door_state_dir, ensure_pond_cert, ensure_pond_cert_as, is_root, plan_pond_door,
127 pond_hostname, resolve_passway_binary, spawn_pond_door, CertPair, PondDoorPlan,
128 DEFAULT_DOOR_PORT, POND_TLD,
129};
130pub use pond_publish::{derive_minio_key, publish_to_pond, PondPublishReport};
131pub use r2_publish::{
132 publish_to_r2, R2PublishReport, R2PurgeOpts, R2_ACCESS_KEY_ENV, R2_ACCESS_KEY_SLOT,
133 R2_SECRET_KEY_ENV, R2_SECRET_KEY_SLOT,
134};
135pub use service_discovery::{
136 DiscoveredRecord, RecordVisibility, ServiceRecordFanout, UnknownReason,
137};
138pub use static_asset::StaticAssetReconciler;
139pub use static_asset_prune::{
140 compute_live_set, compute_prune_candidates, execute_prune, load_service_and_mirror,
141 PruneCandidate, PruneOutcome, PruneReport,
142};
143pub use sync_status::{
144 compute_cell, compute_service, new_sync_id, summarize, CellStatus, DriftEntry, HealthState,
145 MirrorObservation, Runtime, ServiceStatus, StatusSummary, SyncHistoryEntry, SyncOutcome,
146 SyncState, WireContainerStatus,
147};
148
149// ─── Log buffer ─────────────────────────────────────────────────────────────
150
151const LOG_CAP: usize = 500;
152
153#[derive(Debug, Default)]
154struct LogRing {
155 lines: VecDeque<String>,
156 /// Monotonically increasing total lines ever pushed (never decrements).
157 total: usize,
158}
159
160/// Bounded ring buffer for child-process stdout/stderr (R263-F3).
161/// Shared between the reader tasks and the Tauri `mirror_run_logs` command.
162#[derive(Debug, Clone, Default)]
163pub struct LogBuffer(Arc<AsyncMutex<LogRing>>);
164
165impl LogBuffer {
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 /// Append a line; drops the oldest entry when over capacity.
171 pub async fn push(&self, line: String) {
172 let mut ring = self.0.lock().await;
173 ring.total += 1;
174 ring.lines.push_back(line);
175 if ring.lines.len() > LOG_CAP {
176 ring.lines.pop_front();
177 }
178 }
179
180 /// Return lines not yet seen by the caller.
181 ///
182 /// `since` is the `total` cursor from the previous call (0 = nothing
183 /// seen yet). Returns `(new_lines, new_cursor)`. Pass `new_cursor` back
184 /// on the next call to receive only incremental output.
185 pub async fn since(&self, since: usize) -> (Vec<String>, usize) {
186 let ring = self.0.lock().await;
187 let oldest = ring.total.saturating_sub(ring.lines.len());
188 let skip = since.saturating_sub(oldest);
189 let new_lines: Vec<String> = ring.lines.iter().skip(skip).cloned().collect();
190 (new_lines, ring.total)
191 }
192
193 /// Current write cursor — the `total` [`Self::since`] would hand back
194 /// right now if nothing more were pushed. Lets a producer mark a boundary
195 /// (e.g. "everything before this point was the build phase") for a later
196 /// reader to seek past without re-reading lines it doesn't want.
197 pub async fn cursor(&self) -> usize {
198 self.0.lock().await.total
199 }
200}
201
202/// Shared cell for one phase-boundary cursor a reconciler can publish
203/// mid-`up()`, so a poller sees a multi-phase bring-up's internal transition
204/// (e.g. build → run) before the whole call returns — the same problem
205/// [`LogBuffer`] solves for output, for a single position instead of a ring.
206/// `None` until the reconciler reaches that phase; a caller registers one
207/// before calling `up()` to observe it live, same pattern as
208/// [`LogBuffer::clone`]-and-hand-in.
209#[derive(Debug, Clone, Default)]
210pub struct PhaseCursor(Arc<AsyncMutex<Option<usize>>>);
211
212impl PhaseCursor {
213 pub fn new() -> Self {
214 Self::default()
215 }
216
217 pub async fn set(&self, cursor: usize) {
218 *self.0.lock().await = Some(cursor);
219 }
220
221 pub async fn get(&self) -> Option<usize> {
222 *self.0.lock().await
223 }
224}
225
226/// The `(tenant, namespace)` a bring-up is scoped to (W206). Reconcilers that
227/// touch a credentialed provider resolve it at this scope
228/// ([`CfProvider::resolve_scoped`](super::reconciler::cf_creds)) so a namespace's
229/// Cloudflare zone/account/keystore slots come from its own scope rather than the
230/// workspace-global defaults. Defaults to the singleton `(default, default)`,
231/// which collapses every scoped lookup back to the historical global slots — so
232/// single-namespace deployments are unaffected.
233#[derive(Debug, Clone)]
234pub struct ProviderScope {
235 pub tenant: TenantId,
236 pub namespace: NamespaceId,
237}
238
239impl ProviderScope {
240 /// The degenerate single-tenant / single-namespace scope. Scoped provider
241 /// lookups made against it resolve to the pre-W206 global keystore slots.
242 pub fn singleton() -> Self {
243 Self {
244 tenant: TenantId::singleton(),
245 namespace: NamespaceId::singleton(),
246 }
247 }
248}
249
250impl Default for ProviderScope {
251 fn default() -> Self {
252 Self::singleton()
253 }
254}
255
256/// Inputs a reconciler sees for one bring-up.
257pub struct ReconcileCtx<'a> {
258 /// Workspace root (parent of `.yah/`). Used to resolve relative paths
259 /// on the component.
260 pub workspace_root: &'a Path,
261 /// Service that owns the component.
262 pub service: &'a ServiceConfig,
263 /// Component being brought up.
264 pub component: &'a ServiceComponent,
265 /// Mirror manifest the bring-up targets.
266 pub mirror: &'a MirrorConfig,
267 /// Environment name (file stem of `mirrors/<env>.toml`).
268 pub env: &'a str,
269 /// `(tenant, namespace)` this bring-up is scoped to (W206). Credentialed
270 /// providers resolve at this scope; defaults to [`ProviderScope::singleton`].
271 pub scope: ProviderScope,
272}
273
274impl<'a> ReconcileCtx<'a> {
275 /// Absolute path to the component's workload directory (the parent of
276 /// `workload.toml`).
277 ///
278 /// In-tree components resolve to `<workspace_root>/<path>`. For
279 /// `git`-sourced components (R561-F1, "BYO git") this points into the
280 /// local clone — `<source_cache>/<subdir>/<path>` — which is empty until
281 /// [`materialize`](Self::materialize) runs (approach A: clone-at-reconcile,
282 /// so config load + validation stay offline).
283 pub fn workload_dir(&self) -> PathBuf {
284 match &self.component.git {
285 None => self.workspace_root.join(&self.component.path),
286 Some(git) => {
287 let mut dir = self.source_cache_dir();
288 if let Some(subdir) = &git.subdir {
289 dir = dir.join(subdir);
290 }
291 dir.join(&self.component.path)
292 }
293 }
294 }
295
296 /// Root of the local clone for a `git`-sourced component:
297 /// `<workspace_root>/.yah/infra/state/sources/<service>/<component_id>`.
298 fn source_cache_dir(&self) -> PathBuf {
299 self.workspace_root
300 .join(".yah/infra/state/sources")
301 .join(&self.service.name)
302 .join(&self.component.id)
303 }
304
305 /// Ensure a `git`-sourced component's code is present locally before build
306 /// (R561-F1, approach A). No-op for in-tree components. Idempotent: clones
307 /// on the first call, fetches + re-checks-out the pinned ref thereafter.
308 ///
309 /// Reconcilers MUST call this at the top of [`up`](Reconciler::up) before
310 /// reading [`workload_dir`](Self::workload_dir) for a remote component.
311 pub async fn materialize(&self) -> Result<()> {
312 let Some(git) = &self.component.git else {
313 return Ok(());
314 };
315 materialize_git_source(git, &self.source_cache_dir())
316 .await
317 .with_context(|| {
318 format!(
319 "materializing git source {}@{} for {}/{}",
320 git.repo, git.r#ref, self.service.name, self.component.id
321 )
322 })
323 }
324
325 /// Read `<workload_dir>/workload.toml` and extract just the `kind`
326 /// discriminator.
327 ///
328 /// Why this and not the strongly-typed [`workload_spec::Workload`]
329 /// parse: the on-disk `schema_version = 1` form predates the
330 /// `SchemaVersion::V1` enum and won't round-trip through the strong
331 /// types until B3 lands (see `crates/yah/cloud/src/config.rs` test
332 /// `web_workload_round_trips`). Reconcilers only need the kind to
333 /// dispatch; per-kind tooling (e.g. `mesofact-dev`'s
334 /// `WatchOptions::from_workload`) does its own parsing for the
335 /// build/out_dir fields it cares about.
336 pub fn workload_kind(&self) -> Result<String> {
337 workload_kind(&self.workload_dir())
338 }
339
340 /// Look up a provider slot by role (e.g. `"static"`, `"compute"`).
341 ///
342 /// Tries the component-qualified key first (`"<role>:<component id>"`)
343 /// before falling back to the bare role. A mirror role is normally
344 /// service-wide — one `providers.static` slot serves every static-kind
345 /// component — but a service can declare more than one component with
346 /// the same role (e.g. two `mesofact-static`/`mesofact-spa` components
347 /// sharing one mirror), and those need distinct ports to ever both come
348 /// up. The qualified key is how a mirror opts a specific component out
349 /// of sharing the bare-role slot:
350 ///
351 /// ```toml
352 /// [providers."static:site"]
353 /// kind = "local-static"
354 /// port = 4331
355 ///
356 /// [providers."static:app"]
357 /// kind = "local-static"
358 /// port = 4332
359 /// ```
360 ///
361 /// A mirror with only the bare role (the common, single-component case)
362 /// is unaffected — the qualified lookup misses and falls through.
363 pub fn slot(&self, role: &str) -> Option<&'a MirrorProviderSlot> {
364 let qualified = format!("{role}:{}", self.component.id);
365 self.mirror
366 .providers
367 .get(qualified.as_str())
368 .or_else(|| self.mirror.providers.get(role))
369 }
370}
371
372/// An explicit teardown hook for a workload this process did not spawn as a
373/// child — see [`RunningWorkload::with_teardown`] (R714-B1).
374///
375/// Boxed rather than a generic parameter because [`RunningWorkload`] is stored
376/// in heterogeneous collections (the desktop's mirror registry) and cannot
377/// carry a type parameter.
378/// `Sync` on the boxed closure is load-bearing, not belt-and-braces: without
379/// it `RunningWorkload` stops being `Sync`, so `&RunningWorkload` stops being
380/// `Send`, and every desktop `#[tauri::command]` that holds one across an
381/// `.await` (`mirror_run_logs` iterates the registry's handles) fails to
382/// compile with "future cannot be sent between threads safely". The captures a
383/// teardown needs — a container name and a workspace root — are `Sync` anyway.
384type TeardownFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>;
385type TeardownFn = Box<dyn FnOnce() -> TeardownFuture + Send + Sync + 'static>;
386
387/// Newtype so [`RunningWorkload`] can keep its `#[derive(Debug)]` — a boxed
388/// closure is not `Debug`.
389struct Teardown(TeardownFn);
390
391impl std::fmt::Debug for Teardown {
392 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 f.write_str("Teardown(<fn>)")
394 }
395}
396
397/// Handle to a workload that's been brought up. Owns the lifecycle: drop
398/// or call [`RunningWorkload::shutdown`] to take it back down.
399#[derive(Debug)]
400pub struct RunningWorkload {
401 /// Workload kind that was reconciled (e.g. `"mesofact-static"`).
402 pub kind: String,
403 /// Slot role this workload occupies on the mirror (e.g. `"static"`).
404 pub slot: String,
405 /// Local URL the workload exposes, when applicable. `None` for
406 /// workloads that publish to a non-local artifact store (e.g. R2).
407 pub dev_url: Option<String>,
408 /// Notional URL of the deployed artifact in the production case
409 /// (e.g. `https://yah.dev`). `None` until Cloudflare/R2 wiring lands.
410 pub public_url: Option<String>,
411 /// Secondary local UI console, if the workload exposes one (e.g. MinIO
412 /// console on a pond tier). Surfaced as a separate chip in the Services
413 /// matrix next to `dev_url`.
414 pub console_url: Option<String>,
415 /// Ring buffer for stdout/stderr from the workload's child process.
416 /// `None` for workloads that don't capture stdio (e.g. container-backed).
417 pub log_buffer: Option<LogBuffer>,
418
419 /// R546-B12: human-readable lines the reconciler wants the operator to see
420 /// on THIS run — what it actually did, not what is configured. A clean
421 /// static-asset reconcile used to print nothing at all, so a successful
422 /// publish and a successful no-op were indistinguishable at the apply
423 /// surface, and the one view that would have disambiguated them (`yah cloud
424 /// status`) was itself blind.
425 ///
426 /// Deliberately NOT on [`RunningWorkloadSummary`]: that type is serialized
427 /// across the process boundary to the desktop UI, and this is per-run
428 /// console output, not state the UI should cache.
429 pub notes: Vec<String>,
430
431 /// Sender that signals the supervisor task to tear down. Closing the
432 /// channel (drop) is equivalent to sending — supervisor exits on
433 /// channel close.
434 shutdown: Option<oneshot::Sender<()>>,
435 /// Joinable task that owns any child process and reaps it on signal.
436 supervisor: Option<tokio::task::JoinHandle<Result<()>>>,
437 /// R714-B1: teardown for a workload that runs OUTSIDE this process, so
438 /// there is no child to reap and no supervisor to signal.
439 ///
440 /// Deliberately run from [`RunningWorkload::shutdown`] only, never from
441 /// `Drop`. The two are different intents and conflating them breaks both
442 /// directions: a container the desktop started is meant to outlive the
443 /// desktop (the next launch re-adopts it with `adopt_only`), so quitting
444 /// the app must not `docker rm -f` it; but the ■ button IS an explicit
445 /// stop, and must.
446 teardown: Option<Teardown>,
447
448 /// R715-F4: where to ask this workload for a live status document, when
449 /// it declared a process-control channel (W315). `None` for a workload
450 /// with no channel — polling is then simply skipped, not an error.
451 ///
452 /// The desktop holds `RunningWorkload` in-process (it links this crate
453 /// directly, unlike the ad-hoc `run.spawn` path which lives behind the
454 /// camp daemon's socket), so a live poll is [`crate::proc_control::fetch_status`]
455 /// called straight against this endpoint — no RPC hop, no handle registry.
456 control: Option<crate::proc_control::ControlEndpoint>,
457
458 /// [`LogBuffer`] cursor marking the end of the build phase, for a
459 /// component that was compiled before being spawned (`local-process`
460 /// with `cargo_package` set). Lines before this index in `log_buffer` are
461 /// `cargo build` output; lines at or after are the spawned process's own
462 /// stdout/stderr. `None` when nothing was built (no `cargo_package`, or a
463 /// reconciler that predates this field).
464 pub build_log_end: Option<usize>,
465}
466
467impl RunningWorkload {
468 /// Create a handle for a workload that's already running externally
469 /// (e.g. embedded in yah-camp). No subprocess is owned; shutdown is a
470 /// no-op so the caller can call `shutdown()` uniformly.
471 pub fn adopted(
472 kind: impl Into<String>,
473 slot: impl Into<String>,
474 dev_url: Option<String>,
475 ) -> Self {
476 Self {
477 kind: kind.into(),
478 slot: slot.into(),
479 dev_url,
480 public_url: None,
481 console_url: None,
482 log_buffer: None,
483 notes: Vec::new(),
484 shutdown: None,
485 supervisor: None,
486 teardown: None,
487 control: None,
488 build_log_end: None,
489 }
490 }
491
492 /// Attach an explicit teardown to a handle for an externally-running
493 /// workload (R714-B1).
494 ///
495 /// `adopted()` alone gives a handle whose `shutdown()` is a documented
496 /// no-op. That is right for workloads another process owns and will keep
497 /// re-asserting (pond containers under camp's yubaba), and wrong for ones
498 /// this process started and nobody else will ever stop — for those the ■
499 /// button reported success while the container kept running.
500 ///
501 /// `teardown` runs on `shutdown()` and NOT on `Drop`; see [`Self::teardown`].
502 pub fn with_teardown<F, Fut>(mut self, teardown: F) -> Self
503 where
504 F: FnOnce() -> Fut + Send + Sync + 'static,
505 Fut: std::future::Future<Output = Result<()>> + Send + 'static,
506 {
507 self.teardown = Some(Teardown(Box::new(move || Box::pin(teardown()))));
508 self
509 }
510
511 /// Attach per-run operator-facing lines (R546-B12). See [`Self::notes`].
512 pub fn with_notes(mut self, notes: Vec<String>) -> Self {
513 self.notes = notes;
514 self
515 }
516
517 /// Record where to poll this workload's process-control channel, when it
518 /// declared one (R715-F4). A no-op (leaves `control: None`) when the
519 /// argument is `None` — callers can pass the reconciler's resolved
520 /// endpoint straight through without an `if let`.
521 pub fn with_control(mut self, control: Option<crate::proc_control::ControlEndpoint>) -> Self {
522 self.control = control;
523 self
524 }
525
526 /// Ask this workload's process-control channel for a live status
527 /// document (R715-F4). `None` when no channel was declared, or when the
528 /// endpoint didn't answer — both are "nothing new to show", not errors;
529 /// see [`crate::proc_control::fetch_status`] for why a poll failure isn't
530 /// itself meaningful.
531 pub async fn poll_control(&self) -> Option<crate::proc_control::ProcStatus> {
532 let endpoint = self.control.as_ref()?;
533 crate::proc_control::fetch_status(endpoint).await.ok()
534 }
535
536 /// Whether the supervisor task that owns this workload's child process is
537 /// still running. `spawn_native_log_supervisor` (native_support.rs) exits
538 /// as soon as `NativeRuntime::get_workload` reports a terminal state —
539 /// which itself comes from a real `child.wait()` in kamaji's native
540 /// backend, so this catches a crash (segfault, panic, `SIGKILL`) the same
541 /// way it catches a clean exit, not just an unresponsive process.
542 ///
543 /// A workload with no supervisor (`RunningWorkload::adopted` — runs
544 /// outside this process, e.g. a pond container camp re-asserts) has
545 /// nothing to check here and reports alive unconditionally; its liveness
546 /// is whatever tracks it, not this handle.
547 pub fn is_alive(&self) -> bool {
548 self.supervisor.as_ref().is_none_or(|h| !h.is_finished())
549 }
550
551 /// Record where the build phase ends in `log_buffer`, for a component
552 /// that was compiled before being spawned. See [`Self::build_log_end`].
553 pub fn with_build_log_end(mut self, cursor: Option<usize>) -> Self {
554 self.build_log_end = cursor;
555 self
556 }
557
558 /// Set the public URL for a published workload (e.g. `"https://yah.dev"`).
559 pub fn with_public_url(mut self, url: impl Into<String>) -> Self {
560 self.public_url = Some(url.into());
561 self
562 }
563
564 /// Set the console URL for a workload that exposes a secondary local UI
565 /// (e.g. MinIO console on a pond tier).
566 pub fn with_console_url(mut self, url: impl Into<String>) -> Self {
567 self.console_url = Some(url.into());
568 self
569 }
570
571 /// Gracefully tear down: signal the supervisor, await its exit, then run
572 /// any explicit teardown hook.
573 ///
574 /// The hook runs LAST and its error propagates. A stop that could not tear
575 /// the workload down must surface as an error, never as a silent success —
576 /// that silence is the whole of R714-B1.
577 pub async fn shutdown(mut self) -> Result<()> {
578 if let Some(tx) = self.shutdown.take() {
579 let _ = tx.send(());
580 }
581 if let Some(handle) = self.supervisor.take() {
582 handle
583 .await
584 .context("joining workload supervisor")?
585 .context("workload supervisor")?;
586 }
587 if let Some(Teardown(hook)) = self.teardown.take() {
588 hook().await.context("workload teardown")?;
589 }
590 Ok(())
591 }
592}
593
594impl Drop for RunningWorkload {
595 fn drop(&mut self) {
596 // Best-effort signal. The supervisor task is detached and will
597 // reap its child when it observes the closed channel.
598 if let Some(tx) = self.shutdown.take() {
599 let _ = tx.send(());
600 }
601 }
602}
603
604/// Bring one workload up. Each impl handles one [`ServiceComponent::kind`].
605#[async_trait]
606pub trait Reconciler: Send + Sync {
607 /// Workload kind this reconciler handles (matches `ServiceComponent.kind`).
608 fn kind(&self) -> &'static str;
609
610 /// Bring the workload up. Returns a handle whose lifecycle is tied to
611 /// the mirror being up.
612 async fn up(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload>;
613}
614
615/// Read `<workload_dir>/workload.toml` and return just the `kind` field.
616/// See [`ReconcileCtx::workload_kind`] for why we don't deserialize through
617/// the strong types yet.
618pub fn workload_kind(workload_dir: &Path) -> Result<String> {
619 let path = workload_dir.join("workload.toml");
620 let src =
621 std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
622 let value: toml::Value =
623 toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
624 let kind = value
625 .get("kind")
626 .and_then(|v| v.as_str())
627 .with_context(|| format!("{}: missing `kind` field", path.display()))?;
628 Ok(kind.to_string())
629}
630
631/// Shallow-clone (or update) a [`GitSource`] into `dir` (R561-F1). Idempotent:
632/// clones when `dir/.git` is absent, otherwise fetches the pinned ref and
633/// force-checks-it-out. Uses the system `git` so it inherits the operator's
634/// credential helpers / SSH agent — no in-process git library.
635///
636/// `pub` (R615-T3 / W274): `yah infra sync` reuses this verbatim for
637/// `InfraSourceKind::Git` sources rather than a second shallow-clone-or-pull
638/// implementation — same "one git-source shape, reused" discipline R615-F1
639/// already applied to the type.
640pub async fn materialize_git_source(git: &GitSource, dir: &Path) -> Result<()> {
641 use tokio::process::Command;
642
643 async fn run_git(args: &[&std::ffi::OsStr]) -> Result<()> {
644 let out = Command::new("git")
645 .args(args)
646 .output()
647 .await
648 .context("spawning git")?;
649 if !out.status.success() {
650 anyhow::bail!(
651 "git {} failed: {}",
652 args.iter()
653 .map(|a| a.to_string_lossy())
654 .collect::<Vec<_>>()
655 .join(" "),
656 String::from_utf8_lossy(&out.stderr).trim()
657 );
658 }
659 Ok(())
660 }
661
662 use std::ffi::OsStr;
663 let dir_os = dir.as_os_str();
664 let r#ref = git.r#ref.as_str();
665
666 if dir.join(".git").is_dir() {
667 // Existing checkout — update to the pinned ref.
668 run_git(&[
669 OsStr::new("-C"),
670 dir_os,
671 OsStr::new("fetch"),
672 OsStr::new("--depth"),
673 OsStr::new("1"),
674 OsStr::new("origin"),
675 OsStr::new(r#ref),
676 ])
677 .await?;
678 run_git(&[
679 OsStr::new("-C"),
680 dir_os,
681 OsStr::new("checkout"),
682 OsStr::new("--force"),
683 OsStr::new("FETCH_HEAD"),
684 ])
685 .await?;
686 } else {
687 if let Some(parent) = dir.parent() {
688 tokio::fs::create_dir_all(parent)
689 .await
690 .with_context(|| format!("creating {}", parent.display()))?;
691 }
692 // `--branch` accepts a branch or tag. Pinning to a bare commit SHA is a
693 // follow-up (needs clone-then-fetch); the common case is a branch/tag.
694 run_git(&[
695 OsStr::new("clone"),
696 OsStr::new("--depth"),
697 OsStr::new("1"),
698 OsStr::new("--branch"),
699 OsStr::new(r#ref),
700 OsStr::new(git.repo.as_str()),
701 dir_os,
702 ])
703 .await?;
704 }
705 Ok(())
706}
707
708/// Build a `RunningWorkload` from the pieces a reconciler produces.
709pub(crate) fn into_running(
710 kind: impl Into<String>,
711 slot: impl Into<String>,
712 dev_url: Option<String>,
713 public_url: Option<String>,
714 log_buffer: Option<LogBuffer>,
715 shutdown: oneshot::Sender<()>,
716 supervisor: tokio::task::JoinHandle<Result<()>>,
717) -> RunningWorkload {
718 RunningWorkload {
719 kind: kind.into(),
720 slot: slot.into(),
721 dev_url,
722 public_url,
723 console_url: None,
724 log_buffer,
725 notes: Vec::new(),
726 shutdown: Some(shutdown),
727 supervisor: Some(supervisor),
728 teardown: None,
729 control: None,
730 build_log_end: None,
731 }
732}
733
734/// Wait for a TCP port to start accepting connections. Returns `true` if
735/// the port came up within `timeout`, `false` otherwise. Useful for
736/// reconcilers that spawn a server and need to know when it's reachable
737/// before reporting success.
738pub(crate) async fn wait_for_port(
739 addr: std::net::SocketAddr,
740 timeout: std::time::Duration,
741) -> bool {
742 let deadline = tokio::time::Instant::now() + timeout;
743 loop {
744 if tokio::net::TcpStream::connect(addr).await.is_ok() {
745 return true;
746 }
747 if tokio::time::Instant::now() >= deadline {
748 return false;
749 }
750 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
751 }
752}
753
754// `wait_for_http_ready` lived here pre-R374-F3 to back the MinIO health
755// probe in pond's bring-up path. That logic moved to
756// `local_driver::pond_minio::wait_for_http_ready` so yubaba + cloud share
757// it. The mesofact-static reconciler arm uses [`wait_for_port`] for
758// dev-tier port readiness; nothing else needs an HTTP-level probe today.
759
760/// Pluck a `u16` out of a [`MirrorProviderSlot`]'s inline `fields` map.
761/// Returns `None` if the key is absent or out of range.
762pub(crate) fn slot_field_u16(fields: &BTreeMap<String, toml::Value>, key: &str) -> Option<u16> {
763 fields
764 .get(key)
765 .and_then(|v| v.as_integer())
766 .and_then(|n| u16::try_from(n).ok())
767}
768
769/// Serializable summary of a running workload — what the desktop / CLI
770/// hands to the UI. Subset of [`RunningWorkload`] that's safe to cross
771/// process boundaries.
772#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
773pub struct RunningWorkloadSummary {
774 pub kind: String,
775 pub slot: String,
776 pub dev_url: Option<String>,
777 pub public_url: Option<String>,
778 pub console_url: Option<String>,
779 /// Operator-facing lines from [`RunningWorkload::notes`] (R546-B12).
780 ///
781 /// These used to stop here — the summary dropped them, so every note a
782 /// reconciler attached was written into a struct nobody read. They matter
783 /// most for a workload with no `dev_url` to click (R715-T2): the notes are
784 /// then the only structured thing the Run tab has to show about it.
785 #[serde(default, skip_serializing_if = "Vec::is_empty")]
786 pub notes: Vec<String>,
787 /// See [`RunningWorkload::build_log_end`]. Lets a log-tail consumer skip
788 /// straight to run-phase output, or show everything from 0 when the
789 /// operator wants the build log too (e.g. after a compile failure).
790 #[serde(default, skip_serializing_if = "Option::is_none")]
791 pub build_log_end: Option<usize>,
792}
793
794impl From<&RunningWorkload> for RunningWorkloadSummary {
795 fn from(r: &RunningWorkload) -> Self {
796 Self {
797 kind: r.kind.clone(),
798 slot: r.slot.clone(),
799 dev_url: r.dev_url.clone(),
800 public_url: r.public_url.clone(),
801 console_url: r.console_url.clone(),
802 notes: r.notes.clone(),
803 build_log_end: r.build_log_end,
804 }
805 }
806}
807
808#[cfg(test)]
809mod source_seam_tests {
810 //! R561-F1 — the BYO-git source seam: path resolution + materialization.
811 use super::*;
812 use std::collections::BTreeMap;
813
814 fn component(git: Option<GitSource>) -> ServiceComponent {
815 ServiceComponent {
816 mount: None,
817 id: "site".into(),
818 kind: "mesofact-static".into(),
819 path: "site".into(),
820 role: "static".into(),
821 publishes: None,
822 wave: 0,
823 git,
824 }
825 }
826
827 fn service(comp: ServiceComponent) -> ServiceConfig {
828 ServiceConfig {
829 schema_version: 1,
830 name: "scrabcake".into(),
831 domain: "scrabcake.example".into(),
832 components: vec![comp],
833 db: crate::DbCatalog::default(),
834 }
835 }
836
837 fn mirror() -> MirrorConfig {
838 MirrorConfig {
839 schema_version: 1,
840 shape: crate::MirrorShape::Local,
841 providers: BTreeMap::new(),
842 ingress: Default::default(),
843 ingress_machines: Vec::new(),
844 drivers: Default::default(),
845 asset_aliases: BTreeMap::new(),
846 }
847 }
848
849 fn ctx<'a>(ws: &'a Path, svc: &'a ServiceConfig, mir: &'a MirrorConfig) -> ReconcileCtx<'a> {
850 ReconcileCtx {
851 workspace_root: ws,
852 service: svc,
853 component: &svc.components[0],
854 mirror: mir,
855 env: "dev",
856 scope: ProviderScope::singleton(),
857 }
858 }
859
860 #[test]
861 fn workload_dir_in_tree_joins_workspace_root() {
862 let svc = service(component(None));
863 let mir = mirror();
864 assert_eq!(
865 ctx(Path::new("/ws"), &svc, &mir).workload_dir(),
866 Path::new("/ws/site")
867 );
868 }
869
870 #[test]
871 fn workload_dir_git_resolves_into_source_cache_with_subdir() {
872 let git = GitSource {
873 repo: "https://example.com/r.git".into(),
874 r#ref: "main".into(),
875 subdir: Some("apps".into()),
876 };
877 let svc = service(component(Some(git)));
878 let mir = mirror();
879 assert_eq!(
880 ctx(Path::new("/ws"), &svc, &mir).workload_dir(),
881 Path::new("/ws/.yah/infra/state/sources/scrabcake/site/apps/site")
882 );
883 }
884
885 #[tokio::test]
886 async fn materialize_is_noop_for_in_tree_component() {
887 let svc = service(component(None));
888 let mir = mirror();
889 // No git source → Ok, and nothing is written under the workspace.
890 ctx(Path::new("/nonexistent-ws"), &svc, &mir)
891 .materialize()
892 .await
893 .unwrap();
894 }
895
896 #[tokio::test]
897 async fn materialize_clones_git_source_offline() {
898 fn git(args: &[&str], cwd: &Path) {
899 let out = std::process::Command::new("git")
900 .args(args)
901 .current_dir(cwd)
902 .env("GIT_AUTHOR_NAME", "t")
903 .env("GIT_AUTHOR_EMAIL", "t@t")
904 .env("GIT_COMMITTER_NAME", "t")
905 .env("GIT_COMMITTER_EMAIL", "t@t")
906 .output()
907 .unwrap();
908 assert!(
909 out.status.success(),
910 "git {args:?}: {}",
911 String::from_utf8_lossy(&out.stderr)
912 );
913 }
914
915 let tmp = tempfile::tempdir().unwrap();
916 let src = tmp.path().join("src-repo");
917 std::fs::create_dir_all(&src).unwrap();
918 git(&["init", "-b", "main"], &src);
919 std::fs::write(src.join("hello.txt"), "hi").unwrap();
920 git(&["add", "."], &src);
921 git(&["commit", "-m", "init"], &src);
922
923 let source = GitSource {
924 repo: format!("file://{}", src.display()),
925 r#ref: "main".into(),
926 subdir: None,
927 };
928 let dest = tmp.path().join("cache");
929
930 // First call clones.
931 materialize_git_source(&source, &dest).await.unwrap();
932 assert!(dest.join("hello.txt").is_file());
933
934 // Second call takes the update path and stays green (idempotent).
935 materialize_git_source(&source, &dest).await.unwrap();
936 assert!(dest.join("hello.txt").is_file());
937 }
938}
939
940#[cfg(test)]
941mod teardown_tests {
942 //! R714-B1 — the explicit-teardown contract on [`RunningWorkload`].
943 //!
944 //! These are about WHEN the hook runs, not what it does. The bug being
945 //! fixed was a `shutdown()` that reported success having done nothing, and
946 //! the trap in fixing it is a `Drop` that tears down a container which is
947 //! supposed to survive the process.
948 use super::*;
949 use std::sync::atomic::{AtomicUsize, Ordering};
950
951 fn counting() -> (RunningWorkload, Arc<AtomicUsize>) {
952 let hits = Arc::new(AtomicUsize::new(0));
953 let seen = hits.clone();
954 let w = RunningWorkload::adopted("container", "compute", None)
955 .with_teardown(move || {
956 let seen = seen.clone();
957 async move {
958 seen.fetch_add(1, Ordering::SeqCst);
959 Ok(())
960 }
961 });
962 (w, hits)
963 }
964
965 /// Attaching a teardown must not cost `RunningWorkload` its auto traits.
966 /// The desktop stores these handles in a shared registry and its Tauri
967 /// commands iterate them across `.await` points, which needs `Sync` — a
968 /// hook that is `Send` but not `Sync` takes it away here and surfaces two
969 /// crates over as "future cannot be sent between threads safely", with a
970 /// span pointing at `mirror_run_logs` rather than at this file.
971 #[test]
972 fn a_teardown_does_not_cost_the_handle_send_or_sync() {
973 fn assert_send_sync<T: Send + Sync>() {}
974 assert_send_sync::<RunningWorkload>();
975 }
976
977 #[tokio::test]
978 async fn shutdown_runs_the_teardown() {
979 let (w, hits) = counting();
980 w.shutdown().await.unwrap();
981 assert_eq!(hits.load(Ordering::SeqCst), 1);
982 }
983
984 #[tokio::test]
985 async fn dropping_the_handle_does_NOT_run_the_teardown() {
986 // A container this process started is meant to outlive it — the next
987 // launch re-adopts it. Quitting the app must not `docker rm -f` it.
988 let (w, hits) = counting();
989 drop(w);
990 // Yield so a stray spawned task would have had a chance to run.
991 tokio::task::yield_now().await;
992 assert_eq!(hits.load(Ordering::SeqCst), 0);
993 }
994
995 #[tokio::test]
996 async fn a_failing_teardown_makes_shutdown_fail() {
997 // The whole of R714-B1: a stop that could not tear the workload down
998 // must not report success.
999 let w = RunningWorkload::adopted("container", "compute", None)
1000 .with_teardown(|| async { anyhow::bail!("docker stop refused") });
1001 let err = w.shutdown().await.unwrap_err();
1002 assert!(format!("{err:#}").contains("docker stop refused"), "{err:#}");
1003 }
1004
1005 #[tokio::test]
1006 async fn an_adopted_handle_without_a_teardown_still_shuts_down_cleanly() {
1007 // Pond containers are owned by camp's yubaba and stop through
1008 // `workload.stop`; their no-op shutdown is correct and must stay.
1009 let w = RunningWorkload::adopted("mesofact-static", "static", None);
1010 w.shutdown().await.unwrap();
1011 }
1012
1013 #[tokio::test]
1014 async fn the_teardown_runs_after_the_supervisor_is_joined() {
1015 // Ordering matters for a workload that has both: reap the child first,
1016 // then remove the container it was talking to.
1017 let order = Arc::new(AsyncMutex::new(Vec::<&'static str>::new()));
1018 let (tx, rx) = oneshot::channel::<()>();
1019 let sup_order = order.clone();
1020 let supervisor = tokio::spawn(async move {
1021 let _ = rx.await;
1022 sup_order.lock().await.push("supervisor");
1023 Ok(())
1024 });
1025 let hook_order = order.clone();
1026 let w = into_running("container", "compute", None, None, None, tx, supervisor)
1027 .with_teardown(move || {
1028 let hook_order = hook_order.clone();
1029 async move {
1030 hook_order.lock().await.push("teardown");
1031 Ok(())
1032 }
1033 });
1034
1035 w.shutdown().await.unwrap();
1036 assert_eq!(*order.lock().await, vec!["supervisor", "teardown"]);
1037 }
1038}