Skip to main content

stackless_laravel_cloud/
lib.rs

1//! stackless-laravel-cloud (ARCHITECTURE.md §4): the Laravel Cloud substrate.
2//!
3//! Stripe Projects provisions `laravel_cloud/application` and tracks spend; the
4//! Laravel Cloud JSON:API fills its gaps — resolve the environment, trigger a
5//! deploy, poll to `deployment.succeeded`, and the health wait. One long-lived
6//! Stripe project per stack holds each instance as a named environment.
7//!
8//! ## Credential model
9//!
10//! Provisioning returns a Stripe-managed `app_id`. Deploy-time API calls use
11//! `LARAVEL_CLOUD_API_TOKEN` from the Stripe instance environment when present,
12//! otherwise the operator token (`LARAVEL_CLOUD_API_TOKEN` env / secrets /
13//! `.laravel-cloud-token`). Observe/destroy key off the **Stripe resource
14//! registration**, not the Laravel Cloud API.
15//!
16//! ## Deploy paths and cloud invariants
17//!
18//! - **Git deploy:** Laravel Cloud builds from the repository configured at
19//!   provision time (`[services.X.laravel-cloud].repository`); `start` triggers
20//!   POST `/environments/{id}/deployments` and polls until success.
21//! - **Cloud resource names** are `{stack}-{instance}-{service}` — DNS-safe.
22//! - **Setup is skipped on cloud**; **prepare** runs on the operator's machine.
23//! - **Source override is unsupported** — Laravel Cloud deploys committed refs.
24
25pub mod api_key;
26pub mod codes;
27pub mod config;
28pub mod error;
29pub mod laravel_api;
30
31use std::collections::BTreeMap;
32use std::path::PathBuf;
33use std::time::Duration;
34
35use async_trait::async_trait;
36use serde::{Deserialize, Serialize};
37use stackless_core::def::{Namespace, StackDef};
38use stackless_core::engine::StepKind;
39use stackless_core::state::Checkpoint;
40use stackless_core::substrate::{
41    NamespacePurpose, Observation, ServiceLog, StepContext, StepResource, Substrate, SubstrateFault,
42};
43use tokio::sync::Mutex;
44
45use crate::config::{LaravelCloudApplicationConfig, ServiceLaravelCloud};
46use crate::error::LaravelCloudError;
47use crate::laravel_api::{HEALTH_BUDGET, LARAVEL_DEPLOY_BUDGET, LaravelCloudApi};
48use stackless_stripe_projects::ProjectsError;
49use stackless_stripe_projects::provision::{ProvisionContext, provision_outputs};
50use stackless_stripe_projects::stripe::{CommandRunner, StripeProjects, TokioRunner};
51use stackless_stripe_projects::{project, requires_confirmation};
52
53pub const SUBSTRATE_NAME: &str = "laravel-cloud";
54
55/// The hard per-provider spend cap set on first paid confirmation (§4).
56pub const SPEND_CAP_USD: u32 = 25;
57
58/// The provider prefix Stripe uses for `laravel_cloud/application` output env vars.
59const PROVIDER_PREFIX: &str = "LARAVEL_CLOUD";
60
61fn fault(err: LaravelCloudError) -> SubstrateFault {
62    SubstrateFault::from_fault(&err)
63}
64
65fn projects_fault(err: ProjectsError) -> SubstrateFault {
66    SubstrateFault::from_fault(&err)
67}
68
69fn integration_fault(err: stackless_integrations::IntegrationError) -> SubstrateFault {
70    SubstrateFault::from_fault(&err)
71}
72
73fn prepare_fault(f: stackless_cloud::prepare::PrepareFailure) -> SubstrateFault {
74    fault(LaravelCloudError::PrepareFailed {
75        service: f.service,
76        command: f.command,
77        message: f.message,
78        log_tail: f.log_tail,
79    })
80}
81
82/// What a `start:<service>` checkpoint records: the live Laravel Cloud application.
83/// Observe/destroy use the Stripe resource registration, not a Laravel Cloud API.
84#[derive(Debug, Serialize, Deserialize)]
85struct LaravelCloudPayload {
86    stripe_resource: String,
87    app_id: String,
88    app_name: String,
89    environment_id: String,
90    deployment_id: String,
91    origin: String,
92}
93
94/// What a `materialize:<service>` checkpoint records: the pinned source.
95#[derive(Debug, Serialize, Deserialize)]
96struct SourceRefPayload {
97    repo: String,
98    #[serde(rename = "ref")]
99    reference: String,
100}
101
102/// The Laravel Cloud substrate. Generic over the command runner so tests inject
103/// canned Stripe envelopes; production uses the real `stripe` binary.
104pub struct LaravelCloudSubstrate<R: CommandRunner = TokioRunner> {
105    pub definition_dir: PathBuf,
106    pub secrets: BTreeMap<String, String>,
107    pub confirm_paid: bool,
108    runner: R,
109    api_base: Option<String>,
110    poll_interval: Option<Duration>,
111    ensured: Mutex<bool>,
112}
113
114impl<R: CommandRunner> std::fmt::Debug for LaravelCloudSubstrate<R> {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.debug_struct("LaravelCloudSubstrate")
117            .field("definition_dir", &self.definition_dir)
118            .field("confirm_paid", &self.confirm_paid)
119            .finish_non_exhaustive()
120    }
121}
122
123impl LaravelCloudSubstrate<TokioRunner> {
124    pub fn new(
125        definition_dir: impl Into<PathBuf>,
126        secrets: BTreeMap<String, String>,
127        confirm_paid: bool,
128    ) -> Self {
129        Self {
130            definition_dir: definition_dir.into(),
131            secrets,
132            confirm_paid,
133            runner: TokioRunner,
134            api_base: None,
135            poll_interval: None,
136            ensured: Mutex::new(false),
137        }
138    }
139}
140
141impl<R: CommandRunner> LaravelCloudSubstrate<R> {
142    #[cfg(test)]
143    fn for_test(
144        runner: R,
145        definition_dir: impl Into<PathBuf>,
146        api_base: impl Into<String>,
147        confirm_paid: bool,
148    ) -> Self {
149        Self {
150            definition_dir: definition_dir.into(),
151            secrets: BTreeMap::new(),
152            confirm_paid,
153            runner,
154            api_base: Some(api_base.into()),
155            poll_interval: Some(Duration::from_millis(1)),
156            ensured: Mutex::new(false),
157        }
158    }
159
160    fn stripe(&self) -> StripeProjects<&R> {
161        StripeProjects::new(&self.runner, self.definition_dir.clone())
162    }
163
164    async fn laravel_api(&self, instance: &str) -> Result<LaravelCloudApi, SubstrateFault> {
165        let token = self.laravel_token(instance).await?;
166        let api = match &self.api_base {
167            Some(base) => LaravelCloudApi::with_base(token, base.clone()),
168            None => LaravelCloudApi::new(token),
169        };
170        Ok(match self.poll_interval {
171            Some(interval) => api.with_poll_interval(interval),
172            None => api,
173        })
174    }
175
176    async fn laravel_token(&self, instance: &str) -> Result<String, SubstrateFault> {
177        let pulled =
178            project::pull_env_values(&self.stripe(), instance, &["LARAVEL_CLOUD_API_TOKEN"])
179                .await
180                .map_err(projects_fault)?;
181        if let Some(token) = pulled
182            .into_iter()
183            .flatten()
184            .find(|value| !value.trim().is_empty())
185        {
186            return Ok(token);
187        }
188        api_key::resolve(&self.definition_dir, &self.secrets).map_err(fault)
189    }
190
191    /// `{stack}-{instance}-{service}` (DNS-safe).
192    fn resource_name(def: &StackDef, instance: &str, node: &str) -> String {
193        format!("{}-{instance}-{node}", def.stack.name.as_str())
194    }
195
196    /// Best-effort origin before deploy; health uses the recorded deployment URL.
197    fn origin(def: &StackDef, instance: &str, service: &str) -> String {
198        format!(
199            "https://{}.laravel.cloud",
200            Self::resource_name(def, instance, service)
201        )
202    }
203
204    fn namespace(&self, def: &StackDef, instance: &str, prior: &[Checkpoint]) -> Namespace {
205        let mut namespace = Namespace {
206            stack_name: def.stack.name.clone(),
207            instance_name: stackless_core::types::DnsName::from_stored(instance),
208            ..Namespace::default()
209        };
210        for service in def.services.keys() {
211            let origin = prior
212                .iter()
213                .find(|checkpoint| checkpoint.step_id == format!("start:{service}"))
214                .and_then(|checkpoint| {
215                    serde_json::from_str::<LaravelCloudPayload>(&checkpoint.payload)
216                        .ok()
217                        .map(|payload| payload.origin)
218                })
219                .filter(|o| !o.trim().is_empty())
220                .unwrap_or_else(|| Self::origin(def, instance, service));
221            namespace.service_origins.insert(service.clone(), origin);
222        }
223        namespace.secrets = self.secrets.clone();
224        namespace.add_integration_checkpoints(prior);
225        namespace
226    }
227
228    async fn ensure_project_and_env(
229        &self,
230        def: &StackDef,
231        instance: &str,
232    ) -> Result<(), SubstrateFault> {
233        let mut done = self.ensured.lock().await;
234        if *done {
235            return Ok(());
236        }
237        let spend = self
238            .confirm_paid
239            .then_some((SPEND_CAP_USD, "laravel-cloud"));
240        stackless_cloud::ensure::project_and_env(
241            &self.stripe(),
242            def,
243            &self.definition_dir,
244            instance,
245            spend,
246        )
247        .await
248        .map_err(projects_fault)?;
249        *done = true;
250        Ok(())
251    }
252
253    fn require_confirm_paid(&self, resource: &str) -> Result<(), SubstrateFault> {
254        if !self.confirm_paid {
255            return Err(fault(LaravelCloudError::PaymentNotConfirmed {
256                resource: resource.to_owned(),
257            }));
258        }
259        Ok(())
260    }
261
262    async fn start_service(
263        &self,
264        def: &StackDef,
265        instance: &str,
266        service: &str,
267    ) -> Result<StepResource, SubstrateFault> {
268        let laravel_cfg = config::service_laravel_cloud(def, service).map_err(fault)?;
269        let app_name = Self::resource_name(def, instance, service);
270        let resource = format!("{instance}-{service}");
271
272        let catalog = self
273            .stripe()
274            .catalog_for::<LaravelCloudApplicationConfig>()
275            .await
276            .map_err(projects_fault)?;
277        let cfg = application_config(&app_name, &laravel_cfg);
278        if requires_confirmation(&catalog, &cfg).unwrap_or(false) {
279            self.require_confirm_paid(&resource)?;
280        }
281        let ctx = ProvisionContext {
282            def,
283            instance,
284            logical_name: service,
285            definition_dir: &self.definition_dir,
286            substrate: SUBSTRATE_NAME,
287            skip_instance_context: true,
288        };
289        let (_resource_name, outputs) = provision_outputs(
290            &self.stripe(),
291            &catalog,
292            &ctx,
293            &cfg,
294            PROVIDER_PREFIX,
295            stackless_integrations::providers::laravel_cloud::application::OUTPUT_FIELDS,
296        )
297        .await
298        .map_err(projects_fault)?;
299        let app_id = outputs.get("app_id").ok_or_else(|| {
300            fault(LaravelCloudError::ProvisionFailed {
301                resource: resource.clone(),
302                detail: "laravel_cloud/application did not return an app_id".into(),
303            })
304        })?;
305
306        let api = self.laravel_api(instance).await?;
307        let deploy = api
308            .deploy_application(app_id, &app_name, service, LARAVEL_DEPLOY_BUDGET)
309            .await
310            .map_err(fault)?;
311
312        let payload = LaravelCloudPayload {
313            stripe_resource: resource,
314            app_id: app_id.clone(),
315            app_name: app_name.clone(),
316            environment_id: deploy.environment_id,
317            deployment_id: deploy.deployment_id,
318            origin: deploy.origin,
319        };
320        Ok(StepResource {
321            resource_kind: "laravel-cloud-application".into(),
322            resource_id: app_name,
323            payload: serde_json::to_string(&payload).unwrap_or_default(),
324        })
325    }
326
327    async fn run_prepare(
328        &self,
329        def: &StackDef,
330        instance: &str,
331        service: &str,
332        prior: &[Checkpoint],
333    ) -> Result<(), SubstrateFault> {
334        let Some(spec) = def.services.get(service) else {
335            return Ok(());
336        };
337        let namespace = self.namespace(def, instance, prior);
338        stackless_cloud::prepare::run_service_prepare(
339            &namespace,
340            &self.secrets,
341            service,
342            SUBSTRATE_NAME,
343            spec,
344        )
345        .await
346        .map_err(prepare_fault)
347    }
348
349    async fn health_gate(
350        &self,
351        def: &StackDef,
352        instance: &str,
353        service: &str,
354        prior: &[Checkpoint],
355    ) -> Result<(), SubstrateFault> {
356        let spec = def.services.get(service).ok_or_else(|| {
357            fault(LaravelCloudError::ConfigInvalid {
358                location: format!("services.{service}"),
359                detail: "service not in definition".into(),
360            })
361        })?;
362        let origin = prior
363            .iter()
364            .find(|c| {
365                c.resource_kind == "laravel-cloud-application"
366                    && c.step_id == format!("start:{service}")
367            })
368            .and_then(|c| serde_json::from_str::<LaravelCloudPayload>(&c.payload).ok())
369            .map(|p| p.origin)
370            .filter(|o| !o.trim().is_empty())
371            .unwrap_or_else(|| Self::origin(def, instance, service));
372        let url = format!("{origin}{}", spec.health.path);
373        stackless_cloud::health::poll(
374            &url,
375            spec.health.status.get(),
376            spec.health.contains.as_deref(),
377            HEALTH_BUDGET,
378        )
379        .await
380        .map_err(|f| {
381            fault(LaravelCloudError::HealthFailed {
382                service: service.to_owned(),
383                url: f.url,
384                detail: f.detail,
385                budget_secs: f.budget_secs,
386            })
387        })
388    }
389}
390
391fn application_config(name: &str, cfg: &ServiceLaravelCloud) -> LaravelCloudApplicationConfig {
392    LaravelCloudApplicationConfig {
393        name: name.to_owned(),
394        region: cfg.region.clone(),
395        repository: cfg.repository.clone(),
396        create_cache: cfg.create_cache.clone(),
397        create_database: cfg.create_database.clone(),
398    }
399}
400
401#[async_trait]
402impl<R: CommandRunner> Substrate for LaravelCloudSubstrate<R> {
403    fn name(&self) -> &str {
404        SUBSTRATE_NAME
405    }
406
407    fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault> {
408        for service in def.services.keys() {
409            config::service_laravel_cloud(def, service).map_err(fault)?;
410            let service_name = Self::resource_name(def, "i", service);
411            if !config::is_valid_service_name(&service_name) {
412                return Err(fault(LaravelCloudError::ConfigInvalid {
413                    location: format!("services.{service}"),
414                    detail: format!(
415                        "derived Laravel Cloud application name {service_name:?} is not DNS-safe; \
416                         shorten the stack/service name"
417                    ),
418                }));
419            }
420        }
421        Ok(())
422    }
423
424    fn supports_source_override(&self) -> bool {
425        false
426    }
427
428    fn default_lease(&self) -> Duration {
429        Duration::from_secs(8 * 3600)
430    }
431
432    fn service_origin(&self, def: &StackDef, instance: &str, service: &str) -> String {
433        Self::origin(def, instance, service)
434    }
435
436    fn build_namespace(
437        &self,
438        def: &StackDef,
439        instance: &str,
440        prior: &[Checkpoint],
441        secrets: &BTreeMap<String, String>,
442        _purpose: NamespacePurpose,
443    ) -> Namespace {
444        let mut namespace = self.namespace(def, instance, prior);
445        namespace.secrets = secrets.clone();
446        namespace
447    }
448
449    async fn execute(&self, ctx: StepContext<'_>) -> Result<StepResource, SubstrateFault> {
450        self.ensure_project_and_env(ctx.def, ctx.instance).await?;
451
452        let node = ctx.step.node.as_str();
453        match ctx.step.kind {
454            StepKind::ProvisionIntegration => stackless_integrations::provision(
455                SUBSTRATE_NAME,
456                &self.stripe(),
457                ctx.def,
458                &self.definition_dir,
459                ctx.instance,
460                node,
461                true,
462            )
463            .await
464            .map_err(integration_fault),
465            StepKind::Materialize => {
466                let spec = ctx.def.services.get(node).ok_or_else(|| {
467                    fault(LaravelCloudError::ConfigInvalid {
468                        location: format!("services.{node}"),
469                        detail: "service not in definition".into(),
470                    })
471                })?;
472                let payload = SourceRefPayload {
473                    repo: spec.source.repo.clone(),
474                    reference: spec.source.reference.clone(),
475                };
476                Ok(StepResource {
477                    resource_kind: "source-ref".into(),
478                    resource_id: format!("{}@{}", spec.source.repo, spec.source.reference),
479                    payload: serde_json::to_string(&payload).unwrap_or_default(),
480                })
481            }
482            StepKind::Setup => Ok(stackless_core::substrate::action_resource(&ctx.step.id)),
483            StepKind::Prepare => {
484                self.run_prepare(ctx.def, ctx.instance, node, ctx.prior)
485                    .await?;
486                Ok(stackless_core::substrate::action_resource(&ctx.step.id))
487            }
488            StepKind::Start => self.start_service(ctx.def, ctx.instance, node).await,
489            StepKind::HealthGate => {
490                self.health_gate(ctx.def, ctx.instance, node, ctx.prior)
491                    .await?;
492                Ok(stackless_core::substrate::action_resource(&ctx.step.id))
493            }
494        }
495    }
496
497    async fn observe(
498        &self,
499        _instance: &str,
500        checkpoint: &Checkpoint,
501    ) -> Result<Observation, SubstrateFault> {
502        match checkpoint.resource_kind.as_str() {
503            "laravel-cloud-application" => {
504                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
505                    &checkpoint.payload,
506                )
507                .map_err(|detail| {
508                    fault(LaravelCloudError::ConfigInvalid {
509                        location: "checkpoint.payload".into(),
510                        detail,
511                    })
512                })?;
513                let stripe_resource = payload
514                    .map(|p| p.stripe_resource)
515                    .unwrap_or_else(|| checkpoint.resource_id.clone());
516                let present = project::resource_registered(&self.stripe(), &stripe_resource)
517                    .await
518                    .map_err(projects_fault)?;
519                Ok(stackless_core::substrate::present_or_gone(present))
520            }
521            kind if stackless_integrations::is_integration_resource(kind) => {
522                stackless_integrations::observe(
523                    SUBSTRATE_NAME,
524                    &self.stripe(),
525                    &checkpoint.payload,
526                    &checkpoint.resource_id,
527                    kind,
528                )
529                .await
530                .map_err(integration_fault)
531            }
532            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => {
533                Ok(Observation::Gone)
534            }
535            kind => Err(fault(LaravelCloudError::ConfigInvalid {
536                location: "checkpoint.resource_kind".into(),
537                detail: format!("unknown resource kind {kind:?}"),
538            })),
539        }
540    }
541
542    async fn destroy(
543        &self,
544        _instance: &str,
545        checkpoint: &Checkpoint,
546    ) -> Result<(), SubstrateFault> {
547        match checkpoint.resource_kind.as_str() {
548            "laravel-cloud-application" => {
549                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
550                    &checkpoint.payload,
551                )
552                .map_err(|detail| {
553                    fault(LaravelCloudError::ConfigInvalid {
554                        location: "checkpoint.payload".into(),
555                        detail,
556                    })
557                })?;
558                let stripe_resource = payload
559                    .map(|p| p.stripe_resource)
560                    .unwrap_or_else(|| checkpoint.resource_id.clone());
561                project::remove_resource(&self.stripe(), &stripe_resource)
562                    .await
563                    .map_err(projects_fault)
564            }
565            kind if stackless_integrations::is_integration_resource(kind) => {
566                stackless_integrations::destroy(
567                    SUBSTRATE_NAME,
568                    &self.stripe(),
569                    &checkpoint.payload,
570                    &checkpoint.resource_id,
571                    kind,
572                )
573                .await
574                .map_err(integration_fault)
575            }
576            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => Ok(()),
577            kind => Err(fault(LaravelCloudError::ConfigInvalid {
578                location: "checkpoint.resource_kind".into(),
579                detail: format!("unknown resource kind {kind:?}"),
580            })),
581        }
582    }
583
584    async fn finalize_teardown(&self, instance: &str) -> Result<(), SubstrateFault> {
585        stackless_integrations::finalize_stripe_instance(&self.stripe(), instance).await;
586        Ok(())
587    }
588
589    async fn spend(&self) -> Option<stackless_core::substrate::SpendInfo> {
590        Some(
591            stackless_cloud::spend::fetch(
592                &self.definition_dir,
593                SUBSTRATE_NAME,
594                SPEND_CAP_USD,
595                "cloud.laravel.com",
596            )
597            .await,
598        )
599    }
600
601    async fn fetch_logs(
602        &self,
603        _def: &StackDef,
604        instance: &str,
605        services: &[String],
606        tail: usize,
607    ) -> Result<Option<Vec<ServiceLog>>, SubstrateFault> {
608        let api = self.laravel_api(instance).await?;
609        let mut out = Vec::with_capacity(services.len());
610        for service in services {
611            let lines = self
612                .fetch_service_logs(&api, instance, service, tail)
613                .await?;
614            out.push(ServiceLog {
615                service: service.clone(),
616                source: "laravel_cloud_api",
617                log_path: None,
618                lines,
619            });
620        }
621        Ok(Some(out))
622    }
623}
624
625fn start_service_payload(instance: &str, service: &str) -> Option<LaravelCloudPayload> {
626    let store = stackless_core::state::Store::open_configured().ok()?;
627    let checkpoints = store.checkpoints(instance).ok()?;
628    checkpoints.into_iter().find_map(|checkpoint| {
629        if checkpoint.step_id == format!("start:{service}")
630            && checkpoint.resource_kind == "laravel-cloud-application"
631        {
632            serde_json::from_str::<LaravelCloudPayload>(&checkpoint.payload).ok()
633        } else {
634            None
635        }
636    })
637}
638
639impl<R: CommandRunner> LaravelCloudSubstrate<R> {
640    async fn fetch_service_logs(
641        &self,
642        api: &LaravelCloudApi,
643        instance: &str,
644        service: &str,
645        tail: usize,
646    ) -> Result<Vec<String>, SubstrateFault> {
647        let Some(payload) = start_service_payload(instance, service) else {
648            return Ok(vec![format!(
649                "(no start checkpoint for service {service}; run `stackless up` first)"
650            )]);
651        };
652        api.fetch_logs(&payload.deployment_id, &payload.environment_id, tail)
653            .await
654            .map_err(fault)
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use stackless_stripe_projects::stripe::{CommandOutput, CommandRunner};
662    use stackless_stripe_projects::test_support;
663    use std::path::Path as StdPath;
664
665    struct NoRunner;
666    #[async_trait]
667    impl CommandRunner for NoRunner {
668        async fn run(
669            &self,
670            _args: &[String],
671            _cwd: &StdPath,
672        ) -> Result<CommandOutput, ProjectsError> {
673            Err(ProjectsError::Unavailable {
674                detail: "stripe should not be called in this test".into(),
675            })
676        }
677    }
678
679    fn checkpoint(kind: &str, step_id: &str, payload: &str) -> Checkpoint {
680        Checkpoint {
681            instance: "demo".into(),
682            step_id: step_id.into(),
683            resource_kind: kind.into(),
684            resource_id: "atto-demo-web".into(),
685            payload: payload.into(),
686            recorded_at: 0,
687        }
688    }
689
690    fn laravel_def() -> StackDef {
691        StackDef::parse(
692            "[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",
693        )
694        .unwrap()
695    }
696
697    fn subj() -> (tempfile::TempDir, LaravelCloudSubstrate<NoRunner>) {
698        let dir = tempfile::tempdir().unwrap();
699        std::fs::write(dir.path().join(api_key::KEY_FILE), "tok_test").unwrap();
700        let s = LaravelCloudSubstrate::for_test(NoRunner, dir.path(), "http://127.0.0.1:1", false);
701        (dir, s)
702    }
703
704    const PAYLOAD: &str = r#"{"stripe_resource":"demo-web","app_id":"app_1","app_name":"atto-demo-web","environment_id":"env_1","deployment_id":"dep_1","origin":"https://atto-demo-web.laravel.cloud"}"#;
705
706    #[test]
707    fn resource_name_and_origin_are_dns_safe() {
708        let def = laravel_def();
709        assert_eq!(
710            LaravelCloudSubstrate::<TokioRunner>::resource_name(&def, "demo", "web"),
711            "atto-demo-web"
712        );
713        let (_dir, s) = subj();
714        assert_eq!(
715            s.service_origin(&def, "demo", "web"),
716            "https://atto-demo-web.laravel.cloud"
717        );
718    }
719
720    #[test]
721    fn laravel_cloud_substrate_defaults() {
722        let s = LaravelCloudSubstrate::new(std::env::temp_dir(), Default::default(), false);
723        assert_eq!(s.name(), "laravel-cloud");
724        assert!(!s.supports_source_override());
725        assert_eq!(s.default_lease(), Duration::from_secs(8 * 3600));
726    }
727
728    #[tokio::test]
729    async fn application_present_when_stripe_registers_it() {
730        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&["demo-web"])]);
731        let dir = tempfile::tempdir().unwrap();
732        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
733        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
734        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Present);
735    }
736
737    #[tokio::test]
738    async fn application_gone_when_stripe_does_not_register_it() {
739        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&[])]);
740        let dir = tempfile::tempdir().unwrap();
741        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
742        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
743        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Gone);
744    }
745
746    #[tokio::test]
747    async fn source_ref_observes_gone_so_teardown_drops_it() {
748        let (_dir, s) = subj();
749        let cp = checkpoint(
750            "source-ref",
751            "materialize:web",
752            r#"{"repo":"r","ref":"main"}"#,
753        );
754        assert_eq!(s.observe("demo", &cp).await.unwrap(), Observation::Gone);
755        s.destroy("demo", &cp).await.unwrap();
756    }
757
758    #[tokio::test]
759    async fn unknown_resource_kind_fails_closed() {
760        let (_dir, s) = subj();
761        let cp = checkpoint("not-a-real-kind", "start:web", "{}");
762        assert!(s.observe("demo", &cp).await.is_err());
763        assert!(s.destroy("demo", &cp).await.is_err());
764    }
765
766    #[tokio::test]
767    async fn teardown_removes_via_stripe() {
768        let runner = test_support::ScriptedRunner::new(vec![
769            test_support::services(&["demo-web"]),
770            test_support::ok_empty(),
771        ]);
772        let dir = tempfile::tempdir().unwrap();
773        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
774        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
775        s.destroy("demo", &cp).await.unwrap();
776        let calls = runner.calls();
777        assert!(
778            calls
779                .iter()
780                .any(|c| c.first().map(String::as_str) == Some("remove")
781                    && c.iter().any(|a| a == "demo-web")),
782            "expected a `remove demo-web` call, got {calls:?}"
783        );
784    }
785}