Skip to main content

stackless_laravel_cloud/
lib.rs

1//! stackless-laravel-cloud (ARCHITECTURE.md §4): the Laravel Cloud substrate.
2//!
3//! Mirrors the Netlify cloud flow at a smaller v0 scope: Stripe Projects
4//! provisions `laravel_cloud/application` and tracks spend; observe/destroy
5//! key off the Stripe resource registration. A real Laravel Cloud deploy API
6//! client is Phase 2 — v0 records a placeholder origin and resumes via Stripe.
7//!
8//! ## Credential model
9//!
10//! Provisioning `laravel_cloud/application` returns a Stripe-managed `app_id`.
11//! `observe`/`destroy` key off the **Stripe resource registration**, not a
12//! Laravel Cloud API.
13//!
14//! ## v0 scope and cloud invariants
15//!
16//! - **Placeholder origin.** Origins are `https://{stack}-{instance}-{service}.laravel.cloud`
17//!   until a deploy client fills in the real URL.
18//! - **Cloud resource names** are `{stack}-{instance}-{service}` — DNS-safe.
19//! - **Setup is skipped on cloud**; **prepare** runs on the operator's machine.
20//! - **Source override is unsupported** — Laravel Cloud deploys committed refs.
21
22pub mod codes;
23pub mod config;
24pub mod error;
25
26use std::collections::BTreeMap;
27use std::path::PathBuf;
28use std::time::Duration;
29
30use async_trait::async_trait;
31use serde::{Deserialize, Serialize};
32use stackless_core::def::{Namespace, StackDef};
33use stackless_core::engine::StepKind;
34use stackless_core::state::Checkpoint;
35use stackless_core::substrate::{
36    NamespacePurpose, Observation, StepContext, StepResource, Substrate, SubstrateFault,
37};
38use tokio::sync::Mutex;
39
40use crate::config::{LaravelCloudApplicationConfig, ServiceLaravelCloud};
41use crate::error::LaravelCloudError;
42use stackless_stripe_projects::ProjectsError;
43use stackless_stripe_projects::provision::{ProvisionContext, provision_outputs};
44use stackless_stripe_projects::stripe::{CommandRunner, StripeProjects, TokioRunner};
45use stackless_stripe_projects::{project, requires_confirmation};
46
47pub const SUBSTRATE_NAME: &str = "laravel-cloud";
48
49/// The hard per-provider spend cap set on first paid confirmation (§4).
50pub const SPEND_CAP_USD: u32 = 25;
51
52/// The provider prefix Stripe uses for `laravel_cloud/application` output env vars.
53const PROVIDER_PREFIX: &str = "LARAVEL_CLOUD";
54
55fn fault(err: LaravelCloudError) -> SubstrateFault {
56    SubstrateFault::from_fault(&err)
57}
58
59fn projects_fault(err: ProjectsError) -> SubstrateFault {
60    SubstrateFault::from_fault(&err)
61}
62
63fn integration_fault(err: stackless_integrations::IntegrationError) -> SubstrateFault {
64    SubstrateFault::from_fault(&err)
65}
66
67fn prepare_fault(f: stackless_cloud::prepare::PrepareFailure) -> SubstrateFault {
68    fault(LaravelCloudError::PrepareFailed {
69        service: f.service,
70        command: f.command,
71        message: f.message,
72        log_tail: f.log_tail,
73    })
74}
75
76/// What a `start:<service>` checkpoint records: the live Laravel Cloud application.
77/// Observe/destroy use the Stripe resource registration, not a Laravel Cloud API.
78#[derive(Debug, Serialize, Deserialize)]
79struct LaravelCloudPayload {
80    stripe_resource: String,
81    app_id: String,
82    app_name: String,
83    origin: String,
84}
85
86/// What a `materialize:<service>` checkpoint records: the pinned source.
87#[derive(Debug, Serialize, Deserialize)]
88struct SourceRefPayload {
89    repo: String,
90    #[serde(rename = "ref")]
91    reference: String,
92}
93
94/// The Laravel Cloud substrate. Generic over the command runner so tests inject
95/// canned Stripe envelopes; production uses the real `stripe` binary.
96pub struct LaravelCloudSubstrate<R: CommandRunner = TokioRunner> {
97    pub definition_dir: PathBuf,
98    pub secrets: BTreeMap<String, String>,
99    pub confirm_paid: bool,
100    runner: R,
101    ensured: Mutex<bool>,
102}
103
104impl<R: CommandRunner> std::fmt::Debug for LaravelCloudSubstrate<R> {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.debug_struct("LaravelCloudSubstrate")
107            .field("definition_dir", &self.definition_dir)
108            .field("confirm_paid", &self.confirm_paid)
109            .finish_non_exhaustive()
110    }
111}
112
113impl LaravelCloudSubstrate<TokioRunner> {
114    pub fn new(
115        definition_dir: impl Into<PathBuf>,
116        secrets: BTreeMap<String, String>,
117        confirm_paid: bool,
118    ) -> Self {
119        Self {
120            definition_dir: definition_dir.into(),
121            secrets,
122            confirm_paid,
123            runner: TokioRunner,
124            ensured: Mutex::new(false),
125        }
126    }
127}
128
129impl<R: CommandRunner> LaravelCloudSubstrate<R> {
130    #[cfg(test)]
131    fn for_test(runner: R, definition_dir: impl Into<PathBuf>, confirm_paid: bool) -> Self {
132        Self {
133            definition_dir: definition_dir.into(),
134            secrets: BTreeMap::new(),
135            confirm_paid,
136            runner,
137            ensured: Mutex::new(false),
138        }
139    }
140
141    fn stripe(&self) -> StripeProjects<&R> {
142        StripeProjects::new(&self.runner, self.definition_dir.clone())
143    }
144
145    /// `{stack}-{instance}-{service}` (DNS-safe).
146    fn resource_name(def: &StackDef, instance: &str, node: &str) -> String {
147        format!("{}-{instance}-{node}", def.stack.name.as_str())
148    }
149
150    /// Placeholder origin until a deploy client records the real URL.
151    fn origin(def: &StackDef, instance: &str, service: &str) -> String {
152        format!(
153            "https://{}.laravel.cloud",
154            Self::resource_name(def, instance, service)
155        )
156    }
157
158    fn namespace(&self, def: &StackDef, instance: &str, prior: &[Checkpoint]) -> Namespace {
159        let mut namespace = Namespace {
160            stack_name: def.stack.name.clone(),
161            instance_name: stackless_core::types::DnsName::from_stored(instance),
162            ..Namespace::default()
163        };
164        for service in def.services.keys() {
165            namespace
166                .service_origins
167                .insert(service.clone(), Self::origin(def, instance, service));
168        }
169        namespace.secrets = self.secrets.clone();
170        namespace.add_integration_checkpoints(prior);
171        namespace
172    }
173
174    async fn ensure_project_and_env(
175        &self,
176        def: &StackDef,
177        instance: &str,
178    ) -> Result<(), SubstrateFault> {
179        let mut done = self.ensured.lock().await;
180        if *done {
181            return Ok(());
182        }
183        let spend = self
184            .confirm_paid
185            .then_some((SPEND_CAP_USD, "laravel-cloud"));
186        stackless_cloud::ensure::project_and_env(
187            &self.stripe(),
188            def,
189            &self.definition_dir,
190            instance,
191            spend,
192        )
193        .await
194        .map_err(projects_fault)?;
195        *done = true;
196        Ok(())
197    }
198
199    fn require_confirm_paid(&self, resource: &str) -> Result<(), SubstrateFault> {
200        if !self.confirm_paid {
201            return Err(fault(LaravelCloudError::PaymentNotConfirmed {
202                resource: resource.to_owned(),
203            }));
204        }
205        Ok(())
206    }
207
208    async fn start_service(
209        &self,
210        def: &StackDef,
211        instance: &str,
212        service: &str,
213    ) -> Result<StepResource, SubstrateFault> {
214        let laravel_cfg = config::service_laravel_cloud(def, service).map_err(fault)?;
215        let app_name = Self::resource_name(def, instance, service);
216        let resource = format!("{instance}-{service}");
217
218        let catalog = self
219            .stripe()
220            .catalog_for::<LaravelCloudApplicationConfig>()
221            .await
222            .map_err(projects_fault)?;
223        let cfg = application_config(&app_name, &laravel_cfg);
224        if requires_confirmation(&catalog, &cfg).unwrap_or(false) {
225            self.require_confirm_paid(&resource)?;
226        }
227        let ctx = ProvisionContext {
228            def,
229            instance,
230            logical_name: service,
231            definition_dir: &self.definition_dir,
232            substrate: SUBSTRATE_NAME,
233            skip_instance_context: true,
234        };
235        let (_resource_name, outputs) = provision_outputs(
236            &self.stripe(),
237            &catalog,
238            &ctx,
239            &cfg,
240            PROVIDER_PREFIX,
241            // Suffix only — resolved as LARAVEL_CLOUD_APP_ID / {RESOURCE}_APP_ID.
242            &[("APP_ID", "app_id", true)],
243        )
244        .await
245        .map_err(projects_fault)?;
246        let app_id = outputs.get("app_id").ok_or_else(|| {
247            fault(LaravelCloudError::ProvisionFailed {
248                resource: resource.clone(),
249                detail: "laravel_cloud/application did not return an app_id".into(),
250            })
251        })?;
252
253        let payload = LaravelCloudPayload {
254            stripe_resource: resource,
255            app_id: app_id.clone(),
256            app_name: app_name.clone(),
257            origin: Self::origin(def, instance, service),
258        };
259        Ok(StepResource {
260            resource_kind: "laravel-cloud-application".into(),
261            resource_id: app_name,
262            payload: serde_json::to_string(&payload).unwrap_or_default(),
263        })
264    }
265
266    async fn run_prepare(
267        &self,
268        def: &StackDef,
269        instance: &str,
270        service: &str,
271        prior: &[Checkpoint],
272    ) -> Result<(), SubstrateFault> {
273        let Some(spec) = def.services.get(service) else {
274            return Ok(());
275        };
276        let namespace = self.namespace(def, instance, prior);
277        stackless_cloud::prepare::run_service_prepare(
278            &namespace,
279            &self.secrets,
280            service,
281            SUBSTRATE_NAME,
282            spec,
283        )
284        .await
285        .map_err(prepare_fault)
286    }
287}
288
289fn application_config(name: &str, cfg: &ServiceLaravelCloud) -> LaravelCloudApplicationConfig {
290    LaravelCloudApplicationConfig {
291        name: name.to_owned(),
292        region: cfg.region.clone(),
293        repository: cfg.repository.clone(),
294        create_cache: cfg.create_cache.clone(),
295        create_database: cfg.create_database.clone(),
296    }
297}
298
299#[async_trait]
300impl<R: CommandRunner> Substrate for LaravelCloudSubstrate<R> {
301    fn name(&self) -> &str {
302        SUBSTRATE_NAME
303    }
304
305    fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault> {
306        for service in def.services.keys() {
307            config::service_laravel_cloud(def, service).map_err(fault)?;
308            let service_name = Self::resource_name(def, "i", service);
309            if !config::is_valid_service_name(&service_name) {
310                return Err(fault(LaravelCloudError::ConfigInvalid {
311                    location: format!("services.{service}"),
312                    detail: format!(
313                        "derived Laravel Cloud application name {service_name:?} is not DNS-safe; \
314                         shorten the stack/service name"
315                    ),
316                }));
317            }
318        }
319        Ok(())
320    }
321
322    fn supports_source_override(&self) -> bool {
323        false
324    }
325
326    fn default_lease(&self) -> Duration {
327        Duration::from_secs(8 * 3600)
328    }
329
330    fn service_origin(&self, def: &StackDef, instance: &str, service: &str) -> String {
331        Self::origin(def, instance, service)
332    }
333
334    fn build_namespace(
335        &self,
336        def: &StackDef,
337        instance: &str,
338        prior: &[Checkpoint],
339        secrets: &BTreeMap<String, String>,
340        _purpose: NamespacePurpose,
341    ) -> Namespace {
342        let mut namespace = self.namespace(def, instance, prior);
343        namespace.secrets = secrets.clone();
344        namespace
345    }
346
347    async fn execute(&self, ctx: StepContext<'_>) -> Result<StepResource, SubstrateFault> {
348        self.ensure_project_and_env(ctx.def, ctx.instance).await?;
349
350        let node = ctx.step.node.as_str();
351        match ctx.step.kind {
352            StepKind::ProvisionIntegration => stackless_integrations::provision(
353                SUBSTRATE_NAME,
354                &self.stripe(),
355                ctx.def,
356                &self.definition_dir,
357                ctx.instance,
358                node,
359                true,
360            )
361            .await
362            .map_err(integration_fault),
363            StepKind::Materialize => {
364                let spec = ctx.def.services.get(node).ok_or_else(|| {
365                    fault(LaravelCloudError::ConfigInvalid {
366                        location: format!("services.{node}"),
367                        detail: "service not in definition".into(),
368                    })
369                })?;
370                let payload = SourceRefPayload {
371                    repo: spec.source.repo.clone(),
372                    reference: spec.source.reference.clone(),
373                };
374                Ok(StepResource {
375                    resource_kind: "source-ref".into(),
376                    resource_id: format!("{}@{}", spec.source.repo, spec.source.reference),
377                    payload: serde_json::to_string(&payload).unwrap_or_default(),
378                })
379            }
380            StepKind::Setup => Ok(stackless_core::substrate::action_resource(&ctx.step.id)),
381            StepKind::Prepare => {
382                self.run_prepare(ctx.def, ctx.instance, node, ctx.prior)
383                    .await?;
384                Ok(stackless_core::substrate::action_resource(&ctx.step.id))
385            }
386            StepKind::Start => self.start_service(ctx.def, ctx.instance, node).await,
387            StepKind::HealthGate => {
388                // v0: placeholder origin — health polling deferred until a deploy client exists.
389                Ok(stackless_core::substrate::action_resource(&ctx.step.id))
390            }
391        }
392    }
393
394    async fn observe(
395        &self,
396        _instance: &str,
397        checkpoint: &Checkpoint,
398    ) -> Result<Observation, SubstrateFault> {
399        match checkpoint.resource_kind.as_str() {
400            "laravel-cloud-application" => {
401                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
402                    &checkpoint.payload,
403                )
404                .map_err(|detail| {
405                    fault(LaravelCloudError::ConfigInvalid {
406                        location: "checkpoint.payload".into(),
407                        detail,
408                    })
409                })?;
410                let stripe_resource = payload
411                    .map(|p| p.stripe_resource)
412                    .unwrap_or_else(|| checkpoint.resource_id.clone());
413                let present = project::resource_registered(&self.stripe(), &stripe_resource)
414                    .await
415                    .map_err(projects_fault)?;
416                Ok(stackless_core::substrate::present_or_gone(present))
417            }
418            kind if stackless_integrations::is_integration_resource(kind) => {
419                stackless_integrations::observe(
420                    SUBSTRATE_NAME,
421                    &self.stripe(),
422                    &checkpoint.payload,
423                    &checkpoint.resource_id,
424                    kind,
425                )
426                .await
427                .map_err(integration_fault)
428            }
429            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => {
430                Ok(Observation::Gone)
431            }
432            kind => Err(fault(LaravelCloudError::ConfigInvalid {
433                location: "checkpoint.resource_kind".into(),
434                detail: format!("unknown resource kind {kind:?}"),
435            })),
436        }
437    }
438
439    async fn destroy(
440        &self,
441        _instance: &str,
442        checkpoint: &Checkpoint,
443    ) -> Result<(), SubstrateFault> {
444        match checkpoint.resource_kind.as_str() {
445            "laravel-cloud-application" => {
446                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
447                    &checkpoint.payload,
448                )
449                .map_err(|detail| {
450                    fault(LaravelCloudError::ConfigInvalid {
451                        location: "checkpoint.payload".into(),
452                        detail,
453                    })
454                })?;
455                let stripe_resource = payload
456                    .map(|p| p.stripe_resource)
457                    .unwrap_or_else(|| checkpoint.resource_id.clone());
458                project::remove_resource(&self.stripe(), &stripe_resource)
459                    .await
460                    .map_err(projects_fault)
461            }
462            kind if stackless_integrations::is_integration_resource(kind) => {
463                stackless_integrations::destroy(
464                    SUBSTRATE_NAME,
465                    &self.stripe(),
466                    &checkpoint.payload,
467                    &checkpoint.resource_id,
468                    kind,
469                )
470                .await
471                .map_err(integration_fault)
472            }
473            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => Ok(()),
474            kind => Err(fault(LaravelCloudError::ConfigInvalid {
475                location: "checkpoint.resource_kind".into(),
476                detail: format!("unknown resource kind {kind:?}"),
477            })),
478        }
479    }
480
481    async fn finalize_teardown(&self, instance: &str) -> Result<(), SubstrateFault> {
482        stackless_integrations::finalize_stripe_instance(&self.stripe(), instance).await;
483        Ok(())
484    }
485
486    async fn spend(&self) -> Option<stackless_core::substrate::SpendInfo> {
487        Some(
488            stackless_cloud::spend::fetch(
489                &self.definition_dir,
490                SUBSTRATE_NAME,
491                SPEND_CAP_USD,
492                "cloud.laravel.com",
493            )
494            .await,
495        )
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502    use stackless_stripe_projects::stripe::{CommandOutput, CommandRunner};
503    use stackless_stripe_projects::test_support;
504    use std::path::Path as StdPath;
505
506    struct NoRunner;
507    #[async_trait]
508    impl CommandRunner for NoRunner {
509        async fn run(
510            &self,
511            _args: &[String],
512            _cwd: &StdPath,
513        ) -> Result<CommandOutput, ProjectsError> {
514            Err(ProjectsError::Unavailable {
515                detail: "stripe should not be called in this test".into(),
516            })
517        }
518    }
519
520    fn checkpoint(kind: &str, step_id: &str, payload: &str) -> Checkpoint {
521        Checkpoint {
522            instance: "demo".into(),
523            step_id: step_id.into(),
524            resource_kind: kind.into(),
525            resource_id: "atto-demo-web".into(),
526            payload: payload.into(),
527            recorded_at: 0,
528        }
529    }
530
531    fn laravel_def() -> StackDef {
532        StackDef::parse(
533            "[stack]\nname=\"atto\"\n[services.web]\nsource={repo=\"r\",ref=\"main\"}\nenv={}\nhealth={path=\"/\"}\n[services.web.laravel-cloud]\nregion=\"us-east-1\"\nrepository=\"laravel/cloud\"\n",
534        )
535        .unwrap()
536    }
537
538    fn subj() -> (tempfile::TempDir, LaravelCloudSubstrate<NoRunner>) {
539        let dir = tempfile::tempdir().unwrap();
540        let s = LaravelCloudSubstrate::for_test(NoRunner, dir.path(), false);
541        (dir, s)
542    }
543
544    const PAYLOAD: &str = r#"{"stripe_resource":"demo-web","app_id":"app_1","app_name":"atto-demo-web","origin":"https://atto-demo-web.laravel.cloud"}"#;
545
546    #[test]
547    fn resource_name_and_origin_are_dns_safe() {
548        let def = laravel_def();
549        assert_eq!(
550            LaravelCloudSubstrate::<TokioRunner>::resource_name(&def, "demo", "web"),
551            "atto-demo-web"
552        );
553        let (_dir, s) = subj();
554        assert_eq!(
555            s.service_origin(&def, "demo", "web"),
556            "https://atto-demo-web.laravel.cloud"
557        );
558    }
559
560    #[test]
561    fn laravel_cloud_substrate_defaults() {
562        let s = LaravelCloudSubstrate::new(std::env::temp_dir(), Default::default(), false);
563        assert_eq!(s.name(), "laravel-cloud");
564        assert!(!s.supports_source_override());
565        assert_eq!(s.default_lease(), Duration::from_secs(8 * 3600));
566    }
567
568    #[tokio::test]
569    async fn application_present_when_stripe_registers_it() {
570        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&["demo-web"])]);
571        let dir = tempfile::tempdir().unwrap();
572        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), false);
573        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
574        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Present);
575    }
576
577    #[tokio::test]
578    async fn application_gone_when_stripe_does_not_register_it() {
579        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&[])]);
580        let dir = tempfile::tempdir().unwrap();
581        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), false);
582        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
583        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Gone);
584    }
585
586    #[tokio::test]
587    async fn source_ref_observes_gone_so_teardown_drops_it() {
588        let (_dir, s) = subj();
589        let cp = checkpoint(
590            "source-ref",
591            "materialize:web",
592            r#"{"repo":"r","ref":"main"}"#,
593        );
594        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Gone);
595        s.destroy("demo", &cp).await.unwrap();
596    }
597
598    #[tokio::test]
599    async fn unknown_resource_kind_fails_closed() {
600        let (_dir, s) = subj();
601        let cp = checkpoint("not-a-real-kind", "start:web", "{}");
602        assert!(s.observe("demo", &cp).await.is_err());
603        assert!(s.destroy("demo", &cp).await.is_err());
604    }
605
606    #[tokio::test]
607    async fn teardown_removes_via_stripe() {
608        let runner = test_support::ScriptedRunner::new(vec![
609            test_support::services(&["demo-web"]),
610            test_support::ok_empty(),
611        ]);
612        let dir = tempfile::tempdir().unwrap();
613        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), false);
614        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
615        s.destroy("demo", &cp).await.unwrap();
616        let calls = runner.calls();
617        assert!(
618            calls
619                .iter()
620                .any(|c| c.first().map(String::as_str) == Some("remove")
621                    && c.iter().any(|a| a == "demo-web")),
622            "expected a `remove demo-web` call, got {calls:?}"
623        );
624    }
625}