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