use anyhow::{Context, Result};
use tera::Tera;
use crate::models::{
Framework, GeneratedFile, GenerationConfig, InfraKind, InfraService, ProjectAnalysis,
};
pub fn generate_docker_compose(
analysis: &ProjectAnalysis,
config: &GenerationConfig,
tera: &Tera,
) -> Result<Option<GeneratedFile>> {
if !config.emit_compose {
return Ok(None);
}
if analysis.services.is_empty() && analysis.detected_infrastructures.is_empty() {
anyhow::bail!("no services to generate docker-compose.yml for");
}
let is_single_service = !analysis.is_monorepo || analysis.services.len() == 1;
let force_single = config.force_single && analysis.services.len() > 1;
let (mut infra_entries, volume_names) = build_infra_entries(analysis, config);
infra_entries.sort_by(|a, b| {
let na = a.get("name").and_then(|v| v.as_str()).unwrap_or("");
let nb = b.get("name").and_then(|v| v.as_str()).unwrap_or("");
na.cmp(nb)
});
let included_infra_refs = resolve_compose_infra(analysis, config);
let mut svc_entries = Vec::new();
for (idx, service) in analysis.services.iter().enumerate() {
let slug = slugify(&service.name);
let relative_path = service
.path
.strip_prefix(&analysis.root_path)
.map(|p| {
let s = p.to_string_lossy().to_string();
if s.is_empty() {
".".into()
} else {
s.replace('\\', "/")
}
})
.unwrap_or_else(|_| ".".into());
let dockerfile_path = if is_single_service {
"Dockerfile".into()
} else if force_single {
format!("Dockerfile.{}", service.name)
} else {
"Dockerfile".into()
};
let port = custom_port_for_service(&service.name, config)
.or_else(|| config.port_overrides.get(idx).copied())
.or_else(|| service.exposed_ports.first().copied())
.unwrap_or(8080);
let env: Vec<serde_json::Value> = service
.env_vars
.iter()
.map(|(k, v)| serde_json::json!({"key": k, "value": v}))
.collect();
let depends_on = build_depends_on(service, &included_infra_refs, &analysis.root_env_vars);
let command = if let Some(ref answers) = config.interactive_answers {
let run_prisma = answers.run_prisma_migrations.unwrap_or(false);
if run_prisma
&& service
.build_command
.as_deref()
.is_some_and(|c| c.contains("prisma"))
{
Some(format!(
"npx prisma migrate deploy && {}",
service.start_command.as_deref().unwrap_or("npm start")
))
} else {
None
}
} else {
None
};
let mut entry = serde_json::json!({
"name": slug,
"relative_path": relative_path,
"dockerfile_path": dockerfile_path,
"ports": vec![port],
"environment": env,
});
if !depends_on.is_empty() {
entry["depends_on"] = serde_json::json!(depends_on);
}
if let Some(cmd) = command {
entry["command"] = serde_json::json!(cmd);
}
svc_entries.push(entry);
}
let worker_entries = build_worker_entries(analysis, config);
let mut ctx = tera::Context::new();
ctx.insert("services", &svc_entries);
if !worker_entries.is_empty() {
ctx.insert("worker_services", &worker_entries);
}
if !infra_entries.is_empty() {
ctx.insert("infra_services", &infra_entries);
}
if !volume_names.is_empty() {
ctx.insert("volumes", &volume_names);
}
let content = tera
.render("compose/docker-compose.yml.tera", &ctx)
.context("failed to render docker-compose.yml")?;
Ok(Some(GeneratedFile {
relative_path: "docker-compose.yml".into(),
content,
description: "Docker Compose configuration".into(),
}))
}
fn build_infra_entries(
analysis: &ProjectAnalysis,
config: &GenerationConfig,
) -> (Vec<serde_json::Value>, Vec<String>) {
let included = resolve_compose_infra(analysis, config);
let mut entries = Vec::new();
let mut volumes: Vec<String> = Vec::new();
for infra in &included {
let port = config
.interactive_answers
.as_ref()
.and_then(|a| a.custom_service_ports.get(&infra.name))
.copied()
.unwrap_or(infra.port);
let ports = if port > 0 { vec![port] } else { vec![] };
let env: Vec<serde_json::Value> = infra
.env_vars
.iter()
.map(|(k, v)| serde_json::json!({"key": k, "value": v}))
.collect();
let vol_name = format!("{}data", infra.name);
let vol_mount = format!("{vol_name}:{}", infra_volume_mount_path(infra.kind));
let persists = infra_persists_data(infra.kind);
let vol_array = if persists { vec![vol_mount] } else { vec![] };
let mut entry = serde_json::json!({
"name": infra.name,
"image": infra.image,
"ports": ports,
"environment": env,
"volumes": vol_array,
});
if let Some(cmd) = infra_healthcheck_command(infra.kind) {
entry["healthcheck"] = serde_json::json!({
"test": ["CMD-SHELL", cmd],
"interval": "10s",
"timeout": "5s",
"retries": 5,
});
}
entries.push(entry);
if persists {
volumes.push(vol_name);
}
}
volumes.sort();
volumes.dedup();
(entries, volumes)
}
fn resolve_compose_infra<'a>(
analysis: &'a ProjectAnalysis,
config: &GenerationConfig,
) -> Vec<&'a InfraService> {
if let Some(ref answers) = config.interactive_answers {
analysis
.detected_infrastructures
.iter()
.filter(|i| answers.include_infra_in_compose.contains(&i.kind))
.collect()
} else {
analysis
.detected_infrastructures
.iter()
.filter(|i| i.is_attached_to_compose)
.collect()
}
}
fn custom_port_for_service(service_name: &str, config: &GenerationConfig) -> Option<u16> {
config
.interactive_answers
.as_ref()
.and_then(|a| a.custom_service_ports.get(service_name))
.copied()
}
fn build_depends_on(
service: &crate::models::Service,
infra: &[&InfraService],
root_env_vars: &std::collections::BTreeMap<String, String>,
) -> Vec<serde_json::Value> {
let mut deps: Vec<serde_json::Value> = Vec::new();
for detected in infra {
if service_uses_infra(service, detected.kind, root_env_vars) {
deps.push(serde_json::json!({
"service_name": detected.name,
"condition": "service_healthy",
}));
}
}
deps.sort_by(|a, b| {
let na = a["service_name"].as_str().unwrap_or("");
let nb = b["service_name"].as_str().unwrap_or("");
na.cmp(nb)
});
deps.dedup_by(|a, b| a["service_name"] == b["service_name"]);
deps
}
fn service_uses_infra(
service: &crate::models::Service,
kind: InfraKind,
root_env_vars: &std::collections::BTreeMap<String, String>,
) -> bool {
if has_driver_dependency(service, kind) {
return true;
}
let env_key_match = |k: &str| {
let upper = k.to_ascii_uppercase();
matches!(
(kind, upper.as_str()),
(
InfraKind::Postgres,
"DATABASE_URL" | "POSTGRES_URL" | "POSTGRES_HOST" | "PGHOST"
) | (
InfraKind::Mysql,
"DATABASE_URL" | "MYSQL_URL" | "MYSQL_HOST"
) | (
InfraKind::Redis,
"REDIS_URL" | "REDIS_HOST" | "UPSTASH_REDIS_REST_URL"
) | (
InfraKind::Mongo,
"MONGODB_URI" | "MONGO_URL" | "MONGO_URI" | "MONGO_HOST"
) | (
InfraKind::RabbitMq,
"AMQP_URL" | "AMQP_HOST" | "RABBITMQ_URL" | "RABBITMQ_HOST"
) | (
InfraKind::Kafka,
"KAFKA_BROKERS" | "KAFKA_BOOTSTRAP_SERVERS" | "KAFKA_HOST"
)
)
};
let service_env_match = service.env_vars.iter().any(|(k, _)| env_key_match(k));
if service_env_match {
return true;
}
let root_env_match = root_env_vars.keys().any(|k| env_key_match(k));
if root_env_match {
return true;
}
let cmd_text = service
.build_command
.iter()
.chain(service.start_command.iter())
.map(|s| s.as_str())
.collect::<Vec<_>>()
.join(" ");
let pkg_text = service.package_name.as_deref().unwrap_or("");
let has_prisma = cmd_text.contains("prisma")
|| pkg_text.contains("prisma")
|| pkg_text.contains("@prisma/client");
if has_prisma {
if let Some(url) = root_env_vars.get("DATABASE_URL") {
let lower = url.to_ascii_lowercase();
return match kind {
InfraKind::Postgres => {
lower.starts_with("postgres://") || lower.starts_with("postgresql://")
}
InfraKind::Mysql => {
lower.starts_with("mysql://")
|| lower.starts_with("mysql2://")
|| lower.starts_with("mariadb://")
}
InfraKind::Mongo => {
lower.starts_with("mongodb://") || lower.starts_with("mongodb+srv://")
}
_ => false,
};
}
}
false
}
fn has_driver_dependency(service: &crate::models::Service, kind: InfraKind) -> bool {
let deps: Vec<&str> = service.dependencies.iter().map(|s| s.as_str()).collect();
match kind {
InfraKind::Postgres => deps.iter().any(|d| {
matches!(
*d,
"pg" | "postgres"
| "psycopg2"
| "psycopg2-binary"
| "psycopg"
| "asyncpg"
| "pgx"
| "pq"
| "tokio-postgres"
| "diesel"
| "sqlx"
| "pdo_pgsql"
| "github.com/jackc/pgx"
| "github.com/jackc/pgx/v5"
)
}),
InfraKind::Mysql => deps.iter().any(|d| {
matches!(
*d,
"mysql"
| "mysql2"
| "pymysql"
| "mysqlclient"
| "go-sql-driver/mysql"
| "pdo_mysql"
)
}),
InfraKind::Redis => deps.iter().any(|d| {
matches!(
*d,
"redis"
| "ioredis"
| "redis-py"
| "aioredis"
| "go-redis"
| "redigo"
| "predis"
| "redis-rs"
| "deadpool-redis"
| "bull"
| "bullmq"
)
}),
InfraKind::Mongo => deps.iter().any(|d| {
matches!(
*d,
"mongodb" | "mongoose" | "pymongo" | "motor" | "mongoengine" | "mongo-go-driver"
)
}),
InfraKind::RabbitMq => deps.iter().any(|d| {
matches!(
*d,
"amqplib" | "pika" | "aio-pika" | "amqp091-go" | "lapin" | "amqp" | "celery"
)
}),
InfraKind::Kafka => deps.iter().any(|d| {
matches!(
*d,
"kafkajs"
| "kafka-node"
| "confluent-kafka"
| "aiokafka"
| "kafka-python"
| "sarama"
| "rdkafka"
)
}),
InfraKind::Sqlite => false,
}
}
fn is_laravel_service(service: &crate::models::Service) -> bool {
service.language == crate::models::Language::Php && service.framework == Framework::Laravel
}
fn build_worker_entries(
analysis: &ProjectAnalysis,
config: &GenerationConfig,
) -> Vec<serde_json::Value> {
let create_worker = config
.interactive_answers
.as_ref()
.and_then(|a| a.create_queue_worker)
.unwrap_or(false);
let create_scheduler = config
.interactive_answers
.as_ref()
.and_then(|a| a.create_scheduler)
.unwrap_or(false);
if !create_worker && !create_scheduler {
return Vec::new();
}
let is_single_service = !analysis.is_monorepo || analysis.services.len() == 1;
analysis
.services
.iter()
.filter(|svc| is_laravel_service(svc))
.flat_map(|svc| {
let slug = slugify(&svc.name);
let relative_path = svc
.path
.strip_prefix(&analysis.root_path)
.map(|p| {
let s = p.to_string_lossy().to_string();
if s.is_empty() {
".".into()
} else {
s.replace('\\', "/")
}
})
.unwrap_or_else(|_| ".".into());
let dockerfile_path = if is_single_service {
"Dockerfile".into()
} else if config.force_single {
format!("Dockerfile.{}", svc.name)
} else {
"Dockerfile".into()
};
let mut entries = Vec::new();
if create_worker {
let worker_slug = format!("{slug}-worker");
entries.push(serde_json::json!({
"name": worker_slug,
"relative_path": relative_path,
"dockerfile_path": dockerfile_path,
"ports": [],
"environment": [],
"command": "php artisan queue:work",
"depends_on": [{"service_name": slug, "condition": "service_started"}],
}));
}
if create_scheduler {
let scheduler_slug = format!("{slug}-scheduler");
entries.push(serde_json::json!({
"name": scheduler_slug,
"relative_path": relative_path,
"dockerfile_path": dockerfile_path,
"ports": [],
"environment": [],
"command": "php artisan schedule:work",
"depends_on": [{"service_name": slug, "condition": "service_started"}],
}));
}
entries
})
.collect()
}
fn infra_persists_data(kind: InfraKind) -> bool {
matches!(
kind,
InfraKind::Postgres
| InfraKind::Mysql
| InfraKind::Redis
| InfraKind::Mongo
| InfraKind::Kafka
| InfraKind::RabbitMq
)
}
fn infra_volume_mount_path(kind: InfraKind) -> &'static str {
match kind {
InfraKind::Postgres => "/var/lib/postgresql/data",
InfraKind::Mysql => "/var/lib/mysql",
InfraKind::Redis => "/data",
InfraKind::Mongo => "/data/db",
InfraKind::Kafka => "/var/lib/kafka/data",
InfraKind::RabbitMq => "/var/lib/rabbitmq",
InfraKind::Sqlite => "/data",
}
}
fn infra_healthcheck_command(kind: InfraKind) -> Option<&'static str> {
match kind {
InfraKind::Postgres => Some("pg_isready -U $POSTGRES_USER -d $POSTGRES_DB"),
InfraKind::Mysql => Some("mysqladmin ping -h localhost -u root -p$MYSQL_ROOT_PASSWORD"),
InfraKind::Redis => Some("redis-cli ping"),
InfraKind::Mongo => Some("mongosh --eval 'db.runCommand({ping:1})' --quiet"),
InfraKind::RabbitMq => Some("rabbitmq-diagnostics -q ping"),
InfraKind::Kafka => Some("kafka-cluster check"),
InfraKind::Sqlite => None,
}
}
fn slugify(name: &str) -> String {
name.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect::<String>()
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::*;
use crate::templates::create_tera_engine;
use std::collections::BTreeMap;
use std::path::PathBuf;
fn make_service(name: &str, lang: Language, fw: Framework) -> Service {
Service {
name: name.into(),
path: PathBuf::from(format!("/project/{name}")),
package_name: None,
language: lang,
framework: fw,
package_manager: PackageManager::Unknown,
runtime_version: None,
entrypoint: None,
exposed_ports: vec![8080],
env_vars: vec![("RUST_LOG".into(), "info".into())],
service_type: ServiceType::Api,
build_command: None,
start_command: None,
is_monorepo: true,
dependencies: vec![],
}
}
fn make_analysis(services: Vec<Service>, infra: Vec<InfraService>) -> ProjectAnalysis {
ProjectAnalysis {
root_path: PathBuf::from("/project"),
is_monorepo: true,
workspace_tool: Some("turborepo".into()),
services,
detected_infrastructures: infra,
warnings: vec![],
root_env_vars: BTreeMap::new(),
}
}
fn tera_engine() -> Tera {
create_tera_engine().expect("tera engine init failed")
}
fn default_config() -> GenerationConfig {
GenerationConfig {
base_image_override: None,
port_overrides: vec![],
force_single: false,
dry_run: false,
emit_compose: false,
output_dir: None,
interactive: false,
assume_yes: false,
interactive_answers: None,
}
}
fn make_infra(kind: InfraKind, name: &str) -> InfraService {
InfraService {
kind,
name: name.into(),
image: kind.default_image().into(),
port: kind.default_port(),
env_vars: kind
.default_env()
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
is_attached_to_compose: kind != InfraKind::Sqlite,
source: InfraSource::EnvVar("DETECTED".into()),
}
}
#[test]
fn compose_not_generated_when_disabled() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let analysis = make_analysis(svcs, vec![]);
let config = GenerationConfig {
emit_compose: false,
..default_config()
};
let tera = tera_engine();
let result = generate_docker_compose(&analysis, &config, &tera).unwrap();
assert!(result.is_none());
}
#[test]
fn compose_generated_when_enabled() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let analysis = make_analysis(svcs, vec![]);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let result = generate_docker_compose(&analysis, &config, &tera).unwrap();
let file = result.expect("expected Some");
assert_eq!(file.relative_path, PathBuf::from("docker-compose.yml"));
assert!(file.content.contains("api:"));
assert!(file.content.contains("8080:8080"));
assert!(file.content.contains("restart: unless-stopped"));
}
#[test]
fn compose_multi_service() {
let svcs = vec![
make_service("frontend", Language::NodeJs, Framework::NextJs),
make_service("backend", Language::Go, Framework::Gin),
];
let analysis = make_analysis(svcs, vec![]);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("frontend:"));
assert!(file.content.contains("backend:"));
}
#[test]
fn compose_port_overrides() {
let svcs = vec![
make_service("a", Language::NodeJs, Framework::NodeGeneric),
make_service("b", Language::Go, Framework::GoGeneric),
];
let analysis = make_analysis(svcs, vec![]);
let config = GenerationConfig {
emit_compose: true,
port_overrides: vec![4000, 9090],
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("4000:4000"));
assert!(file.content.contains("9090:9090"));
}
#[test]
fn slugify_conversions() {
assert_eq!(slugify("my-app"), "my-app");
assert_eq!(slugify("My_App.Service"), "my-app-service");
assert_eq!(slugify("UPPER"), "upper");
assert_eq!(slugify("--dashes--"), "dashes");
assert_eq!(slugify("simple"), "simple");
}
#[test]
fn empty_services_is_error() {
let analysis = make_analysis(vec![], vec![]);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
assert!(generate_docker_compose(&analysis, &config, &tera).is_err());
}
#[test]
fn compose_with_infra_services() {
let svcs = vec![make_service("api", Language::NodeJs, Framework::Express)];
let infra = vec![make_infra(InfraKind::Postgres, "postgres")];
let analysis = make_analysis(svcs, infra);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("api:"));
assert!(file.content.contains("postgres:"));
assert!(file.content.contains("postgres:16-alpine"));
assert!(file.content.contains("5432:5432"));
assert!(file.content.contains("POSTGRES_USER=app"));
assert!(file.content.contains("volumes:"));
}
#[test]
fn compose_infra_sorted_by_kind() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let infra = vec![
make_infra(InfraKind::Redis, "redis"),
make_infra(InfraKind::Postgres, "postgres"),
];
let analysis = make_analysis(svcs, infra);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
let api_pos = file.content.find("api:").unwrap();
let pg_pos = file.content.find("postgres:").unwrap();
let redis_pos = file.content.find("redis:").unwrap();
assert!(api_pos < pg_pos);
assert!(pg_pos < redis_pos);
}
#[test]
fn compose_infra_with_interactive_answers() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let infra = vec![
make_infra(InfraKind::Postgres, "postgres"),
make_infra(InfraKind::Redis, "redis"),
];
let analysis = make_analysis(svcs, infra);
let mut config = GenerationConfig {
emit_compose: true,
..default_config()
};
config.interactive_answers = Some(InteractiveAnswers {
include_infra_in_compose: vec![InfraKind::Postgres],
..Default::default()
});
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("postgres:"));
assert!(!file.content.contains("redis:"));
}
#[test]
fn compose_infra_custom_port_from_answers() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let infra = vec![make_infra(InfraKind::Postgres, "postgres")];
let analysis = make_analysis(svcs, infra);
let mut custom_ports = BTreeMap::new();
custom_ports.insert("postgres".into(), 5433);
let mut config = GenerationConfig {
emit_compose: true,
..default_config()
};
config.interactive_answers = Some(InteractiveAnswers {
include_infra_in_compose: vec![InfraKind::Postgres],
custom_service_ports: custom_ports,
..Default::default()
});
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("5433:5433"));
}
#[test]
fn compose_infra_volumes_block() {
let svcs = vec![make_service("api", Language::NodeJs, Framework::Express)];
let infra = vec![
make_infra(InfraKind::Postgres, "postgres"),
make_infra(InfraKind::Redis, "redis"),
];
let analysis = make_analysis(svcs, infra);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("volumes:"));
assert!(file.content.contains("postgresdata:"));
assert!(file.content.contains("redisdata:"));
}
#[test]
fn compose_rabbitmq_volume_persistence() {
let svcs = vec![make_service("api", Language::NodeJs, Framework::Express)];
let infra = vec![make_infra(InfraKind::RabbitMq, "rabbitmq")];
let analysis = make_analysis(svcs, infra);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(file.content.contains("rabbitmqdata:/var/lib/rabbitmq"));
assert!(file.content.contains("rabbitmqdata:"));
}
#[test]
fn compose_no_infra_services_block() {
let svcs = vec![make_service("api", Language::Go, Framework::Gin)];
let analysis = make_analysis(svcs, vec![]);
let config = GenerationConfig {
emit_compose: true,
..default_config()
};
let tera = tera_engine();
let file = generate_docker_compose(&analysis, &config, &tera)
.unwrap()
.unwrap();
assert!(!file.content.contains("Infrastructure Services"));
}
#[test]
fn custom_port_for_service_helper() {
let mut answers = InteractiveAnswers::default();
answers.custom_service_ports.insert("api".into(), 4000);
let config = GenerationConfig {
interactive_answers: Some(answers),
..default_config()
};
assert_eq!(custom_port_for_service("api", &config), Some(4000));
assert_eq!(custom_port_for_service("web", &config), None);
}
#[test]
fn custom_port_for_service_no_answers() {
let config = default_config();
assert_eq!(custom_port_for_service("api", &config), None);
}
#[test]
fn service_uses_infra_pg_dependency() {
let svc = Service {
dependencies: vec!["pg".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Redis,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_ioredis_dependency() {
let svc = Service {
dependencies: vec!["ioredis".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Redis, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_mongoose_dependency() {
let svc = Service {
dependencies: vec!["mongoose".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Mongo, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_mysql2_dependency() {
let svc = Service {
dependencies: vec!["mysql2".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Mysql, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mongo,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_amqplib_dependency() {
let svc = Service {
dependencies: vec!["amqplib".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(
&svc,
InfraKind::RabbitMq,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Kafka,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_kafkajs_dependency() {
let svc = Service {
dependencies: vec!["kafkajs".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Kafka, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::RabbitMq,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_rust_pgx() {
let svc = Service {
dependencies: vec!["axum".into(), "tokio".into(), "pgx".into()],
..make_service("api", Language::Rust, Framework::Axum)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_python_asyncpg() {
let svc = Service {
dependencies: vec!["fastapi".into(), "asyncpg".into()],
..make_service("api", Language::Python, Framework::FastApi)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_go_pgx() {
let svc = Service {
dependencies: vec![
"github.com/gin-gonic/gin".into(),
"github.com/jackc/pgx/v5".into(),
],
..make_service("api", Language::Go, Framework::Gin)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_bull_dependency() {
let svc = Service {
dependencies: vec!["bull".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Redis, &BTreeMap::new()));
}
#[test]
fn service_uses_infra_celery_dependency() {
let svc = Service {
dependencies: vec!["celery".into()],
..make_service("api", Language::Python, Framework::PythonGeneric)
};
assert!(service_uses_infra(
&svc,
InfraKind::RabbitMq,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_prisma_package_name_no_false_positive() {
let svc = Service {
package_name: Some("prisma-app".into()),
dependencies: vec!["prisma".into(), "@prisma/client".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(
!service_uses_infra(&svc, InfraKind::Postgres, &BTreeMap::new()),
"prisma package_name should not trigger Postgres"
);
assert!(
!service_uses_infra(&svc, InfraKind::Mysql, &BTreeMap::new()),
"prisma package_name should not trigger MySQL"
);
assert!(
!service_uses_infra(&svc, InfraKind::Mongo, &BTreeMap::new()),
"prisma package_name should not trigger Mongo"
);
}
#[test]
fn service_uses_infra_prisma_with_pg_dep_correctly_detects_postgres() {
let svc = Service {
package_name: Some("prisma-app".into()),
dependencies: vec!["prisma".into(), "@prisma/client".into(), "pg".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mongo,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_prisma_with_mysql_dep_correctly_detects_mysql() {
let svc = Service {
package_name: Some("prisma-app".into()),
dependencies: vec!["prisma".into(), "@prisma/client".into(), "mysql2".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Mysql, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mongo,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_env_var_database_url_postgres() {
let svc = Service {
env_vars: vec![("DATABASE_URL".into(), "postgres://localhost/db".into())],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_env_var_redis_url() {
let svc = Service {
env_vars: vec![("REDIS_URL".into(), "redis://localhost:6379".into())],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Redis, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_env_var_mongo_uri() {
let svc = Service {
env_vars: vec![("MONGODB_URI".into(), "mongodb://localhost:27017".into())],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Mongo, &BTreeMap::new()));
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_env_var_amqp_url() {
let svc = Service {
env_vars: vec![("AMQP_URL".into(), "amqp://guest:guest@localhost".into())],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(
&svc,
InfraKind::RabbitMq,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_env_var_kafka_brokers() {
let svc = Service {
env_vars: vec![("KAFKA_BROKERS".into(), "localhost:9092".into())],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(service_uses_infra(&svc, InfraKind::Kafka, &BTreeMap::new()));
}
#[test]
fn service_uses_infra_no_deps_no_env_returns_false() {
let svc = make_service("api", Language::NodeJs, Framework::Express);
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Redis,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mongo,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::RabbitMq,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Kafka,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Sqlite,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_sqlite_always_false() {
let svc = Service {
dependencies: vec!["rusqlite".into()],
..make_service("api", Language::Rust, Framework::RustGeneric)
};
assert!(!service_uses_infra(
&svc,
InfraKind::Sqlite,
&BTreeMap::new()
));
}
#[test]
fn service_uses_infra_express_dep_not_confused() {
let svc = Service {
dependencies: vec!["express".into(), "lodash".into()],
..make_service("api", Language::NodeJs, Framework::Express)
};
assert!(!service_uses_infra(
&svc,
InfraKind::Postgres,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Redis,
&BTreeMap::new()
));
assert!(!service_uses_infra(
&svc,
InfraKind::Mysql,
&BTreeMap::new()
));
}
}