Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow string interpolation on resource options #597

Merged
merged 2 commits into from
Jan 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 42 additions & 32 deletions codegen/src/shuttle_main/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use proc_macro_error::emit_error;
use quote::{quote, ToTokens};
use syn::{
parenthesized, parse::Parse, parse2, parse_macro_input, parse_quote, punctuated::Punctuated,
spanned::Spanned, token::Paren, Attribute, Expr, FnArg, Ident, ItemFn, Pat, PatIdent, Path,
ReturnType, Signature, Stmt, Token, Type,
spanned::Spanned, token::Paren, Attribute, Expr, ExprLit, FnArg, Ident, ItemFn, Lit, Pat,
PatIdent, Path, ReturnType, Signature, Stmt, Token, Type,
};

pub(crate) fn r#impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
Expand Down Expand Up @@ -97,16 +97,6 @@ impl Parse for BuilderOptions {
}
}

impl ToTokens for BuilderOptions {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let (methods, values): (Vec<_>, Vec<_>) =
self.options.iter().map(|o| (&o.ident, &o.value)).unzip();
let chain = quote!(#(.#methods(#values))*);

chain.to_tokens(tokens);
}
}

impl Parse for BuilderOption {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ident = input.parse()?;
Expand Down Expand Up @@ -203,10 +193,33 @@ impl ToTokens for Wrapper {
let mut fn_inputs_builder: Vec<_> = Vec::with_capacity(self.fn_inputs.len());
let mut fn_inputs_builder_options: Vec<_> = Vec::with_capacity(self.fn_inputs.len());

let mut needs_vars = false;

for input in self.fn_inputs.iter() {
fn_inputs.push(&input.ident);
fn_inputs_builder.push(&input.builder.path);
fn_inputs_builder_options.push(&input.builder.options);

let (methods, values): (Vec<_>, Vec<_>) = input
.builder
.options
.options
.iter()
.map(|o| {
let value = match &o.value {
Expr::Lit(ExprLit {
lit: Lit::Str(str), ..
}) => {
needs_vars = true;
quote!(&shuttle_service::strfmt(#str, &vars)?)
}
other => quote!(#other),
};

(&o.ident, value)
})
.unzip();
let chain = quote!(#(.#methods(#values))*);
fn_inputs_builder_options.push(chain);
}

let factory_ident: Ident = if self.fn_inputs.is_empty() {
Expand All @@ -223,6 +236,14 @@ impl ToTokens for Wrapper {
))
};

let vars: Option<Stmt> = if needs_vars {
Some(parse_quote!(
let vars = std::collections::HashMap::from_iter(factory.get_secrets().await?.into_iter().map(|(key, value)| (format!("secrets.{}", key), value)));
))
} else {
None
};

let wrapper = quote! {
async fn __shuttle_wrapper(
#factory_ident: &mut dyn shuttle_service::Factory,
Expand Down Expand Up @@ -259,6 +280,7 @@ impl ToTokens for Wrapper {
}
})?;

#vars
#(let #fn_inputs = #fn_inputs_builder::new()#fn_inputs_builder_options.build(#factory_ident, runtime).await.context(format!("failed to provision {}", stringify!(#fn_inputs_builder)))?;)*

runtime.spawn(async {
Expand Down Expand Up @@ -500,7 +522,8 @@ mod tests {
boolean = true,
integer = 5,
float = 2.65,
enum_variant = SomeEnum::Variant1
enum_variant = SomeEnum::Variant1,
sensitive = "user:{secrets.password}"
));

let mut expected: BuilderOptions = Default::default();
Expand All @@ -511,25 +534,11 @@ mod tests {
expected
.options
.push(parse_quote!(enum_variant = SomeEnum::Variant1));

assert_eq!(input, expected);
}

#[test]
fn tokenize_builder_options() {
let mut input: BuilderOptions = Default::default();
input.options.push(parse_quote!(string = "string_val"));
input.options.push(parse_quote!(boolean = true));
input.options.push(parse_quote!(integer = 5));
input.options.push(parse_quote!(float = 2.65));
input
expected
.options
.push(parse_quote!(enum_variant = SomeEnum::Variant1));

let actual = quote!(#input);
let expected = quote!(.string("string_val").boolean(true).integer(5).float(2.65).enum_variant(SomeEnum::Variant1));
.push(parse_quote!(sensitive = "user:{secrets.password}"));

assert_eq!(actual.to_string(), expected.to_string());
assert_eq!(input, expected);
}

#[test]
Expand Down Expand Up @@ -627,7 +636,8 @@ mod tests {
}
})?;

let pool = shuttle_shared_db::Postgres::new().size("10Gb").public(false).build(factory, runtime).await.context(format!("failed to provision {}", stringify!(shuttle_shared_db::Postgres)))?;
let vars = std::collections::HashMap::from_iter(factory.get_secrets().await?.into_iter().map(|(key, value)| (format!("secrets.{}", key), value)));
let pool = shuttle_shared_db::Postgres::new().size(&shuttle_service::strfmt("10Gb", &vars)?).public(false).build(factory, runtime).await.context(format!("failed to provision {}", stringify!(shuttle_shared_db::Postgres)))?;

runtime.spawn(async {
complex(pool)
Expand Down
1 change: 1 addition & 0 deletions service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ salvo = { version = "0.37.5", optional = true }
serde_json = { workspace = true }
serenity = { version = "0.11.5", default-features = false, features = ["client", "gateway", "rustls_backend", "model"], optional = true }
poise = { version = "0.5.2", optional = true }
strfmt = "0.2.2"
sync_wrapper = { version = "0.1.1", optional = true }
thiserror = { workspace = true }
thruster = { version = "1.3.0", optional = true }
Expand Down
2 changes: 2 additions & 0 deletions service/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub enum Error {
BuildPanic(String),
#[error("Panic occurred in `Service::bind`: {0}")]
BindPanic(String),
#[error("Failed to interpolate string. Is your Secrets.toml correct?")]
StringInterpolation(#[from] strfmt::FmtError),
#[error("Custom error: {0}")]
Custom(#[from] CustomError),
}
Expand Down
1 change: 1 addition & 0 deletions service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ pub use async_trait::async_trait;

// Pub uses by `codegen`
pub use anyhow::Context;
pub use strfmt::strfmt;
pub use tokio::runtime::Runtime;
pub use tracing;
pub use tracing_subscriber;
Expand Down