Skip to main content

ryra_core/
plan.rs

1//! Typed steps the CLI executes, the warnings it surfaces, and the result
2//! shapes returned from `add` / `remove` / `reset`. Pattern matching ensures
3//! every step type is handled — no string parsing or if-chains.
4
5use std::path::PathBuf;
6
7use crate::generate::GeneratedFile;
8
9/// One port served over a service's Tailscale vIP: TLS-terminated at
10/// `https_port` on the service hostname, proxied to `http://127.0.0.1:<host_port>`.
11/// The entry with `https_port == 443` answers at the bare hostname (web root).
12#[derive(Debug, Clone)]
13pub struct TailscalePort {
14    pub https_port: u16,
15    pub host_port: u16,
16}
17
18/// Resolve which ports a service exposes over its Tailscale vIP.
19///
20/// Ports declaring `tailscale_https` are each served on that HTTPS port,
21/// mapped to their resolved host port. A service that declares none (every
22/// single-port web app — seafile, authelia, …) falls back to serving its
23/// primary port at the web root (`443`), preserving the original behaviour.
24pub fn tailscale_ports(
25    ports: &[crate::registry::service_def::PortDef],
26    resolved: &[(String, u16)],
27    primary_host_port: Option<u16>,
28) -> Vec<TailscalePort> {
29    let mapped: Vec<TailscalePort> = ports
30        .iter()
31        .filter_map(|p| {
32            let https_port = p.tailscale_https?;
33            let host_port = resolved
34                .iter()
35                .find(|(n, _)| n == &p.name)
36                .map(|(_, hp)| *hp)
37                .or(p.host_port)?;
38            Some(TailscalePort {
39                https_port,
40                host_port,
41            })
42        })
43        .collect();
44    if !mapped.is_empty() {
45        return mapped;
46    }
47    primary_host_port
48        .map(|host_port| {
49            vec![TailscalePort {
50                https_port: 443,
51                host_port,
52            }]
53        })
54        .unwrap_or_default()
55}
56
57/// A discrete operation that the CLI executes.
58pub enum Step {
59    /// Write a file.
60    WriteFile(GeneratedFile),
61    /// Create a symlink at `link` pointing to `target`. Idempotent: if
62    /// `link` already exists (whether as a file, dir, or symlink), it's
63    /// removed first. Used to satisfy systemd's fixed quadlet path
64    /// (`~/.config/containers/systemd/<svc>.container`) while keeping
65    /// the real file alongside the rest of the service's data in
66    /// `~/.local/share/services/<svc>/`.
67    Symlink { link: PathBuf, target: PathBuf },
68    /// Reload systemd for the current user.
69    DaemonReload,
70    /// Start a service under the current user's systemd.
71    StartService { unit: String },
72    /// Stop a service under the current user's systemd.
73    StopService { unit: String },
74    /// Restart a service under the current user's systemd.
75    RestartService { unit: String },
76    /// Reload Caddy's config without restarting the container.
77    ReloadCaddy,
78    /// Pull a container image.
79    PullImage { image: String },
80    /// Remove a file.
81    RemoveFile(PathBuf),
82    /// Remove a directory tree.
83    RemoveDir(PathBuf),
84    /// Remove a podman named volume.
85    RemoveVolume { name: String },
86    /// Remove a podman network. Best-effort: skipped when the network is
87    /// still in use by another service (which is the correct outcome) or
88    /// already gone. `ryra remove` emits this after stopping a service's
89    /// `<svc>-network` unit, because stopping a `RemainAfterExit` network
90    /// oneshot leaves the podman network behind — and that leak makes the
91    /// next install fail (its regenerated network unit's `podman network
92    /// create` hits the existing network).
93    RemoveNetwork { name: String },
94    /// Create a directory (with parents).
95    CreateDir(PathBuf),
96    /// Wait for a file to appear (with timeout).
97    WaitForFile { path: PathBuf, timeout_secs: u32 },
98    /// Copy a file from the registry (or similar source) to a destination.
99    /// Used for vendored binary files (e.g. Jellyfin's SSO plugin DLLs)
100    /// that don't fit the templated `configs/` pipeline.
101    CopyFile { src: PathBuf, dst: PathBuf },
102    /// Run a build/prepare command in `dir` (e.g. `cargo build --release`,
103    /// `bun install`) for a `runtime = "native"` service. Runs at apply time
104    /// in the service's source dir, before the unit is (re)started.
105    Build { dir: PathBuf, command: String },
106    /// First-time Tailscale Services setup on this tailnet: ensure ACL
107    /// has `tag:ryra-host` + `tag:ryra-service` tagOwners and the
108    /// services autoApprover entry, then apply `tag:ryra-host` to the
109    /// local node so it's allowed to advertise services. Idempotent:
110    /// reads current state via API and only writes diffs.
111    TailscaleSetup,
112    /// Define a Tailscale Service via the admin API and advertise it
113    /// from the host: `sudo tailscale serve --service=svc:<svc_name>
114    /// --https=443 http://127.0.0.1:<host_port>`. The service gets
115    /// `tag:ryra-service` (matches the autoApprover) so the host's
116    /// advertisement auto-approves with no manual UI clicks.
117    ///
118    /// `svc_name` is the part after `svc:` — already host-scoped at
119    /// planning time (`<service>-<host>`) so two ryra hosts on the
120    /// same tailnet can run independent copies of a service without
121    /// colliding on the global Tailscale Service namespace.
122    TailscaleEnable {
123        svc_name: String,
124        ports: Vec<TailscalePort>,
125    },
126    /// Stop advertising a Tailscale Service on this host and delete
127    /// its definition via the admin API. Used in `ryra remove --purge`
128    /// and `ryra reset` for tailscale-enabled services. `svc_name`
129    /// matches the value used at install time (recovered from the
130    /// stored Tailscale URL so a hostname change post-install doesn't
131    /// break teardown).
132    TailscaleDisable { svc_name: String },
133}
134
135impl Step {
136    /// Render this step as a shell command (for dry-run display).
137    pub fn to_command(&self) -> String {
138        match self {
139            Step::WriteFile(file) => format!("write {}", file.path.display()),
140            Step::Symlink { link, target } => {
141                format!("ln -sf {} {}", target.display(), link.display())
142            }
143            Step::DaemonReload => "systemctl --user daemon-reload".into(),
144            Step::StartService { unit } => format!("systemctl --user start {unit}"),
145            Step::StopService { unit } => format!("systemctl --user stop {unit}"),
146            Step::RestartService { unit } => format!("systemctl --user restart {unit}"),
147            Step::ReloadCaddy => {
148                "podman exec caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile"
149                    .into()
150            }
151            Step::PullImage { image } => format!("podman pull {image}"),
152            Step::RemoveFile(path) => format!("rm -f {}", path.display()),
153            Step::RemoveDir(path) => format!("rm -rf {}", path.display()),
154            Step::CreateDir(path) => format!("mkdir -p {}", path.display()),
155            Step::RemoveVolume { name } => format!("podman volume rm {name}"),
156            Step::RemoveNetwork { name } => format!("podman network rm {name}"),
157            Step::WaitForFile { path, timeout_secs } => {
158                format!("wait for {} (up to {timeout_secs}s)", path.display())
159            }
160            Step::CopyFile { src, dst } => format!("cp {} {}", src.display(), dst.display()),
161            Step::Build { dir, command } => format!("(cd {} && {command})", dir.display()),
162            Step::TailscaleSetup => "tailscale: ensure ACL tags + auto-approval".to_string(),
163            Step::TailscaleEnable { svc_name, ports } => ports
164                .iter()
165                .map(|p| {
166                    format!(
167                        "tailscale serve --service=svc:{svc_name} --https={} http://127.0.0.1:{}",
168                        p.https_port, p.host_port
169                    )
170                })
171                .collect::<Vec<_>>()
172                .join(" && "),
173            Step::TailscaleDisable { svc_name } => {
174                format!("tailscale serve --service=svc:{svc_name} off + delete service")
175            }
176        }
177    }
178}
179
180/// Warnings generated during service operations that the CLI should display.
181pub enum Warning {
182    /// System RAM is below the service's minimum requirement.
183    RamBelowMinimum {
184        service_name: String,
185        min_mb: u64,
186        available_mb: u64,
187    },
188    /// System RAM is below the service's recommended level (but above minimum).
189    RamBelowRecommended {
190        service_name: String,
191        recommended_mb: u64,
192        available_mb: u64,
193    },
194    /// A port was reassigned because the default was privileged or in use.
195    PortReassigned {
196        service_name: String,
197        port_name: String,
198        original_port: u16,
199        assigned_port: u16,
200        reason: String,
201    },
202    /// `--url` was passed but no ryra-managed reverse proxy (Caddy) is installed.
203    /// Ryra still templates the URL into env vars and OIDC config, but routing
204    /// is the user's responsibility (nginx, Cloudflare Tunnel, Tailscale Funnel,
205    /// external load balancer, etc.).
206    UrlWithoutReverseProxy {
207        service_name: String,
208        url: String,
209        host_port: u16,
210    },
211}
212
213pub struct AddResult {
214    pub steps: Vec<Step>,
215    pub warnings: Vec<Warning>,
216    pub repo_url: String,
217    /// Allocated ports for this service (port_name, host_port).
218    pub allocated_ports: Vec<(String, u16)>,
219    /// Names of auto-generated secrets (values are in .env).
220    pub generated_secrets: Vec<String>,
221    /// The generated .env content (for post-install processing).
222    pub env_content: String,
223    /// Public URL for this service (if --url was provided).
224    pub url: Option<String>,
225    /// Static env vars (key, default value, kind, optional human prompt
226    /// label) the registry expects in `.env`. Populated whether or not
227    /// the user is in interactive mode — `ryra upgrade` reads this back
228    /// to decide which additions need to prompt the user (kind=Prompted
229    /// / Required) versus which can be appended silently (kind=Default).
230    pub tracked_envs: Vec<TrackedEnv>,
231}
232
233/// Per-env metadata the planner keeps alongside the rendered value, so
234/// downstream callers (CLI prompts for `ryra upgrade`) can decide
235/// whether a given env var needs user input.
236#[derive(Debug, Clone)]
237pub struct TrackedEnv {
238    pub key: String,
239    pub value: String,
240    pub kind: crate::registry::service_def::EnvKind,
241    pub prompt: Option<String>,
242}
243
244pub struct RemoveResult {
245    pub steps: Vec<Step>,
246    pub service_name: String,
247    /// URL that was assigned to this service (if any).
248    pub url: Option<String>,
249}
250
251pub struct ResetResult {
252    pub steps: Vec<Step>,
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::registry::service_def::{PortDef, PortProtocol};
259
260    fn port(name: &str, container: u16, ts: Option<u16>) -> PortDef {
261        PortDef {
262            name: name.into(),
263            container_port: container,
264            host_port: None,
265            protocol: PortProtocol::default(),
266            tailscale_https: ts,
267        }
268    }
269
270    #[test]
271    fn single_port_service_falls_back_to_primary_on_443() {
272        // No port declares tailscale_https → primary served at the web root.
273        let ports = vec![port("http", 80, None)];
274        let resolved = vec![("http".to_string(), 10001u16)];
275        let out = tailscale_ports(&ports, &resolved, Some(10001));
276        assert_eq!(out.len(), 1);
277        assert_eq!(out[0].https_port, 443);
278        assert_eq!(out[0].host_port, 10001);
279    }
280
281    #[test]
282    fn multiport_maps_each_declared_port_to_its_resolved_host_port() {
283        let ports = vec![
284            port("http", 8080, Some(8080)),
285            port("photos", 3000, Some(443)),
286        ];
287        let resolved = vec![
288            ("http".to_string(), 8080u16),
289            ("photos".to_string(), 10002u16),
290        ];
291        let mut out = tailscale_ports(&ports, &resolved, Some(8080));
292        out.sort_by_key(|p| p.https_port);
293        assert_eq!(out.len(), 2);
294        assert_eq!((out[0].https_port, out[0].host_port), (443, 10002)); // photos root
295        assert_eq!((out[1].https_port, out[1].host_port), (8080, 8080)); // museum api
296    }
297
298    #[test]
299    fn no_ports_and_no_primary_yields_empty() {
300        assert!(tailscale_ports(&[], &[], None).is_empty());
301    }
302}