Docs

Controllers

A controller is the code that creates, updates, and deletes a custom resource in the cloud, and checks on it after initial setup. It uses the same model as Alien's own controllers, so moving one into Alien later is a move, not a rewrite.

It builds to a WebAssembly module, and Alien runs that module in a sandbox wherever it drives the deployment.

This one creates the DNS zone on AWS:

acme/controller/src/aws.rs
use acme_types::{AwsDnsZoneFields, DnsZone, DnsZoneOutputs};
use alien_extension_sdk::controller_prelude::*;
use std::time::{SystemTime, UNIX_EPOCH};

#[controller]
pub struct AwsDnsZoneController {
    #[serde(flatten)]
    fields: AwsDnsZoneFields, // the same fields the importer fills
    /// The caller reference this zone's CreateHostedZone sends. Route53 never reuses one, even
    /// after its zone is deleted, so each create picks a new one and saves it before the call.
    /// A zone the importer read from the setup template has none.
    #[serde(skip_serializing_if = "Option::is_none")]
    caller_reference: Option<String>,
    /// The domain the zone was made for. A rename the update refused still leaves the new domain
    /// in the stack, so the delete reads the zone's own. A zone the importer read has none.
    #[serde(skip_serializing_if = "Option::is_none")]
    domain: Option<String>,
}

#[controller]
impl AwsDnsZoneController {
    #[flow_entry(Create)]
    #[handler(state = CreateStart, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
    async fn create_start(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
        let zone = ctx.desired_resource_config::<DnsZone>()?;
        // Saved by this step, so a CreateZone that runs again after a lost reply sends the same
        // reference and finds the zone it made.
        self.caller_reference = Some(caller_reference(
            ctx.resource_prefix,
            &zone.id,
            SystemTime::now(),
        ));
        self.domain = Some(zone.domain.clone());
        Ok(HandlerAction::Continue {
            state: CreateZone,
            suggested_delay: None,
        })
    }

    #[handler(state = CreateZone, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
    async fn create_zone(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
        let zone = ctx.desired_resource_config::<DnsZone>()?;
        let reference = self.caller_reference.clone().ok_or_else(|| {
            AlienError::new(ErrorData::CloudPlatformError {
                message: "The zone has no caller reference to create it with".to_string(),
                resource_id: Some(zone.id.clone()),
            })
        })?;
        let route53 = aws_sdk_route53::Client::new(&ctx.aws_sdk_config().await?);
        let zone_id = create_hosted_zone(&route53, &zone, &reference).await?;
        // CloudFormation's Ref returns "Z123", so keep that form on both setup paths.
        self.fields.zone_id = Some(zone_id.trim_start_matches("/hostedzone/").to_string());
        Ok(HandlerAction::Continue {
            state: Ready,
            suggested_delay: None,
        })
    }

Alien steps the controller one handler at a time and saves its fields after each step. The next step starts from the state the last one returned.

Handlers and flows

The rest of the controller handles the zone once it exists, then updates and deletes it:

acme/controller/src/aws.rs
    #[handler(state = Ready, on_failure = RefreshFailed, status = ResourceStatus::Running)]
    async fn ready(&mut self, _ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
        // Check that the zone still exists.
        Ok(HandlerAction::Continue {
            state: Ready,
            suggested_delay: Some(Duration::from_secs(60)),
        })
    }

    #[flow_entry(Update, from = [Ready, RefreshFailed])]
    #[handler(state = UpdateStart, on_failure = UpdateFailed, status = ResourceStatus::Updating)]
    async fn update_start(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
        // Route53 can't rename a hosted zone, and the delete finds the zone's apex by its domain.
        let previous = ctx.previous_resource_config::<DnsZone>()?;
        let zone = ctx.desired_resource_config::<DnsZone>()?;
        if !same_domain(&previous.domain, &zone.domain) {
            return Err(AlienError::new(ErrorData::ResourceConfigInvalid {
                message: format!(
                    "A Route53 hosted zone can't be renamed from {} to {}; remove the zone from the stack and add it back with the new domain",
                    previous.domain, zone.domain
                ),
                resource_id: Some(zone.id.clone()),
            }));
        }
        Ok(HandlerAction::Continue {
            state: Ready,
            suggested_delay: None,
        })
    }

    #[flow_entry(Delete)]
    #[handler(state = DeleteStart, on_failure = DeleteFailed, status = ResourceStatus::Deleting)]
    async fn delete_start(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
        let zone = ctx.desired_resource_config::<DnsZone>()?;
        let domain = self.domain.clone().unwrap_or_else(|| zone.domain.clone());
        let route53 = aws_sdk_route53::Client::new(&ctx.aws_sdk_config().await?);
        let zone_id = match (&self.fields.zone_id, &self.caller_reference) {
            (Some(zone_id), _) => Some(zone_id.clone()),
            // A create whose reply was lost may have made the zone: its reference finds it.
            (None, Some(reference)) => {
                find_hosted_zone(&route53, &domain, reference, &zone.id).await?
            }
            (None, None) => None,
        };
        if let Some(zone_id) = zone_id {
            delete_hosted_zone(&route53, &zone_id, &domain, &zone.id).await?;
        }
        self.fields.zone_id = None;
        Ok(HandlerAction::Continue {
            state: Deleted,
            suggested_delay: None,
        })
    }

    terminal_state!(
        state = CreateFailed,
        status = ResourceStatus::ProvisionFailed
    );
    terminal_state!(state = UpdateFailed, status = ResourceStatus::UpdateFailed);
    terminal_state!(
        state = RefreshFailed,
        status = ResourceStatus::RefreshFailed
    );
    terminal_state!(state = DeleteFailed, status = ResourceStatus::DeleteFailed);
    terminal_state!(state = Deleted, status = ResourceStatus::Deleted);

    fn build_outputs(&self) -> Option<ResourceOutputs> {
        let zone_id = self.fields.zone_id.clone()?;
        Some(ResourceOutputs::new(DnsZoneOutputs { zone_id }))
    }
}
  • #[controller] on the struct and its impl makes a controller. The struct's fields are the state Alien saves between steps.
  • #[flow_entry(Create)], #[flow_entry(Update)], and #[flow_entry(Delete)] mark the state each flow starts in.
  • #[handler] runs one state. status is what the dashboard shows while it runs, and on_failure is the state the resource moves to when it fails.
  • A handler returns HandlerAction::Continue to move to the next state, or HandlerAction::Stay to run the same state again after a delay, such as while a zone becomes active.
  • terminal_state! declares a state a flow ends in, with its status.
  • build_outputs returns the outputs your link and linked workloads read.

The Ready handler makes no call yet. It runs again every 60 seconds, which is where a check that the zone still exists goes.

Every controller needs an Update flow. Without one, a change to the resource's config fails with No update flow defined.

The context

Each handler gets a ResourceControllerContext:

  • ctx.desired_resource_config::<DnsZone>(): the resource's config from alien.ts, as your type.
  • ctx.previous_resource_config::<DnsZone>(): the config before the change, during an update.
  • ctx.aws_sdk_config(): an AWS SDK config for any aws-sdk-* client, such as Route53's. Its requests go through Alien, which signs them.
  • ctx.cloud(): sends a request you build to the step's cloud, or to an origin the extension declares. See Cloud calls.
  • ctx.dependency_outputs(id): the outputs of a resource this one depends on, read as your own type. A controller reads a dependency's outputs, never its saved state.
  • ctx.resource_prefix: the deployment's resource prefix, for names and idempotency keys.
  • ctx.time_left(): how long the step has before its deadline.
  • ctx.emit_heartbeat(heartbeat): reports the resource's health, as Alien's own controllers do.

The controller builds for wasm32-wasip1, so it can use any Rust crate that builds for that target. A crate that opens its own connections or reads files doesn't work in the sandbox.

Cloud calls

The module holds no credentials and opens no sockets. It hands each request to Alien, which signs it with credentials for the extension's identity and sends it to the cloud's own API:

CloudWhat you writeWhere Alien sends it
AWSAn aws-sdk-* client built from ctx.aws_sdk_config(), or CloudRequest::aws(service, method, path)The service's endpoint in the step's region, or in the region the request names
Google CloudCloudRequest::gcp(service, method, path)https://<service>.googleapis.com
AzureCloudRequest::azure(method, path)Azure Resource Manager, https://management.azure.com

AWS SDK clients

Add aws-sdk-* crates with default-features = false. Their default HTTP client opens sockets, and ctx.aws_sdk_config() brings one that sends through Alien. An S3 client also needs force_path_style(true), since Alien finds the service by the endpoint's host name.

The client sends each call once, because the SDK's own retries are off in a module. Turn the SDK's error into Alien's with aws_sdk_error:

acme/controller/src/aws.rs
let zones = route53
    .list_hosted_zones_by_name()
    .dns_name(domain)
    .send()
    .await
    .map_err(aws_sdk_error)
    .context(ErrorData::CloudPlatformError {
        message: "Failed to list the Route53 hosted zones for the domain".to_string(),
        resource_id: Some(resource_id.to_string()),
    })?;

aws_sdk_error gives the error the code and retry flag Alien's own AWS clients give the same answer, so Alien runs the step again after a throttled call or one that got no answer. into_alien_error() on an SDK error gives one that is never retried.

Request builders

For Google Cloud and Azure the SDK has request builders, not typed clients. You build the request and read the reply. This handler creates the zone in Cloud DNS, with the reference the step before it saved as a label:

acme/controller/src/gcp.rs
#[handler(state = CreateZone, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
async fn create_zone(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
    let zone = ctx.desired_resource_config::<DnsZone>()?;
    let reference = self.create_reference.clone().ok_or_else(|| {
        AlienError::new(ErrorData::CloudPlatformError {
            message: "The zone has no create reference to create it with".to_string(),
            resource_id: Some(zone.id.clone()),
        })
    })?;
    // The name the Terraform module gives the zone, so both setup paths save the same one.
    let name = format!("{}-{}", ctx.resource_prefix, zone.id);
    let request = CloudRequest::gcp("dns", "POST", &zones_path(ctx)?).json(&json!({
        "name": name,
        "dnsName": format!("{}.", zone.domain),
        "description": format!("The {} zone", zone.id),
        "labels": { CREATE_LABEL: reference },
    }))?;
    let response = ctx.cloud().send(&request)?;
    if response.status == 409 {
        // Taken: by this step's own earlier run, or by a zone someone else made.
        let path = format!("{}/{name}", zones_path(ctx)?);
        let existing: ManagedZone = ctx
            .cloud()
            .send(&CloudRequest::gcp("dns", "GET", &path))?
            .ok("Reading the Cloud DNS zone that has the name")?
            .json()?;
        if existing.labels.get(CREATE_LABEL) != Some(&reference) {
            return Err(AlienError::new(ErrorData::CloudPlatformError {
                message: format!(
                    "A Cloud DNS zone named {name} already exists and this resource didn't create it"
                ),
                resource_id: Some(zone.id.clone()),
            }));
        }
    } else {
        response.ok("Creating the Cloud DNS zone")?;
    }
    self.fields.zone_name = Some(name);
    Ok(HandlerAction::Continue {
        state: Ready,
        suggested_delay: None,
    })
}

ctx.cloud().target() says where the step's calls go. The handler's path comes from it:

acme/controller/src/gcp.rs
/// The path of the managed zones of the project the step is for.
fn zones_path(ctx: &ResourceControllerContext<'_>) -> Result<String> {
    match ctx.cloud().target() {
        Some(CloudTarget::Gcp { project_id, .. }) => {
            Ok(format!("/dns/v1/projects/{project_id}/managedZones"))
        }
        _ => Err(AlienError::new(ErrorData::ResourceConfigInvalid {
            message: "The step is not for a Google Cloud project".to_string(),
            resource_id: Some(ctx.desired_config.id().to_string()),
        })),
    }
}
  • .json(&value)? sets the body and its content type. .body(text) and .body_bytes(&bytes) set a body as it is.
  • send returns the response for any status. .ok(what)? turns a status outside 2xx into the error Alien's own clients return for it, and .json::<T>()? reads the body as your type.
  • The target is CloudTarget::Aws { account_id, region }, Gcp { project_id, region }, or Azure { subscription_id, tenant_id }.

Endpoints and limits

A request names a service, a method, and a path, never a host. Alien picks the host from its own tables and refuses anything else:

  • AWS. The table has AWS's standard endpoints in the commercial regions, without FIPS and dual-stack endpoints. It doesn't cover every service yet, and a request for a service it lacks is refused.
  • Google Cloud. Only <service>.googleapis.com hosts from Google's API directory. Regional hosts, such as us-central1-aiplatform.googleapis.com, are refused.
  • Azure. Resource Manager only. A data-plane host, such as a vault's or a storage account's, is refused.
  • Kubernetes. A module can't call the cluster's API. On EKS, GKE, or AKS it calls the cloud under the cluster.
  • Linux servers. A step has no cloud there, so ctx.cloud().target() is None and Alien refuses send. A module can't act on the machine itself. It can call the origins the extension declares.
  • No permission sets. Setup creates an identity for an extension only when its types hold permission sets. Without one, a step carries no credentials, and Alien refuses send the same way.

Every request also stays inside these limits:

LimitValue
Requests in one step, to the cloud and to declared origins together50
Request body6 MiB, sent whole. There is no streaming upload.
Response body8 MiB. A larger one fails the call.
RedirectsNot followed. The module gets the 3xx response.
Headers on a cloud requestaccept, user-agent, content-type, content-md5, range, if-match, if-none-match, if-modified-since, and if-unmodified-since. On AWS also x-amz-*, x-amzn-*, and amz-sdk-*, except the three Alien sets when it signs.

Alien sends each request once. ctx.cloud() returns EXTENSION_CALL_REFUSED for a request Alien refused, which isn't retried, and HTTP_REQUEST_FAILED for one that got no answer, which is.

The deployment's interceptors run on a module's cloud calls too, before Alien signs them, as they do on the calls of Alien's own controllers.

Declared origins

A controller can also call an API outside the cloud, such as your own, when the extension declares its origin:

acme/Cargo.toml
[workspace.metadata.alien-extension]
hooks = "hooks"
controller = "controller"
types = "types"
egress = ["https://api.acme.dev"]
let request = HttpRequest::new("POST", "https://api.acme.dev/v1/zones")
    .json(&serde_json::json!({ "domain": zone.domain }))?;
ctx.cloud().http(&request)?.ok("the acme API")?;
  • Each origin is https://host or https://host:port, and a request's URL must match one exactly.
  • Alien sends these requests with none of the deployment's credentials. The module may set its own Authorization header.
  • The host must resolve to a public address. Alien refuses private, loopback, and link-local addresses.
  • The release pins the list, and the setup template shows it to the customer on the extension's identity.

Register controllers

The controller crate's library registers one controller per resource type and cloud, and export_controllers! exports them from the module:

acme/controller/src/lib.rs
use acme_types::DnsZone;
use alien_extension_sdk::controller_prelude::*;

pub mod aws;
pub mod azure;
pub mod gcp;

/// Registers the zone's controller for each cloud.
pub fn register(controllers: &mut Controllers) {
    controllers.register(
        DnsZone::RESOURCE_TYPE,
        Platform::Aws,
        aws::AwsDnsZoneController::default(),
    );
    controllers.register(
        DnsZone::RESOURCE_TYPE,
        Platform::Gcp,
        gcp::GcpDnsZoneController::default(),
    );
    controllers.register(
        DnsZone::RESOURCE_TYPE,
        Platform::Azure,
        azure::AzureDnsZoneController::default(),
    );
}

alien_extension_sdk::export_controllers!(register);

alien extensions build builds this library for wasm32-wasip1 into controller.wasm, and reads each type's platforms from the module. The library also builds natively, where the macro writes nothing, so cargo test can step its controllers.

alien dev runs no module. The crate's binary registers the resource's local controller, which alien dev starts as a process:

acme/controller/src/main.rs
use acme_types::DnsZone;
use alien_extension_sdk::local_controller_prelude::*;

mod local;

fn main() -> std::process::ExitCode {
    alien_extension_sdk::run_controllers(|controllers| {
        // Records the zone and returns a placeholder id, with no cloud call.
        controllers.register(
            DnsZone::RESOURCE_TYPE,
            Platform::Local,
            local::LocalDnsZoneController::default(),
        );
    })
}

The binary and its local controller import local_controller_prelude, not controller_prelude. A local controller stays a native process because it may write files or build containers, which the sandbox doesn't allow.

The library holds the controllers of every platform but Platform::Local, and the binary holds only that one. alien extensions build refuses a library that registers Platform::Local, and a binary that registers any other platform.

Hosts and credentials

Whoever drives the deployment runs the controller module, in the same sandbox everywhere, and signs its cloud calls:

Who drivesWhere the controller runsWhose credentials sign its calls
The Alien manager, in a push deploymentA sandboxed module in the managerThe extension's identity, short-lived, for each step
The Operator, in a pull deploymentA sandboxed module in the OperatorThe extension's identity
The setup CLI, when the admin runs initial setup with itA sandboxed module in the CLI, on the admin's machineNone, so the CLI refuses its cloud calls
alien devA process on your machine, running the resource's local controllerNone, since alien dev makes no cloud calls

Architecture diagram. Left: Alien containing Alien manager containing Controller module. Right: Customer 1's AWS account containing Created at initial setup containing Extension identity; Managed by your controller containing DNS zone.

In a push deployment, the manager runs your controller module in a sandbox. The module hands each request to the manager, which signs it with short-lived credentials for the extension's identity and sends it to the customer's cloud. You host nothing.

The sandbox is the same in the manager, the Operator, and the setup CLI:

  • The module holds no credentials. It has no sockets, no files, and no environment variables.
  • Alien sends its requests only to the cloud's API endpoints, and to the origins the extension declares.
  • Every step runs in a new instance of the module, with at most 64 MiB of memory.

Push

The Alien manager runs the module. For each step it gets short-lived credentials for the extension's identity and signs the module's requests with them. The manager's own credentials sign none of them.

Pull

The Operator runs the module, so every cloud call starts inside the customer's environment. The Operator signs the module's requests as the extension's identity, so the customer's audit log shows the controller's calls apart from the Operator's.

The setup CLI

When the customer's admin runs initial setup with the setup CLI, the CLI creates frozen custom resources by running your controller module on the admin's machine.

The CLI gives the module no credentials and refuses its cloud calls. The admin's credentials reach far more than the extension's identity, which is what the customer approves in the setup template, and the admin can't act as that identity. The module can still call the origins the extension declares. A stack with a frozen custom resource whose controller calls the cloud is set up from its setup template.

alien dev

alien dev runs your stack on your machine with local stand-ins instead of cloud resources. A custom resource runs there only if the controller crate's binary registers a controller for Platform::Local, which alien dev starts as a process on your machine.

A custom type with no local controller stops alien dev, which names the type. See Local development.

Steps and retries

Whoever drives the deployment sends the controller one step at a time and saves the state that comes back. Handlers follow these rules:

  • A step runs again when it ends without a reply, for example when the manager restarts mid-step. Make every call a handler sends safe to repeat, as Alien's own controllers do, with the cloud's idempotency key where it has one, as caller_reference does above. Pick the key in one step and use it in the next, so a step that runs again reuses it.
  • A step has a 60-second deadline, and ctx.time_left() says how much of it is left. For longer work, return HandlerAction::Stay or a suggested_delay, and continue in the next step.
  • Alien cuts a request still open at the deadline, and refuses one sent after it. Either way the whole step fails with EXTENSION_STEP_DEADLINE and runs again, whatever the handler returned. Alien stops a module that hasn't replied 2 seconds after the deadline.
  • Alien sends each request once, and an AWS SDK client doesn't retry. The handler returns the error. A retryable error runs the step again, with backoff. Any other error moves the resource to the handler's on_failure state.
  • A module stopped at its deadline, out of memory, or by a panic fails the step, and the step is retried. When the retries run out, the resource fails.
  • One Alien process runs at most 64 module steps at a time, at most 16 of one project's, and at most 2 of one deployment's. Another step waits for one to end.

Other languages

A controller is a Rust crate today: alien extensions build builds only a Cargo library into the controller module.

The module's contract doesn't depend on Rust. Each step is one JSON request and one JSON reply, which export_controllers! handles for you. Step protocol describes it.

Next

  • Testing: step a controller in a test before a release
  • Step protocol: the request and response for each step
  • Security: what an extension's controller can reach

On this page