Skip to content
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
311 changes: 302 additions & 9 deletions Cargo.lock

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion crates/cargo-lambda-build/src/zig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use miette::{IntoDiagnostic, Result};
pub fn print_install_options(options: &[InstallOption]) {
println!("Zig is not installed in your system.");
if is_stdin_tty() {
println!("Run `cargo lambda system --setup` to install Zig.")
println!("Run `cargo lambda system --install-zig` to install Zig.")
}

if !options.is_empty() {
Expand Down Expand Up @@ -51,6 +51,7 @@ pub async fn check_installation() -> Result<()> {
install_zig(options).await
}

#[derive(Debug)]
pub enum InstallOption {
#[cfg(not(windows))]
Brew,
Expand All @@ -63,6 +64,15 @@ pub enum InstallOption {
Scoop,
}

impl serde::Serialize for InstallOption {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.usage())
}
}

impl std::fmt::Display for InstallOption {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down
19 changes: 18 additions & 1 deletion crates/cargo-lambda-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ impl LambdaSubcommand {
Self::Init(mut i) => i.run().await,
Self::Invoke(i) => i.run().await,
Self::New(mut n) => n.run().await,
Self::System(s) => s.run().await,
Self::System(s) => Self::run_system(s, global, context, admerge).await,
Self::Watch(w) => Self::run_watch(w, color, global, context, admerge).await,
}
}
Expand Down Expand Up @@ -206,6 +206,23 @@ impl LambdaSubcommand {

cargo_lambda_deploy::run(&deploy, &metadata).await
}

async fn run_system(
system: System,
global: Option<PathBuf>,
context: Option<String>,
admerge: bool,
) -> Result<()> {
let metadata = load_metadata(system.manifest_path())?;

let options = ConfigOptions {
global,
context,
admerge,
name: system.package(),
};
cargo_lambda_system::run(&system, &metadata, &options).await
}
}

fn print_version() -> Result<()> {
Expand Down
11 changes: 8 additions & 3 deletions crates/cargo-lambda-metadata/src/cargo/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ use std::{collections::HashMap, fmt::Debug, path::PathBuf};
use strum_macros::{Display, EnumString};

use crate::{
cargo::deserialize_vec_or_map,
env::EnvOptions,
error::MetadataError,
lambda::{Memory, MemoryValueParser, Timeout, Tracing},
};

use crate::cargo::deserialize_vec_or_map;

const DEFAULT_MANIFEST_PATH: &str = "Cargo.toml";
const DEFAULT_COMPATIBLE_RUNTIMES: &str = "provided.al2,provided.al2023";
const DEFAULT_RUNTIME: &str = "provided.al2023";
Expand Down Expand Up @@ -452,10 +453,14 @@ pub struct VpcConfig {

/// Allow outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets
#[arg(long)]
#[serde(default)]
#[serde(default, skip_serializing_if = "is_false")]
pub ipv6_allowed_for_dual_stack: bool,
}

fn is_false(b: &bool) -> bool {
!b
}

impl VpcConfig {
fn count_fields(&self) -> usize {
self.subnet_ids.is_some() as usize
Expand Down Expand Up @@ -512,7 +517,7 @@ mod tests {
use crate::{
cargo::load_metadata,
config::{ConfigOptions, load_config_without_cli_flags},
lambda::{Memory, Timeout},
lambda::Timeout,
tests::fixture_metadata,
};

Expand Down
99 changes: 95 additions & 4 deletions crates/cargo-lambda-metadata/src/cargo/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ pub struct WatchConfig {
#[derive(Clone, Debug, Default)]
pub struct FunctionRouter {
inner: Router<FunctionRoutes>,
pub(crate) raw: Vec<(String, FunctionRoutes)>,
pub(crate) raw: Vec<Route>,
}

impl FunctionRouter {
Expand All @@ -254,6 +254,14 @@ impl FunctionRouter {
}
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct Route {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
methods: Option<Vec<String>>,
function: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum FunctionRoutes {
Single(String),
Expand Down Expand Up @@ -284,27 +292,73 @@ impl<'de> Visitor<'de> for FunctionRouterVisitor {
{
let routes: HashMap<String, FunctionRoutes> =
Deserialize::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;

let mut inner = Router::new();
let mut raw = Vec::new();

let mut inverse = HashMap::new();

for (path, route) in &routes {
inner.insert(path, route.clone()).map_err(|e| {
serde::de::Error::custom(format!("Failed to insert route {path}: {e}"))
})?;

match route {
FunctionRoutes::Single(function) => {
raw.push(Route {
path: path.clone(),
methods: None,
function: function.clone(),
});
}
FunctionRoutes::Multiple(routes) => {
for (method, function) in routes {
inverse
.entry((path.clone(), function.clone()))
.and_modify(|route: &mut Route| {
let mut methods = route.methods.clone().unwrap_or_default();
methods.push(method.clone());
route.methods = Some(methods);
})
.or_insert_with(|| Route {
path: path.clone(),
methods: Some(vec![method.clone()]),
function: function.clone(),
});
}
}
}
}

for (_, route) in inverse {
raw.push(route);
}

let raw: Vec<(String, FunctionRoutes)> = routes.into_iter().collect();
Ok(FunctionRouter { inner, raw })
}

fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let raw: Vec<(String, FunctionRoutes)> =
let routes: Vec<Route> =
Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))?;

let mut inner = Router::new();
let mut raw = Vec::new();

let mut routes_by_path = HashMap::new();

for route in &routes {
routes_by_path
.entry(route.path.clone())
.and_modify(|routes| merge_routes(routes, route))
.or_insert_with(|| decode_route(route));

raw.push(route.clone());
}

for (path, route) in &raw {
for (path, route) in &routes_by_path {
inner.insert(path, route.clone()).map_err(|e| {
serde::de::Error::custom(format!("Failed to insert route {path}: {e}"))
})?;
Expand All @@ -314,6 +368,43 @@ impl<'de> Visitor<'de> for FunctionRouterVisitor {
}
}

fn merge_routes(routes: &mut FunctionRoutes, route: &Route) {
let methods = route.methods.clone().unwrap_or_default();
match routes {
FunctionRoutes::Single(function) if !methods.is_empty() => {
let mut tmp = HashMap::new();
for method in methods {
tmp.insert(method.clone(), function.clone());
}
*routes = FunctionRoutes::Multiple(tmp);
}
FunctionRoutes::Multiple(_) if methods.is_empty() => {
*routes = FunctionRoutes::Single(route.function.clone());
}
FunctionRoutes::Multiple(routes) => {
for method in methods {
routes.insert(method.clone(), route.function.clone());
}
}
FunctionRoutes::Single(_) => {
*routes = FunctionRoutes::Single(route.function.clone());
}
}
}

fn decode_route(route: &Route) -> FunctionRoutes {
match &route.methods {
Some(methods) => {
let mut routes = HashMap::new();
for method in methods {
routes.insert(method.clone(), route.function.clone());
}
FunctionRoutes::Multiple(routes)
}
None => FunctionRoutes::Single(route.function.clone()),
}
}

impl<'de> Deserialize<'de> for FunctionRouter {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down
87 changes: 59 additions & 28 deletions crates/cargo-lambda-metadata/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,41 @@ pub fn load_config_without_cli_flags(
}

fn figment_from_metadata(metadata: &CargoMetadata, options: &ConfigOptions) -> Result<Figment> {
let (bin_metadata, package_metadata, mut figment) = general_config_figment(metadata, options)?;

if let Some(bin_metadata) = bin_metadata {
let mut bin_serialized = Serialized::defaults(bin_metadata);
if let Some(context) = &options.context {
bin_serialized = bin_serialized.profile(context);
}

if options.admerge {
figment = figment.admerge(bin_serialized);
} else {
figment = figment.merge(bin_serialized);
}
}

if let Some(package_metadata) = package_metadata {
let mut package_serialized = Serialized::defaults(package_metadata);
if let Some(context) = &options.context {
package_serialized = package_serialized.profile(context);
}

if options.admerge {
figment = figment.admerge(package_serialized);
} else {
figment = figment.merge(package_serialized);
}
}

Ok(figment)
}

pub fn general_config_figment(
metadata: &CargoMetadata,
options: &ConfigOptions,
) -> Result<(Option<Config>, Option<Config>, Figment)> {
let (ws_metadata, bin_metadata) = workspace_metadata(metadata, options.name.as_deref())?;
let package_metadata = package_metadata(metadata, options.name.as_deref())?;

Expand All @@ -82,6 +117,7 @@ fn figment_from_metadata(metadata: &CargoMetadata, options: &ConfigOptions) -> R
.as_ref()
.map(Toml::file)
.unwrap_or_else(|| Toml::file("CargoLambda.toml"));

if options.context.is_some() {
config_file = config_file.nested()
}
Expand All @@ -95,8 +131,8 @@ fn figment_from_metadata(metadata: &CargoMetadata, options: &ConfigOptions) -> R
if let Some(context) = &options.context {
env_serialized = env_serialized.profile(context);
}
figment = figment.merge(env_serialized);

figment = figment.merge(env_serialized);
figment = if options.admerge {
figment.admerge(config_file)
} else {
Expand All @@ -107,39 +143,14 @@ fn figment_from_metadata(metadata: &CargoMetadata, options: &ConfigOptions) -> R
if let Some(context) = &options.context {
ws_serialized = ws_serialized.profile(context);
}

if options.admerge {
figment = figment.admerge(ws_serialized);
} else {
figment = figment.merge(ws_serialized);
}

if let Some(bin_metadata) = bin_metadata {
let mut bin_serialized = Serialized::defaults(bin_metadata);
if let Some(context) = &options.context {
bin_serialized = bin_serialized.profile(context);
}

if options.admerge {
figment = figment.admerge(bin_serialized);
} else {
figment = figment.merge(bin_serialized);
}
}

if let Some(package_metadata) = package_metadata {
let mut package_serialized = Serialized::defaults(package_metadata);
if let Some(context) = &options.context {
package_serialized = package_serialized.profile(context);
}

if options.admerge {
figment = figment.admerge(package_serialized);
} else {
figment = figment.merge(package_serialized);
}
}

Ok(figment)
Ok((bin_metadata, package_metadata, figment))
}

fn workspace_metadata(
Expand Down Expand Up @@ -215,6 +226,26 @@ fn get_config_from_packages(
Ok(None)
}

pub fn get_config_from_all_packages(metadata: &CargoMetadata) -> Result<HashMap<String, Config>> {
let kind_condition = |pkg: &Package, target: &Target| {
target.kind.iter().any(|kind| kind == "bin") && pkg.metadata.is_object()
};

let mut configs = HashMap::new();
for pkg in &metadata.packages {
for target in &pkg.targets {
if kind_condition(pkg, target) {
let meta: Metadata =
serde_json::from_value(pkg.metadata.clone()).into_diagnostic()?;

configs.insert(pkg.name.clone(), meta.lambda.package.into());
}
}
}

Ok(configs)
}

fn get_config_from_root(metadata: &CargoMetadata) -> Result<Option<Config>> {
let Some(root) = metadata.root_package() else {
return Ok(None);
Expand Down
Loading