Skip to content
ImagineWorld

Writing an infrastructure DSL

node_idnode-book_write-powerful-rust-macros_chapter-10-writing-an-infrastructure-dsl
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleWriting an infrastructure DSL
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/wpm-fig-10-01-flowchart-showing-macro-parsing-dsl-into-structs.png, assets/wpm-fig-10-02-flowchart-showing-token-parsing-steps-with-lambda.png
local graph

Chapter 10 — Writing an infrastructure DSL

Section titled “Chapter 10 — Writing an infrastructure DSL”
  • Grasping the ideas behind Infrastructure as Code
  • Parsing a custom syntax with structs and keywords
  • Thinking about parsing tradeoffs
  • Avoiding duplication by combining procedural and declarative macros
  • Calling asynchronous functions in a macro and creating cloud resources

Most of the macros we have created thus far work within Rust, generating new functions, adding methods to enums, etc. But we also know macros can do more than that. For example, they allow you to generate compile-time checked HTML (Yew), or they create infrastructure for your code based on annotations (Shuttle).

This chapter features a macro that boldly goes beyond the confines of Rust and creates infrastructure in Amazon Web Services (AWS). This is interesting because it

allows us to manage both application and infrastructure logic in the same repository and the same language, which might make expanding and maintaining the code easier. And, hopefully, the example also offers inspiration to readers as to what else they might do with procedural macros. But first let’s take a step back to make sure we are all on the same page.

With the rise of cloud providers that allow you to provision or destroy hundreds of servers at the click of a button, a new way of organizing IT infrastructure was needed. In the olden days, sysadmins could administer servers manually or with some light scripting. But that kind of approach is not scalable and works rather poorly in the cloud. It is hard enough to administer hundreds of servers manually, configuring them by logging into each one and entering the right sequence of Bash commands. But now imagine the added ephemeral nature of many cloud resources. The server you get from your cloud provider might be restarted/updated/changed several times a day. What do you do? Manually check your servers every few minutes, reentering your commands when they are replaced?

Never waste a good crisis, engineers thought, and a new philosophy was born—one where servers were no longer treated as pets (i.e., each one special and unique) but rather like cattle (i.e., interchangeable components, easily described based on a few characteristics). The treatment of cattle is also a lot more automated. And so, to enable automation, the configuration of servers and services should be declared in a readable format like JSON or some kind of Domain-Specific Language. That way, we have a written specification of what we need (this OS, this much RAM, CPU, storage) for our application. This specification not only enables us to easily destroy and create resources and environments, but it also serves as living, version-controlled documentation of infrastructure. That makes things easier to reason about, since everything is/should be exactly as described. You don’t need to figure out the specs, OS, languages, dependencies, etc. to reproduce a bug on your server if all that information is available in a text file. When everything we need to run an application is in a readable format that can somehow be executed to create said application, we call that Infrastructure as Code (IaC).

NOTE The aforementioned story is a simplification. Automation and version-controlling infrastructure are ideas with a long history. Nevertheless, these ideas have seen a huge uptick in popularity thanks to the cloud.

AWS is the cloud division of Amazon, currently the biggest player in the cloud business and a mile ahead of other big players like Azure and Google Cloud. A large part of the internet (including Netflix) runs on its infrastructure, which becomes painfully obvious when AWS has problems and countless websites go down.

AWS started simple some two decades ago with compute (Elastic Compute Cloud [EC2]), storage (Simple Storage Service [S3]), and queueing (Simple Queue Service

[SQS]—yes, AWS really likes “simple” things). Nowadays, few people can enumerate all the services that it offers.

It has also been one of the cloud providers that has driven IaC, launching its tool for IaC, AWS CloudFormation, more than 12 years ago. CloudFormation lets you describe your infrastructure in JSON or YAML templates, which are used to create stacks that contain all the actual application infrastructure. Other AWS tools build on the capabilities of CloudFormation. AWS SAM offers a version of CloudFormation that is easier to work with when you create serverless applications. AWS CDK lets you write your infrastructure in a language like Typescript or Python, which will be translated into CloudFormation templates.

There are also many independent tools, like Terraform, Pulumi, or the Serverless Framework, that allow you to create services for multiple cloud providers. The underlying idea stays the same, though: describe what you want in text or code and let the framework make your infrastructure dreams come true! But how do these tools communicate your desires to the cloud providers? Generally, they turn to either REST endpoints that the cloud provides for creating, destroying, and using services or software development kits (SDKs) that abstract away irrelevant details and allow you to work with these services directly from your favorite programming language.

NOTE Behind the scenes, CloudFormation also makes service calls to AWS to create and update services. But it is not 100% clear what calls these are: the REST endpoints? Custom endpoints?

In this chapter, we will work on a DSL that uses the AWS SDK for Rust to create resources, focusing on Amazon S3 and AWS Lambda. S3 provides object-based storage via buckets that theoretically have unlimited storage. Lambda functions allow you to run compute without worrying about infrastructure. You provide code and some configuration, like the amount of memory you require and the maximum amount of time the code is allowed to run (timeout), and AWS makes sure that your code is executed and you only pay for the time that your code requires. Neat.

Besides giving you a beautiful new way to create two AWS services from code, we also want to give users fast feedback. One of the downsides of text-based tools like CloudFormation is that there is no built-in mechanism for feedback when you make mistakes. This almost necessitates using IDE plugins and command-line interface tools as a substitute, because you do not want to start deploying an application just to find out minutes later that your template had a typo.

Rust is different: it likes to give you a lot of feedback before stuff starts running, and so do we. Summarized, what we want to offer is a simple language for describing infrastructure that automatically creates the specified resources and warns you when and where things go wrong, preferably as early as possible.

For example, creating a bucket named unique might look like this:

iac! {
bucket unique
}

That seems simple and easy. As an example of a warning when things go wrong, we will return this error when we type bucke instead of bucket:

error: only 'bucket' and 'lambda' resources are supported
--> src/main.rs:7:9
7 |
| bucke unique
| ^^^^^

We point to the typo and give additional information. This seems actionable enough (one of the exercises tries to make the message even better).

Besides limiting the number of services, we also limit the number of properties you can pass in, because not only do both buckets and lambdas have a huge number of properties, but the added value of having them in this chapter drops rapidly, since the required code is very similar. What we allow is creating buckets (required property: name), creating lambda functions (required: name; optional: memory and timeout), and sending events from buckets to functions. The latter provides very useful functionality, allowing you to react to the creation or changing of objects, which allows for a wide variety of use cases, like updating databases or triggering business workflows. As such, these bucket events are widely used, even now that Amazon EventBridge has become more of a central intermediary for eventing within AWS.

To summarize, this chapter’s macro will parse a DSL that contains instructions for creating a lambda and/or bucket (see figure 9.1). This information will be passed on to clients who will use the AWS SDK to create the specified resources in the cloud.

[!visual-conversion] Flowchart showing macro parsing DSL into structs, then passing to … Cropped from the scan (PDF page 218, printed p. ?): Flowchart showing macro parsing DSL into structs, then passing to clients (LambdaClient, S3Client) which use SDK to create AWS Lambda Function and AWS S3 Bucket.

We will write this macro in two phases. In this first phase, we concentrate on parsing the input into custom structs. Only in the second phase will we start doing something with the parsed information.

One reason for working in two phases is that parsing is very different from creating cloud resources, so treating these two separately makes sense. And if we keep the parsing separate, it could—in theory—be made independent of the concrete cloud that is used behind the scenes. If our example had been something like iac! { object-storage unique } instead, the naming would have focused on high-level desires that could be resolved in different ways. With an AWS backend, that object-storage would create a bucket; with an Azure Cloud backend, it would go for Azure Blob Storage. We would have to write one backend for every cloud but only one parser. That being said, in practice there are often subtle differences between cloud providers that make it hard not to leak implementation details in your IaC.

Another reason is of a practical nature: creating real cloud infrastructure adds much complexity, while also requiring an AWS account. By banning the cloud to the second part of this chapter, we minimize the number of code examples where you have to interact with AWS when coding along.

We can use the two-directory setup from earlier projects, with our macro in a subdirectory called iac-macro, and our usage examples in an iac-macro-usage directory. The following listing shows the familiar Cargo.toml file for the macro itself.

[package]
name = "iac-macro"
version = "0.1.0"
edition = "2021"
[dependencies]
quote = "1.0.33"
syn = { version = "2.0.39", features = ["extra-traits"] }
[lib]
proc-macro = true

The following listing shows one for the usage project.

Listing 9.2 The iac-macro-usage Cargo.toml

Section titled “Listing 9.2 The iac-macro-usage Cargo.toml”
[package]
name = "iac"
version = "0.1.0"
edition = "2021"

iac-macro = { path = ”../iac-macro” }

trybuild = “1.0.85”

Our main.rs consists of a lot of usage examples: you can create a bucket, a lambda, a bucket with a lambda, or a bucket linked to a lambda via an event. For the last two, we use an arrow (=>) to indicate an event coming from the bucket and going to the lambda.

use iac_macro::iac;
fn main() {
iac! {
bucket uniquename
}
iac! {
lambda a_name
}
iac! {
lambda my_name mem 1024 time 15
}
iac! {
lambda name bucket uniquename
}
iac! {
bucket uniquename => lambda anothername
}
iac! {
bucket b => lambda l mem 1024 time 15
}
}

The usage directory also contains compilation tests (in tests) for failure cases, which are not shown here.

Our parsing implementation is about 140 lines of code. The entry point delegates the work to a custom struct. When parsing is done, it prints the result and gives back an empty TokenStream because we don’t have anything sensible to return.

#[proc_macro]
pub fn iac(item: TokenStream) -> TokenStream {
let ii: IacInput = parse_macro_input!(item);
eprintln!("{}", ii);
quote!().into()
}
<!-- page: 221 -->
# 9.3 Parsing our input
Since we are using a custom struct to do the parsing, we should implement the `Parse` trait for `IacInput`.
## 9.3.2 Implementing the Parse trait for our structs
In the following code, you can see that `IacInput` is responsible for high-level parsing, leaving the bucket and lambda specifics to other structs. As long as there is input, we keep looking for a bucket and lambda, trying to parse those inputs. (We could easily extend this part of our code to allow for multiple buckets and lambdas if we wanted to.) To do that, we use `peek`, which takes a look at the next token in the stream.
If we receive anything else, we throw an error because we either encountered an unknown resource or there is an unparseable leftover. Here, we turn to `lookahead1`, which allows us not only to see the next token but also to return an error for that particular piece of code. In our case, we take the span and return our own, custom error.
Once the input has been fully parsed, we check whether our bucket has the `has_event` property set to `true`. If that is the case, we expect a lambda to also be present, since it is required for receiving those events. Finally, when we retrieve the event from the bucket, the type of the bucket variable is not yet clear to Rust, so it can’t be inferred, and we have to make it explicit: `let mut bucket: Option<Bucket>`.
**NOTE** In this chapter, I have done my best to follow the Rust standard of having errors start with a lowercase letter and without trailing punctuation. Capitalization comes more naturally to me, and not every project seems to follow the standard. Even so, it is probably best to follow existing conventions.
### Listing 9.5 IacInput definition and Parse implementation
rust
#[derive(Debug)]
struct IacInput {
bucket: Option<Bucket>,
lambda: Option<Lambda>,
}
impl Parse for IacInput {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let mut bucket: Option<Bucket> = None;
let mut lambda = None;
loop {
if input.peek(kw::bucket) {
bucket = Some(input.parse()?);
} else if input.peek(kw::lambda) {
lambda = Some(input.parse()?);
} else if !input.is_empty() {
return Err(syn::Error::new(
input.lookahead1().error().span(),
"only 'bucket' and 'lambda' resources are supported"
));
} else {
break;
}
}
Ok(IacInput { bucket, lambda })
}
}

These are custom keywords (discussed later).

If we have any other input, returns an error with a helpful span and message

If we have a bucket or lambda, delegates parsing to the Bucket or Lambda struct

<!-- page: 222 -->
# CHAPTER 9 Writing an infrastructure DSL
rust
break;
}
}

No input left; stops looping

if bucket.as_ref().map(|v| v.has_event).unwrap_or(false)
&& lambda.is_none() {
return Err(syn::Error::new(
input.span(),
"a lambda is required for an event ('=>')"
))
}
}
Ok(
IacInput {
bucket,
lambda,
}
)
}

One thing that is probably still unclear: what are kw::bucket and kw::lambda? Yes, those two do require a bit of explaining. Within our macro, lambda and bucket have a special meaning. Both act like a sort of keyword for a “resource declaration,” which is followed by—required and optional—resource details. But for Rust/syn, there is no reason to treat either of these words as something special. So we can use the custom_keyword macro to tell syn that these two are keywords within our macro. By convention, such custom keywords are placed in a separate module called kw (short for “keywords”), as shown in the following listing.

Listing 9.6 Our four keywords: bucket, lambda, memory, and timeout

Section titled “Listing 9.6 Our four keywords: bucket, lambda, memory, and timeout”
pub(crate) mod kw {
syn::custom_keyword!(bucket);
syn::custom_keyword!(lambda);
syn::custom_keyword!(mem);
syn::custom_keyword!(time);
}

Behind the scenes, the macro turns the given keywords into structs that implement Parse, as well as a method for allowing peek. This is useful, since we are using both parse and peek in the code.

Now we can soldier on to take a look at Bucket, the struct that parses the S3 bucket information. The parsing code gets rid of the bucket token, retrieves the name, and sees if an event token (=>) is present.

Listing 9.7 Bucket and its Parse implementation

Section titled “Listing 9.7 Bucket and its Parse implementation”
#[derive(Debug)]
struct Bucket {
name: String,
has_event: bool,
}
impl Parse for Bucket {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let bucket_token = input.parse::<kw::bucket>()
.expect("we just checked for this token");
let bucket_name = input.parse()
.map(|v: Ident| v.to_string())
.map_err(|_| syn::Error::new(
bucket_token.span(),
"bucket needs a name"
))?;
let event_needed = if !input.peek(kw::lambda)
&& input.peek(Token!(=>)) {
let _ = input.parse::<Token!(=>)>().unwrap();
true
} else {
false
};
Ok(Bucket {
name: bucket_name,
has_event: event_needed,
})
}
}

The next identifier should be the bucket name.

We parse the bucket token, which should be present if we end up in this method.

If we have =>, an event is required, so sets has_event to true and gets rid of the arrow

Most of this is familiar: we are parsing the inputs, including those we won’t use (the bucket token and arrow) but have to get rid of. Similar to IacInput, we have made some effort to provide good error handling. But when we expect things to always work, we use expect with a message explaining our thinking.

The code for parsing the lambda is similar but a bit longer due to the additional properties. We parse the token and name. If there is still input and the next token is not the start of a bucket declaration, there are optional properties. We loop and check for the mem and time custom keywords. If we get anything else, we error. As our optional properties can only be numbers, we parse them as LitInt (which is very similar to the LitStr from earlier chapters). That means the library will return sensible errors when the value is not a number. Finally, we parse the values we received into u16 (see figure 9.2).

  • lambda my_name mem 1024 time 15
  • my_name mem 1024 time 15
input.parse().map(|v: Ident| v.to_string())…
Section titled “input.parse().map(|v: Ident| v.to_string())…”
  • mem 1024 time 15
while input.is_empty() && input.peek(kw::bucket)
Section titled “while input.is_empty() && input.peek(kw::bucket)”
  • if input.peek(kw::mem)

####### Tokens

  • time 15
  • Empty (parsing done)

Why u16? Simple: That way, we can get the compiler to do even more work for us! Both memory and timeout can only be positive numbers, so i is not required. And because memory and time can be larger than 255 (the maximum value of u8), u16 is next in line, which will stop illegal values above 65,535. A further improvement to error handling

[!visual-conversion] Flowchart showing token parsing steps with lambda struct, including while … Cropped from the scan (PDF page 224, printed p. ?): Flowchart showing token parsing steps with lambda struct, including while loop conditions and variable assignments.

would be to add additional checks on top of what syn and the compiler are doing for us. For example, in the time branch, we would check that the value is <= 900.

Listing 9.8 Lambda and its Parse implementation

Section titled “Listing 9.8 Lambda and its Parse implementation”
#[derive(Debug)]
struct Lambda {
name: String,
memory: Option<u16>,
time: Option<u16>,
}
impl Parse for Lambda {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let lambda_token = input.parse::<kw::lambda>()
.expect("we just checked for this token");
let lambda_name = input.parse()
.map(|v: Ident| v.to_string())
.map_err(|_| {
syn::Error::new(lambda_token.span, "lambda needs a name")
})?;
let mut lambda_memory = None;
let mut lambda_timeout = None;
while !input.is_empty() && !input.peek(kw::bucket) {
if input.peek(kw::mem) {
let _ = input.parse::<kw::mem>()
.expect("we just checked for this token");
lambda_memory = Some(
input.parse()
.map(|v: LitInt| v.to_string())
.parse()
.map_err(|_| {
syn::Error::new(
v.span(),
"memory needs positive value <= 10240"
)
})
)??
} else if input.peek(kw::time) {
let _ = input.parse::<kw::time>()
.expect("we just checked for this token");
lambda_timeout = Some(
input.parse()
.map(|v: LitInt| v.to_string())
.parse()
.map_err(|_| {
syn::Error::new(
v.span(),
"timeout needs positive value <= 900"
)
})
)??
}
}
}
}

The optional properties should be LitInt values that can be parsed into u16. If that is not the case, we return an error.

Keeps looping while we have input for our lambda

Note: The annotations (comments) in the original image are preserved as blockquotes for clarity and context. The code is presented in a code block with the `rust` language identifier for syntax highlighting. The structure and hierarchy of the document are maintained as closely as possible.
<!-- page: 226 -->
# CHAPTER 9 Writing an infrastructure DSL
rust
} else {
Err(syn::Error::new(
input.span(),
"unknown property passed to lambda"
))?
}
Ok(Lambda {
name: lambda_name,
memory: lambda_memory,
time: lambda_timeout,
})

We don’t have any other optional properties besides time and mem, so if we end up here, we should return an error.

main now runs, and its logging shows that everything is parsed:

IacInput { bucket: Some(Bucket { name: "uniquename", event: true }),
lambda: Some(Lambda { name: "my_name", memory: Some(1024),
time: Some(15) }) }

Plus, we warn users of quite a few errors at compile time (bet you are tired of hearing me say that), like when we forget to give a lambda a name,

error: lambda needs a name
--> tests/fails/bucket_and_no_lambda_name.rs:5:23
|
5 | bucket unique lambda
| ^^^^^^^

when we pass a string as a memory property,

error: expected integer literal
--> tests/fails/lambda_time_not_a_number.rs:5:25
|
5 | lambda name mem "yes"
| ^^^^^

or when the number we pass is invalid:

error: memory needs positive value <= 10240
--> tests/fails/lambda_negative_time.rs:5:25
|
5 | lambda name mem -10
| ^

So now we have a nice, little, helpful parser, which we will soon put to work.

NOTE This is a helpful parser but not a perfect one, as it allows for some odd behavior. For example, we can pass in multiple buckets, but we will save only one. We won’t fix all those oddities here, though the exercises do ask you to make one minor improvement.

First let me show you a few alternatives. And to make things a little more interesting, we are going to use a slight variation in our DSL syntax. Maybe the current style is a bit too loose, and we could make it clearer where a resource starts and ends. So for the lambda and its multiple properties, we can put everything between parentheses and separate property name and value by an equals sign.

Listing 9.9 Alternative example invocation

Section titled “Listing 9.9 Alternative example invocation”
fn main() {
iac! {
bucket uniquename => lambda (
name = my_name, mem = 1024, time = 15
)
}
}

Thus, in our alternatives, we focus on the Lambda struct, which must change because of the updated syntax.

9.4.1 Using Punctuated with a custom struct

Section titled “9.4.1 Using Punctuated with a custom struct”

In the first alternative Parse implementation, we now have to retrieve the content within the parentheses. And instead of manually parsing these parentheses (which is an option), we introduce the parenthesized macro, which will do this work for us. Its usage is very similar to braced, which we encountered earlier: give the macro your braced/parenthesized input and a variable to put the content in.

When we have the content, we know the properties are separated by commas, with every property consisting of a key separated by a value. That kind of repetition calls for Punctuated. So we use it to parse the properties. For the name = value part, we create a struct called KeyValue (as in key-value pairs), which we will discuss in a moment. When we have all the key-value pairs, we go through the results and compare them with the string value of our keys to find the right properties, throwing an error when we encounter an unrecognized property. An error is also thrown when we do not find the required name property.

// other imports
use syn::parenthesized;
use syn::punctuated::Punctuated;
impl Parse for Lambda {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let _ = input.parse::<kw::lambda>();
.expect("we just checked for this token");
let mut lambda_name = None;

let mut lambda_memory = None; let mut lambda_timeout = None;

let content; parenthesized!(content in input);

let kvs = Punctuated::<KeyValue, Token!(,)>::parse_terminated( &content )?; kvs.into_iter().for_each(|kv| { if kv.key == “name” { lambda_name = Some(kv.value); } else if kv.key == “mem” { lambda_memory = Some( kv.value.parse().unwrap() ); } else if kv.key == “time” { lambda_timeout = Some( kv.value.parse().unwrap() ); } });

Ok(Lambda { name: lambda_name.ok_or(syn::Error::new( input.span(), “lambda needs a name” ))? , memory: lambda_memory, time: lambda_timeout, }) }

Because we do string comparisons this time, we do not need the keywords for mem and time, so those can be removed.

The definition of KeyValue holds few surprises. We save the key and value as strings because that will work for all properties. And, in Parse, we retrieve the key, which should be the first part of our input. Next, we get rid of the = token, which we don’t need. But since it is part of our syntax, we do throw an error if it is not present. Note that this is the one place where we check for the equals sign, so if we wanted to use another separator, like a colon, that would be a one-line change.

For the values of the properties, we expect an Ident for the name. If we had used name = “some_name”, it would have been a LitStr. LitInt is used for the other two, which should stop several faulty inputs. In all other cases, the property is unrecognized, which means it’s error time.

Listing 9.11 lib.rs and the new KeyValue struct

Section titled “Listing 9.11 lib.rs and the new KeyValue struct”

#[derive(Debug)] struct KeyValue { key: String,

Annotations:

  • parenthesized is similar to braced: it will put whatever is inside the parentheses in content.
  • Using Punctuated and a custom struct, we parse the content, returning early with ? if there is a problem.
  • We should actually return errors, but we are skipping that for brevity’s sake.
  • A name is required, so a missing lambda_name is an error.
  • The keys are compared with the string values of our properties.

value: String, }

impl Parse for KeyValue { fn parse(input: ParseStream) -> Result<Self, syn::Error> { let key = input.parse() .map(|v: Ident| v.to_string()) .map_err(|_| syn::Error::new( input.span(), “should have property keys within parentheses” ))?;

let _: Token! (=) = input.parse()
.map_err(|_| syn::Error::new(
input.span(),
"prop name and value should be separated by ="
))?;
let value = if key == "name" {
input.parse()
.map(|v: Ident| v.to_string())
.map_err(|_| syn::Error::new(
input.span(),
"Name property needs a value"
))
} else if key == "mem" || key == "time" {
input.parse()
.map(|v: LitInt| v.to_string())
.map_err(|_| {
syn::Error::new(
input.span(),
"memory and time needs a positive value"
)
})
} else {
Err(syn::Error::new(
input.span(),
format!("unknown property for lambda: {}", key)
))
}?;
Ok(KeyValue {
key,
value,
})
}

}

The happy path for this alternative approach is identical to that of the previous setup, producing the same output. Error handling is basically the same, even if it is slightly abbreviated. The use of parentheses and the equals signs does mean we have some additional messages, like

error: prop name and value should be separated by = —> tests/fails/lambda_colon_instead_of_equals.rs:5:22 5 | lambda (name :) | |

<!-- page: 230 -->
# CHAPTER 9 Writing an infrastructure DSL
That concludes the first movement (variation). One nice thing is how it avoids the use of a (while) loop for retrieving the properties by making `punctuated` do part of the work. And having the content within parentheses does not hurt either. It also shows that keywords are a nice convenience but not obligatory.
## 9.4.2 Using Punctuated with a custom enum and builder
Now, take a look at the next approach. On the surface, it’s similar to the previous one: get rid of the token and retrieve the content. Except, this time, we have `LambdaProperty` in our `Punctuated`, and we are folding/reducing the results into our output using a builder.
### Listing 9.12 lib.rs Lambda struct
rust
impl Parse for Lambda {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let _ = input.parse::<kw::lambda>()
.expect("we just checked for this token");
let content;
parenthesized!(content in input);
let kvs = Punctuated::<LambdaProperty, Token!(,)>::parse_terminated(
&content
)?;
let builder = kvs
.into_iter()
.fold(Lambda::builder(content.span()), |acc, curr| {
match curr {
LambdaProperty::Name(val) => acc.name(val),
LambdaProperty::Memory(val) => acc.memory(val),
LambdaProperty::Time(val) => acc.time(val),
}
});
Ok(builder.build()?)
}
}

Parses into a Punctuated of LambdaProperty, a new struct

Folds into LambdaBuilder, another new struct

Builds, returning early if there are errors

Listing 9.13 shows part of the builder definition. Thanks to earlier chapters, you should be intimately familiar with both concept and implementation. We save a span in the struct to allow creating an error when the required name parameter is missing. And build returns a Result because, as we just made clear, the operation might fail when the name is not present.

Listing 9.13 LambdaBuilder struct, and the Lambda method that instantiates it

Section titled “Listing 9.13 LambdaBuilder struct, and the Lambda method that instantiates it”
struct LambdaBuilder {
input_span: Span,
name: Option<String>,
<!-- page: 231 -->
# 9.4 Two alternative parsing approaches
memory: Option<u16>,
time: Option<u16>,
}
impl LambdaBuilder {
fn name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
// similar setters for memory and time
fn build(self) -> Result<Lambda, syn::Error> {
let name = self.name.ok_or(
syn::Error::new(
self.input_span,
"name is required for lambda"
)
)?;
Ok(Lambda {
name,
memory: self.memory,
time: self.time,
})
}
}
impl Lambda {
fn builder(input_span: Span) -> LambdaBuilder {
LambdaBuilder {
input_span,
name: None,
memory: None,
time: None,
}
}
}
The span that we are storing inside the LambdaBuilder comes from proc_macro2, since that is the type of span that syn::Error requires. That means we need to add proc-macro2 = "1.0.69" to our dependencies.
LambdaProperty is an enum with the three kinds of known lambda properties, which allows us to immediately pass in the right type of value (a string or a number). Meanwhile, within parse, our code is similar to what we had in our first approach. We check whether the property matches any of our keywords. If it does, we get rid of what we do not need and return the proper variant.
## Listing 9.14 The LambdaProperty enum
pub(crate) mod kw {
// earlier keywords
syn::custom_keyword!(name);
}
A name is required, so if it is missing we should return an error with a span pointing to the original code.
<!-- page: 232 -->
#[derive(Debug)]
enum LambdaProperty {
Name(String),
Memory(u16),
Time(u16),
}
impl Parse for LambdaProperty {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
let lookahead = input.lookahead1();
if lookahead.peek(kw::name) {
let _ = input.parse::<kw::name>()
.expect("we just checked for this token");
let _: Token! (=) = input.parse()
.map_err(|_| syn::Error::new(
input.span(),
"prop name and value should be separated by ="))?;
let value = input.parse()
.map(|v: Ident| v.to_string())
.map_err(|_| syn::Error::new(
input.span(),
"name property needs a value"))?;
Ok(LambdaProperty::Name(value))
} else if lookahead.peek(kw::mem) {
let value = parse_number::<kw::mem>(
input,
"memory needs a positive value <= 10240")?;
Ok(LambdaProperty::Memory(value))
} else if lookahead.peek(kw::time) {
let value = parse_number::<kw::time>(
input,
"time needs a positive value <= 900")?;
Ok(LambdaProperty::Time(value))
} else {
Err(syn::Error::new(
input.span(),
format!("unknown property for lambda")))
}
}
}
For once, we have a helper for the practically identical parsing required for memory and time, because in both cases, we like to have LitInt as the parsing type to stop errors, necessitating an additional step to turn the result into a u16. That means we cannot just use the function for parsing the name.
The most interesting thing about parse_number is that we made it generic over Parse. That's necessary because we want to parse the memory and time keywords. And
After getting rid of the keyword and equals sign, parses the name value to create the right variant
Uses a helper to do the same for the numeric properties
Returns an error if the property is unknown
<!-- page: 233 -->
# 9.5 Actually creating the services
Parse is a trait implemented by custom keywords. So, as seen earlier, when we want to parse the timeout, we simply call `parse_number::<kw::time>`.
## Listing 9.15 The generic parse_number helper
rust
fn parse_number<T>(input: ParseStream, error_message: &str)
-> Result<u16, syn::Error>
where T: Parse {
let _ = input.parse::<T>()
.expect("we just checked for this token");
let _: Token! (=) = input.parse()
.map_err(|_| syn::Error::new(
input.span(),
"prop name and value should be separated by =")
)?;
let value = input.parse()
.map(|v: LitInt| v.to_string())
.parse()
.map_err(|_| {
syn::Error::new(
v.span(),
error_message,
)
})
)??;
Ok(value)
}

Those are the three implementation options we have on offer today, though you could think of countless more. As usual, the best choice depends on preferences and project specifics. Our first approach was the shortest, mainly because it was leaving a lot of the hard work to a single struct (Lambda). And in the case of a macro of this length, it’s a perfectly fine solution. The second solution is longer, but the abstraction of adding another struct for parsing might pay off in the long run. The third approach is even longer—definitely overkill for a macro like this. However, having a flexible and use-case-specific enum can become worthwhile if the application keeps growing.

Next up is asking AWS to create the requested services. We can do this with the AWS SDK for Rust.

There are several things to be aware of for this part of the project.

Linking the bucket and lambda may occasionally fail because AWS might mistakenly think that the bucket or lambda you created less than a second ago does not exist. A production-grade version of this project would detect such failures and do a retry.

<!-- page: 234 -->
## (continued)
This code only creates resources. If you run it a second time, you will get an error saying that the resources already exist. Production-grade code would check the existence of these resources by names or by keeping a state—like Terraform. See the exercises for a simple example.
Also, be careful when running this code in certain IDEs. IntelliJ, for example, might expand macros to give you better feedback, except that, in our case, expanding has the side effect of creating resources—which won't cost you anything, because buckets and lambdas are free. But it might cause your code to fail because the name you picked was already claimed by the IDE.
When it comes to IntelliJ, you can try to avoid this by skipping resource creation when you know the IDE is expanding your macros:
```rust
impl IacInput {
pub fn has_resources(&self) -> bool {
!is_ide_completion()
&& (self.bucket.is_some() || self.lambda.is_some())
}
}
fn is_ide_completion() -> bool {
match std::env::var_os(
"RUST_IDE_PROC_MACRO_COMPLETION_DUMMY_IDENTIFIER"
) {
None => false,
Some(dummy_identifier) => !dummy_identifier.is_empty(),
}
}

Alternatively, you can use the RUST_IDE_PROC_MACRO_COMPLETION environment variable, which will be set to 1. Of course, there are no guarantees that this will work for your IntelliJ setup or future versions of the IDE.

And, a final caveat, we will be using the first approach (of those presented previously) for parsing our input.

Our project now has two very different tasks to perform. It still needs to parse the input, as we have done in previous sections. But it also needs to communicate with AWS. It might be best to split our project into multiple modules/files, with more specialized tasks:

  • lib.rs still exists as the entry point and coordinator.
  • input.rs contains everything related to parsing.
  • lambda.rs has code to handle creating lambdas.
  • s3.rs similarly contains code for creating a bucket.
  • errors.rs contains a custom error, translating AWS SDK errors into useful syn errors. Errors handled by input.rs are already of type syn, so we leave those untouched.

The example directory contains a basic JavaScript function handler.js, which we will execute in our AWS Lambda.

A minor change, not shown here, is that many of the fields of our parsing structs have become public to allow lambda.rs and s3.rs to access them when creating resources.

Creating a separate file for errors is not always a good idea. Locality, or having everything related to a piece of functionality—including error handling—in one place can be a big plus. And in a large project, having separate files for errors can become unwieldy. In this specific case, it offers us a nice way to unify the errors from lambda and s3 while also allowing us to discuss all our error handling in one go.

We start by looking at lib.rs. Our first step is still to parse that input. When that is done, we use a helper to determine whether we have any resources that need to be created. This is an optimization that helps us avoid some work when it is not necessary.

What kind of work? Well, AWS SDK client initialization (via the new method) is asynchronous. Plus, most of the methods exposed by these clients are also async. And, for this behavior, the SDK relies on Tokio as an asynchronous runtime (i.e., for executing the asynchronous Rust code).

NOTE We have encountered Tokio before when we talked about the tokio::main macro.

So the asynchronous behavior and Tokio runtime from the AWS SDK infect our macro, meaning that when we have resources and need to use the SDK, we have to start a runtime and call block_on to wait until the infrastructure has been created.

// mods and imports
#[proc_macro]
pub fn iac(item: TokenStream) -> TokenStream {
let ii: IacInput = parse_macro_input!(item);
if ii.has_resources() {
let rt = tokio::runtime::Runtime::new()
.unwrap();
match rt.block_on(create_infra(ii)) {
Ok(_) => quote!().into(),
Err(e) => e.into_compile_error()
}
} else {
quote!().into()
}
}

As we are now using tokio, you will need to add it as a dependency to the project. Somewhat surprisingly, the runtime (rt) feature is not enough to get this code working: the new method is sneakily hiding behind the rt-multi-thread flag. We also add

the AWS SDK dependencies we need—s3 and lambda, plus one for creating configuration for the clients of these crates:

aws-config = "1.1.1"
aws-sdk-s3 = "1.11.0"
aws-sdk-lambda = "1.9.0"
tokio = { version = "1.26.0", features = ["rt", "rt-multi-thread"] }

And if you think tokio is too big a dependency for such a simple use case, you may be able to use something more lightweight, like the pollster crate, which has no dependencies and is a fraction of the size of Tokio. Their usage is pretty similar:

use pollster::FutureExt as _;
pub fn iac(item: TokenStream) -> TokenStream {
// ...
match create_infra(ii).block_on() {
Ok(_) => quote!().into(),
Err(e) => e.into_compile_error()
}
}

However, this is not an option for this particular use case because—as we mentioned—the AWS SDK relies on the Tokio runtime. This means you get an error (there is no reactor running, must be called from the context of a Tokio 1.x runtime) when using any alternative runtime.

The async function create_infra is shown in listing 9.17. It creates clients for the SDK calls to Amazon S3 and AWS Lambda. And, as you can see, those are async, since we need to await them—hence the need for an asynchronous function. When the clients are ready, we create the lambda, saving the result in output. Why? Because we will be creating a bucket next, and if it has an event, we need to know the Amazon Resource Name (ARN; a unique identifier) of the lambda so we know where to send the event. We also need to add so-called AWS Identity Access Management (IAM) permissions to tell the lambda that our bucket is allowed to send events. Errors inside the function are changed into IacError, the custom error type that is turned into compile_error by our entry point.

NOTE You could imagine somehow encoding “we have a linked bucket and lambda” in the parsing phase, maybe with an enum variant called BucketLinkedToLambda(Bucket,Lambda). That would make this phase of creating the infrastructure easier and safer. See the exercises.

Listing 9.17 async create_infra function coordinating the infrastructure setup

Section titled “Listing 9.17 async create_infra function coordinating the infrastructure setup”
async fn create_infra(iac_input: IacInput) -> Result<(), IacError> {
let s3_client = S3Client::new()
.await;
let lambda_client = LambdaClient::new()
.await;
let mut output = None;

Creates the AWS SDK clients

if let Some(lambda) = &iac_input.lambda { eprintln!(“creating lambda…”); output = Some(lambda_client.create_lambda(lambda).await?); }

if let Some(bucket) = &iac_input.bucket { eprintln!(“creating bucket…”); s3_client.create_bucket(bucket).await?; }

if bucket.has_event { eprintln!(“linking bucket and lambda by an event…”); let lambda_arn_output = output .expect(“when we have an event, we should have a lambda”); let lambda = iac_input.lambda .expect(“when we have an event, we should have a lambda”);

let lambda_arn = lambda_arn_output.function_arn()
.expect("creating a lambda should return its ARN");
lambda_client.add_bucket_permission(
&lambda, &bucket.name
).await?;
s3_client.link_bucket_with_lambda(
bucket, lambda_arn
).await?;

}

Ok(())

To summarize: Once our input has been parsed, we check whether we have any resources that need creating. When we have a bucket and/or lambda, we start a runtime, block on an asynchronous function, and wait for it to build our resources using the two SDK clients.

All that is left to do is to dive into the code for the two clients. We use aws_config (that additional crate) to create the right configuration, relying on locally available credentials and an AWS region that we pass in (eu-west-1; i.e., in Ireland—you may want to pick another region if you are not in Europe). That is, to run this code locally, make sure you have active AWS admin creds.

rust // imports

pub struct LambdaClient { client: Client, }

impl LambdaClient { pub async fn new() -> Self { let config = aws_config::defaults(BehaviorVersion::latest())

aws_config uses local credentials to load configuration. We set the region to Ireland.

rust .region(Region::new(“eu-west-1”)) .load() .await; LambdaClient { client: Client::new(&config), }

> With that config ready, we create the AWS client and our LambdaClient.
In a real project, we could turn to Default for a default setup, allowing users to pick a region when calling new.
Next are the functions we already saw in action. `create_lambda` uses a builder to send lambda configuration information to AWS. We set the name and optionally add a time and memory size. We also have to fill in several other properties, including a role (which already exists in my account) and a zip with the code, which was already uploaded to a bucket ("my-lambda-bucket") in my account.
## Listing 9.19 create_lambda
```rust
pub async fn create_lambda(&self, lambda: &Lambda)
-> Result<CreateFunctionOutput, SdkError<CreateFunctionError>> {
let mut builder = self.client
.create_function()
.function_name(&lambda.name)
.role("arn:aws:iam::111111111111:role/change")
.code(FunctionCode::builder()
.s3_bucket("my-lambda-bucket")
.s3_key("example.zip")
.build())
.runtime(Runtime::Nodejs18x)
.handler("handler.handler");
if let Some(time) = lambda.time {
builder = builder.timeout(time.into());
};
if let Some(mem) = lambda.memory {
builder = builder.memory_size(mem.into())
};
builder
.send()
.await
}

Sets the name

Sets the role (and the Lambda should be able to “assume” it).

Since the code in the zip is JavaScript, the runtime should be Nodejs.

Tells AWS that the code for this function is in a bucket object called “example.zip”

The zip contains a file called “handler,” which has a function that is also called “handler.” So we point AWS to handler.handler.

Sets the memory and timeout if they are present

Waits for AWS to create your resource

The following code is the handler.js file within example.zip. If you only want the macro to work (and not the Lambda that we are creating), you can even upload an empty file:

exports.handler = async () => {
return {
hello: 'world'
}
}
<!-- page: 239 -->
# 9.6 The two AWS clients
To make the method more unit testable, you could extract the builder, which is pure, into a separate function that contains most of the code and has no need for mocking. The send, which is impure, would be in a different function:
rust
pub async fn create_lambda(&self, lambda: &Lambda)
-> Result<CreateFunctionOutput, SdkError<CreateFunctionError>> {
self.create_lambda_builder(&lambda)
.send()
.await
}

The helper function contains most of the code and is pure.

The second function, add_bucket_permission, allows the bucket to invoke the lambda. It, too, uses a builder and send to talk to AWS. Inside we do some basic AWS IAM things, like allowing anyone (”*”) to invoke the lambda as long as the source of that invocation is our bucket. That way, the bucket can invoke the function when it has an event ready to go.

pub async fn add_bucket_permission(&self, lambda: &Lambda, bucket: &str)
-> Result<AddPermissionOutput, SdkError<AddPermissionError>> {
self.client.add_permission()
.function_name(&lambda.name)
.principal("*")
.statement_id("StatementId")
.action("lambda:InvokeFunction")
.source_arn(
format!("arn:aws:s3:::{}" , bucket)
)
.send()
.await
}

Allows anyone…

…to invoke this lambda…

…as long as the source of the invocation is our bucket

Now let’s look at the S3Client. Its fields and new are very similar to the LambdaClient: we load the config and add the client and region to our struct.

pub struct S3Client {
client: Client,
region: String,
}
impl S3Client {
pub async fn new() -> Self {
let config = aws_config::defaults(BehaviorVersion::latest())
.load()
.await;
<!-- page: 240 -->
# CHAPTER 9 Writing an infrastructure DSL
rust
S3Client {
client: Client::new(&config),
region: "eu-west-1".to_string(),
}

Probably because S3 buckets are a more global concept than Lambdas, which are region-specific like most things in AWS, we do not pass in the region during configuration. But when we create a bucket, we do have to give a location_constraint to make sure the resource is placed in the right region.

pub async fn create_bucket(&self, bucket: &Bucket)
-> Result<CreateBucketOutput, SdkError<CreateBucketError>> {
let constraint = BucketLocationConstraint::from(self.region.as_str());
let cfg = CreateBucketConfiguration::builder()
.location_constraint(constraint)
.build();
self.client.create_bucket()
.bucket(&bucket.name)
.create_bucket_configuration(cfg)
.send()
.await
}

Creates the bucket in our preferred region

An async send asks AWS to create the resource.

We have a bucket and a lambda, and the bucket is allowed to invoke the lambda. But we aren’t doing any eventing yet! Our final method makes sure to send events when an object is created ("s3:ObjectCreated:*").

pub async fn link_bucket_with_lambda(
&self,
bucket: &Bucket,
lambda_arn: &str) -> Result<
PutBucketNotificationConfigurationOutput,
SdkError<PutBucketNotificationConfigurationError>
> {
self.client.put_bucket_notification_configuration()
.bucket(&bucket.name)
.notification_configuration(NotificationConfiguration::builder()
.lambda_function_configurations(
LambdaFunctionConfiguration::builder()
.lambda_function_arn(lambda_arn)
.events(
Event::from("s3:ObjectCreated:*")
)
)
)
.build()
}

Sends events to a Lambda with this ARN (a.k.a. unique identifier) …

…when an object is created in our bucket

9.7 Errors and declarative macros

229

.expect("to create valid lambda function config")
).build()
.send()
.await
}

In brief, our code communicates with AWS to set up the desired resources. When we want to send events, we have to do a lot of additional work, because AWS requires consent from both parties (bucket and lambda) before allowing that.

And that’s every—wait: I forgot about errors.rs. There’s that downside of putting errors in a separate file. On the upside, I can probably get away with only showing you part of the code, because it is all pretty similar. Our custom IacError is an enum with one variant for each kind of error that might occur: creating a bucket or lambda might fail, and setting up the event could go awry. IacError implements Error and has the required Display implementation. It also has a custom method for turning into a TokenStream, which is what we will have to output.

Since the four functions for calling AWS in s3 and lambda all throw their own error, we have four From trait implementations. Each implementation turns one of those AWS errors into our own, retrieving the message from the error.

#[derive(Debug)]
pub enum IacError {
BucketError(String),
LambdaError(String),
EventError(String),
}
impl IacError {
pub fn into_compile_error(self) -> TokenStream {
match self {
IacError::BucketError(message) => {
syn::Error::new(
Span::call_site(),
format!("bucket could not be created: {}", message)
).into_compile_error().into()
},
// similar fo the other two
}
}
}
impl From<SdkError<CreateBucketError>> for IacError {
fn from(value: SdkError<CreateBucketError>) -> Self {
let message = value.message()
.map(|v| v.to_string())
.unwrap_or_else(|| "no message".to_string());

Our IacError is a combination of the three kinds of things that can go wrong.

This custom method returns a sensible syn::Error for every variant.

We implement From for the various errors thrown by AWS. When there’s a useful message in the original error, we keep it.

IacError::BucketError(message) }

// similar for our three other errors // plus simple error and display implementations

It seems like a waste to write boilerplate code in a book that talks so much about macros as a tool for avoiding boilerplate. And nothing is stopping us from using additional declarative or procedural macros within a macro—though the latter would require setting up another project. In this case, a declarative macro will do just fine. We only need to pass in two things: the variant for our error enum (expr will do, though path is also a good candidate) and the type of the AWS error (ty, as you may recall from way back).

NOTE I wrote this code and chapter while the Rust SDK was still in developer preview. In version 0.24, you could match on the error and always get back the same global types (ServiceError, for example). Now that the SDK is generally available, matching on an error returns very specific errors (like BucketAlreadyExists). More specific errors are great, but they are not good for the type of deduplication we are doing. In order to still show this example of combining procedural and declarative macros, I have gone for simply extracting the error message. This is not the best choice per se, but it works for this example.

Listing 9.25 A declarative macro for the From implementations

Section titled “Listing 9.25 A declarative macro for the From implementations”
macro_rules! generate_from_error {
($mine:expr, $aws:ty) => {
impl From<SdkError<$aws>> for IacError {
fn from(value: SdkError<$aws>) -> Self {
// get the message, same as before
$mine(message)
}
}
}
}
generate_from_error!(IacError::BucketError, CreateBucketError);
generate_from_error!(IacError::LambdaError, CreateFunctionError);
generate_from_error!(
IacError::EventError,
PutBucketNotificationConfigurationError
);
generate_from_error!(IacError::EventError, AddPermissionError);

If you want, you can now run the code, which should produce either an error (when you don’t have credentials, or a bucket or lambda with the given name already exists, etc.) or the resources you requested. That means you have succeeded in (ab)using Rust macros to create actual cloud infrastructure. Congratulations!

<!-- page: 243 -->
# 9.9 From the real world
**NOTE** The `thiserror` (https://docs.rs/thiserror/latest/thiserror/) crate is another nice way of reducing error boilerplate when you don’t want to write your own errors. It’s a derive macro, and by now you would probably understand most of its code.
In its current form, our macro is not very useful yet. But it offers a lot of possibilities. For example, instead of just creating a bucket, we could save its details in a struct and add methods to store things in S3. And since we’d be creating the bucket via our macro, we gain safety: at run time, a bucket with the given name *has* to be available for storing stuff or we would have seen the application fail at compile time.
## 9.8 The right kind of testing
When we discussed or used tests earlier in this book, we focused on unit tests. At the time, those were the right tools for the job: fast, simple, and easy to maintain. And why would we ever need more when we are just generating or transforming functions, structs, or enums?
The DSL presented in this chapter is different, though. In its current form, it is not producing any useful output. And even if it did produce something, as suggested in the previous section, would this prove that we’ve done what we promised to do (i.e., create resources in the cloud)? Clearly not. To verify a macro like this, we need a more complex kind of testing. End-to-end testing is one option. We could set up a project that tests our macro—and we have quite some experience with that—and use the AWS SDK to verify that the resources are created. Preferably, there would also be a cleanup step afterward. I like to test things using a combination of my continuous integration/continuous delivery pipeline and AWS Lambda. The latter provides a realistic testing environment for my code, as it is not inconceivable that my macro will be used in a lambda at some point. Plus, lambdas are also cheap and easy to spin up. Sadly, this chapter is already long enough, so implementing this type of testing in your preferred CI/CD tool is left to you.
## 9.9 From the real world
We have already come across several crates that present a DSL for easier creation of things. Let’s recap a bit: SQLx lets us write SQL queries; with Yew we write HTML; and with Leptos we mix Rust and HTML—all within a macro. Shuttle was also mentioned in several places as an example of IaC, which takes the concept one step further. You write your code, and Shuttle takes care of the infrastructure that you need, without you explicitly defining what that is.
Take the following, run `cargo shuttle deploy`, and you have an active endpoint that returns “Hello, World”:
rust
async fn hello_world() -> &'static str {
"Hello, world!"
}
#[shuttle_runtime::main]
<!-- page: 244 -->
# CHAPTER 9 Writing an infrastructure DSL
rust
async fn axum() -> shuttle_axum::ShuttleAxum {
let router = Router::new().route("/hello", get(hello_world));
Ok(router.into())
}

Another brief note: many projects combine the powers of declarative and procedural macros like we did here. Shuttle uses them as you would expect (i.e., to avoid duplication):

macro_rules! aws_engine {
($feature:expr, $pool_path:path, $option_path:path, $struct_ident:ident) => {
paste! {
#[cfg(feature = $feature)]
pub struct $struct_ident{
local_uri: Option<String>,
}
// struct implementations
}
};
}

And yes, paste! is a macro invocation in a declarative macro in a crate with procedural macros. But the other way around exists as well. Rocket has more than one declarative macro that generates procedural macros (and yes, that’s a plural; we’ll briefly come back to having multiple macros in one project in the next chapter):

macro_rules! route_attribute {
($name:ident => $method:expr) => {
// ...
#[proc_macro_attribute]
pub fn $name(args: TokenStream, input: TokenStream) -> TokenStream
{
emit!(attribute::route::route_attribute($method, args, input))
}
}
}

Generates an attribute macro

SQLx’s famous query macro is also a declarative macro that generates a procedural macro. Note that the entry point of that procedural macro is (accidentally) quite similar to ours, in that it does only three things:

  • Delegates parsing to a struct
  • Makes another function handle the result of that parsing
  • Returns the result or error to the user:
#[macro_export]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
macro_rules! query {
// ...
($query:expr) => ({
<!-- page: 245 -->
9.9 From the real world
233
rust
$crate::sqlx_macros::expand_query!(source = $query)
});
);

// other file //

#[proc_macro]
pub fn expand_query(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(
input as query::QueryMacroInput
);
match query::expand_input(input, FOSS_DRIVERS) {
Ok(ts) => ts.into(),
Err(e) => {
if let Some(parse_err) = e.downcast_ref::<syn::Error>() {
parse_err.to_compile_error().into()
} else {
let msg = e.to_string();
quote!(::std::compile_error!(#msg)).into()
}
}
}
}

Generates a function-like macro

A final note for this section: in this chapter, our macros also used quite a few println statements to give information to users, either to show what was parsed or to tell the user that a resource is being created. How do real Rust (macro) crates handle logging? Leptos has its own macro for its logging. As the comment states, behind the scenes, plain old println is used when you’re not in the browser:

/// Uses `println!()`-style formatting to log something to the console
/// (in the browser)
/// or via `println!()` (if not in the browser).
#[macro_export]
macro_rules! log {
($($t:tt)*) => ($crate::console_log(&format_args!($($t)*).to_string()))
}

Plus similar macros for warn and error

Rocket has macros to help with logging, though this one does not use print behind the scenes (as stated in the comment for write_out):

macro_rules! define_log_macro {
($name:ident: $kind:ident, $target:expr, $d:tt) => (
#[doc(hidden)]
#[macro_export]
macro_rules! $name {
($d ($t:tt)*) => (
$crate::log::private::$kind!(target: $target, $d ($t)*)
)
}
);
// more implementation
}

And similar for warn, info, etc.

define_log_macro!(error, error_);
<!-- page: 246 -->
// `print!` panics when stdout isn't available, but this macro doesn't.
#[cfg(not(any(debug_assertions, test, doctest)))]
macro_rules! write_out {
($($arg:tt)*) => ({
use std::io::{Write, stdout, stderr};
let _ = write!(stdout(), $($arg)*)
.or_else(|e| write!(stderr(), "{}", e));
})
}
And some projects just use good, old println and eprintln statements.
# Exercises
See the appendix for solutions.
1. Try to improve the input modeling. As discussed, it should be easier for users of IacInput to know that we have a bucket event. Optionally, you can also rework the creation of infrastructure using the new IacInput.
2. Suggest the right resource (or property) when you cannot find a match. For example, when you type "buck," the error should suggest "bucket." One option is to use Levenshtein distance.
3. Currently, our code fails when the resources we add already exist. Skip creation when you detect that it is unnecessary.
4. Make it possible to add another kind of resource (from AWS or maybe from another cloud provider!) to the iac! macro. (Note: No solution is provided for this exercise.)
# Summary
- With Infrastructure as Code (IaC), we describe the entire infrastructure of our application as text or code, which means the state of our infrastructure is documented, version controlled, and easy to create, destroy, or update.
- We can use a function-like macro to create our own IaC syntax, letting the macro create what we describe behind the scenes.
- Within struct-based parsing, there are many variations for writing code to choose from.
- The ability to create custom keywords in syn is very useful when you are inventing a language within your macro.
- We can use asynchronous calls within a macro to do things like creating AWS infrastructure with the Rust SDK.
- We can mix and match declarative and procedural macros any way we like, combining their powers.