use {
crate::{
cli::CommandResult,
client,
deploy::known_hosts,
ui::{fail_message, fail_symbol, succeed_message, succeed_symbol},
},
anyhow::{anyhow, Result},
base64::{engine::general_purpose::STANDARD as BASE64, Engine as _},
chrono::Utc,
smbcloud_auth::me::me,
smbcloud_model::project::{DeploymentPayload, DeploymentStatus},
smbcloud_network::environment::Environment,
smbcloud_networking_project::{
crud_project_deployment_create::create_deployment, crud_project_deployment_update::update,
},
smbcloud_utils::config::Config,
spinners::{Spinner, Spinners},
std::{
collections::HashMap,
io::Write,
process::{Command, Stdio},
},
tempfile::NamedTempFile,
};
fn prune_dangling_symlinks(root: &std::path::Path) -> std::io::Result<usize> {
let meta = std::fs::symlink_metadata(root)?;
if meta.file_type().is_symlink() {
if !root.try_exists()? {
std::fs::remove_file(root)?;
return Ok(1);
}
return Ok(0);
}
if !meta.is_dir() {
return Ok(0);
}
let mut removed = 0;
for entry in std::fs::read_dir(root)? {
let entry = entry?;
let file_type = entry.file_type()?;
let path = entry.path();
if file_type.is_symlink() {
if !path.try_exists()? {
std::fs::remove_file(&path)?;
removed += 1;
}
} else if file_type.is_dir() {
removed += prune_dangling_symlinks(&path)?;
}
}
Ok(removed)
}
const ECOSYSTEM_ENV_MERGE_JS: &str = r#"
var fs = require('fs');
var path = require('path');
var file = 'ecosystem.config.cjs';
var keysFile = '.smbcloud-env-keys.json';
var app = process.env.SMB_PM2_APP;
var vars = JSON.parse(Buffer.from(process.env.SMB_ENV_B64, 'base64').toString('utf8'));
function plain(v) {
if (typeof v === 'function' || typeof v === 'symbol') return false;
if (v && typeof v === 'object') return Object.keys(v).every(function (k) { return plain(v[k]); });
return true;
}
var cfg = require(path.resolve(file));
if (!plain(cfg)) {
console.error('smbCloud: ' + file + ' contains functions, so env vars cannot be merged into it safely. Edit it by hand or remove the functions.');
process.exit(1);
}
var apps = Array.isArray(cfg) ? cfg : (cfg.apps || []);
var entry = apps.filter(function (a) { return a.name === app; })[0];
if (!entry) {
console.error('smbCloud: no app named ' + app + ' in ' + file + '.');
process.exit(1);
}
entry.env_production = entry.env_production || {};
var previous = [];
try { previous = JSON.parse(fs.readFileSync(keysFile, 'utf8')); } catch (e) {}
previous.forEach(function (k) { if (!Object.prototype.hasOwnProperty.call(vars, k)) delete entry.env_production[k]; });
Object.keys(vars).forEach(function (k) { entry.env_production[k] = vars[k]; });
if (!fs.existsSync(file + '.smbcloud.bak')) fs.copyFileSync(file, file + '.smbcloud.bak');
fs.writeFileSync(file, 'module.exports = ' + JSON.stringify(cfg, null, 2) + ';\n');
fs.writeFileSync(keysFile, JSON.stringify(Object.keys(vars).sort()) + '\n');
"#;
pub(super) fn ecosystem_env_merge_snippet(
pm2_env: Option<&HashMap<String, serde_json::Value>>,
) -> String {
let Some(pm2_env) = pm2_env else {
return String::new();
};
let vars: std::collections::BTreeMap<&str, String> = pm2_env
.iter()
.filter(|(k, _)| !matches!(k.as_str(), "NODE_ENV" | "PORT" | "HOSTNAME"))
.map(|(k, v)| {
let value = match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
(k.as_str(), value)
})
.collect();
let blob = BASE64.encode(serde_json::to_string(&vars).unwrap_or_else(|_| "{}".to_string()));
let guard = if vars.is_empty() {
r#"[ -f ecosystem.config.cjs ] && [ -f .smbcloud-env-keys.json ]"#
} else {
r#"[ -f ecosystem.config.cjs ]"#
};
format!(
r#"# Apply smbCloud env vars to the ecosystem file on every deploy.
if {guard}; then
SMB_PM2_APP="$PM2_APP" SMB_ENV_B64='{blob}' node --input-type=commonjs - << 'SMB_ENV_EOF'
{js}SMB_ENV_EOF
fi
"#,
js = ECOSYSTEM_ENV_MERGE_JS.trim_start_matches('\n'),
)
}
pub(super) fn restart_stanza(process_manager: Option<&str>, port: u16) -> Result<String> {
let use_systemd = match process_manager.map(str::trim) {
None | Some("") => false,
Some(m) if m.eq_ignore_ascii_case("pm2") => false,
Some(m) if m.eq_ignore_ascii_case("systemd") => true,
Some(other) => {
return Err(anyhow!(fail_message(&format!(
"Unknown process_manager '{other}' in .smb/config.toml. \
Expected \"pm2\" (default) or \"systemd\"."
))))
}
};
Ok(if use_systemd {
r#" echo "Restarting $PM2_APP via systemd --user…"
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
UNIT="$PM2_APP.service"
if ! systemctl --user cat "$UNIT" >/dev/null 2>&1; then
echo "Error: systemd --user unit $UNIT not found on the server."
echo "Create ~/.config/systemd/user/$UNIT and enable it (see the"
echo "smbcloud-deploy-nextjs skill, 'Process manager: systemd --user'),"
echo "or unset process_manager to stay on pm2. Then re-deploy."
exit 1
fi
systemctl --user restart "$UNIT"
sleep 3
if ! systemctl --user is-active "$UNIT" >/dev/null 2>&1; then
echo "Error: $UNIT failed to become active after restart."
systemctl --user status "$UNIT" --no-pager 2>&1 | head -20 || true
exit 1
fi
echo "Done."
"#
.to_string()
} else {
format!(
r#" echo "Starting $PM2_APP with pm2..."
if pm2 describe "$PM2_APP" > /dev/null 2>&1; then
pm2 delete "$PM2_APP"
fi
if [ -f ecosystem.config.cjs ]; then
pm2 start ecosystem.config.cjs --only "$PM2_APP" --env production
elif [ -f ecosystem.config.js ]; then
pm2 start ecosystem.config.js --only "$PM2_APP" --env production
else
NODE_ENV=production PORT={port} HOSTNAME=127.0.0.1 pm2 start node --name "$PM2_APP" -- server.js
fi
pm2 save
echo "Done."
"#
)
})
}
pub async fn process_deploy_nextjs_ssr(env: Environment, config: Config) -> Result<CommandResult> {
let source = config.project.source.as_deref().unwrap_or(".");
let package_manager = config.project.package_manager.as_deref().unwrap_or("pnpm");
let remote_path = config.project.path.as_deref().ok_or_else(|| {
anyhow!(fail_message(
"path not set in .smb/config.toml (e.g. path = \"apps/web/myapp\")"
))
})?;
let pm2_app = config.project.pm2_app.as_deref().ok_or_else(|| {
anyhow!(fail_message(
"pm2_app not set in .smb/config.toml (e.g. pm2_app = \"my-app\")"
))
})?;
let access_token = crate::token::get_smb_token::get_smb_token(env)?;
let user = me(env, client(), &access_token).await?;
let source_dir = std::path::Path::new(source);
if !source_dir.exists() {
return Err(anyhow!(fail_message(&format!(
"Source path '{}' does not exist. Check the 'source' field in .smb/config.toml.",
source
))));
}
let mut install_spinner = Spinner::new(
Spinners::SimpleDotsScrolling,
succeed_message(&format!("Installing dependencies in {}…", source)),
);
let mut install_command = Command::new(package_manager);
install_command.args(["install", "--ignore-scripts"]);
let is_pnpm = std::path::Path::new(package_manager)
.file_stem()
.is_some_and(|stem| stem.eq_ignore_ascii_case("pnpm"));
if is_pnpm {
install_command.arg("--config.confirm-modules-purge=false");
}
let install_output = install_command.current_dir(source).output().map_err(|e| {
anyhow!(fail_message(&format!(
"Failed to spawn '{} install': {}",
package_manager, e
)))
})?;
if !install_output.status.success() {
install_spinner.stop_and_persist(&fail_symbol(), fail_message("Install failed."));
let stderr = String::from_utf8_lossy(&install_output.stderr);
let stdout = String::from_utf8_lossy(&install_output.stdout);
let details = if !stderr.trim().is_empty() {
stderr
} else {
stdout
};
if !details.trim().is_empty() {
eprintln!("{}", details.trim());
}
return Err(anyhow!(fail_message(&format!(
"'{} install --ignore-scripts' exited with status {}",
package_manager, install_output.status
))));
}
install_spinner.stop_and_persist(
&succeed_symbol(),
succeed_message("Dependencies installed."),
);
println!();
let build_status = Command::new(package_manager)
.arg("build")
.current_dir(source)
.status()
.map_err(|e| {
anyhow!(fail_message(&format!(
"Failed to spawn '{} build': {}",
package_manager, e
)))
})?;
println!();
if !build_status.success() {
return Err(anyhow!(fail_message(&format!(
"'{} build' exited with status {}",
package_manager, build_status
))));
}
println!(
"{} {}",
succeed_symbol(),
succeed_message("Build complete.")
);
let standalone_dir = format!("{}/.next/standalone", source);
let standalone_path = std::path::Path::new(&standalone_dir);
if !standalone_path.exists() {
return Err(anyhow!(fail_message(
".next/standalone not found. Add `output: 'standalone'` to next.config.js and rebuild."
)));
}
let runtime_subdir = if source != "." && standalone_path.join(source).join("server.js").exists()
{
Some(source.trim_end_matches('/').to_owned())
} else {
None
};
match prune_dangling_symlinks(standalone_path) {
Ok(0) => {}
Ok(n) => println!(
"{} {}",
succeed_symbol(),
succeed_message(&format!(
"Pruned {} dangling symlink{} from .next/standalone before upload.",
n,
if n == 1 { "" } else { "s" }
))
),
Err(e) => {
return Err(anyhow!(fail_message(&format!(
"Failed to prune dangling symlinks from .next/standalone: {}",
e
))));
}
}
let deploy_ref = Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
let created_deployment = create_deployment(
env,
client(),
&access_token,
config.project.id,
DeploymentPayload {
commit_hash: deploy_ref.clone(),
status: DeploymentStatus::Started,
frontend_app_id: config.project.frontend_app_id.clone(),
},
)
.await
.ok();
let runner = config.project.runner;
let rsync_host = runner.rsync_host();
let home = dirs::home_dir().ok_or_else(|| anyhow!("Could not determine home directory"))?;
let identity_file = home.join(".ssh").join(format!("id_{}@smbcloud", user.id));
let identity_file_str = identity_file.to_string_lossy().into_owned();
let mut known_hosts_file = NamedTempFile::new()
.map_err(|e| anyhow!("Failed to create temp known_hosts file: {}", e))?;
writeln!(known_hosts_file, "{}", known_hosts::for_host(&rsync_host))
.map_err(|e| anyhow!("Failed to write known_hosts: {}", e))?;
let ssh_command = format!(
"ssh -i {identity} \
-o StrictHostKeyChecking=yes \
-o UserKnownHostsFile={known_hosts} \
-o IdentitiesOnly=yes \
-o PasswordAuthentication=no \
-o BatchMode=yes",
identity = identity_file_str,
known_hosts = known_hosts_file.path().display(),
);
let remote_base = format!(
"git@{}:{}",
rsync_host,
if remote_path.ends_with('/') {
remote_path.to_owned()
} else {
format!("{}/", remote_path)
}
);
struct Transfer {
local_rel: &'static str,
remote_rel: String,
protect_runtime_files: bool,
copy_links: bool,
}
let runtime_prefix = runtime_subdir
.as_ref()
.map(|path| format!("{}/", path))
.unwrap_or_default();
let env_file_excludes: Vec<String> = {
let mut patterns = vec!["/.env*".to_string()];
if !runtime_prefix.is_empty() {
patterns.push(format!("/{}.env*", runtime_prefix));
}
patterns
};
let local_env_file = [
format!("{}/.env", standalone_dir),
format!("{}/{}.env", standalone_dir, runtime_prefix),
]
.iter()
.any(|path| std::path::Path::new(path).exists());
if local_env_file {
println!(
"{} {}",
succeed_symbol(),
succeed_message(
"Local .env* files found in the standalone build — not uploaded. \
Runtime env comes from the server (ecosystem config or server-side .env).",
)
);
}
let transfers = vec![
Transfer {
local_rel: ".next/standalone/",
remote_rel: String::new(),
copy_links: true,
protect_runtime_files: true,
},
Transfer {
local_rel: ".next/static/",
remote_rel: format!("{}.next/static/", runtime_prefix),
protect_runtime_files: false,
copy_links: false,
},
Transfer {
local_rel: "public/",
remote_rel: format!("{}public/", runtime_prefix),
protect_runtime_files: false,
copy_links: false,
},
];
let mut upload_spinner = Spinner::new(
Spinners::Hamburger,
succeed_message(&format!("Uploading to {}…", remote_path)),
);
for transfer in transfers {
let local_path = format!("{}/{}", source, transfer.local_rel);
let destination = format!("{}{}", remote_base, transfer.remote_rel);
if !std::path::Path::new(&local_path).exists() {
continue;
}
let mut rsync_args = vec!["-az".to_string(), "--delete".to_string()];
if transfer.copy_links {
rsync_args.push("--copy-links".to_string());
}
if transfer.protect_runtime_files {
rsync_args.extend([
"--exclude".to_string(),
"ecosystem.config.js".to_string(),
"--exclude".to_string(),
"ecosystem.config.cjs".to_string(),
"--exclude".to_string(),
"logs/".to_string(),
]);
for pattern in &env_file_excludes {
rsync_args.extend(["--exclude".to_string(), pattern.clone()]);
}
}
rsync_args.extend([
"-e".to_string(),
ssh_command.clone(),
local_path.clone(),
destination,
]);
let output = Command::new("rsync")
.args(&rsync_args)
.output()
.map_err(|e| anyhow!(fail_message(&format!("Failed to launch rsync: {}", e))))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
upload_spinner.stop_and_persist(&fail_symbol(), fail_message("Upload failed."));
mark_failed(
&deploy_ref,
&created_deployment,
&config,
env,
&access_token,
)
.await;
return Err(anyhow!(fail_message(&format!(
"rsync of '{}' failed (status {}): {}",
transfer.local_rel,
output.status.code().unwrap_or(-1),
stderr.trim()
))));
}
}
drop(known_hosts_file);
upload_spinner.stop_and_persist(&succeed_symbol(), succeed_message("Upload complete."));
let port = config.project.port.unwrap_or(3000);
let runtime_subdir_for_shell = runtime_subdir.clone().unwrap_or_default();
let ecosystem_config_content = {
let mut env_entries = format!(
r#" NODE_ENV: "production",
PORT: {port},
HOSTNAME: "127.0.0.1",
"#
);
if let Some(pm2_env) = &config.project.pm2_env {
for (key, value) in pm2_env {
if key == "NODE_ENV" || key == "PORT" || key == "HOSTNAME" {
continue;
}
let val_str = match value {
serde_json::Value::String(s) => {
let escaped = s
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r");
format!(r#""{escaped}""#)
}
other => other.to_string(),
};
env_entries.push_str(&format!(" {key}: {val_str},\n"));
}
}
format!(
r#"module.exports = {{
apps: [
{{
name: "{pm2_app}",
script: "server.js",
cwd: "", // filled at runtime via $APP_PATH
env_production: {{
{env_entries} }},
}},
],
}};
"#
)
};
let env_merge = ecosystem_env_merge_snippet(config.project.pm2_env.as_ref());
let restart_stanza = restart_stanza(config.project.process_manager.as_deref(), port)?;
let deploy_script = format!(
r#"set -e
APP_PATH="{remote_path}"
PM2_APP="{pm2_app}"
RUNTIME_SUBDIR="{runtime_subdir}"
case "$APP_PATH" in
/*) ;;
*) APP_PATH="$HOME/$APP_PATH" ;;
esac
if [ ! -d "$APP_PATH" ]; then
echo "Error: $APP_PATH is not a directory."
exit 1
fi
cd "$APP_PATH"
mkdir -p logs
# Migrate legacy ecosystem.config.js to .cjs so it works when
# package.json has "type": "module".
if [ -f ecosystem.config.js ] && [ ! -f ecosystem.config.cjs ]; then
mv ecosystem.config.js ecosystem.config.cjs
fi
# Write ecosystem.config.cjs from smbCloud server config if none exists yet.
if [ ! -f ecosystem.config.cjs ] && [ ! -f ecosystem.config.js ]; then
cat > ecosystem.config.cjs << 'ECOSYSTEM_EOF'
{ecosystem_config}
ECOSYSTEM_EOF
# Patch the cwd field to the actual runtime path
node --input-type=commonjs -e "
var fs = require('fs');
var src = fs.readFileSync('ecosystem.config.cjs', 'utf8');
src = src.replace('cwd: \"\"', 'cwd: \"' + process.argv[1] + '\"');
fs.writeFileSync('ecosystem.config.cjs', src);
" "$APP_PATH" 2>/dev/null || true
fi
{env_merge}
# The monorepo root package.json may declare "type": "module", which
# Next.js copies into .next/standalone/. Standalone server.js and our
# shims use require() (CJS). Strip the field so Node treats .js as CJS.
if [ -f package.json ] && grep -q '"type"' package.json; then
node --input-type=commonjs -e "
var fs = require('fs');
var p = JSON.parse(fs.readFileSync('package.json','utf8'));
delete p.type;
fs.writeFileSync('package.json', JSON.stringify(p,null,2)+'\\n');
" 2>/dev/null || sed -i '"'"'"type".*"module"'"'d' package.json
fi
# pnpm standalone output buries peer deps inside node_modules/.pnpm/
# without the top-level symlinks Node needs for require.resolve().
# First mirror pnpm's own virtual node_modules directory when it exists —
# this preserves the exact version selection pnpm already resolved, which is
# especially important for scoped packages like @swc/helpers.
# Then fall back to scanning individual .pnpm store entries for anything the
# virtual directory did not expose.
if [ -d "node_modules/.pnpm/node_modules" ]; then
for pkg_path in node_modules/.pnpm/node_modules/*; do
[ -e "$pkg_path" ] || continue
pkg_name=$(basename "$pkg_path")
if [ "${{pkg_name:0:1}}" = "@" ] && [ -d "$pkg_path" ]; then
mkdir -p "node_modules/$pkg_name"
for sub_path in "$pkg_path"/*; do
[ -e "$sub_path" ] || continue
sub_name=$(basename "$sub_path")
rm -rf "node_modules/$pkg_name/$sub_name"
ln -sfn "$APP_PATH/$sub_path" "node_modules/$pkg_name/$sub_name"
done
else
rm -rf "node_modules/$pkg_name"
ln -sfn "$APP_PATH/$pkg_path" "node_modules/$pkg_name"
fi
done
fi
if [ -d "node_modules/.pnpm" ]; then
find node_modules/.pnpm -mindepth 2 -maxdepth 2 -type d -name "node_modules" 2>/dev/null | while read pnpm_nm; do
for pkg_path in "$pnpm_nm"/*; do
[ -e "$pkg_path" ] || continue
pkg_name=$(basename "$pkg_path")
if [ "${{pkg_name:0:1}}" = "@" ] && [ -d "$pkg_path" ]; then
mkdir -p "node_modules/$pkg_name"
for sub_path in "$pkg_path"/*; do
[ -e "$sub_path" ] || continue
sub_name=$(basename "$sub_path")
# Count files in this .pnpm store entry.
entry_files=$(find "$sub_path" -maxdepth 2 -type f 2>/dev/null | wc -l | tr -d ' ')
existing="node_modules/$pkg_name/$sub_name"
if [ -e "$existing" ]; then
# Only replace if existing has fewer files than the .pnpm store entry.
existing_files=$(find "$existing" -maxdepth 2 -type f 2>/dev/null | wc -l | tr -d ' ')
if [ "$entry_files" -gt "$existing_files" ]; then
rm -rf "$existing"
ln -sfn "$APP_PATH/$sub_path" "$existing"
fi
else
ln -sfn "$APP_PATH/$sub_path" "$existing"
fi
done
else
if [ -e "node_modules/$pkg_name" ]; then
continue
fi
ln -sfn "$APP_PATH/$pkg_path" "node_modules/$pkg_name"
fi
done
done
fi
if [ -n "$RUNTIME_SUBDIR" ]; then
cat > server.js <<EOF
import("./$RUNTIME_SUBDIR/server.js").catch(function(e){{console.error(e);process.exit(1)}})
EOF
fi
# Backward compatibility: older operator-managed ecosystem config files
# may still point PM2 at `server.js` or `.next/standalone/server.js` in the
# app root even when standalone preserves the source path inside `web/`.
mkdir -p .next/standalone
rm -rf .next/standalone/node_modules
ln -sfn ../../node_modules .next/standalone/node_modules
if [ -n "$RUNTIME_SUBDIR" ]; then
cat > .next/standalone/server.js <<EOF
import("../../$RUNTIME_SUBDIR/server.js").catch(function(e){{console.error(e);process.exit(1)}})
EOF
else
ln -sfn ../../server.js .next/standalone/server.js
fi
{restart} "#,
remote_path = remote_path,
pm2_app = pm2_app,
runtime_subdir = runtime_subdir_for_shell,
restart = restart_stanza,
ecosystem_config = ecosystem_config_content,
env_merge = env_merge,
);
let mut restart_spinner = Spinner::new(
Spinners::SimpleDotsScrolling,
succeed_message(&format!("Restarting {} on server…", pm2_app)),
);
let mut ssh_known_hosts_file = NamedTempFile::new()
.map_err(|e| anyhow!("Failed to create temp known_hosts file: {}", e))?;
writeln!(
ssh_known_hosts_file,
"{}",
known_hosts::for_host(&rsync_host)
)
.map_err(|e| anyhow!("Failed to write known_hosts: {}", e))?;
let mut child = Command::new("ssh")
.args([
"-i",
&identity_file_str,
"-o",
"StrictHostKeyChecking=yes",
"-o",
&format!(
"UserKnownHostsFile={}",
ssh_known_hosts_file.path().display()
),
"-o",
"IdentitiesOnly=yes",
"-o",
"PasswordAuthentication=no",
"-o",
"BatchMode=yes",
&format!("git@{}", rsync_host),
"bash -s",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| anyhow!(fail_message(&format!("Failed to spawn SSH: {}", e))))?;
if let Some(mut stdin) = child.stdin.take() {
stdin
.write_all(deploy_script.as_bytes())
.map_err(|e| anyhow!("Failed to write deploy script to SSH stdin: {}", e))?;
}
let ssh_output = child
.wait_with_output()
.map_err(|e| anyhow!("Failed to wait for SSH process: {}", e))?;
drop(ssh_known_hosts_file);
if !ssh_output.status.success() {
restart_spinner.stop_and_persist(&fail_symbol(), fail_message("Remote restart failed."));
let stderr = String::from_utf8_lossy(&ssh_output.stderr);
let stdout = String::from_utf8_lossy(&ssh_output.stdout);
let details = if !stderr.trim().is_empty() {
stderr
} else {
stdout
};
if !details.trim().is_empty() {
eprintln!("{}", details.trim());
}
mark_failed(
&deploy_ref,
&created_deployment,
&config,
env,
&access_token,
)
.await;
return Err(anyhow!(fail_message(&format!(
"SSH deploy script exited with status {}",
ssh_output.status
))));
}
restart_spinner.stop_and_persist(
&succeed_symbol(),
succeed_message(&format!("{} restarted.", pm2_app)),
);
if let Some(ref deployment) = created_deployment {
match update(
env,
client(),
access_token,
config.project.id,
deployment.id,
DeploymentPayload {
commit_hash: deploy_ref,
status: DeploymentStatus::Done,
frontend_app_id: config.project.frontend_app_id.clone(),
},
)
.await
{
Ok(_) => println!("App is running {}", succeed_symbol()),
Err(e) => eprintln!("Error updating deployment status to Done: {}", e),
}
}
Ok(CommandResult {
spinner: Spinner::new(Spinners::Hamburger, String::new()),
symbol: succeed_symbol(),
msg: succeed_message("Deployment complete."),
})
}
pub(super) async fn mark_failed(
deploy_ref: &str,
created_deployment: &Option<smbcloud_model::project::Deployment>,
config: &Config,
env: Environment,
access_token: &str,
) {
if let Some(ref deployment) = created_deployment {
let _ = update(
env,
client(),
access_token.to_owned(),
config.project.id,
deployment.id,
DeploymentPayload {
commit_hash: deploy_ref.to_owned(),
status: DeploymentStatus::Failed,
frontend_app_id: config.project.frontend_app_id.clone(),
},
)
.await;
}
}
#[cfg(all(test, unix))]
mod tests {
use {
super::{ecosystem_env_merge_snippet, prune_dangling_symlinks, restart_stanza},
serde_json::{json, Value},
std::{collections::HashMap, os::unix::fs::symlink, path::Path, process::Command},
tempfile::tempdir,
};
#[test]
fn prunes_dangling_but_keeps_valid_links_and_files() {
let root = tempdir().unwrap();
let base = root.path();
let nm = base.join("node_modules/.pnpm/node_modules");
std::fs::create_dir_all(&nm).unwrap();
let real_pkg = base.join("node_modules/.pnpm/semver@7.7.3/node_modules/semver");
std::fs::create_dir_all(&real_pkg).unwrap();
std::fs::write(real_pkg.join("index.js"), "module.exports = {}").unwrap();
let valid_link = nm.join("valid");
symlink("../semver@7.7.3/node_modules/semver", &valid_link).unwrap();
let dangling = nm.join("semver");
symlink("../semver@6.3.1/node_modules/semver", &dangling).unwrap();
let keeper = base.join("server.js");
std::fs::write(&keeper, "// server").unwrap();
let removed = prune_dangling_symlinks(base).unwrap();
assert_eq!(removed, 1, "exactly the dangling link should be removed");
assert!(!dangling.exists(), "dangling link is gone");
assert!(
std::fs::symlink_metadata(&valid_link).is_ok(),
"valid link is preserved"
);
assert!(keeper.exists(), "real files are untouched");
}
#[test]
fn clean_tree_removes_nothing() {
let root = tempdir().unwrap();
std::fs::create_dir_all(root.path().join("a/b")).unwrap();
std::fs::write(root.path().join("a/b/f.txt"), "x").unwrap();
assert_eq!(prune_dangling_symlinks(root.path()).unwrap(), 0);
}
#[test]
fn does_not_follow_valid_directory_symlink() {
let root = tempdir().unwrap();
let base = root.path();
std::fs::write(base.join("server.js"), "// server").unwrap();
let dir_link = base.join("cycle");
symlink(".", &dir_link).unwrap();
let removed = prune_dangling_symlinks(base).unwrap();
assert_eq!(removed, 0, "no dangling links, nothing removed");
assert!(
std::fs::symlink_metadata(&dir_link).is_ok(),
"the valid directory symlink itself is preserved"
);
}
#[test]
fn dangling_symlink_at_root_is_removed() {
let root = tempdir().unwrap();
let link = root.path().join("root_link");
symlink("./missing_target", &link).unwrap();
assert_eq!(prune_dangling_symlinks(&link).unwrap(), 1);
assert!(
std::fs::symlink_metadata(&link).is_err(),
"the dangling root symlink is gone"
);
}
#[test]
fn restart_stanza_defaults_to_pm2() {
for pm in [None, Some(""), Some("pm2"), Some("PM2"), Some(" pm2 ")] {
let s = restart_stanza(pm, 3025).expect("pm2 selector is valid");
assert!(s.contains("pm2 start"), "pm={pm:?} should use pm2");
assert!(s.contains("PORT=3025"), "pm={pm:?} injects the port");
assert!(!s.contains("systemctl"), "pm={pm:?} must not touch systemd");
}
}
#[test]
fn restart_stanza_rejects_unknown_process_manager() {
for pm in ["system", "systemctl", "supervisord", "PM3"] {
let err = restart_stanza(Some(pm), 3025)
.expect_err("unknown process_manager must be rejected");
let msg = err.to_string();
assert!(msg.contains(pm), "error names the offending value: {msg}");
assert!(msg.contains("systemd"), "error lists valid options: {msg}");
}
}
#[test]
fn restart_stanza_systemd_uses_user_unit_no_sudo() {
let s = restart_stanza(Some("systemd"), 3025).expect("systemd selector is valid");
assert!(s.contains("systemctl --user restart \"$UNIT\""));
assert!(s.contains("UNIT=\"$PM2_APP.service\""));
assert!(s.contains("XDG_RUNTIME_DIR=\"/run/user/$(id -u)\""));
assert!(!s.contains("sudo"), "must not require sudo");
assert!(!s.contains("pm2 "), "systemd path must not call pm2");
assert_eq!(s, restart_stanza(Some("SystemD"), 3025).unwrap());
}
const HAND_FILE: &str = r#"module.exports = {
apps: [
{ name: "web", script: "server.js", cwd: "/srv/web",
env_production: { NODE_ENV: "production", PORT: 3026, HAND_KEPT: "mine", OLD: "x" } },
{ name: "other", script: "o.js", env_production: { UNTOUCHED: "1" } },
],
};
"#;
fn have_bash_and_node() -> bool {
["bash", "node"].iter().all(|bin| {
Command::new(bin)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
})
}
fn vars(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect()
}
fn run_merge(dir: &Path, env: Option<&HashMap<String, Value>>) -> std::process::Output {
let script = format!(
"set -e\nPM2_APP=\"web\"\n{}",
ecosystem_env_merge_snippet(env)
);
Command::new("bash")
.arg("-c")
.arg(script)
.current_dir(dir)
.output()
.unwrap()
}
fn env_of(dir: &Path, app: &str) -> Value {
let out = Command::new("node")
.arg("-e")
.arg(format!(
"var c=require('./ecosystem.config.cjs');\
console.log(JSON.stringify(c.apps.find(a=>a.name==='{app}').env_production))"
))
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
serde_json::from_slice(&out.stdout).unwrap()
}
fn env_of_array(dir: &Path, app: &str) -> Value {
let out = Command::new("node")
.arg("-e")
.arg(format!(
"var c=require('./ecosystem.config.cjs');\
console.log(JSON.stringify(c.find(a=>a.name==='{app}').env_production))"
))
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
serde_json::from_slice(&out.stdout).unwrap()
}
#[test]
fn env_merge_sets_keys_and_keeps_hand_maintained_ones() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
let env = vars(&[("STRIPE_WEBHOOK_SECRET", json!("whsec_1")), ("N", json!(5))]);
let out = run_merge(dir.path(), Some(&env));
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let web = env_of(dir.path(), "web");
assert_eq!(web["STRIPE_WEBHOOK_SECRET"], "whsec_1");
assert_eq!(web["N"], "5");
assert_eq!(web["HAND_KEPT"], "mine");
assert_eq!(web["PORT"], 3026);
assert_eq!(env_of(dir.path(), "other"), json!({"UNTOUCHED": "1"}));
let sidecar = std::fs::read_to_string(dir.path().join(".smbcloud-env-keys.json")).unwrap();
assert_eq!(
serde_json::from_str::<Value>(&sidecar).unwrap(),
json!(["N", "STRIPE_WEBHOOK_SECRET"])
);
assert!(!sidecar.contains("whsec_1"), "the sidecar holds names only");
assert!(dir
.path()
.join("ecosystem.config.cjs.smbcloud.bak")
.exists());
}
#[test]
fn env_merge_removes_keys_deleted_since_last_deploy_but_not_hand_kept_ones() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
let first = vars(&[("A", json!("1")), ("B", json!("2"))]);
assert!(run_merge(dir.path(), Some(&first)).status.success());
let second = vars(&[("A", json!("1"))]);
assert!(run_merge(dir.path(), Some(&second)).status.success());
let web = env_of(dir.path(), "web");
assert_eq!(web["A"], "1");
assert!(web.get("B").is_none(), "B was managed and is now deleted");
assert_eq!(web["HAND_KEPT"], "mine");
assert_eq!(web["OLD"], "x");
let empty = vars(&[]);
assert!(run_merge(dir.path(), Some(&empty)).status.success());
assert!(env_of(dir.path(), "web").get("A").is_none());
assert_eq!(env_of(dir.path(), "web")["HAND_KEPT"], "mine");
}
#[test]
fn env_merge_is_a_no_op_without_a_map_or_a_previous_sidecar() {
assert_eq!(ecosystem_env_merge_snippet(None), "");
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
assert!(run_merge(dir.path(), Some(&vars(&[]))).status.success());
assert_eq!(
std::fs::read_to_string(dir.path().join("ecosystem.config.cjs")).unwrap(),
HAND_FILE
);
assert!(!dir.path().join(".smbcloud-env-keys.json").exists());
}
#[test]
fn env_merge_carries_quotes_newlines_and_dollars_verbatim() {
if !have_bash_and_node() {
return;
}
let nasty = "a'b\"c\nline2 $HOME `id` $(whoami) \\n end";
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
let env = vars(&[
("NASTY", json!(nasty)),
("PEM", json!("-----BEGIN-----\nabc\n-----END-----")),
]);
let out = run_merge(dir.path(), Some(&env));
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let web = env_of(dir.path(), "web");
assert_eq!(web["NASTY"], nasty);
assert_eq!(web["PEM"], "-----BEGIN-----\nabc\n-----END-----");
}
#[test]
fn env_merge_never_overrides_the_deploy_owned_keys() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
let env = vars(&[
("PORT", json!("1")),
("NODE_ENV", json!("dev")),
("K", json!("v")),
]);
assert!(run_merge(dir.path(), Some(&env)).status.success());
let web = env_of(dir.path(), "web");
assert_eq!(web["PORT"], 3026);
assert_eq!(web["NODE_ENV"], "production");
assert_eq!(web["K"], "v");
}
#[test]
fn env_merge_handles_an_array_form_ecosystem_file() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(
dir.path().join("ecosystem.config.cjs"),
"module.exports = [{ name: 'web', script: 'server.js', env_production: { HAND_KEPT: 'mine' } }];\n",
)
.unwrap();
let out = run_merge(dir.path(), Some(&vars(&[("K", json!("v"))])));
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let web = env_of_array(dir.path(), "web");
assert_eq!(web["K"], "v");
assert_eq!(web["HAND_KEPT"], "mine");
}
#[test]
fn env_merge_removes_a_managed_key_named_like_an_object_property() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
let first = vars(&[("constructor", json!("x")), ("toString", json!("y"))]);
assert!(run_merge(dir.path(), Some(&first)).status.success());
assert_eq!(env_of(dir.path(), "web")["constructor"], "x");
let second = vars(&[("K", json!("v"))]);
assert!(run_merge(dir.path(), Some(&second)).status.success());
let web = env_of(dir.path(), "web");
assert!(!web.as_object().unwrap().contains_key("constructor"));
assert!(!web.as_object().unwrap().contains_key("toString"));
assert_eq!(web["K"], "v");
}
#[test]
fn env_merge_fails_loudly_when_the_app_is_not_in_the_file() {
if !have_bash_and_node() {
return;
}
let dir = tempdir().unwrap();
std::fs::write(
dir.path().join("ecosystem.config.cjs"),
"module.exports = { apps: [{ name: 'else' }] };\n",
)
.unwrap();
let out = run_merge(dir.path(), Some(&vars(&[("K", json!("v"))])));
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("no app named web"));
}
}