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`). Native lifecycle records retain deployment IDs and
14//! require application absence before removing the Stripe registration.
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;
30mod lifecycle;
31
32use stackless_core::substrate::InstanceContext;
33use std::collections::BTreeMap;
34use std::path::PathBuf;
35use std::time::Duration;
36
37use async_trait::async_trait;
38use serde::{Deserialize, Serialize};
39use stackless_core::def::{Namespace, StackDef};
40use stackless_core::engine::StepKind;
41use stackless_core::state::Checkpoint;
42use stackless_core::substrate::{
43    NamespacePurpose, Observation, ServiceLog, StepContext, StepResource, Substrate, SubstrateFault,
44};
45use tokio::sync::Mutex;
46
47use crate::config::{LaravelCloudApplicationConfig, ServiceLaravelCloud};
48use crate::error::LaravelCloudError;
49use crate::laravel_api::{HEALTH_BUDGET, LARAVEL_DEPLOY_BUDGET, LaravelCloudApi};
50use stackless_stripe_projects::ProjectsError;
51use stackless_stripe_projects::provision::{ProvisionContext, provision_outputs};
52use stackless_stripe_projects::stripe::{CommandRunner, StripeProjects, TokioRunner};
53use stackless_stripe_projects::{project, requires_confirmation};
54
55pub const SUBSTRATE_NAME: &str = "laravel-cloud";
56
57/// The hard per-provider spend cap set on first paid confirmation (§4).
58pub const SPEND_CAP_USD: u32 = 25;
59
60/// The provider prefix Stripe uses for `laravel_cloud/application` output env vars.
61const PROVIDER_PREFIX: &str = "LARAVEL_CLOUD";
62
63fn fault(err: LaravelCloudError) -> SubstrateFault {
64    SubstrateFault::from_fault(&err)
65}
66
67fn projects_fault(err: ProjectsError) -> SubstrateFault {
68    SubstrateFault::from_fault(&err)
69}
70
71fn integration_fault(err: stackless_integrations::IntegrationError) -> SubstrateFault {
72    SubstrateFault::from_fault(&err)
73}
74
75fn prepare_fault(f: stackless_cloud::prepare::PrepareFailure) -> SubstrateFault {
76    fault(LaravelCloudError::PrepareFailed {
77        service: f.service,
78        command: f.command,
79        message: f.message,
80        log_tail: f.log_tail,
81    })
82}
83
84/// What a `start:<service>` checkpoint records: the live Laravel Cloud application.
85/// Native state is merged with the catalog ownership receipt.
86#[derive(Debug, Serialize, Deserialize)]
87struct LaravelCloudPayload {
88    stripe_resource: String,
89    app_id: String,
90    app_name: String,
91    environment_id: String,
92    deployment_id: String,
93    origin: String,
94    #[serde(default)]
95    commit_hash: String,
96    #[serde(default)]
97    branch_name: String,
98    #[serde(default, rename = "_laravel_cloud")]
99    native: Option<lifecycle::NativeState>,
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(
165        &self,
166        instance: &InstanceContext<'_>,
167    ) -> Result<LaravelCloudApi, SubstrateFault> {
168        let token = self.laravel_token(instance).await?;
169        let api = match &self.api_base {
170            Some(base) => LaravelCloudApi::with_base(token, base.clone()),
171            None => LaravelCloudApi::new(token),
172        };
173        Ok(match self.poll_interval {
174            Some(interval) => api.with_poll_interval(interval),
175            None => api,
176        })
177    }
178
179    async fn laravel_token(
180        &self,
181        instance: &InstanceContext<'_>,
182    ) -> Result<String, SubstrateFault> {
183        let pulled = project::pull_env_values(
184            &self.stripe(),
185            instance.resource_namespace,
186            &["LARAVEL_CLOUD_API_TOKEN"],
187        )
188        .await
189        .map_err(projects_fault)?;
190        if let Some(token) = pulled
191            .into_iter()
192            .flatten()
193            .find(|value| !value.trim().is_empty())
194        {
195            return Ok(token);
196        }
197        api_key::resolve(&self.definition_dir, &self.secrets).map_err(fault)
198    }
199
200    /// `{stack}-{instance}-{service}` (DNS-safe).
201    fn resource_name(def: &StackDef, instance: &InstanceContext<'_>, node: &str) -> String {
202        instance.provider_resource_name(def.stack.name.as_str(), node)
203    }
204
205    fn namespace(
206        &self,
207        def: &StackDef,
208        instance: &InstanceContext<'_>,
209        prior: &[Checkpoint],
210    ) -> Namespace {
211        let mut namespace = Namespace {
212            stack_name: def.stack.name.clone(),
213            instance_name: stackless_core::types::DnsName::from_stored(instance.name),
214            ..Namespace::default()
215        };
216        for service in def.services.keys() {
217            if let Some(origin) = prior
218                .iter()
219                .find(|cp| cp.step_id == format!("start:{service}"))
220                .and_then(|cp| serde_json::from_str::<LaravelCloudPayload>(&cp.payload).ok())
221                .map(|payload| payload.origin)
222                .filter(|origin| !origin.is_empty())
223            {
224                namespace.service_origins.insert(service.clone(), origin);
225            }
226        }
227        namespace.secrets = stackless_core::security::application_secrets(&self.secrets);
228        namespace.add_integration_checkpoints(prior);
229        instance.bind_namespace(&mut namespace, def);
230        namespace
231    }
232
233    async fn ensure_project_and_env(
234        &self,
235        def: &StackDef,
236        instance: &InstanceContext<'_>,
237    ) -> Result<(), SubstrateFault> {
238        let mut done = self.ensured.lock().await;
239        if *done {
240            return Ok(());
241        }
242        let spend = self
243            .confirm_paid
244            .then_some((SPEND_CAP_USD, "laravel-cloud"));
245        stackless_cloud::ensure::project_and_env(
246            &self.stripe(),
247            def,
248            &self.definition_dir,
249            instance.resource_namespace,
250            spend,
251        )
252        .await
253        .map_err(projects_fault)?;
254        *done = true;
255        Ok(())
256    }
257
258    fn require_confirm_paid(&self, resource: &str) -> Result<(), SubstrateFault> {
259        if !self.confirm_paid {
260            return Err(fault(LaravelCloudError::PaymentNotConfirmed {
261                resource: resource.to_owned(),
262            }));
263        }
264        Ok(())
265    }
266
267    async fn start_service(
268        &self,
269        step_ctx: &StepContext<'_>,
270    ) -> Result<StepResource, SubstrateFault> {
271        let def = step_ctx.def;
272        let instance = step_ctx.instance;
273        let service = step_ctx.step.node.as_str();
274        let stripe =
275            self.stripe()
276                .with_journal(step_ctx, SUBSTRATE_NAME, "laravel-cloud-application");
277        let catalog_journal = stripe
278            .journal()
279            .ok_or_else(|| fault(lifecycle::invalid("catalog journal missing")))?;
280        let laravel_cfg = config::service_laravel_cloud(def, service).map_err(fault)?;
281        let app_name = Self::resource_name(def, instance, service);
282        let resource = instance.resource_name(service);
283
284        let catalog = stripe
285            .catalog_for::<LaravelCloudApplicationConfig>()
286            .await
287            .map_err(projects_fault)?;
288        let cfg = application_config(&app_name, &laravel_cfg);
289        if requires_confirmation(&catalog, &cfg).unwrap_or(false) {
290            self.require_confirm_paid(&resource)?;
291        }
292        let ctx = ProvisionContext {
293            def,
294            instance: instance.resource_namespace,
295            logical_name: service,
296            definition_dir: &self.definition_dir,
297            substrate: SUBSTRATE_NAME,
298            skip_instance_context: true,
299        };
300        let (_resource_name, outputs) = provision_outputs(
301            &stripe,
302            &catalog,
303            &ctx,
304            &cfg,
305            PROVIDER_PREFIX,
306            stackless_integrations::providers::laravel_cloud::application::OUTPUT_FIELDS,
307        )
308        .await
309        .map_err(projects_fault)?;
310        let app_id = outputs.get("app_id").ok_or_else(|| {
311            fault(LaravelCloudError::ProvisionFailed {
312                resource: resource.clone(),
313                detail: "laravel_cloud/application did not return an app_id".into(),
314            })
315        })?;
316
317        let native = lifecycle::Journal::new(step_ctx, &resource, self.step_revision(step_ctx)?)
318            .map_err(fault)?;
319        native.bind(app_id).map_err(fault)?;
320        let mut payload = LaravelCloudPayload {
321            stripe_resource: resource,
322            app_id: app_id.clone(),
323            app_name: app_name.clone(),
324            environment_id: String::new(),
325            deployment_id: String::new(),
326            origin: String::new(),
327            commit_hash: String::new(),
328            branch_name: String::new(),
329            native: Some(native.load().map_err(fault)?),
330        };
331        save_application(catalog_journal, &payload, false)?;
332        let api = self
333            .laravel_api(instance)
334            .await?
335            .with_journal(native.clone());
336        let deploy = api
337            .deploy_application(
338                laravel_api::DeploymentTarget {
339                    app_id,
340                    app_name: &app_name,
341                    repository: &laravel_cfg.repository,
342                    reference: &def.services[service].source.reference,
343                    root: laravel_cfg.root.as_deref(),
344                },
345                service,
346                LARAVEL_DEPLOY_BUDGET,
347            )
348            .await
349            .map_err(fault)?;
350
351        payload.environment_id = deploy.environment_id;
352        payload.deployment_id = deploy.deployment_id;
353        payload.origin = deploy.origin;
354        payload.commit_hash = deploy.commit_hash;
355        payload.branch_name = deploy.branch_name;
356        payload.native = Some(native.load().map_err(fault)?);
357        save_application(catalog_journal, &payload, true)
358    }
359
360    async fn run_hook(&self, ctx: &StepContext<'_>) -> Result<StepResource, SubstrateFault> {
361        stackless_cloud::prepare::run_snapshot_hook(
362            ctx,
363            &self.definition_dir,
364            &self.namespace(ctx.def, ctx.instance, ctx.prior),
365            &self.secrets,
366            SUBSTRATE_NAME,
367        )
368        .await
369        .map_err(|failure| {
370            stackless_cloud::prepare::hook_fault(ctx.step.kind, failure, prepare_fault)
371        })
372    }
373
374    async fn health_gate(
375        &self,
376        def: &StackDef,
377        _instance: &InstanceContext<'_>,
378        service: &str,
379        prior: &[Checkpoint],
380    ) -> Result<(), SubstrateFault> {
381        let spec = def.services.get(service).ok_or_else(|| {
382            fault(LaravelCloudError::ConfigInvalid {
383                location: format!("services.{service}"),
384                detail: "service not in definition".into(),
385            })
386        })?;
387        let origin = prior
388            .iter()
389            .find(|c| {
390                c.resource_kind == "laravel-cloud-application"
391                    && c.step_id == format!("start:{service}")
392            })
393            .and_then(|c| serde_json::from_str::<LaravelCloudPayload>(&c.payload).ok())
394            .map(|p| p.origin)
395            .filter(|origin| !origin.trim().is_empty())
396            .ok_or_else(|| {
397                fault(LaravelCloudError::ConfigInvalid {
398                    location: format!("services.{service}.health"),
399                    detail: "deployment has no recorded provider endpoint".into(),
400                })
401            })?;
402        let Some(health) = &spec.health else {
403            return Ok(());
404        };
405        let url = format!("{origin}{}", health.path);
406        stackless_cloud::health::poll(
407            &url,
408            health.status.get(),
409            health.contains.as_deref(),
410            HEALTH_BUDGET,
411        )
412        .await
413        .map_err(|f| {
414            fault(LaravelCloudError::HealthFailed {
415                service: service.to_owned(),
416                url: f.url,
417                detail: f.detail,
418                budget_secs: f.budget_secs,
419            })
420        })
421    }
422}
423
424fn application_config(name: &str, cfg: &ServiceLaravelCloud) -> LaravelCloudApplicationConfig {
425    LaravelCloudApplicationConfig {
426        name: name.to_owned(),
427        region: cfg.region.clone(),
428        repository: cfg.repository.clone(),
429        create_cache: cfg.create_cache.clone(),
430        create_database: cfg.create_database.clone(),
431    }
432}
433
434#[async_trait]
435impl<R: CommandRunner> Substrate for LaravelCloudSubstrate<R> {
436    fn name(&self) -> &str {
437        SUBSTRATE_NAME
438    }
439
440    fn capabilities(&self) -> stackless_core::capabilities::Capabilities {
441        stackless_core::capabilities::Capabilities::cloud(false, true)
442    }
443
444    fn validate_definition(&self, def: &StackDef) -> Result<(), SubstrateFault> {
445        for service in def.services.keys() {
446            if def.services[service]
447                .on
448                .as_deref()
449                .is_some_and(|on| on != SUBSTRATE_NAME)
450            {
451                continue;
452            }
453            config::service_laravel_cloud(def, service).map_err(fault)?;
454        }
455        Ok(())
456    }
457
458    fn supports_source_override(&self) -> bool {
459        false
460    }
461
462    fn default_lease(&self) -> Duration {
463        Duration::from_secs(8 * 3600)
464    }
465
466    fn build_namespace(
467        &self,
468        def: &StackDef,
469        instance: &InstanceContext<'_>,
470        prior: &[Checkpoint],
471        secrets: &BTreeMap<String, String>,
472        _purpose: NamespacePurpose,
473    ) -> Namespace {
474        let mut namespace = self.namespace(def, instance, prior);
475        namespace.secrets = stackless_core::security::application_secrets(secrets);
476        namespace
477    }
478
479    fn step_revision(&self, ctx: &StepContext<'_>) -> Result<String, SubstrateFault> {
480        let definition = stackless_core::engine::revision::step_revision(ctx, self)?;
481        if matches!(
482            ctx.step.kind,
483            StepKind::Start | StepKind::Setup | StepKind::Prepare
484        ) {
485            stackless_core::engine::revision::digest(&(
486                definition,
487                stackless_core::security::application_secrets(&self.secrets),
488            ))
489        } else {
490            Ok(definition)
491        }
492    }
493
494    fn refresh_each_operation(&self, step: &stackless_core::engine::Step) -> bool {
495        matches!(
496            step.kind,
497            StepKind::Materialize | StepKind::Prepare | StepKind::HealthGate
498        )
499    }
500
501    async fn execute(&self, ctx: StepContext<'_>) -> Result<StepResource, SubstrateFault> {
502        stackless_cloud::prepare::durable::require_host_grant(&ctx)?;
503        self.ensure_project_and_env(ctx.def, ctx.instance).await?;
504
505        let node = ctx.step.node.as_str();
506        match ctx.step.kind {
507            StepKind::RunJob => Err(stackless_core::capabilities::unsupported_feature(
508                SUBSTRATE_NAME,
509                &ctx.step.node,
510                "jobs",
511            )),
512            StepKind::ProvisionIntegration => stackless_integrations::provision(
513                SUBSTRATE_NAME,
514                &self.stripe(),
515                &ctx,
516                &self.definition_dir,
517                true,
518            )
519            .await
520            .map_err(integration_fault),
521            StepKind::Materialize => {
522                stackless_cloud::source::materialize(
523                    &ctx,
524                    &self.definition_dir,
525                    SUBSTRATE_NAME,
526                    &self.secrets,
527                )
528                .await
529            }
530            StepKind::Setup | StepKind::Prepare => self.run_hook(&ctx).await,
531            StepKind::Start => self.start_service(&ctx).await,
532            StepKind::HealthGate => {
533                self.health_gate(ctx.def, ctx.instance, node, ctx.prior)
534                    .await?;
535                Ok(stackless_core::substrate::action_resource(&ctx.step.id))
536            }
537        }
538    }
539
540    async fn observe(
541        &self,
542        instance: &InstanceContext<'_>,
543        checkpoint: &Checkpoint,
544    ) -> Result<Observation, SubstrateFault> {
545        match checkpoint.resource_kind.as_str() {
546            stackless_cloud::prepare::durable::KIND => stackless_cloud::prepare::durable::observe(
547                &self.definition_dir,
548                instance,
549                SUBSTRATE_NAME,
550                checkpoint,
551            ),
552            stackless_cloud::source::KIND => {
553                stackless_cloud::source::observe(&self.definition_dir, instance, checkpoint)
554            }
555            "laravel-cloud-application" => {
556                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
557                    &checkpoint.payload,
558                )
559                .map_err(|detail| {
560                    fault(LaravelCloudError::ConfigInvalid {
561                        location: "checkpoint.payload".into(),
562                        detail,
563                    })
564                })?;
565                if payload.as_ref().is_some_and(|p| p.native.is_some()) {
566                    let value: serde_json::Value = serde_json::from_str(&checkpoint.payload)
567                        .map_err(|e| fault(lifecycle::invalid(e.to_string())))?;
568                    let (native, name, repository) = self
569                        .native_identity(instance, &checkpoint.resource_id, &value)
570                        .await?;
571                    let id = native.app_id.as_deref().ok_or_else(|| {
572                        fault(lifecycle::invalid("native application ID missing"))
573                    })?;
574                    let api = self.laravel_api(instance).await?;
575                    if api
576                        .owned_application(id, &name, &repository)
577                        .await
578                        .map_err(fault)?
579                        .is_none()
580                    {
581                        return Ok(Observation::Gone);
582                    }
583                    let payload = payload
584                        .as_ref()
585                        .ok_or_else(|| fault(lifecycle::invalid("checkpoint missing")))?;
586                    let matches: Vec<_> = native
587                        .requests
588                        .values()
589                        .filter(|r| r.deployment_id.as_deref() == Some(&payload.deployment_id))
590                        .collect();
591                    if matches.len() != 1
592                        || matches[0].environment_id != payload.environment_id
593                        || matches[0].commit.as_deref() != Some(&payload.commit_hash)
594                        || matches[0].branch.as_deref() != Some(&payload.branch_name)
595                    {
596                        return Err(fault(lifecycle::invalid(
597                            "checkpoint differs from the durable deployment identity",
598                        )));
599                    }
600                    return Ok(
601                        if api
602                            .deployment_ready(
603                                id,
604                                &payload.environment_id,
605                                &payload.deployment_id,
606                                &payload.commit_hash,
607                                &payload.branch_name,
608                            )
609                            .await
610                            .map_err(fault)?
611                        {
612                            Observation::Present
613                        } else {
614                            Observation::Drifted {
615                                settings: vec![stackless_core::substrate::SettingDrift {
616                                    setting: "deployment.revision".into(),
617                                    expected: payload.commit_hash.clone(),
618                                    actual: "not running the recorded deployment".into(),
619                                }],
620                            }
621                        },
622                    );
623                }
624                let stripe_resource = payload
625                    .map(|p| p.stripe_resource)
626                    .unwrap_or_else(|| checkpoint.resource_id.clone());
627                let present = project::resource_registered(&self.stripe(), &stripe_resource)
628                    .await
629                    .map_err(projects_fault)?;
630                Ok(stackless_core::substrate::present_or_gone(present))
631            }
632            kind if stackless_integrations::is_integration_resource(kind) => {
633                stackless_integrations::observe(
634                    SUBSTRATE_NAME,
635                    &self.stripe(),
636                    &checkpoint.payload,
637                    &checkpoint.resource_id,
638                    kind,
639                )
640                .await
641                .map_err(integration_fault)
642            }
643            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => {
644                Ok(Observation::Gone)
645            }
646            kind => Err(fault(LaravelCloudError::ConfigInvalid {
647                location: "checkpoint.resource_kind".into(),
648                detail: format!("unknown resource kind {kind:?}"),
649            })),
650        }
651    }
652
653    async fn destroy(
654        &self,
655        instance: &InstanceContext<'_>,
656        checkpoint: &Checkpoint,
657    ) -> Result<(), SubstrateFault> {
658        match checkpoint.resource_kind.as_str() {
659            stackless_cloud::source::KIND => {
660                stackless_cloud::source::destroy(&self.definition_dir, instance, checkpoint)
661            }
662            "laravel-cloud-application" => {
663                let payload = stackless_cloud::checkpoint::parse_payload::<LaravelCloudPayload>(
664                    &checkpoint.payload,
665                )
666                .map_err(|detail| {
667                    fault(LaravelCloudError::ConfigInvalid {
668                        location: "checkpoint.payload".into(),
669                        detail,
670                    })
671                })?;
672                if payload.as_ref().is_some_and(|p| p.native.is_some()) {
673                    return Err(fault(lifecycle::invalid(
674                        "native teardown requires the resource inventory",
675                    )));
676                }
677                let stripe_resource = payload
678                    .map(|p| p.stripe_resource)
679                    .unwrap_or_else(|| checkpoint.resource_id.clone());
680                project::remove_resource(&self.stripe(), &stripe_resource)
681                    .await
682                    .map_err(projects_fault)
683            }
684            kind if stackless_integrations::is_integration_resource(kind) => {
685                stackless_integrations::destroy(
686                    SUBSTRATE_NAME,
687                    &self.stripe(),
688                    &checkpoint.payload,
689                    &checkpoint.resource_id,
690                    kind,
691                )
692                .await
693                .map_err(integration_fault)
694            }
695            kind if stackless_cloud::checkpoint::is_ephemeral_resource_kind(kind) => Ok(()),
696            kind => Err(fault(LaravelCloudError::ConfigInvalid {
697                location: "checkpoint.resource_kind".into(),
698                detail: format!("unknown resource kind {kind:?}"),
699            })),
700        }
701    }
702
703    async fn destroy_record(
704        &self,
705        store: &stackless_core::state::Store,
706        instance: &InstanceContext<'_>,
707        record: &stackless_core::state::ResourceRecord,
708    ) -> Result<(), SubstrateFault> {
709        if record.resource_kind == stackless_cloud::prepare::durable::KIND {
710            return stackless_cloud::prepare::durable::destroy_record(
711                &self.definition_dir,
712                store,
713                instance,
714                SUBSTRATE_NAME,
715                record,
716            )
717            .await;
718        }
719        if record.owner_id != instance.id
720            || record.ownership != stackless_core::state::Ownership::Owned
721        {
722            return Err(fault(lifecycle::invalid(
723                "teardown requires this instance's ownership record",
724            )));
725        }
726        if !has_catalog_receipt(&record.payload) {
727            return self
728                .destroy(instance, &record.checkpoint(instance.name))
729                .await;
730        }
731        stackless_stripe_projects::journal::recover_for_teardown(&self.stripe(), store, record)
732            .await
733            .map_err(projects_fault)?;
734        let current = store
735            .resource(instance.id, &record.key)
736            .map_err(|e| SubstrateFault::from_fault(&e))?
737            .ok_or_else(|| fault(lifecycle::invalid("catalog record disappeared")))?;
738        if current.phase == stackless_core::state::ResourcePhase::Absent {
739            return Ok(());
740        }
741        if current.resource_kind == "laravel-cloud-application" {
742            let mut value: serde_json::Value = serde_json::from_str(&current.payload)
743                .map_err(|e| fault(lifecycle::invalid(e.to_string())))?;
744            let (mut native, name, repository) = self
745                .native_identity(instance, &current.resource_id, &value)
746                .await?;
747            save_native(store, instance.id, &current, &mut value, &native)?;
748            let id = native
749                .app_id
750                .clone()
751                .ok_or_else(|| fault(lifecycle::invalid("native application ID unresolved")))?;
752            let api = self.laravel_api(instance).await?;
753            if api
754                .owned_application(&id, &name, &repository)
755                .await
756                .map_err(fault)?
757                .is_some()
758            {
759                if !native.removal_submitted {
760                    native.removal_submitted = true;
761                    save_native(store, instance.id, &current, &mut value, &native)?;
762                    api.delete_application(&id).await.map_err(fault)?;
763                }
764                if api
765                    .owned_application(&id, &name, &repository)
766                    .await
767                    .map_err(fault)?
768                    .is_some()
769                {
770                    return Err(fault(lifecycle::invalid(
771                        "native application deletion is unconfirmed; retaining ownership",
772                    )));
773                }
774            }
775        }
776        let current = store
777            .resource(instance.id, &record.key)
778            .map_err(|e| SubstrateFault::from_fault(&e))?
779            .ok_or_else(|| fault(lifecycle::invalid("catalog record disappeared")))?;
780        stackless_stripe_projects::journal::destroy_record(&self.stripe(), store, &current)
781            .await
782            .map_err(projects_fault)
783    }
784
785    async fn observe_record(
786        &self,
787        store: &stackless_core::state::Store,
788        instance: &InstanceContext<'_>,
789        record: &stackless_core::state::ResourceRecord,
790    ) -> Result<Observation, SubstrateFault> {
791        if record.resource_kind == stackless_cloud::prepare::durable::KIND {
792            return stackless_cloud::prepare::durable::observe_record(
793                &self.definition_dir,
794                store,
795                instance,
796                SUBSTRATE_NAME,
797                record,
798            );
799        }
800        if record.owner_id != instance.id {
801            return Err(fault(lifecycle::invalid(
802                "resource belongs to another instance",
803            )));
804        }
805        let current = store
806            .resource(instance.id, &record.key)
807            .map_err(|e| SubstrateFault::from_fault(&e))?
808            .ok_or_else(|| fault(lifecycle::invalid("catalog record disappeared")))?;
809        if current.owner_id != instance.id {
810            return Err(fault(lifecycle::invalid(
811                "resource belongs to another instance",
812            )));
813        }
814        if current.phase == stackless_core::state::ResourcePhase::Absent {
815            return Ok(Observation::Gone);
816        }
817        if !has_catalog_receipt(&current.payload) {
818            return self
819                .observe(instance, &current.checkpoint(instance.name))
820                .await;
821        }
822        let catalog =
823            stackless_stripe_projects::journal::observe_payload(&self.stripe(), &current.payload)
824                .await
825                .map_err(projects_fault)?;
826        if current.resource_kind != "laravel-cloud-application" {
827            return Ok(catalog);
828        }
829        let value: serde_json::Value = serde_json::from_str(&current.payload)
830            .map_err(|e| fault(lifecycle::invalid(e.to_string())))?;
831        let (native, name, repository) = self
832            .native_identity(instance, &current.resource_id, &value)
833            .await?;
834        let api = self.laravel_api(instance).await?;
835        let id = native
836            .app_id
837            .as_deref()
838            .ok_or_else(|| fault(lifecycle::invalid("native application ID unresolved")))?;
839        if api
840            .owned_application(id, &name, &repository)
841            .await
842            .map_err(fault)?
843            .is_some()
844        {
845            return Ok(Observation::Present);
846        }
847        Ok(catalog)
848    }
849
850    async fn finalize_teardown(
851        &self,
852        instance: &InstanceContext<'_>,
853    ) -> Result<(), SubstrateFault> {
854        stackless_integrations::finalize_stripe_instance(
855            &self.stripe(),
856            instance.resource_namespace,
857        )
858        .await;
859        Ok(())
860    }
861
862    async fn spend(&self) -> Option<stackless_core::substrate::SpendInfo> {
863        Some(
864            stackless_cloud::spend::fetch(
865                &self.definition_dir,
866                SUBSTRATE_NAME,
867                SPEND_CAP_USD,
868                "cloud.laravel.com",
869            )
870            .await,
871        )
872    }
873
874    async fn fetch_logs(
875        &self,
876        _store: &stackless_core::state::Store,
877        _def: &StackDef,
878        instance: &InstanceContext<'_>,
879        services: &[String],
880        tail: usize,
881    ) -> Result<Option<Vec<ServiceLog>>, SubstrateFault> {
882        let api = self.laravel_api(instance).await?;
883        let mut out = Vec::with_capacity(services.len());
884        for service in services {
885            let lines = self
886                .fetch_service_logs(&api, instance, service, tail)
887                .await?;
888            out.push(ServiceLog {
889                service: service.clone(),
890                source: "laravel_cloud_api",
891                log_path: None,
892                lines,
893            });
894        }
895        Ok(Some(out))
896    }
897}
898
899fn has_catalog_receipt(payload: &str) -> bool {
900    serde_json::from_str::<serde_json::Value>(payload)
901        .ok()
902        .is_some_and(|value| value.get("_catalog_creation").is_some())
903}
904
905fn save_native(
906    store: &stackless_core::state::Store,
907    owner: &str,
908    record: &stackless_core::state::ResourceRecord,
909    value: &mut serde_json::Value,
910    native: &lifecycle::NativeState,
911) -> Result<(), SubstrateFault> {
912    value["_laravel_cloud"] =
913        serde_json::to_value(native).map_err(|e| fault(lifecycle::invalid(e.to_string())))?;
914    store
915        .resource_refresh_payload(owner, &record.key, &record.resource_id, &value.to_string())
916        .map_err(|e| SubstrateFault::from_fault(&e))
917}
918
919fn save_application(
920    journal: &stackless_stripe_projects::journal::ResourceJournal,
921    payload: &LaravelCloudPayload,
922    ready: bool,
923) -> Result<StepResource, SubstrateFault> {
924    let mut resource = StepResource {
925        resource_kind: "laravel-cloud-application".into(),
926        resource_id: payload.stripe_resource.clone(),
927        payload: serde_json::to_string(payload)
928            .map_err(|e| fault(lifecycle::invalid(e.to_string())))?,
929    };
930    resource.payload = journal.outputs(&resource, ready).map_err(projects_fault)?;
931    Ok(resource)
932}
933
934fn start_service_payload(
935    instance: &InstanceContext<'_>,
936    service: &str,
937) -> Option<LaravelCloudPayload> {
938    instance.checkpoints.iter().find_map(|checkpoint| {
939        if checkpoint.step_id == format!("start:{service}")
940            && checkpoint.resource_kind == "laravel-cloud-application"
941        {
942            serde_json::from_str::<LaravelCloudPayload>(&checkpoint.payload).ok()
943        } else {
944            None
945        }
946    })
947}
948
949impl<R: CommandRunner> LaravelCloudSubstrate<R> {
950    async fn native_identity(
951        &self,
952        instance: &InstanceContext<'_>,
953        resource: &str,
954        value: &serde_json::Value,
955    ) -> Result<(lifecycle::NativeState, String, String), SubstrateFault> {
956        let mut native: lifecycle::NativeState = match value.get("_laravel_cloud") {
957            None | Some(serde_json::Value::Null) => Default::default(),
958            Some(value) => serde_json::from_value(value.clone())
959                .map_err(|e| fault(lifecycle::invalid(e.to_string())))?,
960        };
961        let config = value
962            .pointer("/_catalog_creation/config")
963            .ok_or_else(|| fault(lifecycle::invalid("catalog configuration missing")))?;
964        let name = config
965            .get("name")
966            .and_then(serde_json::Value::as_str)
967            .filter(|v| !v.is_empty())
968            .ok_or_else(|| fault(lifecycle::invalid("catalog application name missing")))?;
969        let repository = config
970            .get("repository")
971            .and_then(serde_json::Value::as_str)
972            .filter(|v| !v.is_empty())
973            .ok_or_else(|| fault(lifecycle::invalid("catalog repository missing")))?;
974        if value
975            .get("app_name")
976            .and_then(serde_json::Value::as_str)
977            .is_some_and(|old| old != name)
978        {
979            return Err(fault(lifecycle::invalid(
980                "native name differs from catalog request",
981            )));
982        }
983        let resource_key = format!("{}_APP_ID", resource.to_ascii_uppercase().replace('-', "_"));
984        let keys = [resource_key.as_str(), "LARAVEL_CLOUD_APP_ID"];
985        let mut candidates = Vec::new();
986        if let Some(id) = &native.app_id {
987            candidates.push(id.clone());
988        }
989        if let Some(id) = value.get("app_id").and_then(serde_json::Value::as_str) {
990            candidates.push(id.into());
991        }
992        if let Some(response) = value.pointer("/_catalog_creation/response") {
993            candidates.extend(
994                keys.iter()
995                    .filter_map(|key| project::find_env_value(response, key)),
996            );
997        }
998        if candidates.is_empty() {
999            candidates.extend(
1000                project::pull_env_values(&self.stripe(), instance.resource_namespace, &keys)
1001                    .await
1002                    .map_err(projects_fault)?
1003                    .into_iter()
1004                    .flatten(),
1005            );
1006        }
1007        let id = candidates.first().ok_or_else(|| {
1008            fault(lifecycle::invalid(
1009                "catalog creation has no recoverable native application ID",
1010            ))
1011        })?;
1012        if !laravel_api::valid_id(id) || candidates.iter().any(|candidate| candidate != id) {
1013            return Err(fault(lifecycle::invalid(
1014                "native application identity fields disagree or are invalid",
1015            )));
1016        }
1017        native.app_id = Some(id.clone());
1018        Ok((native, name.into(), repository.into()))
1019    }
1020
1021    async fn fetch_service_logs(
1022        &self,
1023        api: &LaravelCloudApi,
1024        instance: &InstanceContext<'_>,
1025        service: &str,
1026        tail: usize,
1027    ) -> Result<Vec<String>, SubstrateFault> {
1028        let Some(payload) = start_service_payload(instance, service) else {
1029            return Ok(vec![format!(
1030                "(no start checkpoint for service {service}; run `stackless up` first)"
1031            )]);
1032        };
1033        api.fetch_logs(&payload.deployment_id, &payload.environment_id, tail)
1034            .await
1035            .map_err(fault)
1036    }
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041    use super::*;
1042    use stackless_stripe_projects::stripe::{CommandOutput, CommandRunner};
1043    use stackless_stripe_projects::test_support;
1044    use std::path::Path as StdPath;
1045
1046    struct NoRunner;
1047    #[async_trait]
1048    impl CommandRunner for NoRunner {
1049        async fn run(
1050            &self,
1051            _args: &[String],
1052            _cwd: &StdPath,
1053        ) -> Result<CommandOutput, ProjectsError> {
1054            Err(ProjectsError::Unavailable {
1055                detail: "stripe should not be called in this test".into(),
1056            })
1057        }
1058    }
1059
1060    fn checkpoint(kind: &str, step_id: &str, payload: &str) -> Checkpoint {
1061        Checkpoint {
1062            instance: "demo".into(),
1063            step_id: step_id.into(),
1064            resource_kind: kind.into(),
1065            resource_id: "atto-demo-web".into(),
1066            payload: payload.into(),
1067            recorded_at: 0,
1068        }
1069    }
1070
1071    fn laravel_def() -> StackDef {
1072        StackDef::parse(
1073            "[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",
1074        )
1075        .unwrap()
1076    }
1077
1078    fn subj() -> (tempfile::TempDir, LaravelCloudSubstrate<NoRunner>) {
1079        let dir = tempfile::tempdir().unwrap();
1080        std::fs::write(dir.path().join(api_key::KEY_FILE), "tok_test").unwrap();
1081        let s = LaravelCloudSubstrate::for_test(NoRunner, dir.path(), "http://127.0.0.1:1", false);
1082        (dir, s)
1083    }
1084
1085    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"}"#;
1086
1087    #[tokio::test]
1088    async fn resource_names_are_dns_safe_and_origins_wait_for_outputs() {
1089        let def = laravel_def();
1090        assert_eq!(
1091            LaravelCloudSubstrate::<TokioRunner>::resource_name(
1092                &def,
1093                &InstanceContext {
1094                    routed_origins: None,
1095                    name: "demo",
1096                    id: "legacy-test",
1097                    resource_namespace: "demo",
1098                    checkpoints: &[]
1099                },
1100                "web"
1101            ),
1102            "atto-demo-web"
1103        );
1104        let (_dir, s) = subj();
1105        assert_eq!(
1106            s.service_origin(
1107                &def,
1108                &InstanceContext {
1109                    routed_origins: None,
1110                    name: "demo",
1111                    id: "legacy-test",
1112                    resource_namespace: "demo",
1113                    checkpoints: &[]
1114                },
1115                "web"
1116            ),
1117            ""
1118        );
1119        let context = InstanceContext {
1120            name: "demo",
1121            id: "legacy-test",
1122            resource_namespace: "demo",
1123            checkpoints: &[],
1124            routed_origins: None,
1125        };
1126        let error = tokio::time::timeout(
1127            Duration::from_millis(100),
1128            s.health_gate(&def, &context, "web", &[]),
1129        )
1130        .await
1131        .expect("missing URL must fail before health polling")
1132        .unwrap_err();
1133        assert!(error.message.contains("recorded"), "{error}");
1134    }
1135
1136    #[test]
1137    fn laravel_cloud_substrate_defaults() {
1138        let s = LaravelCloudSubstrate::new(std::env::temp_dir(), Default::default(), false);
1139        assert_eq!(s.name(), "laravel-cloud");
1140        assert!(!s.supports_source_override());
1141        assert_eq!(s.default_lease(), Duration::from_secs(8 * 3600));
1142    }
1143
1144    #[tokio::test]
1145    async fn application_present_when_stripe_registers_it() {
1146        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&["demo-web"])]);
1147        let dir = tempfile::tempdir().unwrap();
1148        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
1149        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
1150        assert_eq!(
1151            s.observe(
1152                &InstanceContext {
1153                    routed_origins: None,
1154                    name: "demo",
1155                    id: "legacy-test",
1156                    resource_namespace: "demo",
1157                    checkpoints: &[]
1158                },
1159                &cp
1160            )
1161            .await
1162            .unwrap(),
1163            Observation::Present
1164        );
1165    }
1166
1167    #[tokio::test]
1168    async fn application_gone_when_stripe_does_not_register_it() {
1169        let runner = test_support::ScriptedRunner::new(vec![test_support::services(&[])]);
1170        let dir = tempfile::tempdir().unwrap();
1171        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
1172        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
1173        assert_eq!(
1174            s.observe(
1175                &InstanceContext {
1176                    routed_origins: None,
1177                    name: "demo",
1178                    id: "legacy-test",
1179                    resource_namespace: "demo",
1180                    checkpoints: &[]
1181                },
1182                &cp
1183            )
1184            .await
1185            .unwrap(),
1186            Observation::Gone
1187        );
1188    }
1189
1190    #[tokio::test]
1191    async fn source_ref_observes_gone_so_teardown_drops_it() {
1192        let (_dir, s) = subj();
1193        let cp = checkpoint(
1194            "source-ref",
1195            "materialize:web",
1196            r#"{"repo":"r","ref":"main"}"#,
1197        );
1198        assert_eq!(
1199            s.observe(
1200                &InstanceContext {
1201                    routed_origins: None,
1202                    name: "demo",
1203                    id: "legacy-test",
1204                    resource_namespace: "demo",
1205                    checkpoints: &[]
1206                },
1207                &cp
1208            )
1209            .await
1210            .unwrap(),
1211            Observation::Gone
1212        );
1213        s.destroy(
1214            &InstanceContext {
1215                routed_origins: None,
1216                name: "demo",
1217                id: "legacy-test",
1218                resource_namespace: "demo",
1219                checkpoints: &[],
1220            },
1221            &cp,
1222        )
1223        .await
1224        .unwrap();
1225    }
1226
1227    #[tokio::test]
1228    async fn unknown_resource_kind_fails_closed() {
1229        let (_dir, s) = subj();
1230        let cp = checkpoint("not-a-real-kind", "start:web", "{}");
1231        assert!(
1232            s.observe(
1233                &InstanceContext {
1234                    routed_origins: None,
1235                    name: "demo",
1236                    id: "legacy-test",
1237                    resource_namespace: "demo",
1238                    checkpoints: &[]
1239                },
1240                &cp
1241            )
1242            .await
1243            .is_err()
1244        );
1245        assert!(
1246            s.destroy(
1247                &InstanceContext {
1248                    routed_origins: None,
1249                    name: "demo",
1250                    id: "legacy-test",
1251                    resource_namespace: "demo",
1252                    checkpoints: &[]
1253                },
1254                &cp
1255            )
1256            .await
1257            .is_err()
1258        );
1259    }
1260
1261    #[tokio::test]
1262    async fn teardown_removes_via_stripe() {
1263        let runner = test_support::ScriptedRunner::new(vec![
1264            test_support::services(&["demo-web"]),
1265            test_support::ok_empty(),
1266        ]);
1267        let dir = tempfile::tempdir().unwrap();
1268        let s = LaravelCloudSubstrate::for_test(&runner, dir.path(), "http://127.0.0.1:1", false);
1269        let cp = checkpoint("laravel-cloud-application", "start:web", PAYLOAD);
1270        s.destroy(
1271            &InstanceContext {
1272                routed_origins: None,
1273                name: "demo",
1274                id: "legacy-test",
1275                resource_namespace: "demo",
1276                checkpoints: &[],
1277            },
1278            &cp,
1279        )
1280        .await
1281        .unwrap();
1282        let calls = runner.calls();
1283        assert!(
1284            calls
1285                .iter()
1286                .any(|c| c.first().map(String::as_str) == Some("remove")
1287                    && c.iter().any(|a| a == "demo-web")),
1288            "expected a `remove demo-web` call, got {calls:?}"
1289        );
1290    }
1291}
1292
1293#[cfg(test)]
1294mod lifecycle_tests;