rustlift 2.0.1

A typestate-driven deployment agent for Azure Web Apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
// Copyright (c) 2026 Hamze Ghalebi. All rights reserved.
// Licensed under the Rustlift Non-Commercial Licence v1.0.

//! Typestate deployment pipeline for Azure Web Apps.
//!
//! This module implements the core state machine that drives the entire
//! deployment lifecycle. It uses the **typestate pattern** — a Rust idiom
//! where generic type parameters encode the *state* of an object at
//! compile time.
//!
//! # Learning: The Typestate Pattern
//!
//! In most languages, you would track pipeline state with an enum field
//! and add runtime checks ("am I authenticated?"). If you forget a check,
//! you get a runtime bug.
//!
//! In Rust, we can do better. Each state is a **separate type**:
//!
//! ```text
//! Init ──authenticate──▸ Authenticated ──ensure_infrastructure──▸ InfraReady
//!   ──build_and_package──▸ ArtifactReady ──deploy_and_verify──▸ Live
//! ```
//!
//! The `Pipeline<State>` struct is generic over `State`. Methods like
//! `authenticate()` are defined *only* on `Pipeline<Init>`, so calling
//! them on `Pipeline<InfraReady>` is a **compile error**. No runtime
//! checks needed — the compiler enforces the correct call order.
//!
//! # Learning: `PhantomData`
//!
//! You may notice `_marker: PhantomData<State>` in the struct definition.
//! This tells the compiler "I use the `State` type parameter even though
//! I do not store a value of that type." Without `PhantomData`, Rust
//! would reject the unused type parameter. It has **zero runtime cost**.
//!
//! # Learning: Ownership Transfer (Move Semantics)
//!
//! Each transition method takes `self` (not `&self`), which **consumes**
//! the current pipeline and returns a new one in the next state. This
//! means the old state is no longer accessible — the compiler prevents
//! you from accidentally using an outdated state.

use azure_core::auth::TokenCredential;
use azure_identity::AzureCliCredential;
use azure_mgmt_resources::{
    models::ResourceGroup, package_resources_2021_04::Client as ResourcesClient,
};
use azure_mgmt_web::package_2024_04::{
    models::{
        app_service_plan, site, AppServicePlan, NameValuePair, Resource, Site, SiteConfig,
        SkuDescription,
    },
    Client as WebSiteManagementClient,
};
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::Arc;
use tracing::info;

use crate::errors::{DeployError, Result};
use crate::resilience::reliable_op;

// ---------------------------------------------------------------------------
// State Types — zero-sized markers for the typestate machine
// ---------------------------------------------------------------------------

/// Initial state — configuration loaded, dependencies verified, no
/// credentials acquired yet.
///
/// This is the entry point. The only method available is
/// [`Pipeline::new`], which performs pre-flight checks.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::Init;
///
/// assert_eq!(std::mem::size_of::<Init>(), 0);
/// ```
///
/// # Safety
///
/// This marker type is always safe to use. It stores no raw pointers and
/// encodes only compile-time state.
pub struct Init;

/// Post-authentication state — holds a valid Azure token credential.
///
/// The `creds` field is an `Arc<dyn TokenCredential>`, which is a
/// reference-counted trait object. Using `Arc` allows sharing the
/// credential across multiple async tasks without cloning the
/// underlying implementation.
///
/// # Learning: Trait Objects (`dyn Trait`)
///
/// `dyn TokenCredential` means "any type that implements the
/// `TokenCredential` trait." We use `dyn` here because the Azure
/// Identity crate has multiple credential types (CLI, environment,
/// managed identity), and we want to be agnostic.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::Authenticated;
///
/// assert_eq!(
///     std::any::type_name::<Authenticated>(),
///     "rustlift::pipeline::Authenticated"
/// );
/// ```
///
/// # Safety
///
/// This state is safe to reference as a type. Construction is controlled by
/// [`Pipeline::authenticate`], which validates Azure credentials first.
pub struct Authenticated {
    creds: Arc<dyn TokenCredential>,
}

/// Infrastructure converged — Resource Group, App Service Plan, and Web
/// App are confirmed to exist on Azure.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::InfraReady;
///
/// assert_eq!(
///     std::any::type_name::<InfraReady>(),
///     "rustlift::pipeline::InfraReady"
/// );
/// ```
///
/// # Safety
///
/// This state type is safe to use. Instances are produced only after Azure
/// infrastructure operations complete successfully.
pub struct InfraReady {
    creds: Arc<dyn TokenCredential>,
}

/// Release artifact built and archived — ready for deployment.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::ArtifactReady;
///
/// assert_eq!(
///     std::any::type_name::<ArtifactReady>(),
///     "rustlift::pipeline::ArtifactReady"
/// );
/// ```
///
/// # Safety
///
/// This state type is safe to use. Instances are created only by
/// [`Pipeline::build_and_package`], which validates build output.
pub struct ArtifactReady {
    _creds: Arc<dyn TokenCredential>,
    zip_path: PathBuf,
}

/// Terminal state — application deployed and health check passed.
///
/// No further transitions are available from this state.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::Live;
///
/// assert_eq!(std::mem::size_of::<Live>(), 0);
/// ```
///
/// # Safety
///
/// This marker type is always safe to use and represents a completed
/// deployment lifecycle.
pub struct Live;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// NewType Definitions
// ---------------------------------------------------------------------------

/// The Azure Subscription ID (GUID).
#[derive(Clone, Debug)]
pub struct SubscriptionId(pub String);

impl std::fmt::Display for SubscriptionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The name of the Azure Web App (globally unique).
#[derive(Clone, Debug)]
pub struct AppName(String);

impl AppName {
    /// Derives the resource group name from the app name.
    pub fn resource_group(&self) -> ResourceGroupName {
        ResourceGroupName(format!("{}-rg", self.0))
    }
}

impl std::fmt::Display for AppName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The name of the Azure Resource Group.
#[derive(Clone, Debug)]
pub struct ResourceGroupName(String);

impl std::fmt::Display for ResourceGroupName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The Azure region (e.g. "eastus").
#[derive(Clone, Debug)]
pub struct Location(pub String);

impl std::fmt::Display for Location {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Deployment target configuration, populated from environment variables.
///
/// | Env Var                  | Field         | Default                |
/// |--------------------------|---------------|------------------------|
/// | `AZURE_SUBSCRIPTION_ID`  | `sub_id`      | *(required)*           |
/// | `APP_NAME`               | `app_name`    | `rust-enterprise-api`  |
/// | `AZURE_LOCATION`         | `location`    | `eastus`               |
///
/// `rg_name` is derived as `"{app_name}-rg"` and `binary_name` is
/// always `"server"`.
///
/// # Learning: `NewType` Pattern
///
/// We use tuple structs (e.g. `AppName(String)`) to enforce semantic
/// distinctions between different string values. This prevents accidental
/// swapping of arguments (e.g. passing a location where a name is expected).
///
/// # Safety
///
/// `Config` is a plain data container with no unsafe invariants.
#[derive(Clone, Debug)]
pub struct Config {
    /// Azure subscription GUID.
    pub sub_id: SubscriptionId,
    /// Web App resource name (also used as the DNS prefix).
    pub app_name: AppName,
    /// Resource Group name, derived as `"{app_name}-rg"`.
    pub rg_name: ResourceGroupName,
    /// Azure region (e.g. `"eastus"`, `"westeurope"`).
    pub location: Location,
    /// Name of the compiled binary inside the deploy zip.
    pub binary_name: String,
}

// ---------------------------------------------------------------------------
// Pipeline Struct
// ---------------------------------------------------------------------------

/// State-machine driver for the deployment workflow.
///
/// The generic `State` parameter progresses through:
/// [`Init`] → [`Authenticated`] → [`InfraReady`] → [`ArtifactReady`] → [`Live`].
///
/// Each transition method consumes `self` and returns the next state,
/// preventing reuse of an outdated pipeline instance.
///
/// # Learning: Why `PhantomData`?
///
/// The `State` type parameter is used to select which `impl` block is
/// active, but the struct itself may not store a value of type `State`
/// (for `Init` and `Live`, the state carries no data). `PhantomData`
/// satisfies the compiler's requirement that every generic parameter
/// must be "used" without adding any runtime cost.
///
/// # Examples
///
/// ```
/// use rustlift::pipeline::{Init, Pipeline};
///
/// let name = std::any::type_name::<Pipeline<Init>>();
/// assert_eq!(name.contains("Pipeline"), true);
/// ```
///
/// ```compile_fail
/// use rustlift::pipeline::{Init, Pipeline};
///
/// # async fn demo() -> rustlift::errors::Result<()> {
/// let p = Pipeline::<Init>::new()?;
/// let _ = p.deploy_and_verify().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Safety
///
/// `Pipeline<State>` is safe to move and consume. State transitions are
/// type-checked and do not require unsafe caller guarantees.
pub struct Pipeline<State> {
    config: Config,
    state: State,
    _marker: PhantomData<State>,
}

// ---------------------------------------------------------------------------
// Init → Authenticated
// ---------------------------------------------------------------------------

impl Pipeline<Init> {
    /// Reads environment variables, verifies that `az` and `cargo` are
    /// installed, and returns a `Pipeline<Init>`.
    ///
    /// This method performs **pre-flight checks** — it fails fast before
    /// making any network calls, saving the user from a slow failure
    /// several minutes into the pipeline.
    ///
    /// # Examples
    ///
    /// ```
    /// use rustlift::pipeline::{Init, Pipeline};
    ///
    /// # fn demo() -> rustlift::errors::Result<()> {
    /// # std::env::set_var(
    /// #     "AZURE_SUBSCRIPTION_ID",
    /// #     "00000000-0000-0000-0000-000000000000",
    /// # );
    /// # if which::which("az").is_err() {
    /// #     return Ok(());
    /// # }
    /// let pipeline = Pipeline::<Init>::new()?;
    /// assert_eq!(
    ///     std::any::type_name_of_val(&pipeline).contains("Pipeline"),
    ///     true
    /// );
    /// # Ok(())
    /// # }
    /// # demo().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// - [`DeployError::Config`] if `AZURE_SUBSCRIPTION_ID` is not set.
    /// - [`DeployError::Dependency`] if `az` or `cargo` cannot be found
    ///   on `$PATH`.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    /// # Safety
    ///
    /// Safe to call. There are no additional caller-side safety
    /// requirements.
    pub fn new() -> Result<Self> {
        let sub_id = std::env::var("AZURE_SUBSCRIPTION_ID")
            .map_err(|_| DeployError::Config("Missing AZURE_SUBSCRIPTION_ID".into()))?;

        let app_name = AppName(
            std::env::var("APP_NAME").unwrap_or_else(|_| "rust-enterprise-api".to_string()),
        );

        // Pre-flight dependency checks — fail fast before any cloud calls.
        which::which("az")
            .map_err(|_| DeployError::Dependency("Azure CLI ('az') not found".into()))?;
        which::which("cargo")
            .map_err(|_| DeployError::Dependency("Rust Toolchain ('cargo') not found".into()))?;

        let config = Config {
            rg_name: app_name.resource_group(),
            app_name,
            sub_id: SubscriptionId(sub_id),
            location: Location(std::env::var("AZURE_LOCATION").unwrap_or_else(|_| "eastus".into())),
            binary_name: "server".to_string(),
        };

        info!(app = %config.app_name, location = %config.location, "Pipeline initialised");

        Ok(Self {
            config,
            state: Init,
            _marker: PhantomData,
        })
    }

    /// Acquires an Azure CLI credential and verifies it can mint a token.
    ///
    /// Uses [`reliable_op`] to retry transient auth failures (e.g. token
    /// cache refresh race conditions).
    ///
    /// # Learning: `Arc<dyn TokenCredential>`
    ///
    /// `Arc` (Atomic Reference Counting) is Rust's thread-safe
    /// shared-ownership pointer. We need it because the credential is
    /// shared across multiple pipeline stages (authenticate, provision,
    /// deploy) which may run on different async tasks.
    ///
    /// `dyn TokenCredential` is a **trait object** — it erases the
    /// concrete type and allows any credential implementation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rustlift::pipeline::{Init, Pipeline};
    ///
    /// # async fn demo() -> rustlift::errors::Result<()> {
    /// # std::env::set_var(
    /// #     "AZURE_SUBSCRIPTION_ID",
    /// #     "00000000-0000-0000-0000-000000000000",
    /// # );
    /// let init = Pipeline::<Init>::new()?;
    /// let authed = init.authenticate().await?;
    /// assert_eq!(
    ///     std::any::type_name_of_val(&authed).contains("Authenticated"),
    ///     true
    /// );
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`DeployError::Auth`] if `az login` has not been run or the
    ///   session has expired.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    /// # Safety
    ///
    /// Safe to call. Credential acquisition is handled internally and
    /// requires no unsafe preconditions from the caller.
    pub async fn authenticate(self) -> Result<Pipeline<Authenticated>> {
        info!("🔐 [1/4] Authenticating via Azure CLI...");

        let creds = reliable_op("Auth Handshake", || async {
            let credential = AzureCliCredential::new();
            // Verify the token immediately — fail fast before provisioning.
            credential
                .get_token(&["https://management.azure.com/.default"])
                .await
                .map_err(DeployError::Auth)?;
            Ok(Arc::new(credential) as Arc<dyn TokenCredential>)
        })
        .await?;

        Ok(Pipeline {
            config: self.config,
            state: Authenticated { creds },
            _marker: PhantomData,
        })
    }
}

// ---------------------------------------------------------------------------
// Authenticated → InfraReady
// ---------------------------------------------------------------------------

impl Pipeline<Authenticated> {
    /// Idempotently provisions a Resource Group, App Service Plan
    /// (Linux/B1), and Web App configured for custom binary deployment.
    ///
    /// All ARM calls go through [`reliable_op`] for transient-failure
    /// resilience.
    ///
    /// # Azure Configuration Applied
    ///
    /// | Setting                    | Value                          |
    /// |----------------------------|--------------------------------|
    /// | `linux_fx_version`         | `DOTNETCORE\|8.0` (base image) |
    /// | `app_command_line`         | `sh startup.sh`                |
    /// | `WEBSITES_PORT`            | `8080`                         |
    /// | `WEBSITE_RUN_FROM_PACKAGE` | `1`                            |
    /// | `https_only`               | `true`                         |
    ///
    /// # Learning: Idempotent Provisioning
    ///
    /// The code uses `create_or_update` rather than separate `create` and
    /// `update` calls. This means running the pipeline twice produces
    /// the same result — a crucial property for deployment automation
    /// where retries and re-runs are common.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rustlift::pipeline::{Init, Pipeline};
    ///
    /// # async fn demo() -> rustlift::errors::Result<()> {
    /// # std::env::set_var(
    /// #     "AZURE_SUBSCRIPTION_ID",
    /// #     "00000000-0000-0000-0000-000000000000",
    /// # );
    /// let infra = Pipeline::<Init>::new()?
    ///     .authenticate()
    ///     .await?
    ///     .ensure_infrastructure()
    ///     .await?;
    /// assert_eq!(
    ///     std::any::type_name_of_val(&infra).contains("InfraReady"),
    ///     true
    /// );
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`DeployError::Infra`] if any ARM call fails or returns non-2xx.
    ///
    /// # Panics
    ///
    /// Panics only if the hard-coded ARM endpoint
    /// `https://management.azure.com` becomes an invalid URL.
    ///
    /// # Safety
    ///
    /// Safe to call. All Azure SDK calls are encapsulated and no unsafe
    /// caller contract is required.
    pub async fn ensure_infrastructure(self) -> Result<Pipeline<InfraReady>> {
        info!("🏗️  [2/4] Converging Infrastructure...");
        let cfg = self.config.clone();
        let creds = self.state.creds.clone();

        reliable_op("Azure Provisioning (Group)", || {
            let cfg = cfg.clone();
            let creds = creds.clone();
            async move {
                ensure_resource_group(&cfg, creds).await
            }
        })
        .await?;

        reliable_op("Azure Provisioning (Plan)", || {
            let cfg = cfg.clone();
            let creds = creds.clone();
            async move {
                let plan_id = ensure_app_service_plan(&cfg, creds).await?;
                Ok(plan_id)
            }
        })
        .await?;

        // We need to pass the plan_id to the web app provisioning
        let plan_id = format!(
            "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Web/serverfarms/{}-plan",
            cfg.sub_id, cfg.rg_name, cfg.app_name
        );

        reliable_op("Azure Provisioning (App)", || {
            let cfg = cfg.clone();
            let creds = creds.clone();
            let plan_id = plan_id.clone();
            async move {
                ensure_web_app(&cfg, creds, &plan_id).await
            }
        })
        .await?;

        Ok(Pipeline {
            config: self.config,
            state: InfraReady {
                creds: self.state.creds,
            },
            _marker: PhantomData,
        })
    }
}

// --- Infrastructure Helpers ---

async fn ensure_resource_group(cfg: &Config, creds: Arc<dyn TokenCredential>) -> Result<()> {
    let resources_client = ResourcesClient::new(
        azure_core::Url::parse("https://management.azure.com").expect("Invalid Azure URL"),
        creds,
        vec!["https://management.azure.com/.default".to_string()],
        azure_core::ClientOptions::default(),
    );
    let rg_client = resources_client.resource_groups_client();

    if rg_client.get(cfg.rg_name.to_string(), cfg.sub_id.to_string()).await.is_err() {
        let rg = ResourceGroup::new(cfg.location.to_string());
        rg_client
            .create_or_update(cfg.rg_name.to_string(), rg, cfg.sub_id.to_string())
            .await
            .map_err(|e| DeployError::Infra(format!("RG Error: {e}")))?;
    }
    Ok(())
}

async fn ensure_app_service_plan(cfg: &Config, creds: Arc<dyn TokenCredential>) -> Result<String> {
    let web_client = WebSiteManagementClient::new(
        azure_core::Url::parse("https://management.azure.com").expect("Invalid Azure URL"),
        creds,
        vec!["https://management.azure.com/.default".to_string()],
        azure_core::ClientOptions::default(),
    );
    let plan_name = format!("{}-plan", cfg.app_name);

    let resource = Resource::new(cfg.location.to_string());
    let mut plan = AppServicePlan::new(resource);
    plan.resource.kind = Some("linux".into());
    plan.sku = Some(SkuDescription {
        name: Some("B1".into()),
        tier: Some("Basic".into()),
        ..Default::default()
    });
    plan.properties = Some(app_service_plan::Properties {
        reserved: Some(true), // Critical for Linux
        ..Default::default()
    });

    // Workaround for azure_mgmt_web 0.21.0 deserialization bug
    let response = web_client
        .app_service_plans_client()
        .create_or_update(cfg.rg_name.to_string(), &plan_name, plan, cfg.sub_id.to_string())
        .send()
        .await
        .map_err(|e| DeployError::Infra(format!("Plan Error: {e}")))?;

    let status = response.into_raw_response().status();
    if !status.is_success() {
        return Err(DeployError::Infra(format!(
            "HTTP {status} from App Service Plan API"
        )));
    }

    Ok(format!(
        "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Web/serverfarms/{}",
        cfg.sub_id, cfg.rg_name, plan_name
    ))
}

async fn ensure_web_app(
    cfg: &Config,
    creds: Arc<dyn TokenCredential>,
    plan_id: &str,
) -> Result<()> {
    let web_client = WebSiteManagementClient::new(
        azure_core::Url::parse("https://management.azure.com").expect("Invalid Azure URL"),
        creds,
        vec!["https://management.azure.com/.default".to_string()],
        azure_core::ClientOptions::default(),
    );

    let resource = Resource::new(cfg.location.to_string());
    let mut site = Site::new(resource);
    site.resource.kind = Some("app,linux".into());

    let site_config = SiteConfig {
        linux_fx_version: Some("DOTNETCORE|8.0".into()),
        app_command_line: Some("sh startup.sh".into()),
        app_settings: vec![
            NameValuePair {
                name: Some("WEBSITES_PORT".into()),
                value: Some("8080".into()),
            },
            NameValuePair {
                name: Some("WEBSITE_RUN_FROM_PACKAGE".into()),
                value: Some("1".into()),
            },
        ],
        ..Default::default()
    };

    site.properties = Some(site::Properties {
        server_farm_id: Some(plan_id.to_string()),
        site_config: Some(site_config),
        https_only: Some(true),
        ..Default::default()
    });

    // Workaround for azure_mgmt_web 0.21.0 deserialization bug
    let response = web_client
        .web_apps_client()
        .create_or_update(cfg.rg_name.to_string(), cfg.app_name.to_string(), site, cfg.sub_id.to_string())
        .send()
        .await
        .map_err(|e| DeployError::Infra(format!("WebApp Error: {e}")))?;

    let status = response.into_raw_response().status();
    if !status.is_success() {
        return Err(DeployError::Infra(format!(
            "HTTP {status} from Web App API"
        )));
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// InfraReady → ArtifactReady
// ---------------------------------------------------------------------------

impl Pipeline<InfraReady> {
    /// Cross-compiles the server binary via `cross` and bundles it with
    /// `startup.sh` into a deployable zip archive.
    ///
    /// The zip includes two entries:
    /// - `server` — the `x86_64-unknown-linux-musl` release binary
    ///   (mode `0o755`).
    /// - `startup.sh` — the process wrapper that uses `exec` for signal
    ///   propagation.
    ///
    /// # Learning: `spawn_blocking`
    ///
    /// Zip creation involves synchronous disk I/O (reading a large binary,
    /// writing compressed data). Running this on the async runtime would
    /// **block** the Tokio worker thread, starving other tasks.
    ///
    /// `tokio::task::spawn_blocking` moves the work to a dedicated
    /// thread pool designed for blocking operations, keeping the async
    /// runtime responsive.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rustlift::pipeline::{Init, Pipeline};
    ///
    /// # async fn demo() -> rustlift::errors::Result<()> {
    /// # std::env::set_var(
    /// #     "AZURE_SUBSCRIPTION_ID",
    /// #     "00000000-0000-0000-0000-000000000000",
    /// # );
    /// let artifact = Pipeline::<Init>::new()?
    ///     .authenticate()
    ///     .await?
    ///     .ensure_infrastructure()
    ///     .await?
    ///     .build_and_package()
    ///     .await?;
    /// assert_eq!(
    ///     std::any::type_name_of_val(&artifact).contains("ArtifactReady"),
    ///     true
    /// );
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`DeployError::Build`] if `cross build` returns non-zero or the
    ///   binary is missing.
    /// - [`DeployError::Io`] if any file read/write fails.
    /// - [`DeployError::Zip`] if the archive cannot be finalised.
    /// - [`DeployError::JoinError`] if the background zip task panics or is
    ///   cancelled.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    /// # Safety
    ///
    /// Safe to call. Blocking file work is moved to
    /// [`tokio::task::spawn_blocking`] and does not rely on unsafe caller
    /// behavior.
    pub async fn build_and_package(self) -> Result<Pipeline<ArtifactReady>> {
        info!("📦 [3/4] Building Release...");
        let cfg = self.config.clone();

        // ── A. Cross-compile for Linux musl ─────────────────────────
        reliable_op("Cargo Build", || async {
            let status = tokio::process::Command::new("cross")
                .args([
                    "build",
                    "--release",
                    "--target",
                    "x86_64-unknown-linux-musl",
                ])
                .status()
                .await
                .map_err(|e| DeployError::Io {
                    source: e,
                    context: "Spawning cross".into(),
                })?;

            if !status.success() {
                return Err(DeployError::Build(
                    "Compilation failed (ensure target is valid)".into(),
                ));
            }
            Ok(())
        })
        .await?;

        // ── B. Zip creation (blocking I/O, offloaded) ───────────────
        let zip_path = PathBuf::from("deploy.zip");
        let zip_clone = zip_path.clone();
        let bin_name = cfg.binary_name.clone();

        let bin_path = PathBuf::from(format!(
            "target/x86_64-unknown-linux-musl/release/{}",
            cfg.binary_name
        ));

        if !bin_path.exists() {
            return Err(DeployError::Build(format!(
                "Binary not found at {}",
                bin_path.display()
            )));
        }

        info!("   Compressing Artifact (Off-thread)...");
        
        // Learning: Extracted helper for cognitive clarity
        compress_artifact(zip_clone.clone(), bin_path, bin_name).await?;

        Ok(Pipeline {
            config: self.config,
            state: ArtifactReady {
                _creds: self.state.creds,
                zip_path,
            },
            _marker: PhantomData,
        })
    }
}

/// Helper to compress the binary and startup script into a zip archive.
///
/// This runs on a blocking thread to avoid stalling the async runtime.
async fn compress_artifact(zip_path: PathBuf, bin_path: PathBuf, bin_name: String) -> Result<()> {
    tokio::task::spawn_blocking(move || -> Result<()> {
        use std::io::Write;
        let file = std::fs::File::create(&zip_path).map_err(|e| DeployError::Io {
            source: e,
            context: "Creating zip file".into(),
        })?;

        let mut zip = zip::ZipWriter::new(file);
        let options = zip::write::FileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .unix_permissions(0o755);

        // Entry 1: the server binary
        zip.start_file(&bin_name, options)?;
        let data = std::fs::read(&bin_path).map_err(|e| DeployError::Io {
            source: e,
            context: "Reading binary".into(),
        })?;
        zip.write_all(&data).map_err(|e| DeployError::Io {
            source: e,
            context: "Writing to zip".into(),
        })?;

        // Entry 2: startup.sh (exec wrapper for signal propagation)
        zip.start_file("startup.sh", options)?;
        let startup_script = std::fs::read("startup.sh").map_err(|e| DeployError::Io {
            source: e,
            context: "Reading startup.sh".into(),
        })?;
        zip.write_all(&startup_script)
            .map_err(|e| DeployError::Io {
                source: e,
                context: "Writing startup.sh to zip".into(),
            })?;

        zip.finish()?;
        Ok(())
    })
    .await?
}

// ---------------------------------------------------------------------------
// ArtifactReady → Live
// ---------------------------------------------------------------------------

impl Pipeline<ArtifactReady> {
    /// Uploads the zip artifact via `az webapp deployment source config-zip`
    /// and polls the `/health` endpoint until it returns HTTP 2xx.
    ///
    /// Both the CLI upload and the health poll use [`reliable_op`] for
    /// automatic retry with exponential backoff.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rustlift::pipeline::{Init, Pipeline};
    ///
    /// # async fn demo() -> rustlift::errors::Result<()> {
    /// # std::env::set_var(
    /// #     "AZURE_SUBSCRIPTION_ID",
    /// #     "00000000-0000-0000-0000-000000000000",
    /// # );
    /// let live = Pipeline::<Init>::new()?
    ///     .authenticate()
    ///     .await?
    ///     .ensure_infrastructure()
    ///     .await?
    ///     .build_and_package()
    ///     .await?
    ///     .deploy_and_verify()
    ///     .await?;
    /// assert_eq!(std::any::type_name_of_val(&live).contains("Live"), true);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`DeployError::Cli`] if the `az` command returns a non-zero exit
    ///   code.
    /// - [`DeployError::PathEncoding`] if the deploy zip path is not valid
    ///   UTF-8.
    /// - [`DeployError::Io`] if spawning the Azure CLI process fails.
    /// - [`DeployError::Health`] or [`DeployError::Network`] if the health
    ///   endpoint is unreachable within the retry window.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    /// # Safety
    ///
    /// Safe to call. Process execution and HTTP polling are contained
    /// within safe abstractions.
    pub async fn deploy_and_verify(self) -> Result<Pipeline<Live>> {
        info!("🚀 [4/4] Deploying to Azure...");
        let cfg = &self.config;
        let zip_path = &self.state.zip_path;

        // ── A. CLI Upload ───────────────────────────────────────────
        reliable_op("CLI ZipDeploy", || async {
            let path_str = zip_path
                .to_str()
                .ok_or(DeployError::PathEncoding(format!("{}", zip_path.display())))?;

            let output = tokio::process::Command::new("az")
                .args([
                    "webapp",
                    "deployment",
                    "source",
                    "config-zip",
                    "-g",
                    &cfg.rg_name.to_string(),
                    "-n",
                    &cfg.app_name.to_string(),
                    "--src",
                    path_str,
                ])
                .output()
                .await
                .map_err(|e| DeployError::Io {
                    source: e,
                    context: "Spawning az CLI".into(),
                })?;

            if !output.status.success() {
                let err = String::from_utf8_lossy(&output.stderr);
                return Err(DeployError::Cli(err.to_string()));
            }
            Ok(())
        })
        .await?;

        // ── B. Health Verification ──────────────────────────────────
        info!("🏥 Verifying Health...");
        let url = format!("https://{}.azurewebsites.net/health", cfg.app_name);
        let client = reqwest::Client::new();

        reliable_op("Health Check", || async {
            let resp = client
                .get(&url)
                .timeout(std::time::Duration::from_secs(5))
                .send()
                .await?;

            if resp.status().is_success() {
                Ok(())
            } else {
                Err(DeployError::Health(format!("Status: {}", resp.status())))
            }
        })
        .await?;

        Ok(Pipeline {
            config: self.config.clone(),
            state: Live,
            _marker: PhantomData,
        })
    }
}