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