Skip to content

Commit

Permalink
Switch PHP prestart from Perl to JS (#1000)
Browse files Browse the repository at this point in the history
* Switch PHP prestart from Perl to JS

* Update snapshots

* gosh hecking csharp dev kit

* fix /app/storage permissions

* Fix snapshots

* hecking clippy
  • Loading branch information
aleksrutins authored Nov 17, 2023
1 parent 125659a commit 58c8a81
Show file tree
Hide file tree
Showing 20 changed files with 200 additions and 261 deletions.
8 changes: 4 additions & 4 deletions src/providers/go.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,9 @@ mod test {

#[test]
fn test_with_go_mod() -> Result<()> {
let go_mod_contents = r#"
let go_mod_contents = r"
go 1.18
"#;
";

assert_eq!(
GolangProvider::get_nix_golang_pkg(Some(&go_mod_contents.to_string()))?,
Expand All @@ -136,9 +136,9 @@ mod test {

#[test]
fn test_fallback_on_invalid_version() -> Result<()> {
let go_mod_contents = r#"
let go_mod_contents = r"
go 1.8
"#;
";

assert_eq!(
GolangProvider::get_nix_golang_pkg(Some(&go_mod_contents.to_string()))?,
Expand Down
52 changes: 0 additions & 52 deletions src/providers/php/Nixpacks/Config/Template.pm

This file was deleted.

13 changes: 0 additions & 13 deletions src/providers/php/Nixpacks/Nix.pm

This file was deleted.

16 changes: 0 additions & 16 deletions src/providers/php/Nixpacks/Util/ChmodRecursive.pm

This file was deleted.

47 changes: 0 additions & 47 deletions src/providers/php/Nixpacks/Util/Laravel.pm

This file was deleted.

29 changes: 0 additions & 29 deletions src/providers/php/Nixpacks/Util/Logger.pm

This file was deleted.

25 changes: 11 additions & 14 deletions src/providers/php/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ impl PhpProvider {
.collect::<Vec<_>>()
.join(" ")
)),
Pkg::new("perl"),
Pkg::new("nginx"),
Pkg::new("libmysqlclient"),
Pkg::new(&format!("{}Packages.composer", &php_pkg)),
Expand All @@ -79,9 +78,7 @@ impl PhpProvider {
.map(|extension| format!("{}Extensions.{extension}", &php_pkg))
.collect();

if app.includes_file("package.json") {
pkgs.append(&mut NodeProvider::get_nix_packages(app, env)?);
}
pkgs.append(&mut NodeProvider::get_nix_packages(app, env)?);

{
let mut tmp_ext_pkgs = ext_pkgs.iter().map(|pkg| Pkg::new(pkg)).collect();
Expand Down Expand Up @@ -134,14 +131,14 @@ impl PhpProvider {
))
} else if app.includes_file("nginx.template.conf") {
StartPhase::new(format!(
"perl {} /app/nginx.template.conf /nginx.conf && (php-fpm -y {} & nginx -c /nginx.conf)",
app.asset_path("prestart.pl"),
"node {} /app/nginx.template.conf /nginx.conf && (php-fpm -y {} & nginx -c /nginx.conf)",
app.asset_path("scripts/prestart.mjs"),
app.asset_path("php-fpm.conf"),
))
} else {
StartPhase::new(format!(
"perl {} {} /nginx.conf && (php-fpm -y {} & nginx -c /nginx.conf)",
app.asset_path("prestart.pl"),
"node {} {} /nginx.conf && (php-fpm -y {} & nginx -c /nginx.conf)",
app.asset_path("scripts/prestart.mjs"),
app.asset_path("nginx.template.conf"),
app.asset_path("php-fpm.conf"),
))
Expand All @@ -151,13 +148,13 @@ impl PhpProvider {
fn static_assets() -> StaticAssets {
static_asset_list! {
"nginx.template.conf" => include_str!("nginx.template.conf"),
"prestart.pl" => include_str!("prestart.pl"),
"scripts/prestart.mjs" => include_str!("scripts/prestart.mjs"),
"php-fpm.conf" => include_str!("php-fpm.conf"),
"Nixpacks/Nix.pm" => include_str!("Nixpacks/Nix.pm"),
"Nixpacks/Config/Template.pm" => include_str!("Nixpacks/Config/Template.pm"),
"Nixpacks/Util/ChmodRecursive.pm" => include_str!("Nixpacks/Util/ChmodRecursive.pm"),
"Nixpacks/Util/Laravel.pm" => include_str!("Nixpacks/Util/Laravel.pm"),
"Nixpacks/Util/Logger.pm" => include_str!("Nixpacks/Util/Logger.pm")
"scripts/util/cmd.mjs" => include_str!("scripts/util/cmd.mjs"),
"scripts/util/nix.mjs" => include_str!("scripts/util/nix.mjs"),
"scripts/config/template.mjs" => include_str!("scripts/config/template.mjs"),
"scripts/util/laravel.mjs" => include_str!("scripts/util/laravel.mjs"),
"scripts/util/logger.mjs" => include_str!("scripts/util/logger.mjs")
}
}

Expand Down
32 changes: 0 additions & 32 deletions src/providers/php/prestart.pl

This file was deleted.

24 changes: 24 additions & 0 deletions src/providers/php/scripts/config/template.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { readFile, writeFile } from "fs/promises";
import { getNixPath } from "../util/nix.mjs";

const replaceStr = input =>
input
// If statements
.replaceAll(/\$if\s*\((\w+)\)\s*\(([^]*?)\)\s*else\s*\(([^]*?)\)/gm,
(_all, condition, value, otherwise) =>
process.env[condition] ? replaceStr(value) : replaceStr(otherwise)
)
// Variables
.replaceAll(/\${(\w+)}/g,
(_all, name) => process.env[name]
)
// Nix paths
.replaceAll(/\$!{(\w+)}/g,
(_all, exe) => getNixPath(exe)
)

export async function compileTemplate(infile, outfile) {
await writeFile(outfile,
replaceStr(await readFile(infile, { encoding: 'utf8' })),
{ encoding: 'utf8' })
}
27 changes: 27 additions & 0 deletions src/providers/php/scripts/prestart.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env node
import { compileTemplate } from "./config/template.mjs";
import { e } from "./util/cmd.mjs";
import { checkEnvErrors, isLaravel } from "./util/laravel.mjs";
import Logger from "./util/logger.mjs";
import { access, constants } from 'node:fs/promises'

const prestartLogger = new Logger('prestart');
const serverLogger = new Logger('server');

if (process.argv.length != 4) {
prestartLogger.error(`Usage: ${process.argv[1]} <config-file> <output-file>`)
process.exit(1);
}

if (isLaravel()) {
checkEnvErrors('/app')
}

await Promise.all([
access('/app/storage', constants.R_OK)
.then(() => e('chmod -R ugo+rw /app/storage'))
.catch(() => {}),
compileTemplate(process.argv[2], process.argv[3])
]).catch(err => prestartLogger.error(err));

serverLogger.info(`Server starting on port ${process.env.PORT}`)
3 changes: 3 additions & 0 deletions src/providers/php/scripts/util/cmd.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { execSync } from "child_process";

export const e = cmd => execSync(cmd).toString().replace('\n', '');
41 changes: 41 additions & 0 deletions src/providers/php/scripts/util/laravel.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Logger from "./logger.mjs"
import * as fs from 'node:fs/promises'
import * as path from 'node:path'

const variableHints = {
'APP_ENV': 'You should probably set this to `production`.'
};

const logger = new Logger('laravel');

export const isLaravel = () => process.env['IS_LARAVEL'] != null;

function checkVariable(name) {
if (!process.env[name]) {
let hint =
`Your app configuration references the ${name} environment variable, but it is not set.`
+ (variableHints[name] ?? '');

logger.warn(hint);
}
}

export async function checkEnvErrors(srcdir) {
const envRegex = /env\(["']([^,]*)["']\)/g;
const configDir = path.join(srcdir, 'config');

const config =
(await Promise.all(
(await fs.readdir(configDir))
.filter(fileName => fileName.endsWith('.php'))
.map(fileName => fs.readFile(path.join(configDir, fileName)))
)).join('');

for (const match of config.matchAll(envRegex)) {
if (match[1] != 'APP_KEY') checkVariable(match[1]);
}

if (!process.env.APP_KEY) {
logger.warn('Your app key is not set! Please set a random 32-character string in your APP_KEY environment variable. This can be easily generated with `openssl rand -hex 16`.');
}
}
Loading

0 comments on commit 58c8a81

Please sign in to comment.