alien_core/hooks.rs
1//! What crosses between Alien and an extension's hooks module: the hooks the module declares, and
2//! the input and output of each kind of hook.
3//!
4//! Every value crosses as JSON in the serde forms below. The extension SDK writes them inside the
5//! module and the hosts that call hooks read them, so both sides compile against these types.
6//! Where a hook returns a type a format crate owns (a CloudFormation template, a resource or an
7//! expression), [`HookKind`] names it and it crosses in that type's own serde form.
8
9use crate::{
10 ManagementConfig, Platform, ResourceStatus, ResourceType, ResourceTypeDescriptor, StackSettings,
11};
12use indexmap::IndexMap;
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15use std::collections::BTreeMap;
16
17/// A hook's error as it crosses back to the host: the hook's code and message, and whether
18/// another try may pass. The host keeps the code when it is a short `[A-Z0-9_]` token and the
19/// retry flag, and cuts the message short. Only an error that sets `retryable` itself is
20/// retried; one converted from an `AlienError` is final, since a hook gives the same answer to
21/// the same input.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct HookError {
25 pub code: String,
26 pub message: String,
27 pub retryable: bool,
28}
29
30impl HookError {
31 /// The code of an error the hook gave only as text.
32 pub const UNCODED: &'static str = "HOOK_FAILED";
33
34 /// A final error with `message` and no code of its own.
35 pub fn new(message: impl Into<String>) -> Self {
36 Self {
37 code: Self::UNCODED.to_string(),
38 message: message.into(),
39 retryable: false,
40 }
41 }
42}
43
44impl std::fmt::Display for HookError {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 write!(f, "{} ({})", self.message, self.code)
47 }
48}
49
50impl std::error::Error for HookError {}
51
52impl From<String> for HookError {
53 fn from(message: String) -> Self {
54 Self::new(message)
55 }
56}
57
58impl From<&str> for HookError {
59 fn from(message: &str) -> Self {
60 Self::new(message)
61 }
62}
63
64/// A hook written with the Rust SDK reports its errors as final: a hook computes from its input
65/// alone, so another try gives the same answer. The runtime keeps the flag a module sets, for a
66/// module that sets it itself.
67impl<E> From<alien_error::AlienError<E>> for HookError
68where
69 E: alien_error::AlienErrorData + Clone + std::fmt::Debug + Serialize,
70{
71 fn from(error: alien_error::AlienError<E>) -> Self {
72 Self {
73 code: error.code.clone(),
74 message: error.message.clone(),
75 retryable: false,
76 }
77 }
78}
79
80/// The hooks a module declares, as its `alien_hooks_manifest` export returns them.
81///
82/// The runtime reads it once per module, at load, so a host can route each call to a hook
83/// without running the module first.
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub struct HooksManifest {
87 /// The extension's name, as errors from its hooks show it
88 pub extension: String,
89 /// The hooks, in the order the extension registered them, which is the order modifiers run in
90 pub hooks: Vec<HookEntry>,
91 /// The resource types the extension declares, with what the module knows of each: every
92 /// field but `controllerPlatforms`, which the controller binary lists
93 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
94 pub resource_types: IndexMap<ResourceType, ResourceTypeDescriptor>,
95}
96
97/// One hook the module declares.
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct HookEntry {
101 /// The name a host calls the hook by
102 pub name: String,
103 /// What the hook does, which decides its input, its output and when Alien calls it
104 pub kind: HookKind,
105 /// What a host needs to route calls to the hook: `resourceType` and `platform` for an
106 /// emitter or an importer, `resourceType` for a link
107 #[serde(flatten)]
108 pub routing: Map<String, Value>,
109}
110
111/// The kinds of hook a module can declare. A module that declares any other kind is refused
112/// at load, since no host could call that hook.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub enum HookKind {
116 /// Changes the CloudFormation template Alien generates: a `CfTemplate` in, a `CfTemplate` out
117 CloudformationModifier,
118 /// Changes the Terraform module Alien generates: [`TemplateFiles`] in,
119 /// [`TerraformModifierOutput`] out
120 TerraformModifier,
121 /// Adds templates to the Helm chart Alien generates: [`TemplateFiles`] in,
122 /// [`HelmModifierOutput`] out
123 HelmModifier,
124 /// Writes a custom resource into a CloudFormation template: [`EmitInput`] in. Out, by
125 /// method: `emit`, the resources as `[logicalId, CfResource]` pairs; `emitImportRef`, a
126 /// `CfExpression`; `emitBindingRef`, a `CfExpression` or `null`
127 CloudformationEmitter,
128 /// Writes a custom resource into a Terraform module: [`EmitInput`] in. Out, by method:
129 /// `emit`, a [`TerraformFragment`]; `emitImportRef`, an HCL expression as text;
130 /// `emitBindingRef`, an HCL expression as text or `null`
131 TerraformEmitter,
132 /// Writes a custom resource into a Helm chart: [`EmitInput`] in, [`HelmFragmentOutput`] out
133 HelmEmitter,
134 /// Turns what a setup template created into a custom resource's controller state:
135 /// [`ImportInput`] in, [`ImportOutput`] out
136 Importer,
137 /// Says what a workload gets when it links a custom resource: the resource's outputs in,
138 /// [`LinkOutput`] out
139 Link,
140 /// Changes the requests Alien's controllers send to AWS: [`InterceptorInput`] in,
141 /// [`InterceptorOutput`] out
142 AwsInterceptor,
143 /// Changes the requests Alien's controllers send to Google Cloud
144 GcpInterceptor,
145 /// Changes the requests Alien's controllers send to Azure
146 AzureInterceptor,
147 /// Changes the requests Alien's controllers send to Kubernetes
148 KubernetesInterceptor,
149}
150
151/// A Terraform module or a Helm chart, file by file.
152#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase")]
154pub struct TemplateFiles {
155 /// Path to contents, in the order Alien renders them
156 pub files: IndexMap<String, String>,
157}
158
159/// What a Terraform modifier returns.
160#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(rename_all = "camelCase")]
162pub struct TerraformModifierOutput {
163 /// The files the modifier changed, whole, by path. Every other file stays as Alien wrote it.
164 pub changed: IndexMap<String, String>,
165}
166
167/// What a Helm modifier returns.
168#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170pub struct HelmModifierOutput {
171 /// New files for the chart's `templates/` directory, by file name
172 pub templates: BTreeMap<String, String>,
173}
174
175/// Which method of an emitter a call runs.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "camelCase")]
178pub enum EmitMethod {
179 /// The resources or blocks that back the resource
180 Emit,
181 /// The expression that resolves to the importer's input once the template is applied
182 EmitImportRef,
183 /// The expression that resolves to the resource's runtime binding, if it has one
184 EmitBindingRef,
185}
186
187/// What an emitter gets: the parts of Alien's `EmitContext` that serialize.
188#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct EmitInput {
191 /// The emitter method to run
192 pub method: EmitMethod,
193 /// The id of the resource being emitted
194 pub resource_id: String,
195 /// The platform the template is for
196 pub platform: Platform,
197 /// Whether the template runs workloads on Kubernetes rather than the cloud's own compute
198 pub targets_kubernetes: bool,
199 /// The deployer's stack settings
200 pub stack_settings: StackSettings,
201 /// The names the generator gave each resource id in the template
202 pub names: IndexMap<String, String>,
203 /// The resource's entry in the stack, `ResourceEntry` in its serde form
204 pub resource: Value,
205}
206
207/// The blocks a Terraform emitter returns, each list as HCL text.
208#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "camelCase")]
210pub struct TerraformFragment {
211 /// The oldest setup reader that understands the fragment's import payload
212 pub minimum_setup_import_format_version: u32,
213 /// `variable` blocks
214 pub variable_blocks: String,
215 /// `moved` blocks
216 pub moved_blocks: String,
217 /// `resource` blocks
218 pub resource_blocks: String,
219 /// `data` blocks
220 pub data_blocks: String,
221 /// `ephemeral` blocks
222 pub ephemeral_blocks: String,
223 /// Entries for the module's `locals`, each an HCL expression as text
224 pub locals: IndexMap<String, String>,
225}
226
227/// What a Helm emitter returns.
228#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
229#[serde(rename_all = "camelCase")]
230pub struct HelmFragmentOutput {
231 /// The resource's entry under `infrastructure:` in `values.yaml`, if it has one
232 pub infrastructure: Option<HelmInfrastructureValue>,
233 /// Extra files for the chart's `templates/` directory, by path
234 pub extra_templates: IndexMap<String, String>,
235}
236
237/// One entry under `infrastructure:` in a chart's `values.yaml`.
238#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(rename_all = "camelCase")]
240pub struct HelmInfrastructureValue {
241 /// The resource id, the entry's key
242 pub id: String,
243 /// The runtime binding family
244 pub binding_type: String,
245 /// The service the resource binds to
246 pub service: String,
247 /// The entry's fields, in the order the emitter wrote them
248 pub fields: IndexMap<String, String>,
249}
250
251/// What an importer gets: the parts of Alien's `ImportContext` that serialize, and the data
252/// the setup template returned.
253#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255pub struct ImportInput {
256 /// The id of the resource being imported
257 pub resource_id: String,
258 /// The platform the resource was set up on
259 pub platform: Platform,
260 /// The region or location the setup template reported
261 pub region: String,
262 /// The stack settings the setup template reported
263 pub stack_settings: StackSettings,
264 /// The management configuration, when setup created a management identity
265 pub management_config: Option<ManagementConfig>,
266 /// The resource's entry in the stack, `ResourceEntry` in its serde form
267 pub resource: Value,
268 /// What the emitter's import reference resolved to after setup
269 pub import_data: Value,
270}
271
272/// What an importer returns. The controller state carries no type tag or state version, which
273/// only Alien writes.
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct ImportOutput {
277 /// The controller's saved fields and its state name
278 pub internal_state: Value,
279 /// The resource's status after the import
280 pub status: ResourceStatus,
281 /// The resource's outputs, without a type tag
282 pub outputs: Option<Value>,
283}
284
285/// What a link returns for a workload that links the resource.
286#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(rename_all = "camelCase")]
288pub struct LinkOutput {
289 /// Environment variables the workload gets, in the order the link set them
290 pub env: IndexMap<String, String>,
291 /// Ids of the permission sets the workload gets on the resource
292 pub permission_sets: Vec<String>,
293}
294
295/// A call to an interceptor, by what it asks.
296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
297#[serde(tag = "op", rename_all = "camelCase")]
298pub enum InterceptorInput {
299 /// Whether the interceptor sees this call. Answered by [`InterceptorOutput::Matches`].
300 Matches {
301 /// The call
302 request: InterceptedRequest,
303 },
304 /// Change the request. Answered by [`InterceptorOutput::Request`].
305 ModifyRequest {
306 /// The request as Alien built it and earlier interceptors left it
307 request: InterceptedRequest,
308 },
309 /// Change the response. Answered by [`InterceptorOutput::Response`].
310 ModifyResponse {
311 /// The request as it was sent
312 request: InterceptedRequest,
313 /// The response as the cloud sent it and earlier interceptors left it
314 response: InterceptedResponse,
315 },
316}
317
318/// An interceptor's answer.
319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
320#[serde(rename_all = "camelCase")]
321pub enum InterceptorOutput {
322 /// Whether the interceptor sees the call
323 Matches(bool),
324 /// The request to send. Alien sends it only when its destination, method, path, AWS
325 /// operation, the identities it names and its credential headers are the ones the
326 /// interceptor got, and it does not change who has access or act as another identity. Alien
327 /// never offers an interceptor a call that does.
328 Request(InterceptedRequest),
329 /// The response Alien reads
330 Response(InterceptedResponse),
331}
332
333/// The API a call goes to.
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
335#[serde(rename_all = "camelCase")]
336pub enum InterceptedCloud {
337 Aws,
338 Gcp,
339 Azure,
340 Kubernetes,
341}
342
343/// A request as an interceptor sees it: no credential headers, and a text body or none.
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(rename_all = "camelCase")]
346pub struct InterceptedRequest {
347 /// The API the call goes to
348 pub cloud: InterceptedCloud,
349 /// The service the call is signed for: the SigV4 signing name on AWS (`rds`), Alien's
350 /// endpoint key on Google Cloud (`cloudsql`), `management` for Azure Resource Manager, and
351 /// `kubernetes` for the API server
352 pub service: String,
353 /// The HTTP method
354 pub method: String,
355 /// The full URL
356 pub url: String,
357 /// The headers, in order, a name once per value
358 pub headers: Vec<(String, String)>,
359 /// The body as text, or `None` when the request has none
360 pub body: Option<String>,
361 /// The Azure tenant the call is made in, on Azure
362 pub tenant_id: Option<String>,
363}
364
365/// A response as an interceptor sees it.
366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "camelCase")]
368pub struct InterceptedResponse {
369 /// The HTTP status
370 pub status: u16,
371 /// The headers, in order, a name once per value
372 pub headers: Vec<(String, String)>,
373 /// The body as text
374 pub body: String,
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 #[test]
382 fn an_alien_error_crosses_as_final() {
383 let error = alien_error::AlienError::new(crate::error::ErrorData::GenericError {
384 message: "the zone already exists".to_string(),
385 });
386 assert!(error.retryable);
387 let error = HookError::from(error);
388 assert!(
389 !error.retryable,
390 "a hook gives the same answer to the same input"
391 );
392 assert_eq!(error.code, "GENERIC_ERROR");
393 }
394}