Repository: php/frankenphp Branch: main Commit: 33fcc4d5c08a Files: 457 Total size: 2.0 MB Directory structure: gitextract_hy3ir2xo/ ├── .clang-format-ignore ├── .codespellrc ├── .dockerignore ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yaml │ │ └── feature_request.yaml │ ├── actions/ │ │ └── watcher/ │ │ └── action.yaml │ ├── dependabot.yaml │ ├── scripts/ │ │ ├── docker-compute-fingerprints.sh │ │ └── docker-verify-fingerprints.sh │ └── workflows/ │ ├── docker.yaml │ ├── docs.yaml │ ├── lint.yaml │ ├── sanitizers.yaml │ ├── static.yaml │ ├── tests.yaml │ ├── translate.yaml │ ├── windows.yaml │ └── wrap-issue-details.yaml ├── .gitignore ├── .gitleaksignore ├── .golangci.yaml ├── .hadolint.yaml ├── .markdown-lint.yaml ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── SECURITY.md ├── alpine.Dockerfile ├── app_checksum.txt ├── build-static.sh ├── caddy/ │ ├── admin.go │ ├── admin_test.go │ ├── app.go │ ├── br-skip.go │ ├── br.go │ ├── caddy.go │ ├── caddy_test.go │ ├── config_test.go │ ├── extinit.go │ ├── frankenphp/ │ │ ├── Caddyfile │ │ ├── cbrotli.go │ │ └── main.go │ ├── go.mod │ ├── go.sum │ ├── hotreload-skip.go │ ├── hotreload.go │ ├── hotreload_test.go │ ├── mercure-skip.go │ ├── mercure.go │ ├── module.go │ ├── module_test.go │ ├── php-cli.go │ ├── php-server.go │ ├── watcher_test.go │ └── workerconfig.go ├── cgi.go ├── cgi_test.go ├── cgo.go ├── cli.go ├── cli_test.go ├── context.go ├── debugstate.go ├── dev-alpine.Dockerfile ├── dev.Dockerfile ├── docker-bake.hcl ├── docs/ │ ├── classic.md │ ├── cn/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── classic.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── extensions.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ ├── worker.md │ │ └── x-sendfile.md │ ├── compile.md │ ├── config.md │ ├── docker.md │ ├── early-hints.md │ ├── embed.md │ ├── es/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── classic.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── extensions.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── logging.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ ├── wordpress.md │ │ ├── worker.md │ │ └── x-sendfile.md │ ├── extension-workers.md │ ├── extensions.md │ ├── fr/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── classic.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── extensions.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ ├── worker.md │ │ └── x-sendfile.md │ ├── github-actions.md │ ├── hot-reload.md │ ├── ja/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── classic.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── extensions.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ ├── worker.md │ │ └── x-sendfile.md │ ├── known-issues.md │ ├── laravel.md │ ├── logging.md │ ├── mercure.md │ ├── metrics.md │ ├── performance.md │ ├── production.md │ ├── pt-br/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── classic.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── extensions.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ ├── worker.md │ │ └── x-sendfile.md │ ├── ru/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── metrics.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ └── worker.md │ ├── static.md │ ├── tr/ │ │ ├── CONTRIBUTING.md │ │ ├── README.md │ │ ├── compile.md │ │ ├── config.md │ │ ├── docker.md │ │ ├── early-hints.md │ │ ├── embed.md │ │ ├── extension-workers.md │ │ ├── github-actions.md │ │ ├── hot-reload.md │ │ ├── known-issues.md │ │ ├── laravel.md │ │ ├── mercure.md │ │ ├── performance.md │ │ ├── production.md │ │ ├── static.md │ │ └── worker.md │ ├── translate.php │ ├── wordpress.md │ ├── worker.md │ └── x-sendfile.md ├── embed.go ├── env.go ├── ext.go ├── frankenphp.c ├── frankenphp.go ├── frankenphp.h ├── frankenphp.stub.php ├── frankenphp_arginfo.h ├── frankenphp_test.go ├── go.mod ├── go.sh ├── go.sum ├── hotreload.go ├── install.ps1 ├── install.sh ├── internal/ │ ├── cpu/ │ │ ├── cpu_unix.go │ │ └── cpu_windows.go │ ├── extgen/ │ │ ├── arginfo.go │ │ ├── cfile.go │ │ ├── cfile_namespace_test.go │ │ ├── cfile_phpmethod_test.go │ │ ├── cfile_test.go │ │ ├── classparser.go │ │ ├── classparser_test.go │ │ ├── constants_test.go │ │ ├── constparser.go │ │ ├── constparser_test.go │ │ ├── docs.go │ │ ├── docs_test.go │ │ ├── errors.go │ │ ├── funcparser.go │ │ ├── funcparser_test.go │ │ ├── generator.go │ │ ├── gofile.go │ │ ├── gofile_test.go │ │ ├── hfile.go │ │ ├── hfile_test.go │ │ ├── integration_test.go │ │ ├── namespace_test.go │ │ ├── nodes.go │ │ ├── nsparser.go │ │ ├── paramparser.go │ │ ├── paramparser_test.go │ │ ├── parser.go │ │ ├── phpfunc.go │ │ ├── phpfunc_namespace_test.go │ │ ├── phpfunc_test.go │ │ ├── srcanalyzer.go │ │ ├── srcanalyzer_test.go │ │ ├── stub.go │ │ ├── stub_test.go │ │ ├── templates/ │ │ │ ├── README.md.tpl │ │ │ ├── extension.c.tpl │ │ │ ├── extension.go.tpl │ │ │ ├── extension.h.tpl │ │ │ └── stub.php.tpl │ │ ├── utils.go │ │ ├── utils_namespace_test.go │ │ ├── utils_test.go │ │ ├── validator.go │ │ └── validator_test.go │ ├── fastabs/ │ │ ├── filepath.go │ │ └── filepath_unix.go │ ├── memory/ │ │ ├── memory_linux.go │ │ └── memory_others.go │ ├── phpheaders/ │ │ ├── phpheaders.go │ │ └── phpheaders_test.go │ ├── state/ │ │ ├── state.go │ │ └── state_test.go │ ├── testcli/ │ │ └── main.go │ ├── testext/ │ │ ├── ext_test.go │ │ ├── extension.h │ │ ├── extensions.c │ │ ├── exttest.go │ │ └── testdata/ │ │ └── index.php │ ├── testserver/ │ │ └── main.go │ └── watcher/ │ ├── pattern.go │ ├── pattern_test.go │ └── watcher.go ├── log_test.go ├── mercure-skip.go ├── mercure.go ├── mercure_test.go ├── metrics.go ├── metrics_test.go ├── options.go ├── package/ │ ├── Caddyfile │ ├── alpine/ │ │ ├── frankenphp.openrc │ │ ├── post-deinstall.sh │ │ ├── post-install.sh │ │ └── pre-deinstall.sh │ ├── content/ │ │ └── index.php │ ├── debian/ │ │ ├── frankenphp.service │ │ ├── postinst.sh │ │ ├── postrm.sh │ │ └── prerm.sh │ └── rhel/ │ ├── frankenphp.service │ ├── postinstall.sh │ ├── postuninstall.sh │ ├── preinstall.sh │ └── preuninstall.sh ├── phpmainthread.go ├── phpmainthread_test.go ├── phpthread.go ├── recorder_test.go ├── release.sh ├── reload_test.sh ├── requestoptions.go ├── requestoptions_test.go ├── scaling.go ├── scaling_test.go ├── static-builder-gnu.Dockerfile ├── static-builder-musl.Dockerfile ├── testdata/ │ ├── Caddyfile │ ├── _executor.php │ ├── autoloader-require.php │ ├── autoloader.php │ ├── benchmark.Caddyfile │ ├── command.php │ ├── connection_status.php │ ├── cookies.php │ ├── dd.php │ ├── die.php │ ├── dirindex/ │ │ └── index.php │ ├── early-hints.php │ ├── echo.php │ ├── env/ │ │ ├── env.php │ │ ├── import-env.php │ │ ├── overwrite-env.php │ │ ├── putenv.php │ │ ├── remember-env.php │ │ └── test-env.php │ ├── exception.php │ ├── failing-worker.php │ ├── fiber-basic.php │ ├── fiber-no-cgo.php │ ├── file-stream.php │ ├── file-stream.txt │ ├── file-upload.php │ ├── files/ │ │ ├── .gitignore │ │ └── static.txt │ ├── finish-request.php │ ├── flush.php │ ├── headers.php │ ├── hello.php │ ├── hello.txt │ ├── index.php │ ├── ini.php │ ├── input.php │ ├── integration/ │ │ ├── basic_function.go │ │ ├── callable.go │ │ ├── class_methods.go │ │ ├── constants.go │ │ ├── invalid_signature.go │ │ ├── namespace.go │ │ └── type_mismatch.go │ ├── large-request.php │ ├── large-response.php │ ├── load-test.js │ ├── log-error_log.php │ ├── log-frankenphp_log.php │ ├── mercure-publish.php │ ├── message-worker.php │ ├── non-worker.php │ ├── only-headers.php │ ├── performance/ │ │ ├── api.js │ │ ├── computation.js │ │ ├── database.js │ │ ├── flamegraph.sh │ │ ├── hanging-requests.js │ │ ├── hello-world.js │ │ ├── k6.Caddyfile │ │ ├── perf-test.sh │ │ ├── performance-testing.md │ │ ├── start-server.sh │ │ └── timeouts.js │ ├── persistent-object-require.php │ ├── persistent-object.php │ ├── phpinfo.php │ ├── preload-check.php │ ├── preload.php │ ├── request-headers.php │ ├── request-superglobal-conditional-include.php │ ├── request-superglobal-conditional.php │ ├── request-superglobal.php │ ├── response-headers.php │ ├── server-all-vars-ordered.php │ ├── server-all-vars-ordered.txt │ ├── server-variable.php │ ├── session-handler.php │ ├── session-leak.php │ ├── session.php │ ├── sleep.php │ ├── super-globals.php │ ├── symlinks/ │ │ └── test/ │ │ ├── document-root.php │ │ ├── index.php │ │ └── nested/ │ │ └── index.php │ ├── timeout.php │ ├── transition-regular.php │ ├── transition-worker-1.php │ ├── transition-worker-2.php │ ├── worker-env.php │ ├── worker-getopt.php │ ├── worker-restart.php │ ├── worker-with-counter.php │ ├── worker-with-env.php │ ├── worker-with-session-handler.php │ └── worker.php ├── threadinactive.go ├── threadregular.go ├── threadtasks_test.go ├── threadworker.go ├── types.c ├── types.go ├── types.h ├── types_test.go ├── vcpkg.json ├── watcher-skip.go ├── watcher.go ├── watcher_test.go ├── worker.go ├── worker_test.go ├── workerextension.go ├── workerextension_test.go └── zizmor.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format-ignore ================================================ frankenphp_arginfo.h ================================================ FILE: .codespellrc ================================================ [codespell] check-hidden = skip = .git,docs/*/*,docs,*/go.mod,*/go.sum,./internal/phpheaders/phpheaders.go ================================================ FILE: .dockerignore ================================================ /caddy/frankenphp/frankenphp /internal/testserver/testserver /internal/testcli/testcli /dist .DS_Store .idea/ .vscode/ __debug_bin frankenphp.test caddy/frankenphp/Build *.log ================================================ FILE: .editorconfig ================================================ root = true [*] end_of_line = lf insert_final_newline = true [*.{sh,Dockerfile}] indent_style = tab tab_width = 4 [*.{yaml,yml}] indent_style = space tab_width = 2 ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yaml ================================================ --- name: Bug Report description: File a bug report labels: [bug] body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! Before submitting, please ensure that your issue: * Is not [a known issue](https://frankenphp.dev/docs/known-issues/). * Has not [already been reported](https://github.com/php/frankenphp/issues). * Is not caused by a dependency (like Caddy or PHP itself). If the issue is with a dependency, please report it to the upstream project directly. - type: textarea id: what-happened attributes: label: What happened? description: | Tell us what you do, what you get, and what you expected. Provide us with some step-by-step instructions to reproduce the issue. validations: required: true - type: dropdown id: build attributes: label: Build Type description: What build of FrankenPHP do you use? options: - Docker (Debian Trixie) - Docker (Debian Bookworm) - Docker (Alpine) - apk packages - deb packages - RPM packages - Static binary - Custom (tell us more in the description) default: 0 validations: required: true - type: dropdown id: worker attributes: label: Worker Mode description: Does the problem happen only when using the worker mode? options: - "Yes" - "No" default: 0 validations: required: true - type: dropdown id: os attributes: label: Operating System description: What operating system are you executing FrankenPHP with? options: - GNU/Linux - macOS - Windows - FreeBSD - Other (tell us more in the description) default: 0 validations: required: true - type: dropdown id: arch attributes: label: CPU Architecture description: What CPU architecture are you using? options: - x86_64 - Apple Silicon - x86 - aarch64 - Other (tell us more in the description) default: 0 - type: textarea id: php attributes: label: PHP configuration description: | Please copy and paste the output of the `phpinfo()` function -- remember to remove **sensitive information** like passwords, API keys, etc. render: shell validations: required: true - type: textarea id: logs attributes: label: Relevant log output description: | Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. render: shell ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yaml ================================================ --- name: Feature Request description: Suggest an idea for this project labels: [enhancement] body: - type: textarea id: description attributes: label: Describe your feature request value: | **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. ================================================ FILE: .github/actions/watcher/action.yaml ================================================ name: watcher description: Install e-dant/watcher runs: using: composite steps: - name: Determine e-dant/watcher version id: determine-watcher-version run: echo version="$(gh release view --repo e-dant/watcher --json tagName --template '{{ .tagName }}')" >> "${GITHUB_OUTPUT}" shell: bash env: GH_TOKEN: ${{ github.token }} - name: Cache e-dant/watcher id: cache-watcher uses: actions/cache@v4 with: path: watcher/target key: watcher-${{ runner.os }}-${{ runner.arch }}-${{ steps.determine-watcher-version.outputs.version }}-${{ env.CC && env.CC || 'gcc' }} - if: steps.cache-watcher.outputs.cache-hit != 'true' name: Compile e-dant/watcher run: | mkdir watcher gh release download --repo e-dant/watcher -A tar.gz -O - | tar -xz -C watcher --strip-components 1 cd watcher cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build sudo cmake --install build --prefix target shell: bash env: GH_TOKEN: ${{ github.token }} - name: Update LD_LIBRARY_PATH run: | sudo sh -c "echo ${PWD}/watcher/target/lib > /etc/ld.so.conf.d/watcher.conf" sudo ldconfig shell: bash ================================================ FILE: .github/dependabot.yaml ================================================ --- version: 2 updates: - package-ecosystem: gomod directory: / schedule: interval: weekly commit-message: prefix: chore groups: go-modules: patterns: - "*" cooldown: default-days: 7 - package-ecosystem: gomod directory: /caddy schedule: interval: weekly commit-message: prefix: chore(caddy) groups: go-modules: patterns: - "*" cooldown: default-days: 7 - package-ecosystem: github-actions directory: / schedule: interval: weekly commit-message: prefix: ci groups: github-actions: patterns: - "*" cooldown: default-days: 7 ================================================ FILE: .github/scripts/docker-compute-fingerprints.sh ================================================ #!/usr/bin/env bash set -euo pipefail write_output() { if [[ -n "${GITHUB_OUTPUT:-}" ]]; then echo "$1" >>"${GITHUB_OUTPUT}" else echo "$1" fi } get_php_version() { local version="$1" skopeo inspect "docker://docker.io/library/php:${version}" \ --override-os linux \ --override-arch amd64 | jq -r '.Env[] | select(test("^PHP_VERSION=")) | sub("^PHP_VERSION="; "")' } PHP_82_LATEST="$(get_php_version 8.2)" PHP_83_LATEST="$(get_php_version 8.3)" PHP_84_LATEST="$(get_php_version 8.4)" PHP_85_LATEST="$(get_php_version 8.5)" PHP_VERSION="${PHP_82_LATEST},${PHP_83_LATEST},${PHP_84_LATEST},${PHP_85_LATEST}" write_output "php_version=${PHP_VERSION}" write_output "php82_version=${PHP_82_LATEST//./-}" write_output "php83_version=${PHP_83_LATEST//./-}" write_output "php84_version=${PHP_84_LATEST//./-}" write_output "php85_version=${PHP_85_LATEST//./-}" if [[ "${GITHUB_EVENT_NAME:-}" == "schedule" ]]; then FRANKENPHP_LATEST_TAG="$(gh release view --repo php/frankenphp --json tagName --jq '.tagName')" git checkout "${FRANKENPHP_LATEST_TAG}" fi METADATA="$(PHP_VERSION="${PHP_VERSION}" docker buildx bake --print | jq -c)" BASE_IMAGES=() while IFS= read -r image; do BASE_IMAGES+=("${image}") done < <(jq -r ' .target[]?.contexts? | to_entries[]? | select(.value | startswith("docker-image://")) | .value | sub("^docker-image://"; "") ' <<<"${METADATA}" | sort -u) BASE_IMAGE_DIGESTS=() for image in "${BASE_IMAGES[@]}"; do if [[ "${image}" == */* ]]; then ref="docker://docker.io/${image}" else ref="docker://docker.io/library/${image}" fi digest="$(skopeo inspect "${ref}" \ --override-os linux \ --override-arch amd64 \ --format '{{.Digest}}')" BASE_IMAGE_DIGESTS+=("${image}@${digest}") done BASE_FINGERPRINT="$(printf '%s\n' "${BASE_IMAGE_DIGESTS[@]}" | sort | sha256sum | awk '{print $1}')" write_output "base_fingerprint=${BASE_FINGERPRINT}" if [[ "${GITHUB_EVENT_NAME:-}" != "schedule" ]]; then write_output "skip=false" exit 0 fi FRANKENPHP_LATEST_TAG_NO_PREFIX="${FRANKENPHP_LATEST_TAG#v}" EXISTING_FINGERPRINT=$( skopeo inspect "docker://docker.io/dunglas/frankenphp:${FRANKENPHP_LATEST_TAG_NO_PREFIX}" \ --override-os linux \ --override-arch amd64 | jq -r '.Labels["dev.frankenphp.base.fingerprint"] // empty' ) if [[ -n "${EXISTING_FINGERPRINT}" ]] && [[ "${EXISTING_FINGERPRINT}" == "${BASE_FINGERPRINT}" ]]; then write_output "skip=true" exit 0 fi write_output "ref=${FRANKENPHP_LATEST_TAG}" write_output "skip=false" ================================================ FILE: .github/scripts/docker-verify-fingerprints.sh ================================================ #!/usr/bin/env bash set -euo pipefail PHP_VERSION="${PHP_VERSION:-}" GO_VERSION="${GO_VERSION:-}" USE_LATEST_PHP="${USE_LATEST_PHP:-0}" if [[ -z "${GO_VERSION}" ]]; then GO_VERSION="$(awk -F'"' '/variable "GO_VERSION"/ {f=1} f && /default/ {print $2; exit}' docker-bake.hcl)" GO_VERSION="${GO_VERSION:-1.26}" fi if [[ -z "${PHP_VERSION}" ]]; then PHP_VERSION="$(awk -F'"' '/variable "PHP_VERSION"/ {f=1} f && /default/ {print $2; exit}' docker-bake.hcl)" PHP_VERSION="${PHP_VERSION:-8.2,8.3,8.4,8.5}" fi if [[ "${USE_LATEST_PHP}" == "1" ]]; then PHP_82_LATEST=$(skopeo inspect docker://docker.io/library/php:8.2 --override-os linux --override-arch amd64 | jq -r '.Env[] | select(test("^PHP_VERSION=")) | sub("^PHP_VERSION="; "")') PHP_83_LATEST=$(skopeo inspect docker://docker.io/library/php:8.3 --override-os linux --override-arch amd64 | jq -r '.Env[] | select(test("^PHP_VERSION=")) | sub("^PHP_VERSION="; "")') PHP_84_LATEST=$(skopeo inspect docker://docker.io/library/php:8.4 --override-os linux --override-arch amd64 | jq -r '.Env[] | select(test("^PHP_VERSION=")) | sub("^PHP_VERSION="; "")') PHP_85_LATEST=$(skopeo inspect docker://docker.io/library/php:8.5 --override-os linux --override-arch amd64 | jq -r '.Env[] | select(test("^PHP_VERSION=")) | sub("^PHP_VERSION="; "")') PHP_VERSION="${PHP_82_LATEST},${PHP_83_LATEST},${PHP_84_LATEST},${PHP_85_LATEST}" fi OS_LIST=() while IFS= read -r os; do OS_LIST+=("${os}") done < <( python3 - <<'PY' import re with open("docker-bake.hcl", "r", encoding="utf-8") as f: data = f.read() # Find the first "os = [ ... ]" block and extract quoted values m = re.search(r'os\s*=\s*\[(.*?)\]', data, re.S) if not m: raise SystemExit(1) vals = re.findall(r'"([^"]+)"', m.group(1)) for v in vals: print(v) PY ) IFS=',' read -r -a PHP_VERSIONS <<<"${PHP_VERSION}" BASE_IMAGES=() for os in "${OS_LIST[@]}"; do BASE_IMAGES+=("golang:${GO_VERSION}-${os}") for pv in "${PHP_VERSIONS[@]}"; do BASE_IMAGES+=("php:${pv}-zts-${os}") done done mapfile -t BASE_IMAGES < <(printf '%s\n' "${BASE_IMAGES[@]}" | sort -u) BASE_IMAGE_DIGESTS=() for image in "${BASE_IMAGES[@]}"; do if [[ "${image}" == */* ]]; then ref="docker://docker.io/${image}" else ref="docker://docker.io/library/${image}" fi digest="$(skopeo inspect "${ref}" --override-os linux --override-arch amd64 --format '{{.Digest}}')" BASE_IMAGE_DIGESTS+=("${image}@${digest}") done hash_cmd="sha256sum" if ! command -v "${hash_cmd}" >/dev/null 2>&1; then hash_cmd="shasum -a 256" fi fingerprint="$(printf '%s\n' "${BASE_IMAGE_DIGESTS[@]}" | sort | ${hash_cmd} | awk '{print $1}')" echo "PHP_VERSION=${PHP_VERSION}" echo "GO_VERSION=${GO_VERSION}" echo "OS_LIST=${OS_LIST[*]}" echo "Base images:" printf ' %s\n' "${BASE_IMAGES[@]}" echo "Fingerprint: ${fingerprint}" ================================================ FILE: .github/workflows/docker.yaml ================================================ --- name: Build Docker Images concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main paths: - "docker-bake.hcl" - ".github/workflows/docker.yaml" - "**cgo.go" - "**Dockerfile" - "**.c" - "**.h" - "**.sh" - "**.stub.php" push: branches: - main tags: - v*.*.* workflow_dispatch: inputs: #checkov:skip=CKV_GHA_7 version: description: "FrankenPHP version" required: false type: string schedule: - cron: "0 4 * * *" permissions: contents: read env: IMAGE_NAME: ${{ (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.version) || startsWith(github.ref, 'refs/tags/')) && 'dunglas/frankenphp' || 'dunglas/frankenphp-dev' }} jobs: prepare: runs-on: ubuntu-24.04 outputs: # Push if it's a scheduled job, a tag, or if we're committing to the main branch push: ${{ (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.version) || startsWith(github.ref, 'refs/tags/') || (github.ref == 'refs/heads/main' && github.event_name != 'pull_request')) && true || false }} variants: ${{ steps.matrix.outputs.variants }} platforms: ${{ steps.matrix.outputs.platforms }} metadata: ${{ steps.matrix.outputs.metadata }} php_version: ${{ steps.check.outputs.php_version }} php82_version: ${{ steps.check.outputs.php82_version }} php83_version: ${{ steps.check.outputs.php83_version }} php84_version: ${{ steps.check.outputs.php84_version }} php85_version: ${{ steps.check.outputs.php85_version }} skip: ${{ steps.check.outputs.skip }} ref: ${{ steps.check.outputs.ref || (github.event_name == 'workflow_dispatch' && inputs.version) || '' }} base_fingerprint: ${{ steps.check.outputs.base_fingerprint }} steps: - uses: actions/checkout@v6 with: fetch-depth: 0 persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - name: Check PHP versions and base image fingerprint id: check env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: ./.github/scripts/docker-compute-fingerprints.sh - name: Create variants matrix if: ${{ !fromJson(steps.check.outputs.skip) }} id: matrix shell: bash run: | set -e METADATA="$(docker buildx bake --print | jq -c)" { echo metadata="${METADATA}" echo variants="$(jq -c '.group.default.targets|map(sub("runner-|builder-"; ""))|unique' <<< "${METADATA}")" echo platforms="$(jq -c 'first(.target[]) | .platforms' <<< "${METADATA}")" } >> "${GITHUB_OUTPUT}" env: SHA: ${{ github.sha }} VERSION: ${{ (github.ref_type == 'tag' && github.ref_name) || steps.check.outputs.ref || 'dev' }} PHP_VERSION: ${{ steps.check.outputs.php_version }} build: runs-on: ${{ startsWith(matrix.platform, 'linux/arm') && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} needs: - prepare if: ${{ !fromJson(needs.prepare.outputs.skip) }} strategy: fail-fast: false matrix: variant: ${{ fromJson(needs.prepare.outputs.variants) }} platform: ${{ fromJson(needs.prepare.outputs.platforms) }} include: - race: "" - platform: linux/amd64 race: "-race" # The Go race detector is only supported on amd64 exclude: # arm/v6 is only available for Alpine: https://github.com/docker-library/golang/issues/502 - variant: php-${{ needs.prepare.outputs.php82_version }}-trixie platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php83_version }}-trixie platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php84_version }}-trixie platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php85_version }}-trixie platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php82_version }}-bookworm platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php83_version }}-bookworm platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php84_version }}-bookworm platform: linux/arm/v6 - variant: php-${{ needs.prepare.outputs.php85_version }}-bookworm platform: linux/arm/v6 steps: - name: Prepare id: prepare run: echo "sanitized_platform=${PLATFORM//\//-}" >> "${GITHUB_OUTPUT}" env: PLATFORM: ${{ matrix.platform }} - uses: actions/checkout@v6 with: ref: ${{ needs.prepare.outputs.ref }} persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 with: platforms: ${{ matrix.platform }} - name: Login to DockerHub uses: docker/login-action@v4 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository with: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - name: Build id: build uses: docker/bake-action@v7 with: pull: true load: ${{ !fromJson(needs.prepare.outputs.push) }} source: . targets: | builder-${{ matrix.variant }} runner-${{ matrix.variant }} # Remove tags to prevent "can't push tagged ref [...] by digest" error set: | ${{ (github.event_name == 'pull_request') && '*.args.NO_COMPRESS=1' || '' }} *.tags= *.platform=${{ matrix.platform }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('builder-{0}.cache-from=type=gha,scope=builder-{0}-{1}-{2}', matrix.variant, needs.prepare.outputs.ref || github.ref, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('builder-{0}.cache-from=type=gha,scope=refs/heads/main-builder-{0}-{1}', matrix.variant, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('builder-{0}.cache-to=type=gha,scope=builder-{0}-{1}-{2},ignore-error=true', matrix.variant, needs.prepare.outputs.ref || github.ref, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('runner-{0}.cache-from=type=gha,scope=runner-{0}-{1}-{2}', matrix.variant, needs.prepare.outputs.ref || github.ref, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('runner-{0}.cache-from=type=gha,scope=refs/heads/main-runner-{0}-{1}', matrix.variant, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('runner-{0}.cache-to=type=gha,scope=runner-{0}-{1}-{2},ignore-error=true', matrix.variant, needs.prepare.outputs.ref || github.ref, matrix.platform) }} ${{ fromJson(needs.prepare.outputs.push) && format('*.output=type=image,name={0},push-by-digest=true,name-canonical=true,push=true', env.IMAGE_NAME) || '' }} env: SHA: ${{ github.sha }} VERSION: ${{ (github.ref_type == 'tag' && github.ref_name) || needs.prepare.outputs.ref || 'dev' }} PHP_VERSION: ${{ needs.prepare.outputs.php_version }} BASE_FINGERPRINT: ${{ needs.prepare.outputs.base_fingerprint }} - # Workaround for https://github.com/actions/runner/pull/2477#issuecomment-1501003600 name: Export metadata if: fromJson(needs.prepare.outputs.push) run: | mkdir -p /tmp/metadata/builder /tmp/metadata/runner builderDigest=$(jq -r ".\"builder-${VARIANT}\".\"containerimage.digest\"" <<< "${METADATA}") touch "/tmp/metadata/builder/${builderDigest#sha256:}" runnerDigest=$(jq -r ".\"runner-${VARIANT}\".\"containerimage.digest\"" <<< "${METADATA}") touch "/tmp/metadata/runner/${runnerDigest#sha256:}" env: METADATA: ${{ steps.build.outputs.metadata }} VARIANT: ${{ matrix.variant }} - name: Upload builder metadata if: fromJson(needs.prepare.outputs.push) uses: actions/upload-artifact@v7 with: name: metadata-builder-${{ matrix.variant }}-${{ steps.prepare.outputs.sanitized_platform }} path: /tmp/metadata/builder/* if-no-files-found: error retention-days: 1 - name: Upload runner metadata if: fromJson(needs.prepare.outputs.push) uses: actions/upload-artifact@v7 with: name: metadata-runner-${{ matrix.variant }}-${{ steps.prepare.outputs.sanitized_platform }} path: /tmp/metadata/runner/* if-no-files-found: error retention-days: 1 - name: Run tests if: ${{ !fromJson(needs.prepare.outputs.push) }} run: | # TODO: remove "containerimage.config.digest" fallback once all runners use buildx v0.18+ # which replaced it with "containerimage.digest" and "containerimage.descriptor" docker run --platform="${PLATFORM}" --rm \ "$(jq -r ".\"builder-${VARIANT}\" | .\"containerimage.config.digest\" // .\"containerimage.digest\"" <<< "${METADATA}")" \ sh -c "./go.sh test ${RACE} -v $(./go.sh list ./... | grep -v github.com/dunglas/frankenphp/internal/testext | grep -v github.com/dunglas/frankenphp/internal/extgen | tr '\n' ' ') && cd caddy && ../go.sh test ${RACE} -v ./..." env: METADATA: ${{ steps.build.outputs.metadata }} PLATFORM: ${{ matrix.platform }} VARIANT: ${{ matrix.variant }} RACE: ${{ matrix.race }} # Adapted from https://docs.docker.com/build/ci/github-actions/multi-platform/ push: runs-on: ubuntu-24.04 needs: - prepare - build if: fromJson(needs.prepare.outputs.push) strategy: fail-fast: false matrix: variant: ${{ fromJson(needs.prepare.outputs.variants) }} target: ["builder", "runner"] steps: - name: Download metadata uses: actions/download-artifact@v8 with: pattern: metadata-${{ matrix.target }}-${{ matrix.variant }}-* path: /tmp/metadata merge-multiple: true - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - name: Login to DockerHub uses: docker/login-action@v4 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository with: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - name: Create manifest list and push working-directory: /tmp/metadata run: | set -x # shellcheck disable=SC2046,SC2086 docker buildx imagetools create $(jq -cr ".target.\"${TARGET}-${VARIANT}\".tags | map(\"-t \" + .) | join(\" \")" <<< ${METADATA}) \ $(printf "${IMAGE_NAME}@sha256:%s " *) env: METADATA: ${{ needs.prepare.outputs.metadata }} TARGET: ${{ matrix.target }} VARIANT: ${{ matrix.variant }} - name: Inspect image run: | # shellcheck disable=SC2046,SC2086 docker buildx imagetools inspect $(jq -cr ".target.\"${TARGET}-${VARIANT}\".tags | first" <<< ${METADATA}) env: METADATA: ${{ needs.prepare.outputs.metadata }} TARGET: ${{ matrix.target }} VARIANT: ${{ matrix.variant }} ================================================ FILE: .github/workflows/docs.yaml ================================================ --- name: Deploy Docs on: push: branches: - main paths: - "docs/**" - "README.md" - "CONTRIBUTING.md" - "install.ps1" - "install.sh" permissions: {} concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: deploy: runs-on: ubuntu-slim steps: - name: Trigger website deployment env: GH_TOKEN: ${{ secrets.WEBSITE_DEPLOY_TOKEN }} run: gh api repos/dunglas/frankenphp-website/actions/workflows/hugo.yaml/dispatches -f ref=main ================================================ FILE: .github/workflows/lint.yaml ================================================ --- name: Lint Code Base concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main push: branches: - main permissions: contents: read packages: read statuses: write jobs: build: name: Lint Code Base runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v6 with: fetch-depth: 0 persist-credentials: false - name: Lint Code Base uses: super-linter/super-linter/slim@v8 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} LINTER_RULES_PATH: / MARKDOWN_CONFIG_FILE: .markdown-lint.yaml FILTER_REGEX_EXCLUDE: docs/(cn|es|fr|ja|pt-br|ru|tr)/ VALIDATE_CPP: false VALIDATE_JSCPD: false VALIDATE_GO: false VALIDATE_GO_MODULES: false VALIDATE_PHP_PHPCS: false VALIDATE_PHP_PHPSTAN: false VALIDATE_PHP_PSALM: false VALIDATE_TERRAGRUNT: false VALIDATE_DOCKERFILE_HADOLINT: false VALIDATE_TRIVY: false # Prettier, Biome and StandardJS are incompatible VALIDATE_JAVASCRIPT_PRETTIER: false VALIDATE_TYPESCRIPT_PRETTIER: false VALIDATE_BIOME_FORMAT: false VALIDATE_BIOME_LINT: false # Conflicts with MARKDOWN VALIDATE_MARKDOWN_PRETTIER: false # To re-enable when https://github.com/super-linter/super-linter/issues/7466 will be closed VALIDATE_SPELL_CODESPELL: false ================================================ FILE: .github/workflows/sanitizers.yaml ================================================ --- name: Sanitizers concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main paths-ignore: - "docs/**" push: branches: - main paths-ignore: - "docs/**" permissions: contents: read env: GOTOOLCHAIN: local jobs: # Adapted from https://github.com/beberlei/hdrhistogram-php sanitizers: name: ${{ matrix.sanitizer }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: sanitizer: ["asan", "msan"] env: CFLAGS: -g -O0 -fsanitize=${{ matrix.sanitizer == 'asan' && 'address' || 'memory' }} -DZEND_TRACK_ARENA_ALLOC LDFLAGS: -fsanitize=${{ matrix.sanitizer == 'asan' && 'address' || 'memory' }} CC: clang CXX: clang++ USE_ZEND_ALLOC: 0 LIBRARY_PATH: ${{ github.workspace }}/php/target/lib:${{ github.workspace }}/watcher/target/lib LD_LIBRARY_PATH: ${{ github.workspace }}/php/target/lib # PHP doesn't free some memory on purpose, we have to disable leaks detection: https://go.dev/doc/go1.26#go-command ASAN_OPTIONS: detect_leaks=0 steps: - name: Remove local PHP run: sudo apt-get remove --purge --autoremove 'php*' 'libmemcached*' - uses: actions/checkout@v6 with: persist-credentials: false - uses: actions/setup-go@v6 with: go-version: "1.26" cache-dependency-path: | go.sum caddy/go.sum - name: Determine PHP version id: determine-php-version run: | curl -fsSL 'https://www.php.net/releases/index.php?json&max=1&version=8.5' -o version.json 2>/dev/null || curl -fsSL 'https://phpmirror.static-php.dev/releases/index.php?json&max=1&version=8.5' -o version.json echo version="$(jq -r 'keys[0]' version.json)" >> "$GITHUB_OUTPUT" echo archive="$(jq -r '.[] .source[] | select(.filename |endswith(".xz")) | "https://www.php.net/distributions/" + .filename' version.json)" >> "$GITHUB_OUTPUT" - name: Cache PHP id: cache-php uses: actions/cache@v5 with: path: php/target key: php-sanitizers-${{ matrix.sanitizer }}-${{ runner.arch }}-${{ steps.determine-php-version.outputs.version }} - if: steps.cache-php.outputs.cache-hit != 'true' name: Compile PHP run: | mkdir php/ MIRROR_URL=${URL/https:\/\/www.php.net/https:\/\/phpmirror.static-php.dev} (curl -fsSL "${URL}" || curl -fsSL "${MIRROR_URL}") | tar -Jx -C php --strip-components=1 cd php/ ./configure \ CFLAGS="$CFLAGS" \ LDFLAGS="$LDFLAGS" \ --enable-debug \ --enable-embed \ --enable-zts \ --enable-option-checking=fatal \ --disable-zend-signals \ --without-sqlite3 \ --without-pdo-sqlite \ --without-libxml \ --disable-dom \ --disable-simplexml \ --disable-xml \ --disable-xmlreader \ --disable-xmlwriter \ --without-pcre-jit \ --disable-opcache-jit \ --disable-cli \ --disable-cgi \ --disable-phpdbg \ --without-pear \ --disable-mbregex \ --enable-werror \ ${{ matrix.sanitizer == 'msan' && '--enable-memory-sanitizer' || '' }} \ --prefix="$(pwd)/target/" make -j"$(getconf _NPROCESSORS_ONLN)" make install env: URL: ${{ steps.determine-php-version.outputs.archive }} - name: Add PHP to the PATH run: echo "$(pwd)/php/target/bin" >> "$GITHUB_PATH" - name: Install e-dant/watcher uses: ./.github/actions/watcher - name: Set Set CGO flags run: | { echo "CGO_CFLAGS=$CFLAGS -I${PWD}/watcher/target/include $(php-config --includes)" echo "CGO_LDFLAGS=$LDFLAGS $(php-config --ldflags) $(php-config --libs)" } >> "$GITHUB_ENV" - name: Compile tests run: go test ${{ matrix.sanitizer == 'msan' && '-tags=nowatcher' || '' }} -${{ matrix.sanitizer }} -v -x -c - name: Run tests run: ./frankenphp.test -test.v ================================================ FILE: .github/workflows/static.yaml ================================================ --- name: Build binary releases concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main paths: - "docker-bake.hcl" - ".github/workflows/static.yaml" - "**cgo.go" - "**Dockerfile" - "**.c" - "**.h" - "**.sh" - "**.stub.php" push: branches: - main tags: - v*.*.* workflow_dispatch: inputs: #checkov:skip=CKV_GHA_7 version: description: "FrankenPHP version" required: false type: string schedule: - cron: "0 0 * * *" permissions: contents: read env: IMAGE_NAME: ${{ (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.version) || startsWith(github.ref, 'refs/tags/')) && 'dunglas/frankenphp' || 'dunglas/frankenphp-dev' }} SPC_OPT_BUILD_ARGS: --debug GOTOOLCHAIN: local jobs: prepare: runs-on: ubuntu-24.04 outputs: push: ${{ toJson((steps.check.outputs.ref || (github.event_name == 'workflow_dispatch' && inputs.version) || startsWith(github.ref, 'refs/tags/') || (github.ref == 'refs/heads/main' && github.event_name != 'pull_request')) && true || false) }} platforms: ${{ steps.matrix.outputs.platforms }} metadata: ${{ steps.matrix.outputs.metadata }} gnu_metadata: ${{ steps.matrix.outputs.gnu_metadata }} ref: ${{ steps.check.outputs.ref }} steps: - name: Get version id: check if: github.event_name == 'schedule' run: | ref="${REF}" if [[ -z "${ref}" ]]; then ref="$(gh release view --repo dunglas/frankenphp --json tagName --jq '.tagName')" fi echo "ref=${ref}" >> "${GITHUB_OUTPUT}" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} REF: ${{ (github.ref_type == 'tag' && github.ref_name) || (github.event_name == 'workflow_dispatch' && inputs.version) || '' }} - uses: actions/checkout@v6 with: ref: ${{ steps.check.outputs.ref }} persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - name: Create platforms matrix id: matrix run: | METADATA="$(docker buildx bake --print static-builder-musl | jq -c)" GNU_METADATA="$(docker buildx bake --print static-builder-gnu | jq -c)" { echo metadata="${METADATA}" echo platforms="$(jq -c 'first(.target[]) | .platforms' <<< "${METADATA}")" echo gnu_metadata="${GNU_METADATA}" } >> "${GITHUB_OUTPUT}" env: SHA: ${{ github.sha }} VERSION: ${{ steps.check.outputs.ref || 'dev' }} build-linux-musl: permissions: contents: write id-token: write attestations: write strategy: fail-fast: false matrix: platform: ${{ fromJson(needs.prepare.outputs.platforms) }} debug: [false] mimalloc: [false] include: - platform: linux/amd64 - platform: linux/amd64 debug: true - platform: linux/amd64 mimalloc: true name: Build ${{ matrix.platform }} static musl binary${{ matrix.debug && ' (debug)' || '' }}${{ matrix.mimalloc && ' (mimalloc)' || '' }} runs-on: ${{ startsWith(matrix.platform, 'linux/arm') && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} needs: [prepare] steps: - name: Prepare id: prepare run: echo "sanitized_platform=${PLATFORM//\//-}" >> "${GITHUB_OUTPUT}" env: PLATFORM: ${{ matrix.platform }} - uses: actions/checkout@v6 with: ref: ${{ needs.prepare.outputs.ref }} persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 with: platforms: ${{ matrix.platform }} - name: Login to DockerHub uses: docker/login-action@v4 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository with: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - name: Set VERSION run: | if [ "${GITHUB_REF_TYPE}" == "tag" ]; then export VERSION=${GITHUB_REF_NAME:1} elif [ "${GITHUB_EVENT_NAME}" == "schedule" ]; then export VERSION="${REF}" else export VERSION=${GITHUB_SHA} fi echo "VERSION=${VERSION}" >> "${GITHUB_ENV}" env: REF: ${{ needs.prepare.outputs.ref }} - name: Build id: build uses: docker/bake-action@v7 with: pull: true load: ${{ !fromJson(needs.prepare.outputs.push) || matrix.debug || matrix.mimalloc }} source: . targets: static-builder-musl set: | ${{ matrix.debug && 'static-builder-musl.args.DEBUG_SYMBOLS=1' || '' }} ${{ matrix.mimalloc && 'static-builder-musl.args.MIMALLOC=1' || '' }} ${{ (github.event_name == 'pull_request' || matrix.platform == 'linux/arm64') && 'static-builder-musl.args.NO_COMPRESS=1' || '' }} *.tags= *.platform=${{ matrix.platform }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('*.cache-from=type=gha,scope={0}-static-builder-musl{1}{2}', needs.prepare.outputs.ref || github.ref, matrix.debug && '-debug' || '', matrix.mimalloc && '-mimalloc' || '') }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('*.cache-from=type=gha,scope=refs/heads/main-static-builder-musl{0}{1}', matrix.debug && '-debug' || '', matrix.mimalloc && '-mimalloc' || '') }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('*.cache-to=type=gha,scope={0}-static-builder-musl{1}{2},ignore-error=true', needs.prepare.outputs.ref || github.ref, matrix.debug && '-debug' || '', matrix.mimalloc && '-mimalloc' || '') }} ${{ (fromJson(needs.prepare.outputs.push) && !matrix.debug && !matrix.mimalloc) && format('*.output=type=image,name={0},push-by-digest=true,name-canonical=true,push=true', env.IMAGE_NAME) || '' }} env: SHA: ${{ github.sha }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Workaround for https://github.com/actions/runner/pull/2477#issuecomment-1501003600 name: Export metadata if: fromJson(needs.prepare.outputs.push) && !matrix.debug && !matrix.mimalloc run: | mkdir -p /tmp/metadata # shellcheck disable=SC2086 digest=$(jq -r '."static-builder-musl"."containerimage.digest"' <<< ${METADATA}) touch "/tmp/metadata/${digest#sha256:}" env: METADATA: ${{ steps.build.outputs.metadata }} - name: Upload metadata if: fromJson(needs.prepare.outputs.push) && !matrix.debug && !matrix.mimalloc uses: actions/upload-artifact@v7 with: name: metadata-static-builder-musl-${{ steps.prepare.outputs.sanitized_platform }} path: /tmp/metadata/* if-no-files-found: error retention-days: 1 - name: Copy binary run: | # shellcheck disable=SC2034 # TODO: remove "containerimage.config.digest" fallback once all runners use buildx v0.18+ # which replaced it with "containerimage.digest" and "containerimage.descriptor" digest=$(jq -r '."static-builder-musl" | ${{ (fromJson(needs.prepare.outputs.push) && !matrix.debug && !matrix.mimalloc) && '."containerimage.digest"' || '(."containerimage.config.digest" // ."containerimage.digest")' }}' <<< "${METADATA}") docker create --platform="${PLATFORM}" --name static-builder-musl "${{ (fromJson(needs.prepare.outputs.push) && !matrix.debug && !matrix.mimalloc) && '${IMAGE_NAME}@${digest}' || '${digest}' }}" docker cp "static-builder-musl:/go/src/app/dist/${BINARY}" "${BINARY}${{ matrix.debug && '-debug' || '' }}${{ matrix.mimalloc && '-mimalloc' || '' }}" env: METADATA: ${{ steps.build.outputs.metadata }} BINARY: frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }} PLATFORM: ${{ matrix.platform }} - name: Upload artifact if: ${{ !fromJson(needs.prepare.outputs.push) }} uses: actions/upload-artifact@v7 with: name: frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}${{ matrix.debug && '-debug' || '' }}${{ matrix.mimalloc && '-mimalloc' || '' }} path: frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}${{ matrix.debug && '-debug' || '' }}${{ matrix.mimalloc && '-mimalloc' || '' }} compression-level: 0 - name: Upload assets if: fromJson(needs.prepare.outputs.push) && (needs.prepare.outputs.ref || github.ref_type == 'tag') run: gh release upload "${REF}" frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}${{ matrix.debug && '-debug' || '' }}${{ matrix.mimalloc && '-mimalloc' || '' }} --repo dunglas/frankenphp --clobber env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} REF: ${{ (github.ref_type == 'tag' && github.ref_name) || needs.prepare.outputs.ref }} - if: fromJson(needs.prepare.outputs.push) && (needs.prepare.outputs.ref || github.ref_type == 'tag') uses: actions/attest-build-provenance@v4 with: subject-path: ${{ github.workspace }}/frankenphp-linux-* - name: Run sanity checks run: | "${BINARY}" version "${BINARY}" build-info "${BINARY}" list-modules | grep frankenphp "${BINARY}" list-modules | grep http.encoders.br "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.vulcain "${BINARY}" php-cli -r "echo 'Sanity check passed';" env: BINARY: ./frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}${{ matrix.debug && '-debug' || '' }}${{ matrix.mimalloc && '-mimalloc' || '' }} build-linux-gnu: permissions: contents: write id-token: write attestations: write strategy: fail-fast: false matrix: platform: ${{ fromJson(needs.prepare.outputs.platforms) }} name: Build ${{ matrix.platform }} static GNU binary runs-on: ${{ startsWith(matrix.platform, 'linux/arm') && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} needs: [prepare] steps: # Inspired by https://gist.github.com/antiphishfish/1e3fbc3f64ef6f1ab2f47457d2da5d9d and https://github.com/apache/flink/blob/master/tools/azure-pipelines/free_disk_space.sh - name: Free disk space run: | set -xe sudo rm -rf /usr/share/dotnet sudo rm -rf /usr/share/swift sudo rm -rf /usr/local/lib/android sudo rm -rf /opt/ghc sudo rm -rf /usr/local/.ghcup sudo rm -rf "/usr/local/share/boost" sudo rm -rf "$AGENT_TOOLSDIRECTORY" sudo rm -rf /opt/hostedtoolcache/ sudo rm -rf /usr/local/graalvm/ sudo rm -rf /usr/local/share/powershell sudo rm -rf /usr/local/share/chromium sudo rm -rf /usr/local/lib/node_modules sudo docker image prune --all --force APT_PARAMS='sudo apt -y -qq -o=Dpkg::Use-Pty=0' $APT_PARAMS remove -y '^dotnet-.*' $APT_PARAMS remove -y '^llvm-.*' $APT_PARAMS remove -y '^php.*' $APT_PARAMS remove -y '^mongodb-.*' $APT_PARAMS remove -y '^mysql-.*' $APT_PARAMS remove -y azure-cli firefox powershell mono-devel libgl1-mesa-dri $APT_PARAMS autoremove --purge -y $APT_PARAMS autoclean $APT_PARAMS clean - name: Prepare id: prepare run: echo "sanitized_platform=${PLATFORM//\//-}" >> "${GITHUB_OUTPUT}" env: PLATFORM: ${{ matrix.platform }} - uses: actions/checkout@v6 with: ref: ${{ needs.prepare.outputs.ref }} persist-credentials: false - name: Set VERSION run: | if [ "${GITHUB_REF_TYPE}" == "tag" ]; then export VERSION=${GITHUB_REF_NAME:1} elif [ "${GITHUB_EVENT_NAME}" == "schedule" ]; then export VERSION="${REF}" else export VERSION=${GITHUB_SHA} fi echo "VERSION=${VERSION}" >> "${GITHUB_ENV}" env: REF: ${{ needs.prepare.outputs.ref }} - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 with: platforms: ${{ matrix.platform }} - name: Login to DockerHub uses: docker/login-action@v4 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository with: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - name: Build id: build uses: docker/bake-action@v7 with: pull: true load: ${{ !fromJson(needs.prepare.outputs.push) }} source: . targets: static-builder-gnu set: | ${{ (github.event_name == 'pull_request' || matrix.platform == 'linux/arm64') && 'static-builder-gnu.args.NO_COMPRESS=1' || '' }} *.tags= *.platform=${{ matrix.platform }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('*.cache-from=type=gha,scope={0}-static-builder-gnu', needs.prepare.outputs.ref || github.ref) }} ${{ fromJson(needs.prepare.outputs.push) && '' || '*.cache-from=type=gha,scope=refs/heads/main-static-builder-gnu' }} ${{ fromJson(needs.prepare.outputs.push) && '' || format('*.cache-to=type=gha,scope={0}-static-builder-gnu,ignore-error=true', needs.prepare.outputs.ref || github.ref) }} ${{ fromJson(needs.prepare.outputs.push) && format('*.output=type=image,name={0},push-by-digest=true,name-canonical=true,push=true', env.IMAGE_NAME) || '' }} env: SHA: ${{ github.sha }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # Workaround for https://github.com/actions/runner/pull/2477#issuecomment-1501003600 name: Export metadata if: fromJson(needs.prepare.outputs.push) run: | mkdir -p /tmp/metadata-gnu # shellcheck disable=SC2086 digest=$(jq -r '."static-builder-gnu"."containerimage.digest"' <<< ${METADATA}) touch "/tmp/metadata-gnu/${digest#sha256:}" env: METADATA: ${{ steps.build.outputs.metadata }} - name: Upload metadata if: fromJson(needs.prepare.outputs.push) uses: actions/upload-artifact@v7 with: name: metadata-static-builder-gnu-${{ steps.prepare.outputs.sanitized_platform }} path: /tmp/metadata-gnu/* if-no-files-found: error retention-days: 1 - name: Copy all frankenphp* files run: | # shellcheck disable=SC2034 # TODO: remove "containerimage.config.digest" fallback once all runners use buildx v0.18+ # which replaced it with "containerimage.digest" and "containerimage.descriptor" digest=$(jq -r '."static-builder-gnu" | ${{ fromJson(needs.prepare.outputs.push) && '."containerimage.digest"' || '(."containerimage.config.digest" // ."containerimage.digest")' }}' <<< "${METADATA}") container_id=$(docker create --platform="${PLATFORM}" "${{ fromJson(needs.prepare.outputs.push) && '${IMAGE_NAME}@${digest}' || '${digest}' }}") mkdir -p gh-output cd gh-output for file in $(docker run --rm "${{ fromJson(needs.prepare.outputs.push) && '${IMAGE_NAME}@${digest}' || '${digest}' }}" sh -c "ls /go/src/app/dist | grep '^frankenphp'"); do docker cp "${container_id}:/go/src/app/dist/${file}" "./${file}" done docker rm "${container_id}" mv "${BINARY}" "${BINARY}-gnu" env: METADATA: ${{ steps.build.outputs.metadata }} BINARY: frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }} PLATFORM: ${{ matrix.platform }} - name: Upload artifact if: ${{ !fromJson(needs.prepare.outputs.push) }} uses: actions/upload-artifact@v7 with: name: frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}-gnu-files path: gh-output/* - name: Upload assets if: fromJson(needs.prepare.outputs.push) && (needs.prepare.outputs.ref || github.ref_type == 'tag') run: gh release upload "${REF}" gh-output/* --repo dunglas/frankenphp --clobber env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} REF: ${{ (github.ref_type == 'tag' && github.ref_name) || needs.prepare.outputs.ref }} - if: fromJson(needs.prepare.outputs.push) && (needs.prepare.outputs.ref || github.ref_type == 'tag') uses: actions/attest-build-provenance@v4 with: subject-path: ${{ github.workspace }}/gh-output/frankenphp-linux-*-gnu - name: Run sanity checks run: | "${BINARY}" version "${BINARY}" list-modules | grep frankenphp "${BINARY}" list-modules | grep http.encoders.br "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.vulcain "${BINARY}" php-cli -r "echo 'Sanity check passed';" env: BINARY: ./gh-output/frankenphp-linux-${{ matrix.platform == 'linux/amd64' && 'x86_64' || 'aarch64' }}-gnu # Adapted from https://docs.docker.com/build/ci/github-actions/multi-platform/ push: runs-on: ubuntu-24.04 needs: - prepare - build-linux-musl - build-linux-gnu if: fromJson(needs.prepare.outputs.push) steps: - name: Download metadata uses: actions/download-artifact@v8 with: pattern: metadata-static-builder-musl-* path: /tmp/metadata merge-multiple: true - name: Download GNU metadata uses: actions/download-artifact@v8 with: pattern: metadata-static-builder-gnu-* path: /tmp/metadata-gnu merge-multiple: true - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - name: Login to DockerHub uses: docker/login-action@v4 if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository with: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - name: Create manifest list and push working-directory: /tmp/metadata run: | # shellcheck disable=SC2046,SC2086 docker buildx imagetools create $(jq -cr '.target."static-builder-musl".tags | map("-t " + .) | join(" ")' <<< "${METADATA}") \ $(printf "${IMAGE_NAME}@sha256:%s " *) env: METADATA: ${{ needs.prepare.outputs.metadata }} - name: Create GNU manifest list and push working-directory: /tmp/metadata-gnu run: | # shellcheck disable=SC2046,SC2086 docker buildx imagetools create $(jq -cr '.target."static-builder-gnu".tags | map("-t " + .) | join(" ")' <<< "${GNU_METADATA}") \ $(printf "${IMAGE_NAME}@sha256:%s " *) env: GNU_METADATA: ${{ needs.prepare.outputs.gnu_metadata }} - name: Inspect image run: | # shellcheck disable=SC2046,SC2086 docker buildx imagetools inspect "$(jq -cr '.target."static-builder-musl".tags | first' <<< "${METADATA}")" env: METADATA: ${{ needs.prepare.outputs.metadata }} - name: Inspect GNU image run: | # shellcheck disable=SC2046,SC2086 docker buildx imagetools inspect "$(jq -cr '.target."static-builder-gnu".tags | first' <<< "${GNU_METADATA}")-gnu" env: GNU_METADATA: ${{ needs.prepare.outputs.gnu_metadata }} build-mac: permissions: contents: write id-token: write attestations: write strategy: fail-fast: false matrix: platform: ["arm64", "x86_64"] name: Build macOS ${{ matrix.platform }} binaries runs-on: ${{ matrix.platform == 'arm64' && 'macos-15' || 'macos-15-intel' }} needs: [prepare] env: HOMEBREW_NO_AUTO_UPDATE: 1 steps: - uses: actions/checkout@v6 with: ref: ${{ needs.prepare.outputs.ref }} persist-credentials: false - uses: actions/setup-go@v6 with: # zizmor: ignore[cache-poisoning] go-version: "1.26" cache-dependency-path: | go.sum caddy/go.sum cache: ${{ github.event_name != 'release' }} - name: Set FRANKENPHP_VERSION run: | if [ "${GITHUB_REF_TYPE}" == "tag" ]; then export FRANKENPHP_VERSION=${GITHUB_REF_NAME:1} elif [ "${GITHUB_EVENT_NAME}" == "schedule" ]; then export FRANKENPHP_VERSION="${REF}" else export FRANKENPHP_VERSION=${GITHUB_SHA} fi echo "FRANKENPHP_VERSION=${FRANKENPHP_VERSION}" >> "${GITHUB_ENV}" env: REF: ${{ needs.prepare.outputs.ref }} - name: Build FrankenPHP run: ./build-static.sh env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} RELEASE: ${{ (needs.prepare.outputs.ref || github.ref_type == 'tag') && '1' || '' }} NO_COMPRESS: ${{ github.event_name == 'pull_request' && '1' || '' }} - name: Upload logs if: ${{ failure() }} uses: actions/upload-artifact@v7 with: path: dist/static-php-cli/log name: static-php-cli-log-${{ matrix.platform }}-${{ github.sha }} - if: needs.prepare.outputs.ref || github.ref_type == 'tag' uses: actions/attest-build-provenance@v4 with: subject-path: ${{ github.workspace }}/dist/frankenphp-mac-* - name: Upload artifact if: github.ref_type == 'branch' uses: actions/upload-artifact@v7 with: name: frankenphp-mac-${{ matrix.platform }} path: dist/frankenphp-mac-${{ matrix.platform }} compression-level: 0 - name: Run sanity checks run: | "${BINARY}" version "${BINARY}" build-info "${BINARY}" list-modules | grep frankenphp "${BINARY}" list-modules | grep http.encoders.br "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.mercure "${BINARY}" list-modules | grep http.handlers.vulcain "${BINARY}" php-cli -r "echo 'Sanity check passed';" env: BINARY: dist/frankenphp-mac-${{ matrix.platform }} ================================================ FILE: .github/workflows/tests.yaml ================================================ --- name: Tests concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main paths-ignore: - "docs/**" push: branches: - main paths-ignore: - "docs/**" permissions: contents: read env: GOTOOLCHAIN: local GOEXPERIMENT: cgocheck2 jobs: tests-linux: name: Tests (Linux, PHP ${{ matrix.php-versions }}) runs-on: ubuntu-latest continue-on-error: false strategy: fail-fast: false matrix: include: - php-versions: "8.2" - php-versions: "8.3" - php-versions: "8.4" - php-versions: "8.5" env: GOMAXPROCS: 10 LIBRARY_PATH: ${{ github.workspace }}/watcher/target/lib GOFLAGS: "-tags=nobadger,nomysql,nopgx" steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: actions/setup-go@v6 with: go-version: "1.26" cache-dependency-path: | go.sum caddy/go.sum - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-versions }} ini-file: development coverage: none tools: none env: phpts: ts debug: true - name: Install e-dant/watcher uses: ./.github/actions/watcher - name: Set CGO flags run: echo "CGO_CFLAGS=-I${PWD}/watcher/target/include $(php-config --includes)" >> "${GITHUB_ENV}" - name: Build run: go build - name: Build testcli binary working-directory: internal/testcli/ run: go build - name: Compile library tests run: go test -race -v -x -c - name: Run library tests run: ./frankenphp.test -test.v - name: Run Caddy module tests working-directory: caddy/ run: go test -race -v ./... - name: Run Fuzzing Tests working-directory: caddy/ run: go test -fuzz FuzzRequest -fuzztime 20s - name: Build the server working-directory: caddy/frankenphp/ run: go build - name: Start the server working-directory: testdata/ run: sudo ../caddy/frankenphp/frankenphp start - name: Run integrations tests run: ./reload_test.sh - name: Lint Go code uses: golangci/golangci-lint-action@v9 if: matrix.php-versions == '8.5' with: version: latest - name: Ensure go.mod is tidy if: matrix.php-versions == '8.5' run: go mod tidy -diff - name: Ensure caddy/go.mod is tidy if: matrix.php-versions == '8.5' run: go mod tidy -diff working-directory: caddy/ integration-tests: name: Integration Tests (Linux, PHP ${{ matrix.php-versions }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: php-versions: ["8.3", "8.4", "8.5"] env: XCADDY_GO_BUILD_FLAGS: "-tags=nobadger,nomysql,nopgx" steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: actions/setup-go@v6 with: go-version: "1.26" cache-dependency-path: | go.sum caddy/go.sum - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-versions }} ini-file: development coverage: none tools: none env: phpts: ts debug: true - name: Install PHP development libraries run: sudo apt-get update && sudo apt-get install -y libkrb5-dev libsodium-dev libargon2-dev - name: Install xcaddy run: go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest - name: Download PHP sources run: | PHP_VERSION=$(php -r "echo PHP_VERSION;") wget -q "https://www.php.net/distributions/php-${PHP_VERSION}.tar.gz" || wget -q "https://phpmirror.static-php.dev/distributions/php-${PHP_VERSION}.tar.gz" tar xzf "php-${PHP_VERSION}.tar.gz" echo "GEN_STUB_SCRIPT=${PWD}/php-${PHP_VERSION}/build/gen_stub.php" >> "${GITHUB_ENV}" - name: Set CGO flags run: | echo "CGO_CFLAGS=$(php-config --includes)" >> "${GITHUB_ENV}" echo "CGO_LDFLAGS=$(php-config --ldflags) $(php-config --libs)" >> "${GITHUB_ENV}" - name: Run integration tests working-directory: internal/extgen/ run: go test -tags integration -v -timeout 30m tests-mac: name: Tests (macOS, PHP 8.5) runs-on: macos-latest env: HOMEBREW_NO_AUTO_UPDATE: 1 GOFLAGS: "-tags=nowatcher,nobadger,nomysql,nopgx" steps: - uses: actions/checkout@v6 with: persist-credentials: false - uses: actions/setup-go@v6 with: go-version: "1.26" cache-dependency-path: | go.sum caddy/go.sum - uses: shivammathur/setup-php@v2 with: php-version: 8.5 ini-file: development coverage: none tools: none env: phpts: ts debug: true - name: Set Set CGO flags run: | { echo "CGO_CFLAGS=-I/opt/homebrew/include/ $(php-config --includes)" echo "CGO_LDFLAGS=-L/opt/homebrew/lib/ $(php-config --ldflags) $(php-config --libs)" } >> "${GITHUB_ENV}" - name: Build run: go build -tags nowatcher - name: Run library tests run: go test -tags nowatcher -race -v ./... - name: Run Caddy module tests working-directory: caddy/ run: go test -race -v ./... ================================================ FILE: .github/workflows/translate.yaml ================================================ name: Translate Docs concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: push: branches: - main paths: - "docs/*" permissions: contents: write pull-requests: write jobs: build: name: Translate Docs runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v6 with: fetch-depth: 0 # zizmor: ignore[artipacked] # persist-credentials is intentionally left enabled (unlike other workflows) # because this workflow needs to push a branch via git push - id: md_files run: | FILES=$(git diff --name-only "${{ github.event.before }}" "${{ github.sha }}" -- 'docs/*.md' ':(exclude)docs/*/*.md') FILES=$(echo "$FILES" | xargs -n1 basename | tr '\n' ' ') [ -z "$FILES" ] && echo "found=false" >> "$GITHUB_OUTPUT" || echo "found=true" >> "$GITHUB_OUTPUT" echo "files=$FILES" >> "$GITHUB_OUTPUT" - name: Set up PHP if: steps.md_files.outputs.found == 'true' uses: shivammathur/setup-php@v2 with: php-version: "8.5" - name: run translation script if: steps.md_files.outputs.found == 'true' env: GEMINI_API_KEY: "${{ secrets.GEMINI_API_KEY }}" MD_FILES: "${{ steps.md_files.outputs.files }}" run: | php ./docs/translate.php "$MD_FILES" - name: Run Linter if: steps.md_files.outputs.found == 'true' continue-on-error: true uses: super-linter/super-linter/slim@v8 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} LINTER_RULES_PATH: / MARKDOWN_CONFIG_FILE: .markdown-lint.yaml VALIDATE_NATURAL_LANGUAGE: false FIX_MARKDOWN: true - name: Create Pull Request if: steps.md_files.outputs.found == 'true' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} ACTOR: ${{ github.actor }} ACTOR_ID: ${{ github.actor_id }} RUN_ID: ${{ github.run_id }} MD_FILES_LIST: ${{ steps.md_files.outputs.files }} run: | git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" BRANCH="translations/$RUN_ID" git checkout -b "$BRANCH" git add docs/ git diff --cached --quiet && exit 0 git commit -m "docs: update translations" --author="$ACTOR <$ACTOR_ID+$ACTOR@users.noreply.github.com>" git push origin "$BRANCH" gh pr create \ --title "docs: update translations" \ --body "Translation updates for: $MD_FILES_LIST." \ --label "translations" \ --label "bot" ================================================ FILE: .github/workflows/windows.yaml ================================================ --- name: Build Windows release concurrency: cancel-in-progress: true group: ${{ github.workflow }}-${{ github.ref }} on: pull_request: branches: - main paths-ignore: - "docs/**" push: branches: - main tags: - v*.*.* paths-ignore: - "docs/**" workflow_dispatch: inputs: #checkov:skip=CKV_GHA_7 version: description: "FrankenPHP version" required: false type: string schedule: - cron: "0 8 * * *" permissions: contents: read env: GOTOOLCHAIN: local GOFLAGS: "-ldflags=-extldflags=-fuse-ld=lld -tags=nobadger,nomysql,nopgx" PHP_DOWNLOAD_BASE: "https://downloads.php.net/~windows/releases/" CC: clang CXX: clang++ jobs: build: permissions: contents: write runs-on: windows-latest steps: - name: Determine ref run: | $ref = $env:REF if (-not $ref -and $env:GITHUB_EVENT_NAME -eq "schedule") { $ref = (gh release view --repo php/frankenphp --json tagName --jq '.tagName') } "REF=$ref" >> $env:GITHUB_ENV env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REF: ${{ (github.ref_type == 'tag' && github.ref_name) || (github.event_name == 'workflow_dispatch' && inputs.version) || '' }} - name: Configure Git run: | git config --global core.autocrlf false git config --global core.eol lf - name: Checkout Code uses: actions/checkout@v6 with: ref: ${{ env.REF || '' }} path: frankenphp persist-credentials: false - name: Set FRANKENPHP_VERSION run: | $ref = $env:REF if ($env:GITHUB_REF_TYPE -eq "tag") { $frankenphpVersion = $env:GITHUB_REF_NAME.Substring(1) } elseif ($ref) { if ($ref.StartsWith("v")) { $frankenphpVersion = $ref.Substring(1) } else { $frankenphpVersion = $ref } } else { $frankenphpVersion = $env:GITHUB_SHA } "FRANKENPHP_VERSION=$frankenphpVersion" >> $env:GITHUB_ENV - name: Setup Go uses: actions/setup-go@v6 with: # zizmor: ignore[cache-poisoning] go-version: "1.26" cache-dependency-path: | frankenphp/go.sum frankenphp/caddy/go.sum cache: ${{ !startsWith(github.ref, 'refs/tags/') }} check-latest: true - name: Install Vcpkg Libraries working-directory: frankenphp run: "vcpkg install" - name: Download Watcher run: | $latestTag = gh release list --repo e-dant/watcher --limit 1 --exclude-drafts --exclude-pre-releases --json tagName --jq '.[0].tagName' Write-Host "Latest Watcher version: $latestTag" gh release download $latestTag --repo e-dant/watcher --pattern "*x86_64-pc-windows-msvc.tar" -O watcher.tar tar -xf "watcher.tar" -C "$env:GITHUB_WORKSPACE" Rename-Item -Path "$env:GITHUB_WORKSPACE\x86_64-pc-windows-msvc" -NewName "watcher" env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Download PHP run: | $webContent = Invoke-WebRequest -Uri $env:PHP_DOWNLOAD_BASE $links = $webContent.Links.Href | Where-Object { $_ -match "php-\d+\.\d+\.\d+-Win32-vs17-x64\.zip$" } if (-not $links) { throw "Could not find PHP zip files at $env:PHP_DOWNLOAD_BASE" } $latestFile = $links | Sort-Object { if ($_ -match '(\d+\.\d+\.\d+)') { [version]$matches[1] } } | Select-Object -Last 1 $version = if ($latestFile -match '(\d+\.\d+\.\d+)') { $matches[1] } Write-Host "Detected latest PHP version: $version" "PHP_VERSION=$version" >> $env:GITHUB_ENV $phpZip = "php-$version-Win32-vs17-x64.zip" $develZip = "php-devel-pack-$version-Win32-vs17-x64.zip" $dirName = "frankenphp-windows-x86_64" "DIR_NAME=$dirName" >> $env:GITHUB_ENV Invoke-WebRequest -Uri "$env:PHP_DOWNLOAD_BASE/$phpZip" -OutFile "$env:TEMP\php.zip" Expand-Archive -Path "$env:TEMP\php.zip" -DestinationPath "$env:GITHUB_WORKSPACE\$dirName" Invoke-WebRequest -Uri "$env:PHP_DOWNLOAD_BASE/$develZip" -OutFile "$env:TEMP\php-devel.zip" Expand-Archive -Path "$env:TEMP\php-devel.zip" -DestinationPath "$env:GITHUB_WORKSPACE\php-devel" - name: Prepare env run: | $vcpkgRoot = "$env:GITHUB_WORKSPACE\frankenphp\vcpkg_installed\x64-windows" $watcherRoot = "$env:GITHUB_WORKSPACE\watcher" $phpBin = "$env:GITHUB_WORKSPACE\$env:DIR_NAME" $phpDevel = "$env:GITHUB_WORKSPACE\php-devel\php-$env:PHP_VERSION-devel-vs17-x64" "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\Llvm\bin" >> $env:GITHUB_PATH "$vcpkgRoot\bin" >> $env:GITHUB_PATH "$watcherRoot" >> $env:GITHUB_PATH "$phpBin" >> $env:GITHUB_PATH "CGO_CFLAGS=-DFRANKENPHP_VERSION=$env:FRANKENPHP_VERSION -I$vcpkgRoot\include -I$watcherRoot -I$phpDevel\include -I$phpDevel\include\main -I$phpDevel\include\TSRM -I$phpDevel\include\Zend -I$phpDevel\include\ext" >> $env:GITHUB_ENV "CGO_LDFLAGS=-L$vcpkgRoot\lib -lbrotlienc -L$watcherRoot -llibwatcher-c -L$phpBin -L$phpDevel\lib -lphp8ts -lphp8embed" >> $env:GITHUB_ENV - name: Embed Windows icon and metadata working-directory: frankenphp\caddy\frankenphp run: | go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest $major = 0; $minor = 0; $patch = 0; $build = 0 if ($env:FRANKENPHP_VERSION -match '^(?\d+)\.(?\d+)\.(?\d+)$') { $major = [int]$Matches['major'] $minor = [int]$Matches['minor'] $patch = [int]$Matches['patch'] } $json = @{ FixedFileInfo = @{ FileVersion = @{ Major = $major; Minor = $minor; Patch = $patch; Build = $build } ProductVersion = @{ Major = $major; Minor = $minor; Patch = $patch; Build = $build } } StringFileInfo = @{ CompanyName = "FrankenPHP" FileDescription = "The modern PHP app server" FileVersion = $env:FRANKENPHP_VERSION InternalName = "frankenphp" OriginalFilename = "frankenphp.exe" LegalCopyright = "(c) 2022 Kévin Dunglas, MIT License" ProductName = "FrankenPHP" ProductVersion = $env:FRANKENPHP_VERSION Comments = "https://frankenphp.dev/" } VarFileInfo = @{ Translation = @{ LangID = 9; CharsetID = 1200 } } } | ConvertTo-Json -Depth 10 $json | Set-Content "versioninfo.json" goversioninfo -64 -icon ..\..\frankenphp.ico versioninfo.json -o resource.syso - name: Build FrankenPHP run: | $customVersion = "FrankenPHP $env:FRANKENPHP_VERSION PHP $env:PHP_VERSION Caddy" go build -ldflags="-extldflags=-fuse-ld=lld -X 'github.com/caddyserver/caddy/v2.CustomVersion=$customVersion' -X 'github.com/caddyserver/caddy/v2.CustomBinaryName=frankenphp' -X 'github.com/caddyserver/caddy/v2/modules/caddyhttp.ServerHeader=FrankenPHP Caddy'" working-directory: frankenphp\caddy\frankenphp - name: Create Directory run: | Copy-Item frankenphp\caddy\frankenphp\frankenphp.exe $env:DIR_NAME Copy-Item watcher\libwatcher-c.dll $env:DIR_NAME Copy-Item frankenphp\vcpkg_installed\x64-windows\bin\brotlienc.dll $env:DIR_NAME Copy-Item frankenphp\vcpkg_installed\x64-windows\bin\brotlidec.dll $env:DIR_NAME Copy-Item frankenphp\vcpkg_installed\x64-windows\bin\brotlicommon.dll $env:DIR_NAME Copy-Item frankenphp\vcpkg_installed\x64-windows\bin\pthreadVC3.dll $env:DIR_NAME - name: Upload Artifact if: ${{ !env.REF }} uses: actions/upload-artifact@v7 with: name: ${{ env.DIR_NAME }} path: ${{ env.DIR_NAME }} if-no-files-found: error - name: Zip Release Artifact if: ${{ env.REF }} run: Compress-Archive -Path "$env:DIR_NAME\*" -DestinationPath "$env:DIR_NAME.zip" - name: Upload Release Asset if: ${{ env.REF }} run: gh release upload "$env:REF" "$env:DIR_NAME.zip" --repo php/frankenphp --clobber env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run Tests run: | "opcache.enable=0`r`nopcache.enable_cli=0" | Out-File php.ini $env:PHPRC = Get-Location go test -race ./... cd caddy go test -race ./... working-directory: ${{ github.workspace }}\frankenphp ================================================ FILE: .github/workflows/wrap-issue-details.yaml ================================================ name: Wrap Issue Content on: issues: types: [opened, edited] permissions: contents: read jobs: wrap_content: runs-on: ubuntu-latest permissions: issues: write steps: - uses: actions/github-script@v8 with: script: | const body = context.payload.issue.body; const wrapSection = (inputBody, marker, summary) => { const regex = new RegExp(`(${marker})\\s*([\\s\\S]*?)(?=\\n### |$)`); return inputBody.replace(regex, (match, header, content) => { const trimmed = content.trim(); if (!trimmed || trimmed.includes("
")) return match; return `${header}\n\n
\n${summary}\n\n${trimmed}\n\n
\n`; }); }; let newBody = body; newBody = wrapSection(newBody, "### PHP configuration", "phpinfo() output"); newBody = wrapSection(newBody, "### Relevant log output", "Relevant log output"); if (newBody !== body) { await github.rest.issues.update({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, body: newBody }); } ================================================ FILE: .gitignore ================================================ /caddy/frankenphp/Build /caddy/frankenphp/frankenphp /caddy/frankenphp/frankenphp.exe /dist /github_conf /internal/testserver/testserver /internal/testcli/testcli /package/etc/php.ini /super-linter-output /vcpkg_installed/ .DS_Store .idea/ .vscode/ __debug_bin frankenphp.test *.log compile_flags.txt ================================================ FILE: .gitleaksignore ================================================ /github/workspace/docs/mercure.md:jwt:88 /github/workspace/docs/mercure.md:jwt:90 ================================================ FILE: .golangci.yaml ================================================ --- version: "2" run: build-tags: - nobadger - nomysql - nopgx ================================================ FILE: .hadolint.yaml ================================================ --- ignored: - DL3006 - DL3008 - DL3018 - DL3022 ================================================ FILE: .markdown-lint.yaml ================================================ --- MD010: false MD013: false MD033: false MD060: false ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing ## Compiling PHP ### With Docker (Linux) Build the dev Docker image: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` The image contains the usual development tools (Go, GDB, Valgrind, Neovim...) and uses the following php setting locations - php.ini: `/etc/frankenphp/php.ini` A php.ini file with development presets is provided by default. - additional configuration files: `/etc/frankenphp/php.d/*.ini` - php extensions: `/usr/lib/frankenphp/modules/` If your Docker version is lower than 23.0, the build will fail due to dockerignore [pattern issue](https://github.com/moby/moby/pull/42676). Add directories to `.dockerignore`: ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### Without Docker (Linux and macOS) [Follow the instructions to compile from sources](https://frankenphp.dev/docs/compile/) and pass the `--debug` configuration flag. ## Running the Test Suite ```console export CGO_CFLAGS=-O0 -g $(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go test -race -v ./... ``` ## Caddy Module Build Caddy with the FrankenPHP Caddy module: ```console cd caddy/frankenphp/ go build -tags nobadger,nomysql,nopgx cd ../../ ``` Run the Caddy with the FrankenPHP Caddy module: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` The server is listening on `127.0.0.1:80`: > [!NOTE] > If you are using Docker, you will have to either bind container port 80 or execute from inside the container ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## Minimal Test Server Build the minimal test server: ```console cd internal/testserver/ go build cd ../../ ``` Run the test server: ```console cd testdata/ ../internal/testserver/testserver ``` The server is listening on `127.0.0.1:8080`: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Windows Development 1. Configure Git to always use `lf` line endings ```powershell git config --global core.autocrlf false git config --global core.eol lf ``` 2. Install Visual Studio, Git, and Go: ```powershell winget install -e --id Microsoft.VisualStudio.2022.Community --override "--passive --wait --add Microsoft.VisualStudio.Workload.NativeDesktop --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --includeRecommended" winget install -e --id GoLang.Go winget install -e --id Git.Git ``` 3. Install vcpkg: ```powershell cd C:\ git clone https://github.com/microsoft/vcpkg .\vcpkg\bootstrap-vcpkg.bat ``` 4. [Download the latest version of the watcher library for Windows](https://github.com/e-dant/watcher/releases) and extract it to a directory named `C:\watcher` 5. [Download the latest **Thread Safe** version of PHP and of the PHP SDK for Windows](https://windows.php.net/download/), extract them in directories named `C:\php` and `C:\php-devel` 6. Clone the FrankenPHP Git repository: ```powershell git clone https://github.com/php/frankenphp C:\frankenphp cd C:\frankenphp ``` 7. Install the dependencies: ```powershell C:\vcpkg\vcpkg.exe install ``` 8. Configure the needed environment variables (PowerShell): ```powershell $env:PATH += ';C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\Llvm\bin' $env:CC = 'clang' $env:CXX = 'clang++' $env:CGO_CFLAGS = "-O0 -g -IC:\frankenphp\vcpkg_installed\x64-windows\include -IC:\watcher -IC:\php-devel\include -IC:\php-devel\include\main -IC:\php-devel\include\TSRM -IC:\php-devel\include\Zend -IC:\php-devel\include\ext" $env:CGO_LDFLAGS = '-LC:\frankenphp\vcpkg_installed\x64-windows\lib -lbrotlienc -LC:\watcher -llibwatcher-c -LC:\php -LC:\php-devel\lib -lphp8ts -lphp8embed' ``` 9. Run the tests: ```powershell go test -race -ldflags '-extldflags="-fuse-ld=lld"' ./... cd caddy go test -race -ldflags '-extldflags="-fuse-ld=lld"' -tags nobadger,nomysql,nopgx ./... cd .. ``` 10. Build the binary: ```powershell cd caddy/frankenphp go build -ldflags '-extldflags="-fuse-ld=lld"' -tags nobadger,nomysql,nopgx cd ../.. ``` ## Building Docker Images Locally Print Bake plan: ```console docker buildx bake -f docker-bake.hcl --print ``` Build FrankenPHP images for amd64 locally: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` Build FrankenPHP images for arm64 locally: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` Build FrankenPHP images from scratch for arm64 & amd64 and push to Docker Hub: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## Debugging Segmentation Faults With Static Builds 1. Download the debug version of the FrankenPHP binary from GitHub or create your custom static build including debug symbols: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. Replace your current version of `frankenphp` with the debug FrankenPHP executable 3. Start FrankenPHP as usual (alternatively, you can directly start FrankenPHP with GDB: `gdb --args frankenphp run`) 4. Attach to the process with GDB: ```console gdb -p `pidof frankenphp` ``` 5. If necessary, type `continue` in the GDB shell 6. Make FrankenPHP crash 7. Type `bt` in the GDB shell 8. Copy the output ## Debugging Segmentation Faults in GitHub Actions 1. Open `.github/workflows/tests.yml` 2. Enable PHP debug symbols ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. Enable `tmate` to connect to the container ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=-O0 -g $(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. Connect to the container 5. Open `frankenphp.go` 6. Enable `cgosymbolizer` ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Download the module: `go get` 8. In the container, you can use GDB and the like: ```console go test -tags -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. When the bug is fixed, revert all these changes ## Development Environment Setup (WSL/Unix) ### Initial setup Follow the instructions in [compiling from sources](https://frankenphp.dev/docs/compile/). The steps assume the following environment: - Go installed at `/usr/local/go` - PHP source cloned to `~/php-src` - PHP built at: `/usr/local/bin/php` - FrankenPHP source cloned to `~/frankenphp` ### CLion Setup for CGO glue/PHP Source Development 1. Install CLion (on your host OS) - Download from [JetBrains](https://www.jetbrains.com/clion/download/) - Launch (if on Windows, in WSL): ```bash clion &>/dev/null ``` 2. Open Project in CLion - Open CLion → Open → Select the `~/frankenphp` directory - Add a build chain: Settings → Build, Execution, Deployment → Custom Build Targets - Select any Build Target, under `Build` set up an External Tool (call it e.g. go build) - Set up a wrapper script that builds frankenphp for you, called `go_compile_frankenphp.sh` ```bash CGO_CFLAGS="-O0 -g" ./go.sh ``` - Under Program, select `go_compile_frankenphp.sh` - Leave Arguments blank - Working Directory: `~/frankenphp/caddy/frankenphp` 3. Configure Run Targets - Go to Run → Edit Configurations - Create: - frankenphp: - Type: Native Application - Target: select the `go build` target you created - Executable: `~/frankenphp/caddy/frankenphp/frankenphp` - Arguments: the arguments you want to start frankenphp with, e.g. `php-cli test.php` 4. Debug Go files from CLion - Right click on a *.go file in the Project view on the left - Override file type → C/C++ Now you can place breakpoints in C, C++ and Go files. To get syntax highlighting for imports from php-src, you may need to tell CLion about the include paths. Create a `compile_flags.txt` file in `~/frankenphp` with the following contents: ```gcc -I/usr/local/include/php -I/usr/local/include/php/Zend -I/usr/local/include/php/main -I/usr/local/include/php/TSRM ``` --- ### GoLand Setup for FrankenPHP Development Use GoLand for primary Go development, but the debugger cannot debug C code. 1. Install GoLand (on your host OS) - Download from [JetBrains](https://www.jetbrains.com/go/download/) ```bash goland &>/dev/null ``` 2. Open in GoLand - Launch GoLand → Open → Select the `~/frankenphp` directory --- ### Go Configuration - Select Go Build - Name `frankenphp` - Run kind: Directory - Directory: `~/frankenphp/caddy/frankenphp` - Output directory: `~/frankenphp/caddy/frankenphp` - Working directory: `~/frankenphp/caddy/frankenphp` - Environment (adjust for your $(php-config ...) output): `CGO_CFLAGS=-O0 -g -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib;CGO_LDFLAGS=-lm -lpthread -lsqlite3 -lxml2 -lbrotlienc -lbrotlidec -lbrotlicommon -lwatcher` - Go tool arguments: `-tags=nobadger,nomysql,nopgx` - Program arguments: e.g. `php-cli -i` To debug C files from GoLand - Right click on a *.c file in the Project view on the left - Override file type → Go Now you can place breakpoints in C, C++ and Go files. --- ### GoLand Setup on Windows 1. Follow the [Windows Development section](#windows-development) 2. Install GoLand - Download from [JetBrains](https://www.jetbrains.com/go/download/) - Launch GoLand 3. Open in GoLand - Select **Open** → Choose the directory where you cloned `frankenphp` 4. Configure Go Build - Go to **Run** → **Edit Configurations** - Click **+** and select **Go Build** - Name: `frankenphp` - Run kind: **Directory** - Directory: `.\caddy\frankenphp` - Output directory: `.\caddy\frankenphp` - Working directory: `.\caddy\frankenphp` - Go tool arguments: `-tags=nobadger,nomysql,nopgx` - Environment variables: see the [Windows Development section](#windows-development) - Program arguments: e.g. `php-server` --- ### Debugging and Integration Notes - Use CLion for debugging PHP internals and `cgo` glue code - Use GoLand for primary Go development and debugging - FrankenPHP can be added as a run configuration in CLion for unified C/Go debugging if needed, but syntax highlighting won't work in Go files ## Misc Dev Resources - [PHP embedding in uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [PHP embedding in NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [PHP embedding in Go (go-php)](https://github.com/deuill/go-php) - [PHP embedding in Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [PHP embedding in C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Extending and Embedding PHP by Sara Golemon](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [What the heck is TSRMLS_CC, anyway?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [SDL bindings](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Docker-Related Resources - [Bake file definition](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Useful Command ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## Translating the Documentation To translate the documentation and the site into a new language, follow these steps: 1. Create a new directory named with the language's 2-character ISO code in this repository's `docs/` directory 2. Copy all the `.md` files in the root of the `docs/` directory into the new directory (always use the English version as source for translation, as it's always up to date) 3. Copy the `README.md` and `CONTRIBUTING.md` files from the root directory to the new directory 4. Translate the content of the files, but don't change the filenames, also don't translate strings starting with `> [!` (it's special markup for GitHub) 5. Create a Pull Request with the translations 6. In the [site repository](https://github.com/dunglas/frankenphp-website/tree/main), copy and translate the translation files in the `content/`, `data/`, and `i18n/` directories 7. Translate the values in the created YAML file 8. Open a Pull Request on the site repository ================================================ FILE: Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 #checkov:skip=CKV_DOCKER_7 FROM php-base AS common WORKDIR /app RUN apt-get update && \ apt-get -y --no-install-recommends install \ mailcap \ libcap2-bin \ && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN set -eux; \ mkdir -p \ /app/public \ /config/caddy \ /data/caddy \ /etc/caddy \ /etc/frankenphp; \ sed -i 's/php/frankenphp run/g' /usr/local/bin/docker-php-entrypoint; \ echo ' /app/public/index.php COPY --link caddy/frankenphp/Caddyfile /etc/caddy/Caddyfile RUN ln /etc/caddy/Caddyfile /etc/frankenphp/Caddyfile && \ curl -sSLf \ -o /usr/local/bin/install-php-extensions \ https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions && \ chmod +x /usr/local/bin/install-php-extensions CMD ["--config", "/etc/frankenphp/Caddyfile", "--adapter", "caddyfile"] HEALTHCHECK CMD curl -f http://localhost:2019/metrics || exit 1 # See https://caddyserver.com/docs/conventions#file-locations for details ENV XDG_CONFIG_HOME=/config ENV XDG_DATA_HOME=/data EXPOSE 80 EXPOSE 443 EXPOSE 443/udp EXPOSE 2019 LABEL org.opencontainers.image.title=FrankenPHP LABEL org.opencontainers.image.description="The modern PHP app server" LABEL org.opencontainers.image.url=https://frankenphp.dev LABEL org.opencontainers.image.source=https://github.com/php/frankenphp LABEL org.opencontainers.image.licenses=MIT LABEL org.opencontainers.image.vendor="Kévin Dunglas" FROM common AS builder ARG FRANKENPHP_VERSION='dev' SHELL ["/bin/bash", "-o", "pipefail", "-c"] COPY --from=golang-base /usr/local/go /usr/local/go ENV PATH=/usr/local/go/bin:$PATH ENV GOTOOLCHAIN=local # This is required to link the FrankenPHP binary to the PHP binary RUN apt-get update && \ apt-get -y --no-install-recommends install \ cmake \ git \ libargon2-dev \ libbrotli-dev \ libcurl4-openssl-dev \ libonig-dev \ libreadline-dev \ libsodium-dev \ libsqlite3-dev \ libssl-dev \ libxml2-dev \ zlib1g-dev \ && \ apt-get clean # Install e-dant/watcher (necessary for file watching) WORKDIR /usr/local/src/watcher RUN --mount=type=secret,id=github-token \ if [ -f /run/secrets/github-token ] && [ -s /run/secrets/github-token ]; then \ curl -s -H "Authorization: Bearer $(cat /run/secrets/github-token)" https://api.github.com/repos/e-dant/watcher/releases/latest; \ else \ curl -s https://api.github.com/repos/e-dant/watcher/releases/latest; \ fi | \ grep tarball_url | \ awk '{ print $2 }' | \ sed 's/,$//' | \ sed 's/"//g' | \ xargs curl -L | \ tar xz --strip-components 1 && \ # -Wno-error=use-after-free: GCC 12 on Bookworm i386 emits a spurious warning in libstdc++ basic_string.h cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-Wno-error=use-after-free" && \ cmake --build build && \ cmake --install build && \ ldconfig WORKDIR /go/src/app COPY --link go.mod go.sum ./ RUN go mod download WORKDIR /go/src/app/caddy COPY --link caddy/go.mod caddy/go.sum ./ RUN go mod download WORKDIR /go/src/app COPY --link . ./ # See https://github.com/docker-library/php/blob/master/8.5/trixie/zts/Dockerfile#L57-L59 for PHP values ENV CGO_CFLAGS="-DFRANKENPHP_VERSION=$FRANKENPHP_VERSION $PHP_CFLAGS" ENV CGO_CPPFLAGS=$PHP_CPPFLAGS ENV CGO_LDFLAGS="-L/usr/local/lib -lssl -lcrypto -lreadline -largon2 -lcurl -lonig -lz $PHP_LDFLAGS" WORKDIR /go/src/app/caddy/frankenphp RUN GOBIN=/usr/local/bin \ ../../go.sh install -ldflags "-w -s -X 'github.com/caddyserver/caddy/v2.CustomVersion=FrankenPHP $FRANKENPHP_VERSION PHP $PHP_VERSION Caddy' -X 'github.com/caddyserver/caddy/v2.CustomBinaryName=frankenphp' -X 'github.com/caddyserver/caddy/v2/modules/caddyhttp.ServerHeader=FrankenPHP Caddy'" -buildvcs=true && \ setcap cap_net_bind_service=+ep /usr/local/bin/frankenphp && \ cp Caddyfile /etc/frankenphp/Caddyfile && \ frankenphp version && \ frankenphp build-info WORKDIR /go/src/app FROM common AS runner ENV GODEBUG=cgocheck=0 # copy watcher shared library COPY --from=builder /usr/local/lib/libwatcher* /usr/local/lib/ # fix for the file watcher on arm RUN apt-get install -y --no-install-recommends libstdc++6 && \ apt-get clean && \ ldconfig COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp RUN setcap cap_net_bind_service=+ep /usr/local/bin/frankenphp && \ frankenphp version && \ frankenphp build-info ================================================ FILE: LICENSE ================================================ The MIT license Copyright (c) 2022-present Kévin Dunglas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # FrankenPHP: Modern App Server for PHP

FrankenPHP

FrankenPHP is a modern application server for PHP built on top of the [Caddy](https://caddyserver.com/) web server. FrankenPHP gives superpowers to your PHP apps thanks to its stunning features: [_Early Hints_](https://frankenphp.dev/docs/early-hints/), [worker mode](https://frankenphp.dev/docs/worker/), [real-time capabilities](https://frankenphp.dev/docs/mercure/), [hot reloading](https://frankenphp.dev/docs/hot-reload/), automatic HTTPS, HTTP/2, and HTTP/3 support... FrankenPHP works with any PHP app and makes your Laravel and Symfony projects faster than ever thanks to their official integrations with the worker mode. FrankenPHP can also be used as a standalone Go library to embed PHP in any app using `net/http`. [**Learn more** on _frankenphp.dev_](https://frankenphp.dev) and in this slide deck: Slides ## Getting Started ### Install Script On Linux and macOS, copy this line into your terminal to automatically install an appropriate version for your platform: ```console curl https://frankenphp.dev/install.sh | sh ``` On Windows, run this in PowerShell: ```powershell irm https://frankenphp.dev/install.ps1 | iex ``` ### Standalone Binary We provide FrankenPHP binaries for Linux, macOS and Windows containing [PHP 8.5](https://www.php.net/releases/8.5/). Linux binaries are statically linked, so they can be used on any Linux distribution without installing any dependency. macOS binaries are also self-contained. They contain most popular PHP extensions. Windows archives contain the official PHP binary for Windows. [Download FrankenPHP](https://github.com/php/frankenphp/releases) ### rpm Packages Our maintainers offer rpm packages for all systems using `dnf`. To install, run: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.5 # 8.2-8.5 available sudo dnf install frankenphp ``` **Installing extensions:** `sudo dnf install php-zts-` For extensions not available by default, use [PIE](https://github.com/php/pie): ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### deb Packages Our maintainers offer deb packages for all systems using `apt`. To install, run: ```console VERSION=85 # 82-85 available sudo curl https://pkg.henderkes.com/api/packages/${VERSION}/debian/repository.key -o /etc/apt/keyrings/static-php${VERSION}.asc echo "deb [signed-by=/etc/apt/keyrings/static-php${VERSION}.asc] https://pkg.henderkes.com/api/packages/${VERSION}/debian php-zts main" | sudo tee -a /etc/apt/sources.list.d/static-php${VERSION}.list sudo apt update sudo apt install frankenphp ``` **Installing extensions:** `sudo apt install php-zts-` For extensions not available by default, use [PIE](https://github.com/php/pie): ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### apk Packages Our maintainers offer apk packages for all systems using `apk`. To install, run: ```console VERSION=85 # 82-85 available echo "https://pkg.henderkes.com/api/packages/${VERSION}/alpine/main/php-zts" | sudo tee -a /etc/apk/repositories KEYFILE=$(curl -sJOw '%{filename_effective}' https://pkg.henderkes.com/api/packages/${VERSION}/alpine/key) sudo mv ${KEYFILE} /etc/apk/keys/ && sudo apk update && sudo apk add frankenphp ``` **Installing extensions:** `sudo apk add php-zts-` For extensions not available by default, use [PIE](https://github.com/php/pie): ```console sudo apk add pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Homebrew FrankenPHP is also available as a [Homebrew](https://brew.sh) package for macOS and Linux. ```console brew install dunglas/frankenphp/frankenphp ``` **Installing extensions:** Use [PIE](https://github.com/php/pie). ### Usage To serve the content of the current directory, run: ```console frankenphp php-server ``` You can also run command-line scripts with: ```console frankenphp php-cli /path/to/your/script.php ``` For the deb and rpm packages, you can also start the systemd service: ```console sudo systemctl start frankenphp ``` ### Docker Alternatively, [Docker images](https://frankenphp.dev/docs/docker/) are available: ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Go to `https://localhost`, and enjoy! > [!TIP] > > Do not attempt to use `https://127.0.0.1`. Use `https://localhost` and accept the self-signed certificate. > Use the [`SERVER_NAME` environment variable](docs/config.md#environment-variables) to change the domain to use. ## Docs - [Classic mode](https://frankenphp.dev/docs/classic/) - [Worker mode](https://frankenphp.dev/docs/worker/) - [Early Hints support (103 HTTP status code)](https://frankenphp.dev/docs/early-hints/) - [Real-time](https://frankenphp.dev/docs/mercure/) - [Logging](https://frankenphp.dev/docs/logging/) - [Hot reloading](https://frankenphp.dev/docs/hot-reload/) - [Efficiently Serving Large Static Files](https://frankenphp.dev/docs/x-sendfile/) - [Configuration](https://frankenphp.dev/docs/config/) - [Writing PHP Extensions in Go](https://frankenphp.dev/docs/extensions/) - [Docker images](https://frankenphp.dev/docs/docker/) - [Deploy in production](https://frankenphp.dev/docs/production/) - [Performance optimization](https://frankenphp.dev/docs/performance/) - [Create **standalone**, self-executable PHP apps](https://frankenphp.dev/docs/embed/) - [Create static binaries](https://frankenphp.dev/docs/static/) - [Compile from sources](https://frankenphp.dev/docs/compile/) - [Monitoring FrankenPHP](https://frankenphp.dev/docs/metrics/) - [WordPress integration](https://frankenphp.dev/docs/wordpress/) - [Laravel integration](https://frankenphp.dev/docs/laravel/) - [Known issues](https://frankenphp.dev/docs/known-issues/) - [Demo app (Symfony) and benchmarks](https://github.com/dunglas/frankenphp-demo) - [Go library documentation](https://pkg.go.dev/github.com/dunglas/frankenphp) - [Contributing and debugging](https://frankenphp.dev/docs/contributing/) ## Examples and Skeletons - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/symfony) - [Laravel](https://frankenphp.dev/docs/laravel/) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Supported Versions Only the latest version is supported. Please ensure that you're always using the latest release. Binaries and Docker images are rebuilt nightly using the latest versions of dependencies. ## Reporting a Vulnerability If you believe you have discovered a security issue directly affecting FrankenPHP, please do **NOT** report it publicly. Please write a detailed vulnerability report and send it [through GitHub](https://github.com/php/frankenphp/security/advisories/new) or to [kevin+frankenphp-security@dunglas.dev](mailto:kevin+frankenphp-security@dunglas.dev?subject=Security%20issue%20affecting%20FrankenPHP). Only vulnerabilities directly affecting FrankenPHP should be reported to this project. Flaws affecting components used by FrankenPHP (PHP, Caddy, Go...) or using FrankenPHP (Laravel Octane, PHP Runtime...) should be reported to the relevant projects. ================================================ FILE: alpine.Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 #checkov:skip=CKV_DOCKER_7 FROM php-base AS common ARG TARGETARCH WORKDIR /app RUN apk add --no-cache \ ca-certificates \ libcap \ mailcap RUN set -eux; \ mkdir -p \ /app/public \ /config/caddy \ /data/caddy \ /etc/caddy \ /etc/frankenphp; \ sed -i 's/php/frankenphp run/g' /usr/local/bin/docker-php-entrypoint; \ echo ' /app/public/index.php COPY --link caddy/frankenphp/Caddyfile /etc/caddy/Caddyfile RUN ln /etc/caddy/Caddyfile /etc/frankenphp/Caddyfile && \ curl -sSLf \ -o /usr/local/bin/install-php-extensions \ https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions && \ chmod +x /usr/local/bin/install-php-extensions CMD ["--config", "/etc/frankenphp/Caddyfile", "--adapter", "caddyfile"] HEALTHCHECK CMD curl -f http://localhost:2019/metrics || exit 1 # See https://caddyserver.com/docs/conventions#file-locations for details ENV XDG_CONFIG_HOME=/config ENV XDG_DATA_HOME=/data EXPOSE 80 EXPOSE 443 EXPOSE 443/udp EXPOSE 2019 LABEL org.opencontainers.image.title=FrankenPHP LABEL org.opencontainers.image.description="The modern PHP app server" LABEL org.opencontainers.image.url=https://frankenphp.dev LABEL org.opencontainers.image.source=https://github.com/php/frankenphp LABEL org.opencontainers.image.licenses=MIT LABEL org.opencontainers.image.vendor="Kévin Dunglas" FROM common AS builder ARG FRANKENPHP_VERSION='dev' ARG NO_COMPRESS='' SHELL ["/bin/ash", "-eo", "pipefail", "-c"] COPY --link --from=golang-base /usr/local/go /usr/local/go ENV PATH=/usr/local/go/bin:$PATH ENV GOTOOLCHAIN=local # hadolint ignore=SC2086 RUN apk add --no-cache --virtual .build-deps \ $PHPIZE_DEPS \ argon2-dev \ # Needed for the custom Go build \ bash \ brotli-dev \ coreutils \ curl-dev \ # Needed for the custom Go build \ git \ gnu-libiconv-dev \ libsodium-dev \ # Needed for the file watcher \ cmake \ libstdc++ \ libxml2-dev \ linux-headers \ oniguruma-dev \ openssl-dev \ readline-dev \ sqlite-dev \ upx # Install e-dant/watcher (necessary for file watching) WORKDIR /usr/local/src/watcher RUN --mount=type=secret,id=github-token \ if [ -f /run/secrets/github-token ] && [ -s /run/secrets/github-token ]; then \ curl -s -H "Authorization: Bearer $(cat /run/secrets/github-token)" https://api.github.com/repos/e-dant/watcher/releases/latest; \ else \ curl -s https://api.github.com/repos/e-dant/watcher/releases/latest; \ fi | \ grep tarball_url | \ awk '{ print $2 }' | \ sed 's/,$//' | \ sed 's/"//g' | \ xargs curl -L | \ tar xz --strip-components 1 && \ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && \ cmake --build build && \ cmake --install build WORKDIR /go/src/app COPY --link go.mod go.sum ./ RUN go mod download WORKDIR /go/src/app/caddy COPY caddy/go.mod caddy/go.sum ./ RUN go mod download WORKDIR /go/src/app COPY --link . ./ # See https://github.com/docker-library/php/blob/master/8.3/alpine3.20/zts/Dockerfile#L53-L55 ENV CGO_CFLAGS="-DFRANKENPHP_VERSION=$FRANKENPHP_VERSION $PHP_CFLAGS" ENV CGO_CPPFLAGS=$PHP_CPPFLAGS ENV CGO_LDFLAGS="-lssl -lcrypto -lreadline -largon2 -lcurl -lonig -lz $PHP_LDFLAGS" WORKDIR /go/src/app/caddy/frankenphp RUN GOBIN=/usr/local/bin \ ../../go.sh install -ldflags "-w -s -extldflags '-Wl,-z,stack-size=0x80000' -X 'github.com/caddyserver/caddy/v2.CustomVersion=FrankenPHP $FRANKENPHP_VERSION PHP $PHP_VERSION Caddy' -X 'github.com/caddyserver/caddy/v2.CustomBinaryName=frankenphp' -X 'github.com/caddyserver/caddy/v2/modules/caddyhttp.ServerHeader=FrankenPHP Caddy'" -buildvcs=true && \ setcap cap_net_bind_service=+ep /usr/local/bin/frankenphp && \ ([ -z "${NO_COMPRESS}" ] && upx --best /usr/local/bin/frankenphp || true) && \ frankenphp version && \ frankenphp build-info WORKDIR /go/src/app FROM common AS runner ENV GODEBUG=cgocheck=0 # copy watcher shared library (libgcc and libstdc++ are needed for the watcher) COPY --from=builder /usr/local/lib/libwatcher* /usr/local/lib/ RUN apk add --no-cache libstdc++ && \ ldconfig /usr/local/lib COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp RUN setcap cap_net_bind_service=+ep /usr/local/bin/frankenphp && \ frankenphp version && \ frankenphp build-info ================================================ FILE: app_checksum.txt ================================================ ================================================ FILE: build-static.sh ================================================ #!/bin/bash set -o errexit set -x if ! type "git" >/dev/null 2>&1; then echo "The \"git\" command must be installed." exit 1 fi CURRENT_DIR=$(pwd) arch="$(uname -m)" os="$(uname -s | tr '[:upper:]' '[:lower:]')" [ "$os" = "darwin" ] && os="mac" # Supported variables: # - PHP_VERSION: PHP version to build (default: "8.4") # - PHP_EXTENSIONS: PHP extensions to build (default: ${defaultExtensions} set below) # - PHP_EXTENSION_LIBS: PHP extension libraries to build (default: ${defaultExtensionLibs} set below) # - FRANKENPHP_VERSION: FrankenPHP version (default: current Git commit) # - EMBED: Path to the PHP app to embed (default: none) # - DEBUG_SYMBOLS: Enable debug symbols if set to 1 (default: none) # - MIMALLOC: Use mimalloc as the allocator if set to 1 (default: none) # - XCADDY_ARGS: Additional arguments to pass to xcaddy # - RELEASE: [maintainer only] Create a GitHub release if set to 1 (default: none) # - SPC_REL_TYPE: Release type to download (accept "source" and "binary", default: "source") # - SPC_OPT_BUILD_ARGS: Additional arguments to pass to spc build # - SPC_OPT_DOWNLOAD_ARGS: Additional arguments to pass to spc download # - SPC_LIBC: Set to glibc to build with GNU toolchain (default: musl) # init spc command, if we use spc binary, just use it instead of fetching source if [ -z "${SPC_REL_TYPE}" ]; then SPC_REL_TYPE="source" fi # init spc libc if [ -z "${SPC_LIBC}" ]; then if [ "${os}" = "linux" ]; then SPC_LIBC="musl" fi fi # init spc build additional args if [ -z "${SPC_OPT_BUILD_ARGS}" ]; then SPC_OPT_BUILD_ARGS="" fi if [ "${SPC_LIBC}" = "musl" ] && [[ "${SPC_OPT_BUILD_ARGS}" != *"--disable-opcache-jit"* ]]; then SPC_OPT_BUILD_ARGS="${SPC_OPT_BUILD_ARGS} --disable-opcache-jit" fi # init spc download additional args if [ -z "${SPC_OPT_DOWNLOAD_ARGS}" ]; then SPC_OPT_DOWNLOAD_ARGS="--ignore-cache-sources=php-src --retry 5" if [ "${SPC_LIBC}" = "musl" ]; then SPC_OPT_DOWNLOAD_ARGS="${SPC_OPT_DOWNLOAD_ARGS} --prefer-pre-built" fi fi # if we need debug symbols, disable strip if [ -n "${DEBUG_SYMBOLS}" ]; then SPC_OPT_BUILD_ARGS="${SPC_OPT_BUILD_ARGS} --no-strip" fi # php version to build if [ -z "${PHP_VERSION}" ]; then get_latest_php_version() { input="$1" json=$(curl -fsSL "https://www.php.net/releases/index.php?json&version=$input" 2>/dev/null || curl -fsSL "https://phpmirror.static-php.dev/releases/index.php?json&version=$input") latest=$(echo "$json" | jq -r '.version') if [[ "$latest" == "$input"* ]]; then echo "$latest" else echo "$input" fi } PHP_VERSION="$(get_latest_php_version "8.5")" export PHP_VERSION fi # default extension set defaultExtensions="amqp,apcu,ast,bcmath,brotli,bz2,calendar,ctype,curl,dba,dom,exif,fileinfo,filter,ftp,gd,gmp,gettext,iconv,igbinary,imagick,intl,ldap,lz4,mbregex,mbstring,memcached,mysqli,mysqlnd,opcache,openssl,password-argon2,parallel,pcntl,pdo,pdo_mysql,pdo_pgsql,pdo_sqlite,pgsql,phar,posix,protobuf,readline,redis,session,shmop,simplexml,soap,sockets,sodium,sqlite3,ssh2,sysvmsg,sysvsem,sysvshm,tidy,tokenizer,xlswriter,xml,xmlreader,xmlwriter,xsl,xz,zip,zlib,yaml,zstd" defaultExtensionLibs="libavif,nghttp2,nghttp3,ngtcp2,watcher" if [ -z "${FRANKENPHP_VERSION}" ]; then FRANKENPHP_VERSION="$(git rev-parse --verify HEAD)" export FRANKENPHP_VERSION elif [ -d ".git/" ]; then CURRENT_REF="$(git rev-parse --abbrev-ref HEAD)" export CURRENT_REF if echo "${FRANKENPHP_VERSION}" | grep -F -q "."; then # Tag # Trim "v" prefix if any FRANKENPHP_VERSION=${FRANKENPHP_VERSION#v} export FRANKENPHP_VERSION git checkout "v${FRANKENPHP_VERSION}" else git checkout "${FRANKENPHP_VERSION}" fi fi if [ -n "${CLEAN}" ]; then rm -Rf dist/ go clean -cache fi mkdir -p dist/ cd dist/ if type "brew" >/dev/null 2>&1; then if ! type "composer" >/dev/null; then packages="composer" fi if ! type "go" >/dev/null 2>&1; then packages="${packages} go" fi if [ -n "${RELEASE}" ] && ! type "gh" >/dev/null 2>&1; then packages="${packages} gh" fi if [ -n "${packages}" ]; then # shellcheck disable=SC2086 brew install --formula --quiet ${packages} fi fi if [ "${SPC_REL_TYPE}" = "binary" ]; then mkdir -p static-php-cli/ cd static-php-cli/ if [[ "${arch}" =~ "arm" ]]; then dl_arch="aarch64" else dl_arch="${arch}" fi curl -o spc -fsSL "https://dl.static-php.dev/static-php-cli/spc-bin/nightly/spc-linux-${dl_arch}" chmod +x spc spcCommand="./spc" elif [ -d "static-php-cli/src" ]; then cd static-php-cli/ git pull composer install --no-dev -a --no-interaction spcCommand="./bin/spc" else git clone --depth 1 https://github.com/crazywhalecc/static-php-cli --branch main cd static-php-cli/ composer install --no-dev -a --no-interaction spcCommand="./bin/spc" fi # turn potentially relative EMBED path into absolute path if [ -n "${EMBED}" ]; then if [[ "${EMBED}" != /* ]]; then EMBED="${CURRENT_DIR}/${EMBED}" fi fi # Extensions to build if [ -z "${PHP_EXTENSIONS}" ]; then # enable EMBED mode, first check if project has dumped extensions if [ -n "${EMBED}" ] && [ -f "${EMBED}/composer.json" ] && [ -f "${EMBED}/composer.lock" ] && [ -f "${EMBED}/vendor/composer/installed.json" ]; then cd "${EMBED}" # read the extensions using spc dump-extensions PHP_EXTENSIONS=$(${spcCommand} dump-extensions "${EMBED}" --format=text --no-dev --no-ext-output="${defaultExtensions}") else PHP_EXTENSIONS="${defaultExtensions}" fi fi # Additional libraries to build if [ -z "${PHP_EXTENSION_LIBS}" ]; then PHP_EXTENSION_LIBS="${defaultExtensionLibs}" fi # The Brotli library must always be built as it is required by http://github.com/dunglas/caddy-cbrotli if ! echo "${PHP_EXTENSION_LIBS}" | grep -q "\bbrotli\b"; then PHP_EXTENSION_LIBS="${PHP_EXTENSION_LIBS},brotli" fi # The mimalloc library must be built if MIMALLOC is true if [ -n "${MIMALLOC}" ]; then if ! echo "${PHP_EXTENSION_LIBS}" | grep -q "\bmimalloc\b"; then PHP_EXTENSION_LIBS="${PHP_EXTENSION_LIBS},mimalloc" fi fi # Embed PHP app, if any if [ -n "${EMBED}" ] && [ -d "${EMBED}" ]; then # shellcheck disable=SC2089 SPC_OPT_BUILD_ARGS="${SPC_OPT_BUILD_ARGS} --with-frankenphp-app='${EMBED}'" fi SPC_OPT_INSTALL_ARGS="go-xcaddy" if [ -z "${DEBUG_SYMBOLS}" ] && [ -z "${NO_COMPRESS}" ] && [ "${os}" = "linux" ]; then SPC_OPT_BUILD_ARGS="${SPC_OPT_BUILD_ARGS} --with-upx-pack" SPC_OPT_INSTALL_ARGS="${SPC_OPT_INSTALL_ARGS} upx" fi export SPC_DEFAULT_C_FLAGS="-fPIC -O2" if [ -n "${DEBUG_SYMBOLS}" ]; then SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS="${SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS} -fPIE -g" else SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS="${SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS} -fPIE -fstack-protector-strong -O2 -w -s" fi export SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS if [ -z "$SPC_CMD_VAR_FRANKENPHP_XCADDY_MODULES" ]; then export SPC_CMD_VAR_FRANKENPHP_XCADDY_MODULES="--with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy --with github.com/dunglas/caddy-cbrotli" fi # Build FrankenPHP ${spcCommand} doctor --auto-fix for pkg in ${SPC_OPT_INSTALL_ARGS}; do ${spcCommand} install-pkg "${pkg}" done # shellcheck disable=SC2086 ${spcCommand} download --with-php="${PHP_VERSION}" --for-extensions="${PHP_EXTENSIONS}" --for-libs="${PHP_EXTENSION_LIBS}" ${SPC_OPT_DOWNLOAD_ARGS} export FRANKENPHP_SOURCE_PATH="${CURRENT_DIR}" # shellcheck disable=SC2086,SC2090 ${spcCommand} build --enable-zts --build-embed --build-frankenphp ${SPC_OPT_BUILD_ARGS} "${PHP_EXTENSIONS}" --with-libs="${PHP_EXTENSION_LIBS}" if [ -n "$CI" ]; then rm -rf ./downloads rm -rf ./source fi cd ../.. bin="dist/frankenphp-${os}-${arch}" cp "dist/static-php-cli/buildroot/bin/frankenphp" "${bin}" "${bin}" version "${bin}" build-info if [ -n "${RELEASE}" ]; then gh release upload "v${FRANKENPHP_VERSION}" "${bin}" --repo dunglas/frankenphp --clobber fi if [ -n "${CURRENT_REF}" ]; then git checkout "${CURRENT_REF}" fi ================================================ FILE: caddy/admin.go ================================================ package caddy import ( "encoding/json" "fmt" "net/http" "github.com/caddyserver/caddy/v2" "github.com/dunglas/frankenphp" ) type FrankenPHPAdmin struct { } // if the id starts with "admin.api" the module will register AdminRoutes via module.Routes() func (FrankenPHPAdmin) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.frankenphp", New: func() caddy.Module { return new(FrankenPHPAdmin) }, } } // EXPERIMENTAL: These routes are not yet stable and may change in the future. func (admin FrankenPHPAdmin) Routes() []caddy.AdminRoute { return []caddy.AdminRoute{ { Pattern: "/frankenphp/workers/restart", Handler: caddy.AdminHandlerFunc(admin.restartWorkers), }, { Pattern: "/frankenphp/threads", Handler: caddy.AdminHandlerFunc(admin.threads), }, } } func (admin *FrankenPHPAdmin) restartWorkers(w http.ResponseWriter, r *http.Request) error { if r.Method != http.MethodPost { return admin.error(http.StatusMethodNotAllowed, fmt.Errorf("method not allowed")) } frankenphp.RestartWorkers() caddy.Log().Info("workers restarted from admin api") admin.success(w, "workers restarted successfully\n") return nil } func (admin *FrankenPHPAdmin) threads(w http.ResponseWriter, _ *http.Request) error { debugState := frankenphp.DebugState() prettyJson, err := json.MarshalIndent(debugState, "", " ") if err != nil { return admin.error(http.StatusInternalServerError, err) } return admin.success(w, string(prettyJson)) } func (admin *FrankenPHPAdmin) success(w http.ResponseWriter, message string) error { w.WriteHeader(http.StatusOK) _, err := w.Write([]byte(message)) return err } func (admin *FrankenPHPAdmin) error(statusCode int, err error) error { return caddy.APIError{HTTPStatus: statusCode, Err: err} } ================================================ FILE: caddy/admin_test.go ================================================ package caddy_test import ( "bytes" "encoding/json" "fmt" "io" "net/http" "strings" "sync" "testing" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/caddyserver/caddy/v2/caddytest" "github.com/dunglas/frankenphp" "github.com/stretchr/testify/assert" ) func TestRestartWorkerViaAdminApi(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker ../testdata/worker-with-counter.php 1 } } localhost:`+testPort+` { route { root ../testdata rewrite worker-with-counter.php php } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/", http.StatusOK, "requests:1") tester.AssertGetResponse("http://localhost:"+testPort+"/", http.StatusOK, "requests:2") assertAdminResponse(t, tester, "POST", "workers/restart", http.StatusOK, "workers restarted successfully\n") tester.AssertGetResponse("http://localhost:"+testPort+"/", http.StatusOK, "requests:1") } func TestShowTheCorrectThreadDebugStatus(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { num_threads 3 max_threads 6 worker ../testdata/worker-with-counter.php 1 worker ../testdata/index.php 1 } } localhost:`+testPort+` { route { root ../testdata rewrite worker-with-counter.php php } } `, "caddyfile") debugState := getDebugState(t, tester) // assert that the correct threads are present in the thread info assert.Equal(t, debugState.ThreadDebugStates[0].State, "ready") assert.Contains(t, debugState.ThreadDebugStates[1].Name, "worker-with-counter.php") assert.Contains(t, debugState.ThreadDebugStates[2].Name, "index.php") assert.Equal(t, debugState.ReservedThreadCount, 3) assert.Len(t, debugState.ThreadDebugStates, 3) } func TestAutoScaleWorkerThreads(t *testing.T) { wg := sync.WaitGroup{} maxTries := 10 requestsPerTry := 200 tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { max_threads 10 num_threads 2 worker ../testdata/sleep.php { num 1 max_threads 3 } } } localhost:`+testPort+` { route { root ../testdata rewrite sleep.php php } } `, "caddyfile") // spam an endpoint that simulates IO endpoint := "http://localhost:" + testPort + "/?sleep=2&work=1000" amountOfThreads := getNumThreads(t, tester) // try to spawn the additional threads by spamming the server for range maxTries { wg.Add(requestsPerTry) for range requestsPerTry { go func() { tester.AssertGetResponse(endpoint, http.StatusOK, "slept for 2 ms and worked for 1000 iterations") wg.Done() }() } wg.Wait() amountOfThreads = getNumThreads(t, tester) if amountOfThreads > 2 { break } } assert.NotEqual(t, amountOfThreads, 2, "at least one thread should have been auto-scaled") assert.LessOrEqual(t, amountOfThreads, 4, "at most 3 max_threads + 1 regular thread should be present") } // Note this test requires at least 2x40MB available memory for the process func TestAutoScaleRegularThreadsOnAutomaticThreadLimit(t *testing.T) { wg := sync.WaitGroup{} maxTries := 10 requestsPerTry := 200 tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { max_threads auto num_threads 1 php_ini memory_limit 40M # a reasonable limit for the test } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") // spam an endpoint that simulates IO endpoint := "http://localhost:" + testPort + "/sleep.php?sleep=2&work=1000" amountOfThreads := getNumThreads(t, tester) // try to spawn the additional threads by spamming the server for range maxTries { wg.Add(requestsPerTry) for range requestsPerTry { go func() { tester.AssertGetResponse(endpoint, http.StatusOK, "slept for 2 ms and worked for 1000 iterations") wg.Done() }() } wg.Wait() amountOfThreads = getNumThreads(t, tester) if amountOfThreads > 1 { break } } // assert that there are now more threads present assert.NotEqual(t, amountOfThreads, 1) } func assertAdminResponse(t *testing.T, tester *caddytest.Tester, method string, path string, expectedStatus int, expectedBody string) { adminUrl := "http://localhost:2999/frankenphp/" r, err := http.NewRequest(method, adminUrl+path, nil) assert.NoError(t, err) if expectedBody == "" { _ = tester.AssertResponseCode(r, expectedStatus) return } _, _ = tester.AssertResponse(r, expectedStatus, expectedBody) } func getAdminResponseBody(t *testing.T, tester *caddytest.Tester, method string, path string) string { adminUrl := "http://localhost:2999/frankenphp/" r, err := http.NewRequest(method, adminUrl+path, nil) assert.NoError(t, err) resp := tester.AssertResponseCode(r, http.StatusOK) defer resp.Body.Close() bytes, err := io.ReadAll(resp.Body) assert.NoError(t, err) return string(bytes) } func getDebugState(t *testing.T, tester *caddytest.Tester) frankenphp.FrankenPHPDebugState { t.Helper() threadStates := getAdminResponseBody(t, tester, "GET", "threads") var debugStates frankenphp.FrankenPHPDebugState err := json.Unmarshal([]byte(threadStates), &debugStates) assert.NoError(t, err) return debugStates } func getNumThreads(t *testing.T, tester *caddytest.Tester) int { t.Helper() return len(getDebugState(t, tester).ThreadDebugStates) } func TestAddModuleWorkerViaAdminApi(t *testing.T) { // Initialize a server with admin API enabled tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") // Get initial debug state to check number of workers initialDebugState := getDebugState(t, tester) initialWorkerCount := 0 for _, thread := range initialDebugState.ThreadDebugStates { if strings.HasPrefix(thread.Name, "Worker PHP Thread") { initialWorkerCount++ } } // Create a Caddyfile configuration with a module worker workerConfig := ` { skip_install_trust admin localhost:2999 http_port ` + testPort + ` } localhost:` + testPort + ` { route { root ../testdata php { worker ../testdata/worker-with-counter.php 1 } } } ` // Send the configuration to the admin API adminUrl := "http://localhost:2999/load" r, err := http.NewRequest("POST", adminUrl, bytes.NewBufferString(workerConfig)) assert.NoError(t, err) r.Header.Set("Content-Type", "text/caddyfile") resp := tester.AssertResponseCode(r, http.StatusOK) defer resp.Body.Close() // Get the updated debug state to check if the worker was added updatedDebugState := getDebugState(t, tester) updatedWorkerCount := 0 workerFound := false filename, _ := fastabs.FastAbs("../testdata/worker-with-counter.php") for _, thread := range updatedDebugState.ThreadDebugStates { if strings.HasPrefix(thread.Name, "Worker PHP Thread") { updatedWorkerCount++ if thread.Name == "Worker PHP Thread - "+filename { workerFound = true } } } // Assert that the worker was added assert.Greater(t, updatedWorkerCount, initialWorkerCount, "Worker count should have increased") assert.True(t, workerFound, fmt.Sprintf("Worker with name %q should be found", "Worker PHP Thread - "+filename)) // Make a request to the worker to verify it's working tester.AssertGetResponse("http://localhost:"+testPort+"/worker-with-counter.php", http.StatusOK, "requests:1") } ================================================ FILE: caddy/app.go ================================================ package caddy import ( "context" "errors" "fmt" "log/slog" "path/filepath" "strconv" "strings" "sync" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/internal/fastabs" ) var ( options []frankenphp.Option optionsMU sync.RWMutex ) // EXPERIMENTAL: RegisterWorkers provides a way for extensions to register frankenphp.Workers func RegisterWorkers(name, fileName string, num int, wo ...frankenphp.WorkerOption) frankenphp.Workers { w, opt := frankenphp.WithExtensionWorkers(name, fileName, num, wo...) optionsMU.Lock() options = append(options, opt) optionsMU.Unlock() return w } // FrankenPHPApp represents the global "frankenphp" directive in the Caddyfile // it's responsible for starting up the global PHP instance and all threads // // { // frankenphp { // num_threads 20 // } // } type FrankenPHPApp struct { // NumThreads sets the number of PHP threads to start. Default: 2x the number of available CPUs. NumThreads int `json:"num_threads,omitempty"` // MaxThreads limits how many threads can be started at runtime. Default 2x NumThreads MaxThreads int `json:"max_threads,omitempty"` // Workers configures the worker scripts to start Workers []workerConfig `json:"workers,omitempty"` // Overwrites the default php ini configuration PhpIni map[string]string `json:"php_ini,omitempty"` // The maximum amount of time a request may be stalled waiting for a thread MaxWaitTime time.Duration `json:"max_wait_time,omitempty"` // The maximum amount of time an autoscaled thread may be idle before being deactivated MaxIdleTime time.Duration `json:"max_idle_time,omitempty"` opts []frankenphp.Option metrics frankenphp.Metrics ctx context.Context logger *slog.Logger } var iniError = errors.New(`"php_ini" must be in the format: php_ini "" ""`) // CaddyModule returns the Caddy module information. func (f FrankenPHPApp) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "frankenphp", New: func() caddy.Module { return &f }, } } // Provision sets up the module. func (f *FrankenPHPApp) Provision(ctx caddy.Context) error { f.ctx = ctx f.logger = ctx.Slogger() // We have at least 7 hardcoded options f.opts = make([]frankenphp.Option, 0, 7+len(options)) if httpApp, err := ctx.AppIfConfigured("http"); err == nil { if httpApp.(*caddyhttp.App).Metrics != nil { f.metrics = frankenphp.NewPrometheusMetrics(ctx.GetMetricsRegistry()) } } else { // if the http module is not configured (this should never happen) then collect the metrics by default if errors.Is(err, caddy.ErrNotConfigured) { f.metrics = frankenphp.NewPrometheusMetrics(ctx.GetMetricsRegistry()) } else { // the http module failed to provision due to invalid configuration return fmt.Errorf("failed to provision caddy http: %w", err) } } return nil } func (f *FrankenPHPApp) generateUniqueModuleWorkerName(filepath string) string { var i uint filepath, _ = fastabs.FastAbs(filepath) name := "m#" + filepath retry: for _, wc := range f.Workers { if wc.Name == name { name = fmt.Sprintf("m#%s_%d", filepath, i) i++ goto retry } } return name } func (f *FrankenPHPApp) addModuleWorkers(workers ...workerConfig) ([]workerConfig, error) { for i := range workers { w := &workers[i] if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(w.FileName) { w.FileName = filepath.Join(frankenphp.EmbeddedAppPath, w.FileName) } if w.Name == "" { w.Name = f.generateUniqueModuleWorkerName(w.FileName) } else if !strings.HasPrefix(w.Name, "m#") { w.Name = "m#" + w.Name } f.Workers = append(f.Workers, *w) } return workers, nil } func (f *FrankenPHPApp) Start() error { repl := caddy.NewReplacer() optionsMU.RLock() f.opts = append(f.opts, options...) optionsMU.RUnlock() f.opts = append(f.opts, frankenphp.WithContext(f.ctx), frankenphp.WithLogger(f.logger), frankenphp.WithNumThreads(f.NumThreads), frankenphp.WithMaxThreads(f.MaxThreads), frankenphp.WithMetrics(f.metrics), frankenphp.WithPhpIni(f.PhpIni), frankenphp.WithMaxWaitTime(f.MaxWaitTime), frankenphp.WithMaxIdleTime(f.MaxIdleTime), ) for _, w := range f.Workers { w.options = append(w.options, frankenphp.WithWorkerEnv(w.Env), frankenphp.WithWorkerWatchMode(w.Watch), frankenphp.WithWorkerMaxFailures(w.MaxConsecutiveFailures), frankenphp.WithWorkerMaxThreads(w.MaxThreads), frankenphp.WithWorkerRequestOptions(w.requestOptions...), ) f.opts = append(f.opts, frankenphp.WithWorkers(w.Name, repl.ReplaceKnown(w.FileName, ""), w.Num, w.options...)) } frankenphp.Shutdown() if err := frankenphp.Init(f.opts...); err != nil { return err } return nil } func (f *FrankenPHPApp) Stop() error { if f.logger.Enabled(f.ctx, slog.LevelInfo) { f.logger.LogAttrs(f.ctx, slog.LevelInfo, "FrankenPHP stopped 🐘") } // attempt a graceful shutdown if caddy is exiting // note: Exiting() is currently marked as 'experimental' // https://github.com/caddyserver/caddy/blob/e76405d55058b0a3e5ba222b44b5ef00516116aa/caddy.go#L810 if caddy.Exiting() { frankenphp.Shutdown() } // reset the configuration so it doesn't bleed into later tests f.Workers = nil f.NumThreads = 0 f.MaxWaitTime = 0 f.MaxIdleTime = 0 optionsMU.Lock() options = nil optionsMU.Unlock() return nil } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (f *FrankenPHPApp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.Next() { for d.NextBlock(0) { // when adding a new directive, also update the allowedDirectives error message switch d.Val() { case "num_threads": if !d.NextArg() { return d.ArgErr() } v, err := strconv.ParseUint(d.Val(), 10, 32) if err != nil { return err } f.NumThreads = int(v) case "max_threads": if !d.NextArg() { return d.ArgErr() } if d.Val() == "auto" { f.MaxThreads = -1 continue } v, err := strconv.ParseUint(d.Val(), 10, 32) if err != nil { return err } f.MaxThreads = int(v) case "max_wait_time": if !d.NextArg() { return d.ArgErr() } v, err := time.ParseDuration(d.Val()) if err != nil { return d.Err("max_wait_time must be a valid duration (example: 10s)") } f.MaxWaitTime = v case "max_idle_time": if !d.NextArg() { return d.ArgErr() } v, err := time.ParseDuration(d.Val()) if err != nil { return d.Err("max_idle_time must be a valid duration (example: 30s)") } f.MaxIdleTime = v case "php_ini": parseIniLine := func(d *caddyfile.Dispenser) error { key := d.Val() if !d.NextArg() { return d.WrapErr(iniError) } if f.PhpIni == nil { f.PhpIni = make(map[string]string) } f.PhpIni[key] = d.Val() if d.NextArg() { return d.WrapErr(iniError) } return nil } isBlock := false for d.NextBlock(1) { isBlock = true err := parseIniLine(d) if err != nil { return err } } if !isBlock { if !d.NextArg() { return d.WrapErr(iniError) } err := parseIniLine(d) if err != nil { return err } } case "worker": wc, err := unmarshalWorker(d) if err != nil { return err } if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(wc.FileName) { wc.FileName = filepath.Join(frankenphp.EmbeddedAppPath, wc.FileName) } if strings.HasPrefix(wc.Name, "m#") { return d.Errf(`global worker names must not start with "m#": %q`, wc.Name) } // check for duplicate workers for _, existingWorker := range f.Workers { if existingWorker.FileName == wc.FileName { return d.Errf("global workers must not have duplicate filenames: %q", wc.FileName) } } f.Workers = append(f.Workers, wc) default: return wrongSubDirectiveError("frankenphp", "num_threads, max_threads, php_ini, worker, max_wait_time, max_idle_time", d.Val()) } } } if f.MaxThreads > 0 && f.NumThreads > 0 && f.MaxThreads < f.NumThreads { return d.Err(`"max_threads"" must be greater than or equal to "num_threads"`) } return nil } func parseGlobalOption(d *caddyfile.Dispenser, _ any) (any, error) { app := &FrankenPHPApp{} if err := app.UnmarshalCaddyfile(d); err != nil { return nil, err } // tell Caddyfile adapter that this is the JSON for an app return httpcaddyfile.App{ Name: "frankenphp", Value: caddyconfig.JSON(app, nil), }, nil } var ( _ caddy.App = (*FrankenPHPApp)(nil) _ caddy.Provisioner = (*FrankenPHPApp)(nil) ) ================================================ FILE: caddy/br-skip.go ================================================ //go:build nobrotli package caddy var brotli = false ================================================ FILE: caddy/br.go ================================================ //go:build !nobrotli package caddy var brotli = true ================================================ FILE: caddy/caddy.go ================================================ // Package caddy provides a PHP module for the Caddy web server. // FrankenPHP embeds the PHP interpreter directly in Caddy, giving it the ability to run your PHP scripts directly. // No PHP FPM required! package caddy import ( "fmt" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" ) const ( defaultDocumentRoot = "public" defaultWatchPattern = "./**/*.{env,php,twig,yaml,yml}" ) func init() { caddy.RegisterModule(FrankenPHPApp{}) caddy.RegisterModule(FrankenPHPModule{}) caddy.RegisterModule(FrankenPHPAdmin{}) httpcaddyfile.RegisterGlobalOption("frankenphp", parseGlobalOption) httpcaddyfile.RegisterHandlerDirective("php", parseCaddyfile) httpcaddyfile.RegisterDirectiveOrder("php", "before", "file_server") httpcaddyfile.RegisterDirective("php_server", parsePhpServer) httpcaddyfile.RegisterDirectiveOrder("php_server", "before", "file_server") } // wrongSubDirectiveError returns a nice error message. func wrongSubDirectiveError(module string, allowedDirectives string, wrongValue string) error { return fmt.Errorf("unknown %q subdirective: %s (allowed directives are: %s)", module, wrongValue, allowedDirectives) } ================================================ FILE: caddy/caddy_test.go ================================================ package caddy_test import ( "bytes" "fmt" "net/http" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddytest" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" ) // initServer initializes a Caddy test server and waits for it to be ready. // After InitServer, it polls the server to handle a race condition on macOS where // SO_REUSEPORT can briefly route connections to the old listener being shut down, // resulting in "connection reset by peer". func initServer(t *testing.T, tester *caddytest.Tester, config string, format string) { t.Helper() tester.InitServer(config, format) client := &http.Client{Timeout: 1 * time.Second} require.Eventually(t, func() bool { resp, err := client.Get("http://localhost:" + testPort) if err != nil { return false } require.NoError(t, resp.Body.Close()) return true }, 5*time.Second, 100*time.Millisecond, "server failed to become ready") } var testPort = "9080" // skipIfSymlinkNotValid skips the test if the given path is not a valid symlink func skipIfSymlinkNotValid(t *testing.T, path string) { t.Helper() info, err := os.Lstat(path) if err != nil { t.Skipf("symlink test skipped: cannot stat %s: %v", path, err) } if info.Mode()&os.ModeSymlink == 0 { t.Skipf("symlink test skipped: %s is not a symlink (git may not support symlinks on this platform)", path) } } // escapeMetricLabel escapes backslashes in label values for Prometheus text format func escapeMetricLabel(s string) string { return strings.ReplaceAll(s, "\\", "\\\\") } func TestMain(m *testing.M) { // setup custom environment vars for TestOsEnv if os.Setenv("ENV1", "value1") != nil || os.Setenv("ENV2", "value2") != nil { fmt.Println("Failed to set environment variables for tests") os.Exit(1) } os.Exit(m.Run()) } func TestPHP(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") for i := range 100 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() } func TestLargeRequest(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") tester.AssertPostResponseBody( "http://localhost:"+testPort+"/large-request.php", []string{}, bytes.NewBufferString(strings.Repeat("f", 1_048_576)), http.StatusOK, "Request body size: 1048576 (unknown)", ) } func TestWorker(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 frankenphp { worker ../testdata/index.php 2 } } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") for i := range 100 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() } func TestGlobalAndModuleWorker(t *testing.T) { var wg sync.WaitGroup testPortNum, _ := strconv.Atoi(testPort) testPortTwo := strconv.Itoa(testPortNum + 1) tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 frankenphp { worker { file ../testdata/worker-with-env.php num 1 env APP_ENV global } } } http://localhost:`+testPort+` { route { php { root ../testdata worker { file worker-with-env.php num 2 env APP_ENV module } } } } http://localhost:`+testPortTwo+` { route { php { root ../testdata } } } `, "caddyfile") for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse("http://localhost:"+testPort+"/worker-with-env.php", http.StatusOK, "Worker has APP_ENV=module") tester.AssertGetResponse("http://localhost:"+testPortTwo+"/worker-with-env.php", http.StatusOK, "Worker has APP_ENV=global") wg.Done() }(i) } wg.Wait() } func TestModuleWorkerInheritsEnv(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { route { php { root ../testdata env APP_ENV inherit_this worker worker-with-env.php } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/worker-with-env.php", http.StatusOK, "Worker has APP_ENV=inherit_this") } func TestNamedModuleWorkers(t *testing.T) { var wg sync.WaitGroup testPortNum, _ := strconv.Atoi(testPort) testPortTwo := strconv.Itoa(testPortNum + 1) tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { route { php { root ../testdata worker { file worker-with-env.php num 2 env APP_ENV one name module1 } } } } http://localhost:`+testPortTwo+` { route { php { root ../testdata worker { file worker-with-env.php num 1 env APP_ENV two name module2 } } } } `, "caddyfile") for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse("http://localhost:"+testPort+"/worker-with-env.php", http.StatusOK, "Worker has APP_ENV=one") tester.AssertGetResponse("http://localhost:"+testPortTwo+"/worker-with-env.php", http.StatusOK, "Worker has APP_ENV=two") wg.Done() }(i) } wg.Wait() } func TestEnv(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 frankenphp { worker { file ../testdata/worker-env.php num 1 env FOO bar } } } localhost:`+testPort+` { route { php { root ../testdata env FOO baz } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/worker-env.php", http.StatusOK, "bazbar") } func TestJsonEnv(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { "admin": { "listen": "localhost:2999" }, "apps": { "frankenphp": { "workers": [ { "env": { "FOO": "bar" }, "file_name": "../testdata/worker-env.php", "num": 1 } ] }, "http": { "http_port": `+testPort+`, "https_port": 9443, "servers": { "srv0": { "listen": [ ":`+testPort+`" ], "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "handler": "subroute", "routes": [ { "handle": [ { "env": { "FOO": "baz" }, "handler": "php", "root": "../testdata" } ] } ] } ] } ] } ], "match": [ { "host": [ "localhost" ] } ], "terminal": true } ] } } }, "pki": { "certificate_authorities": { "local": { "install_trust": false } } } } } `, "json") tester.AssertGetResponse("http://localhost:"+testPort+"/worker-env.php", http.StatusOK, "bazbar") } func TestCustomCaddyVariablesInEnv(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 frankenphp { worker { file ../testdata/worker-env.php num 1 env FOO world } } } localhost:`+testPort+` { route { map 1 {my_customvar} { default "hello " } php { root ../testdata env FOO {my_customvar} } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/worker-env.php", http.StatusOK, "hello world") } func TestPHPServerDirective(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 } localhost:`+testPort+` { root ../testdata php_server } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort, http.StatusOK, "I am by birth a Genevese (i not set)") tester.AssertGetResponse("http://localhost:"+testPort+"/hello.txt", http.StatusOK, "Hello\n") tester.AssertGetResponse("http://localhost:"+testPort+"/not-found.txt", http.StatusOK, "I am by birth a Genevese (i not set)") } func TestPHPServerDirectiveDisableFileServer(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 order php_server before respond } localhost:`+testPort+` { root ../testdata php_server { file_server off } respond "Not found" 404 } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort, http.StatusOK, "I am by birth a Genevese (i not set)") tester.AssertGetResponse("http://localhost:"+testPort+"/not-found.txt", http.StatusOK, "I am by birth a Genevese (i not set)") } func TestMetrics(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics } localhost:`+testPort+` { route { mercure { transport local anonymous publisher_jwt !ChangeMe! } php { root ../testdata } } } example.com:`+testPort+` { route { mercure { transport local anonymous publisher_jwt !ChangeMe! } php { root ../testdata } } } `, "caddyfile") // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") cpus := strconv.Itoa(getNumThreads(t, tester)) // Check metrics expectedMetrics := ` # HELP frankenphp_total_threads Total number of PHP threads # TYPE frankenphp_total_threads counter frankenphp_total_threads ` + cpus + ` # HELP frankenphp_busy_threads Number of busy PHP threads # TYPE frankenphp_busy_threads gauge frankenphp_busy_threads 0 ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare(ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_threads", "frankenphp_busy_threads")) } func TestWorkerMetrics(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics frankenphp { worker ../testdata/index.php 2 } } localhost:`+testPort+` { route { php { root ../testdata } } } example.com:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") workerName, _ := fastabs.FastAbs("../testdata/index.php") workerName = escapeMetricLabel(workerName) // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") cpus := strconv.Itoa(getNumThreads(t, tester)) // Check metrics expectedMetrics := ` # HELP frankenphp_total_threads Total number of PHP threads # TYPE frankenphp_total_threads counter frankenphp_total_threads ` + cpus + ` # HELP frankenphp_busy_threads Number of busy PHP threads # TYPE frankenphp_busy_threads gauge frankenphp_busy_threads 2 # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge frankenphp_busy_workers{worker="` + workerName + `"} 0 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="` + workerName + `"} 2 # HELP frankenphp_worker_request_count # TYPE frankenphp_worker_request_count counter frankenphp_worker_request_count{worker="` + workerName + `"} 10 # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="` + workerName + `"} 2 ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_threads", "frankenphp_busy_threads", "frankenphp_busy_workers", "frankenphp_total_workers", "frankenphp_worker_request_count", "frankenphp_ready_workers", )) } func TestNamedWorkerMetrics(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics frankenphp { worker { name my_app file ../testdata/index.php num 2 } } } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") cpus := strconv.Itoa(getNumThreads(t, tester)) // Check metrics expectedMetrics := ` # HELP frankenphp_total_threads Total number of PHP threads # TYPE frankenphp_total_threads counter frankenphp_total_threads ` + cpus + ` # HELP frankenphp_busy_threads Number of busy PHP threads # TYPE frankenphp_busy_threads gauge frankenphp_busy_threads 2 # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge frankenphp_busy_workers{worker="my_app"} 0 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="my_app"} 2 # HELP frankenphp_worker_request_count # TYPE frankenphp_worker_request_count counter frankenphp_worker_request_count{worker="my_app"} 10 # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="my_app"} 2 ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_threads", "frankenphp_busy_threads", "frankenphp_busy_workers", "frankenphp_total_workers", "frankenphp_worker_request_count", "frankenphp_ready_workers", ), ) } func TestAutoWorkerConfig(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics frankenphp { worker ../testdata/index.php } } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") workerName, _ := fastabs.FastAbs("../testdata/index.php") workerName = escapeMetricLabel(workerName) // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") numThreads := getNumThreads(t, tester) cpus := strconv.Itoa(numThreads) workers := strconv.Itoa(numThreads - 1) // Check metrics expectedMetrics := ` # HELP frankenphp_total_threads Total number of PHP threads # TYPE frankenphp_total_threads counter frankenphp_total_threads ` + cpus + ` # HELP frankenphp_busy_threads Number of busy PHP threads # TYPE frankenphp_busy_threads gauge frankenphp_busy_threads ` + workers + ` # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge frankenphp_busy_workers{worker="` + workerName + `"} 0 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="` + workerName + `"} ` + workers + ` # HELP frankenphp_worker_request_count # TYPE frankenphp_worker_request_count counter frankenphp_worker_request_count{worker="` + workerName + `"} 10 # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="` + workerName + `"} ` + workers + ` ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_threads", "frankenphp_busy_threads", "frankenphp_busy_workers", "frankenphp_total_workers", "frankenphp_worker_request_count", "frankenphp_ready_workers", )) } func TestAllDefinedServerVars(t *testing.T) { documentRoot, _ := filepath.Abs("../testdata/") expectedBodyFile, _ := os.ReadFile("../testdata/server-all-vars-ordered.txt") expectedBody := string(expectedBodyFile) expectedBody = strings.ReplaceAll(expectedBody, "{documentRoot}", documentRoot) expectedBody = strings.ReplaceAll(expectedBody, "\r\n", "\n") expectedBody = strings.ReplaceAll(expectedBody, "{testPort}", testPort) expectedBody = strings.ReplaceAll(expectedBody, documentRoot+"/", documentRoot+string(filepath.Separator)) tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` } localhost:`+testPort+` { route { root ../testdata # rewrite to test that the original path is passed as $REQUEST_URI rewrite /server-all-vars-ordered.php/path php } } `, "caddyfile") tester.AssertPostResponseBody( "http://user@localhost:"+testPort+"/original-path?specialChars=%3E\\x00%00", []string{ "Content-Type: application/x-www-form-urlencoded", "Content-Length: 14", // maliciously set to 14 "Special-Chars: <%00>", "Host: Malicious Host", "X-Empty-Header:", }, bytes.NewBufferString("foo=bar"), http.StatusOK, expectedBody, ) } func TestPHPIniConfiguration(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { num_threads 2 worker ../testdata/ini.php 1 php_ini upload_max_filesize 100M php_ini memory_limit 10000000 } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") testSingleIniConfiguration(tester, "upload_max_filesize", "100M") testSingleIniConfiguration(tester, "memory_limit", "10000000") } func TestPHPIniBlockConfiguration(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { num_threads 1 php_ini { upload_max_filesize 100M memory_limit 20000000 } } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") testSingleIniConfiguration(tester, "upload_max_filesize", "100M") testSingleIniConfiguration(tester, "memory_limit", "20000000") } func testSingleIniConfiguration(tester *caddytest.Tester, key string, value string) { // test twice to ensure the ini setting is not lost for range 2 { tester.AssertGetResponse( "http://localhost:"+testPort+"/ini.php?key="+key, http.StatusOK, key+":"+value, ) } } func TestOsEnv(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { num_threads 2 php_ini variables_order "EGPCS" worker ../testdata/env/env.php 1 } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") tester.AssertGetResponse( "http://localhost:"+testPort+"/env/env.php?keys[]=ENV1&keys[]=ENV2", http.StatusOK, "ENV1=value1,ENV2=value2", ) } func TestMaxWaitTime(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { num_threads 1 max_wait_time 1ns } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") // send 10 requests simultaneously, at least one request should be stalled longer than 1ns // since we only have 1 thread, this will cause a 504 Gateway Timeout wg := sync.WaitGroup{} success := atomic.Bool{} wg.Add(10) for range 10 { go func() { statusCode := getStatusCode("http://localhost:"+testPort+"/sleep.php?sleep=10", t) if statusCode == http.StatusServiceUnavailable { success.Store(true) } wg.Done() }() } wg.Wait() require.True(t, success.Load(), "At least one request should have failed with a 503 Service Unavailable status") } func TestMaxWaitTimeWorker(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` metrics frankenphp { num_threads 2 max_wait_time 1ns worker { num 1 name service file ../testdata/sleep.php } } } localhost:`+testPort+` { route { root ../testdata php } } `, "caddyfile") // send 10 requests simultaneously, at least one request should be stalled longer than 1ns // since we only have 1 thread, this will cause a 504 Gateway Timeout wg := sync.WaitGroup{} success := atomic.Bool{} wg.Add(10) for range 10 { go func() { statusCode := getStatusCode("http://localhost:"+testPort+"/sleep.php?sleep=10&iteration=1", t) if statusCode == http.StatusServiceUnavailable { success.Store(true) } wg.Done() }() } wg.Wait() require.True(t, success.Load(), "At least one request should have failed with a 503 Service Unavailable status") // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err) expectedMetrics := ` # TYPE frankenphp_worker_queue_depth gauge frankenphp_worker_queue_depth{worker="service"} 0 ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_worker_queue_depth", )) } func getStatusCode(url string, t *testing.T) int { req, err := http.NewRequest("GET", url, nil) require.NoError(t, err) resp, err := http.DefaultClient.Do(req) require.NoError(t, err) require.NoError(t, resp.Body.Close()) return resp.StatusCode } func TestMultiWorkersMetrics(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics frankenphp { worker { name service1 file ../testdata/index.php num 2 } worker { name service2 file ../testdata/ini.php num 3 } } } localhost:`+testPort+` { route { php { root ../testdata } } } example.com:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") cpus := strconv.Itoa(getNumThreads(t, tester)) // Check metrics expectedMetrics := ` # HELP frankenphp_total_threads Total number of PHP threads # TYPE frankenphp_total_threads counter frankenphp_total_threads ` + cpus + ` # HELP frankenphp_busy_threads Number of busy PHP threads # TYPE frankenphp_busy_threads gauge frankenphp_busy_threads 5 # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge frankenphp_busy_workers{worker="service1"} 0 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="service1"} 2 frankenphp_total_workers{worker="service2"} 3 # HELP frankenphp_worker_request_count # TYPE frankenphp_worker_request_count counter frankenphp_worker_request_count{worker="service1"} 10 # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="service1"} 2 frankenphp_ready_workers{worker="service2"} 3 ` ctx := caddy.ActiveContext() require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_threads", "frankenphp_busy_threads", "frankenphp_busy_workers", "frankenphp_total_workers", "frankenphp_worker_request_count", "frankenphp_ready_workers", )) } func TestDisabledMetrics(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 frankenphp { worker { name service1 file ../testdata/index.php num 2 } worker { name service2 file ../testdata/ini.php num 3 } } } localhost:`+testPort+` { route { php { root ../testdata } } } example.com:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/index.php?i=%d", i), http.StatusOK, fmt.Sprintf("I am by birth a Genevese (%d)", i)) wg.Done() }(i) } wg.Wait() // Fetch metrics resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") ctx := caddy.ActiveContext() count, err := testutil.GatherAndCount( ctx.GetMetricsRegistry(), "frankenphp_busy_threads", "frankenphp_busy_workers", "frankenphp_queue_depth", "frankenphp_ready_workers", "frankenphp_total_threads", "frankenphp_total_workers", "frankenphp_worker_request_count", "frankenphp_worker_request_time", ) require.NoError(t, err, "failed to count metrics") require.Zero(t, count, "metrics should be missing") } func TestWorkerRestart(t *testing.T) { var wg sync.WaitGroup tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` https_port 9443 metrics frankenphp { worker { name service file ../testdata/worker-restart.php num 1 # restart every 3 requests env EVERY 3 } } } localhost:`+testPort+` { route { php { root ../testdata } } } `, "caddyfile") ctx := caddy.ActiveContext() resp, err := http.Get("http://localhost:2999/metrics") require.NoError(t, err, "failed to fetch metrics") t.Cleanup(func() { require.NoError(t, resp.Body.Close()) }) // Read and parse metrics metrics := new(bytes.Buffer) _, err = metrics.ReadFrom(resp.Body) require.NoError(t, err, "failed to read metrics") // frankenphp_worker_restarts should be missing count, err := testutil.GatherAndCount( ctx.GetMetricsRegistry(), "frankenphp_worker_restarts", ) require.NoError(t, err, "failed to count metrics") require.Zero(t, count, "metrics should be missing") // Check metrics expectedMetrics := ` # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="service"} 1 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="service"} 1 ` require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_workers", "frankenphp_ready_workers", )) // Make some requests for i := range 10 { wg.Add(1) go func(i int) { tester.AssertGetResponse(fmt.Sprintf("http://localhost:"+testPort+"/worker-restart.php?i=%d", i), http.StatusOK, fmt.Sprintf("Counter (%d)", i)) wg.Done() }(i) } wg.Wait() // frankenphp_ready_workers should be back to 1 even after worker restarts expectedMetrics = ` # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge frankenphp_ready_workers{worker="service"} 1 # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge frankenphp_total_workers{worker="service"} 1 # HELP frankenphp_worker_restarts Number of PHP worker restarts for this worker # TYPE frankenphp_worker_restarts counter frankenphp_worker_restarts{worker="service"} 3 ` require.NoError(t, testutil.GatherAndCompare( ctx.GetMetricsRegistry(), strings.NewReader(expectedMetrics), "frankenphp_total_workers", "frankenphp_ready_workers", "frankenphp_worker_restarts", )) } func TestWorkerMatchDirective(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { php_server { root ../testdata/files worker { file ../worker-with-counter.php match /matched-path* num 1 } } } `, "caddyfile") // worker is outside public directory, match anyway tester.AssertGetResponse("http://localhost:"+testPort+"/matched-path", http.StatusOK, "requests:1") tester.AssertGetResponse("http://localhost:"+testPort+"/matched-path/anywhere", http.StatusOK, "requests:2") // 404 on unmatched paths tester.AssertGetResponse("http://localhost:"+testPort+"/elsewhere", http.StatusNotFound, "") // static file will be served by the fileserver expectedFileResponse, err := os.ReadFile("../testdata/files/static.txt") require.NoError(t, err, "static.txt file must be readable for this test") tester.AssertGetResponse("http://localhost:"+testPort+"/static.txt", http.StatusOK, string(expectedFileResponse)) } func TestWorkerMatchDirectiveWithMultipleWorkers(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { php_server { root ../testdata worker { file worker-with-counter.php match /counter/* num 1 } worker { file index.php match /index/* num 1 } } } `, "caddyfile") // match 2 workers respectively (in the public directory) tester.AssertGetResponse("http://localhost:"+testPort+"/counter/sub-path", http.StatusOK, "requests:1") tester.AssertGetResponse("http://localhost:"+testPort+"/index/sub-path", http.StatusOK, "I am by birth a Genevese (i not set)") // static file will be served by the fileserver expectedFileResponse, err := os.ReadFile("../testdata/files/static.txt") require.NoError(t, err, "static.txt file must be readable for this test") tester.AssertGetResponse("http://localhost:"+testPort+"/files/static.txt", http.StatusOK, string(expectedFileResponse)) // serve php file directly as fallback tester.AssertGetResponse("http://localhost:"+testPort+"/hello.php", http.StatusOK, "Hello from PHP") // serve index.php file directly as fallback tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, "I am by birth a Genevese (i not set)") tester.AssertGetResponse("http://localhost:"+testPort+"/not-matched", http.StatusOK, "I am by birth a Genevese (i not set)") } func TestWorkerMatchDirectiveWithoutFileServer(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { route { php_server { index off file_server off root ../testdata/files worker { file ../worker-with-counter.php match /some-path } } respond "Request falls through" 404 } } `, "caddyfile") // find the worker at some-path tester.AssertGetResponse("http://localhost:"+testPort+"/some-path", http.StatusOK, "requests:1") // do not find the file at static.txt // the request should completely fall through the php_server module tester.AssertGetResponse("http://localhost:"+testPort+"/static.txt", http.StatusNotFound, "Request falls through") } func TestDd(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { php { worker ../testdata/dd.php 1 { match * } } `, "caddyfile") // simulate Symfony's dd() tester.AssertGetResponse( "http://localhost:"+testPort+"/some-path?output=dump123", http.StatusInternalServerError, "dump123", ) } func TestLog(t *testing.T) { tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { log { output stdout format json } root ../testdata php_server { worker ../testdata/log-frankenphp_log.php } } `, "caddyfile") tester.AssertGetResponse( "http://localhost:"+testPort+"/log-frankenphp_log.php?i=0", http.StatusOK, "", ) } // TestSymlinkWorkerPaths tests different ways to reference worker scripts in symlinked directories func TestSymlinkWorkerPaths(t *testing.T) { cwd, _ := os.Getwd() publicDir := filepath.Join(cwd, "..", "testdata", "symlinks", "public") skipIfSymlinkNotValid(t, publicDir) t.Run("NeighboringWorkerScript", func(t *testing.T) { // Scenario: neighboring worker script // Given frankenphp located in the test folder // When I execute `frankenphp php-server --listen localhost:8080 -w index.php` from `public` // Then I expect to see the worker script executed successfully tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker `+publicDir+`/index.php 1 } } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, "Request: 0\n") }) t.Run("NestedWorkerScript", func(t *testing.T) { // Scenario: nested worker script // Given frankenphp located in the test folder // When I execute `frankenphp --listen localhost:8080 -w nested/index.php` from `public` // Then I expect to see the worker script executed successfully tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker `+publicDir+`/nested/index.php 1 } } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/nested/index.php", http.StatusOK, "Nested request: 0\n") }) t.Run("OutsideSymlinkedFolder", func(t *testing.T) { // Scenario: outside the symlinked folder // Given frankenphp located in the root folder // When I execute `frankenphp --listen localhost:8080 -w public/index.php` from the root folder // Then I expect to see the worker script executed successfully tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker { name outside_worker file `+publicDir+`/index.php num 1 } } } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, "Request: 0\n") }) t.Run("SpecifiedRootDirectory", func(t *testing.T) { // Scenario: specified root directory // Given frankenphp located in the root folder // When I execute `frankenphp --listen localhost:8080 -w public/index.php -r public` from the root folder // Then I expect to see the worker script executed successfully tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker { name specified_root_worker file `+publicDir+`/index.php num 1 } } } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true } } } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, "Request: 0\n") }) } // TestSymlinkResolveRoot tests the resolve_root_symlink directive behavior func TestSymlinkResolveRoot(t *testing.T) { cwd, _ := os.Getwd() testDir := filepath.Join(cwd, "..", "testdata", "symlinks", "test") publicDir := filepath.Join(cwd, "..", "testdata", "symlinks", "public") skipIfSymlinkNotValid(t, publicDir) t.Run("ResolveRootSymlink", func(t *testing.T) { // Tests that resolve_root_symlink directive works correctly tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker `+publicDir+`/document-root.php 1 } } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true } } } `, "caddyfile") // DOCUMENT_ROOT should be the resolved path (testDir) tester.AssertGetResponse("http://localhost:"+testPort+"/document-root.php", http.StatusOK, "DOCUMENT_ROOT="+testDir+"\n") }) t.Run("NoResolveRootSymlink", func(t *testing.T) { // Tests that symlinks are preserved when resolve_root_symlink is false (non-worker mode) tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink false } } } `, "caddyfile") // DOCUMENT_ROOT should be the symlink path (publicDir) when resolve_root_symlink is false tester.AssertGetResponse("http://localhost:"+testPort+"/document-root.php", http.StatusOK, "DOCUMENT_ROOT="+publicDir+"\n") }) } // TestSymlinkWorkerBehavior tests worker behavior with symlinked directories func TestSymlinkWorkerBehavior(t *testing.T) { cwd, _ := os.Getwd() publicDir := filepath.Join(cwd, "..", "testdata", "symlinks", "public") skipIfSymlinkNotValid(t, publicDir) t.Run("WorkerScriptFailsWithoutWorkerMode", func(t *testing.T) { // Tests that accessing a worker-only script without configuring it as a worker actually results in an error tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` } localhost:`+testPort+` { route { php { root `+publicDir+` } } } `, "caddyfile") // Accessing the worker script without worker configuration MUST fail // The script checks $_SERVER['FRANKENPHP_WORKER'] and dies if not set tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, "Error: This script must be run in worker mode (FRANKENPHP_WORKER not set to '1')\n") }) t.Run("MultipleRequests", func(t *testing.T) { // Tests that symlinked workers handle multiple requests correctly tester := caddytest.NewTester(t) initServer(t, tester, ` { skip_install_trust admin localhost:2999 http_port `+testPort+` } localhost:`+testPort+` { route { php { root `+publicDir+` resolve_root_symlink true worker index.php 1 } } } `, "caddyfile") // Make multiple requests - each should increment the counter for i := 0; i < 5; i++ { tester.AssertGetResponse("http://localhost:"+testPort+"/index.php", http.StatusOK, fmt.Sprintf("Request: %d\n", i)) } }) } ================================================ FILE: caddy/config_test.go ================================================ package caddy import ( "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/stretchr/testify/require" ) func TestModuleWorkerDuplicateFilenamesFail(t *testing.T) { // Create a test configuration with duplicate worker filenames configWithDuplicateFilenames := ` { php { worker { file worker-with-env.php num 1 } worker { file worker-with-env.php num 2 } } }` // Parse the configuration d := caddyfile.NewTestDispenser(configWithDuplicateFilenames) module := &FrankenPHPModule{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) // Verify that an error was returned require.Error(t, err, "Expected an error when two workers in the same module have the same filename") require.Contains(t, err.Error(), "must not have duplicate filenames", "Error message should mention duplicate filenames") } func TestModuleWorkersWithDifferentFilenames(t *testing.T) { // Create a test configuration with different worker filenames configWithDifferentFilenames := ` { php { worker ../testdata/worker-with-env.php worker ../testdata/worker-with-counter.php } }` // Parse the configuration d := caddyfile.NewTestDispenser(configWithDifferentFilenames) module := &FrankenPHPModule{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) // Verify that no error was returned require.NoError(t, err, "Expected no error when two workers in the same module have different filenames") // Verify that both workers were added to the module require.Len(t, module.Workers, 2, "Expected two workers to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "First worker should have the correct filename") require.Equal(t, "../testdata/worker-with-counter.php", module.Workers[1].FileName, "Second worker should have the correct filename") } func TestModuleWorkersDifferentNamesSucceed(t *testing.T) { // Create a test configuration with a worker name configWithWorkerName1 := ` { php_server { worker { name test-worker-1 file ../testdata/worker-with-env.php num 1 } } }` // Parse the first configuration d1 := caddyfile.NewTestDispenser(configWithWorkerName1) app := &FrankenPHPApp{} module1 := &FrankenPHPModule{} // Unmarshal the first configuration err := module1.UnmarshalCaddyfile(d1) require.NoError(t, err, "First module should be configured without errors") // Create a second test configuration with a different worker name configWithWorkerName2 := ` { php_server { worker { name test-worker-2 file ../testdata/worker-with-env.php num 1 } } }` // Parse the second configuration d2 := caddyfile.NewTestDispenser(configWithWorkerName2) module2 := &FrankenPHPModule{} // Unmarshal the second configuration err = module2.UnmarshalCaddyfile(d2) // Verify that no error was returned require.NoError(t, err, "Expected no error when two workers have different names") _, err = app.addModuleWorkers(module1.Workers...) require.NoError(t, err, "Expected no error when adding the first module workers") _, err = app.addModuleWorkers(module2.Workers...) require.NoError(t, err, "Expected no error when adding the second module workers") // Verify that both workers were added require.Len(t, app.Workers, 2, "Expected two workers in the app") require.Equal(t, "m#test-worker-1", app.Workers[0].Name, "First worker should have the correct name") require.Equal(t, "m#test-worker-2", app.Workers[1].Name, "Second worker should have the correct name") } func TestModuleWorkerWithEnvironmentVariables(t *testing.T) { // Create a test configuration with environment variables configWithEnv := ` { php { worker { file ../testdata/worker-with-env.php num 1 env APP_ENV production env DEBUG true } } }` // Parse the configuration d := caddyfile.NewTestDispenser(configWithEnv) module := &FrankenPHPModule{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) // Verify that no error was returned require.NoError(t, err, "Expected no error when configuring a worker with environment variables") // Verify that the worker was added to the module require.Len(t, module.Workers, 1, "Expected one worker to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "Worker should have the correct filename") // Verify that the environment variables were set correctly require.Len(t, module.Workers[0].Env, 2, "Expected two environment variables") require.Equal(t, "production", module.Workers[0].Env["APP_ENV"], "APP_ENV should be set to production") require.Equal(t, "true", module.Workers[0].Env["DEBUG"], "DEBUG should be set to true") } func TestModuleWorkerWithWatchConfiguration(t *testing.T) { // Create a test configuration with watch directories configWithWatch := ` { php { worker { file ../testdata/worker-with-env.php num 1 watch watch ./src/**/*.php watch ./config/**/*.yaml } } }` // Parse the configuration d := caddyfile.NewTestDispenser(configWithWatch) module := &FrankenPHPModule{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) // Verify that no error was returned require.NoError(t, err, "Expected no error when configuring a worker with watch directories") // Verify that the worker was added to the module require.Len(t, module.Workers, 1, "Expected one worker to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "Worker should have the correct filename") // Verify that the watch directories were set correctly require.Len(t, module.Workers[0].Watch, 3, "Expected three watch patterns") require.Equal(t, defaultWatchPattern, module.Workers[0].Watch[0], "First watch pattern should be the default") require.Equal(t, "./src/**/*.php", module.Workers[0].Watch[1], "Second watch pattern should match the configuration") require.Equal(t, "./config/**/*.yaml", module.Workers[0].Watch[2], "Third watch pattern should match the configuration") } func TestModuleWorkerWithCustomName(t *testing.T) { // Create a test configuration with a custom worker name configWithCustomName := ` { php { worker { file ../testdata/worker-with-env.php num 1 name custom-worker-name } } }` // Parse the configuration d := caddyfile.NewTestDispenser(configWithCustomName) module := &FrankenPHPModule{} app := &FrankenPHPApp{} // Unmarshal the configuration err := module.UnmarshalCaddyfile(d) // Verify that no error was returned require.NoError(t, err, "Expected no error when configuring a worker with a custom name") // Verify that the worker was added to the module require.Len(t, module.Workers, 1, "Expected one worker to be added to the module") require.Equal(t, "../testdata/worker-with-env.php", module.Workers[0].FileName, "Worker should have the correct filename") // Verify that the worker was added to app.Workers with the m# prefix module.Workers, err = app.addModuleWorkers(module.Workers...) require.NoError(t, err, "Expected no error when adding the worker to the app") require.Equal(t, "m#custom-worker-name", module.Workers[0].Name, "Worker should have the custom name, prefixed with m#") require.Equal(t, "m#custom-worker-name", app.Workers[0].Name, "Worker should have the custom name, prefixed with m#") } ================================================ FILE: caddy/extinit.go ================================================ package caddy import ( "errors" "log" "os" "path/filepath" "strings" "github.com/dunglas/frankenphp/internal/extgen" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/spf13/cobra" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "extension-init", Usage: "go_extension.go [--verbose]", Short: "Initializes a PHP extension from a Go file (EXPERIMENTAL)", Long: ` Initializes a PHP extension from a Go file. This command generates the necessary C files for the extension, including the header and source files, as well as the arginfo file.`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdInitExtension) }, }) } func cmdInitExtension(_ caddycmd.Flags) (int, error) { if len(os.Args) < 3 { return 1, errors.New("the path to the Go source is required") } sourceFile := os.Args[2] baseName := extgen.SanitizePackageName(strings.TrimSuffix(filepath.Base(sourceFile), ".go")) generator := extgen.Generator{BaseName: baseName, SourceFile: sourceFile, BuildDir: filepath.Dir(sourceFile)} if err := generator.Generate(); err != nil { return 1, err } log.Printf("PHP extension %q initialized successfully in directory %q", baseName, generator.BuildDir) return 0, nil } ================================================ FILE: caddy/frankenphp/Caddyfile ================================================ # The Caddyfile is an easy way to configure FrankenPHP and the Caddy web server. # # https://frankenphp.dev/docs/config # https://caddyserver.com/docs/caddyfile { skip_install_trust {$CADDY_GLOBAL_OPTIONS} frankenphp { {$FRANKENPHP_CONFIG} } } {$CADDY_EXTRA_CONFIG} {$SERVER_NAME:localhost} { #log { # # Redact the authorization query parameter that can be set by Mercure # format filter { # request>uri query { # replace authorization REDACTED # } # } #} root {$SERVER_ROOT:public/} encode zstd br gzip # Uncomment the following lines to enable Mercure and Vulcain modules #mercure { # # Publisher JWT key # publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG} # # Subscriber JWT key # subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG} # # Allow anonymous subscribers (double-check that it's what you want) # anonymous # # Enable the subscription API (double-check that it's what you want) # subscriptions # # Extra directives # {$MERCURE_EXTRA_DIRECTIVES} #} #vulcain {$CADDY_SERVER_EXTRA_DIRECTIVES} php_server { #worker /path/to/your/worker.php } } # As an alternative to editing the above site block, you can add your own site # block files in the Caddyfile.d directory, and they will be included as long # as they use the .caddyfile extension. import Caddyfile.d/*.caddyfile ================================================ FILE: caddy/frankenphp/cbrotli.go ================================================ //go:build !nobrotli package main import _ "github.com/dunglas/caddy-cbrotli" ================================================ FILE: caddy/frankenphp/main.go ================================================ package main import ( caddycmd "github.com/caddyserver/caddy/v2/cmd" // plug in Caddy modules here. _ "github.com/caddyserver/caddy/v2/modules/standard" _ "github.com/dunglas/frankenphp/caddy" _ "github.com/dunglas/mercure/caddy" _ "github.com/dunglas/vulcain/caddy" ) func main() { caddycmd.Main() } ================================================ FILE: caddy/go.mod ================================================ module github.com/dunglas/frankenphp/caddy go 1.26.0 replace github.com/dunglas/frankenphp => ../ retract v1.0.0-rc.1 // Human error require ( github.com/caddyserver/caddy/v2 v2.11.2 github.com/caddyserver/certmagic v0.25.2 github.com/dunglas/caddy-cbrotli v1.0.1 github.com/dunglas/frankenphp v1.12.1 github.com/dunglas/mercure v0.21.11 github.com/dunglas/mercure/caddy v0.21.11 github.com/dunglas/vulcain/caddy v1.4.0 github.com/prometheus/client_golang v1.23.2 github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.11.1 ) require github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca // indirect require ( cel.dev/expr v0.25.1 // indirect cloud.google.com/go/auth v0.18.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect dario.cat/mergo v1.0.2 // indirect filippo.io/bigmod v0.1.0 // indirect filippo.io/edwards25519 v1.2.0 // indirect github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect github.com/BurntSushi/toml v1.6.0 // indirect github.com/DeRuina/timberjack v1.3.9 // indirect github.com/KimMachineGun/automemlimit v0.7.5 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/Masterminds/sprig/v3 v3.3.0 // indirect github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145 // indirect github.com/MicahParks/jwkset v0.11.0 // indirect github.com/MicahParks/keyfunc/v3 v3.8.0 // indirect github.com/RoaringBitmap/roaring/v2 v2.15.0 // indirect github.com/alecthomas/chroma/v2 v2.23.1 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bits-and-blooms/bitset v1.24.4 // indirect github.com/caddyserver/zerossl v0.1.5 // indirect github.com/ccoveille/go-safecast/v2 v2.0.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/cloudflare/circl v1.6.3 // indirect github.com/coreos/go-oidc/v3 v3.17.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgraph-io/badger v1.6.2 // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.2.0 // indirect github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/dunglas/httpsfv v1.1.0 // indirect github.com/dunglas/skipfilter v1.0.0 // indirect github.com/dunglas/vulcain v1.4.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect github.com/getkin/kin-openapi v0.133.0 // indirect github.com/go-chi/chi/v5 v5.2.5 // indirect github.com/go-jose/go-jose/v3 v3.0.4 // indirect github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.22.5 // indirect github.com/go-openapi/swag/jsonname v0.25.5 // indirect github.com/go-sql-driver/mysql v1.9.3 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/gofrs/uuid v4.4.0+incompatible // indirect github.com/gofrs/uuid/v5 v5.4.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/brotli/go/cbrotli v1.1.0 // indirect github.com/google/cel-go v0.27.0 // indirect github.com/google/certificate-transparency-go v1.3.3 // indirect github.com/google/go-tpm v0.9.8 // indirect github.com/google/go-tspi v0.3.0 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect github.com/googleapis/gax-go/v2 v2.17.0 // indirect github.com/gorilla/handlers v1.5.2 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect github.com/huandu/xstrings v1.5.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.8.0 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/klauspost/compress v1.18.4 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/libdns/libdns v1.1.1 // indirect github.com/mailru/easyjson v0.9.1 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/maypok86/otter/v2 v2.3.0 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/mholt/acmez/v3 v3.1.6 // indirect github.com/miekg/dns v1.1.72 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-ps v1.0.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/mschoch/smat v0.2.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/pires/go-proxyproto v0.11.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/otlptranslator v1.0.0 // indirect github.com/prometheus/procfs v0.20.1 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/rs/cors v1.11.1 // indirect github.com/rs/xid v1.6.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/slackhq/nebula v1.10.3 // indirect github.com/smallstep/certificates v0.30.0-rc3 // indirect github.com/smallstep/cli-utils v0.12.2 // indirect github.com/smallstep/linkedca v0.25.0 // indirect github.com/smallstep/nosql v0.7.0 // indirect github.com/smallstep/pkcs7 v0.2.1 // indirect github.com/smallstep/scep v0.0.0-20250318231241-a25cabb69492 // indirect github.com/smallstep/truststore v0.13.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/viper v1.21.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect github.com/tailscale/tscert v0.0.0-20251216020129-aea342f6d747 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.2.0 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect github.com/unrolled/secure v1.17.0 // indirect github.com/urfave/cli v1.22.17 // indirect github.com/woodsbury/decimal128 v1.4.0 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yuin/goldmark v1.7.16 // indirect github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc // indirect github.com/zeebo/blake3 v0.2.4 // indirect go.etcd.io/bbolt v1.4.3 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/bridges/prometheus v0.67.0 // indirect go.opentelemetry.io/contrib/exporters/autoexport v0.67.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect go.opentelemetry.io/contrib/propagators/autoprop v0.67.0 // indirect go.opentelemetry.io/contrib/propagators/aws v1.42.0 // indirect go.opentelemetry.io/contrib/propagators/b3 v1.42.0 // indirect go.opentelemetry.io/contrib/propagators/jaeger v1.42.0 // indirect go.opentelemetry.io/contrib/propagators/ot v1.42.0 // indirect go.opentelemetry.io/otel v1.42.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect go.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect go.opentelemetry.io/otel/log v0.18.0 // indirect go.opentelemetry.io/otel/metric v1.42.0 // indirect go.opentelemetry.io/otel/sdk v1.42.0 // indirect go.opentelemetry.io/otel/sdk/log v0.18.0 // indirect go.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect go.opentelemetry.io/otel/trace v1.42.0 // indirect go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.step.sm/crypto v0.76.2 // indirect go.uber.org/automaxprocs v1.6.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.1 // indirect go.uber.org/zap/exp v0.3.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541 // indirect golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect golang.org/x/mod v0.33.0 // indirect golang.org/x/net v0.51.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.42.0 // indirect golang.org/x/term v0.40.0 // indirect golang.org/x/text v0.34.0 // indirect golang.org/x/time v0.15.0 // indirect golang.org/x/tools v0.42.0 // indirect google.golang.org/api v0.270.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect google.golang.org/grpc v1.79.2 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.1 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect howett.net/plist v1.0.1 // indirect ) ================================================ FILE: caddy/go.sum ================================================ cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= cloud.google.com/go/kms v1.25.0 h1:gVqvGGUmz0nYCmtoxWmdc1wli2L1apgP8U4fghPGSbQ= cloud.google.com/go/kms v1.25.0/go.mod h1:XIdHkzfj0bUO3E+LvwPg+oc7s58/Ns8Nd8Sdtljihbk= cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8= cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk= code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE= code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM= dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= filippo.io/bigmod v0.1.0 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8= filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 h1:cTp8I5+VIoKjsnZuH8vjyaysT/ses3EvZeaV/1UkF2M= github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/DeRuina/timberjack v1.3.9 h1:6UXZ1I7ExPGTX/1UNYawR58LlOJUHKBPiYC7WQ91eBo= github.com/DeRuina/timberjack v1.3.9/go.mod h1:RLoeQrwrCGIEF8gO5nV5b/gMD0QIy7bzQhBUgpp1EqE= github.com/KimMachineGun/automemlimit v0.7.5 h1:RkbaC0MwhjL1ZuBKunGDjE/ggwAX43DwZrJqVwyveTk= github.com/KimMachineGun/automemlimit v0.7.5/go.mod h1:QZxpHaGOQoYvFhv/r4u3U0JTC2ZcOwbSr11UZF46UBM= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145 h1:1yw6O62BReQ+uA1oyk9XaQTvLhcoHWmoQAgXmDFXpIY= github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145/go.mod h1:877WBceefKn14QwVVn4xRFUsHsZb9clICgdeTj4XsUg= github.com/MicahParks/jwkset v0.11.0 h1:yc0zG+jCvZpWgFDFmvs8/8jqqVBG9oyIbmBtmjOhoyQ= github.com/MicahParks/jwkset v0.11.0/go.mod h1:U2oRhRaLgDCLjtpGL2GseNKGmZtLs/3O7p+OZaL5vo0= github.com/MicahParks/keyfunc/v3 v3.8.0 h1:Hx2dgIjAXGk9slakM6rV9BOeaWDPEXXZ4Us8guNBfds= github.com/MicahParks/keyfunc/v3 v3.8.0/go.mod h1:z66bkCviwqfg2YUp+Jcc/xRE9IXLcMq6DrgV/+Htru0= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/RoaringBitmap/roaring/v2 v2.15.0 h1:gCbixa3UiG7g6WUZNVOfEEg2HTc1vR4OVdMkX8t1ZFc= github.com/RoaringBitmap/roaring/v2 v2.15.0/go.mod h1:eq4wdNXxtJIS/oikeCzdX1rBzek7ANzbth041hrU8Q4= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.2.0/go.mod h1:vf4zrexSH54oEjJ7EdB65tGNHmH3pGZmVkgTP5RHvAs= github.com/alecthomas/chroma/v2 v2.23.1 h1:nv2AVZdTyClGbVQkIzlDm/rnhk1E9bU9nXwmZ/Vk/iY= github.com/alecthomas/chroma/v2 v2.23.1/go.mod h1:NqVhfBR0lte5Ouh3DcthuUCTUpDC9cxBOfyMbMQPs3o= github.com/alecthomas/repr v0.0.0-20220113201626-b1b626ac65ae/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b h1:uUXgbcPDK3KpW29o4iy7GtuappbWT0l5NaMo9H9pJDw= github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= github.com/aws/aws-sdk-go-v2/service/kms v1.49.5 h1:DKibav4XF66XSeaXcrn9GlWGHos6D/vJ4r7jsK7z5CE= github.com/aws/aws-sdk-go-v2/service/kms v1.49.5/go.mod h1:1SdcmEGUEQE1mrU2sIgeHtcMSxHuybhPvuEPANzIDfI= github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bits-and-blooms/bitset v1.24.4 h1:95H15Og1clikBrKr/DuzMXkQzECs1M6hhoGXLwLQOZE= github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/caddyserver/caddy/v2 v2.11.2 h1:iOlpsSiSKqEW+SIXrcZsZ/NO74SzB/ycqqvAIEfIm64= github.com/caddyserver/caddy/v2 v2.11.2/go.mod h1:ASNYYmKhIVWWMGPfNxclI5DqKEgU3FhmL+6NZWzQEag= github.com/caddyserver/certmagic v0.25.2 h1:D7xcS7ggX/WEY54x0czj7ioTkmDWKIgxtIi2OcQclUc= github.com/caddyserver/certmagic v0.25.2/go.mod h1:llW/CvsNmza8S6hmsuggsZeiX+uS27dkqY27wDIuBWg= github.com/caddyserver/zerossl v0.1.5 h1:dkvOjBAEEtY6LIGAHei7sw2UgqSD6TrWweXpV7lvEvE= github.com/caddyserver/zerossl v0.1.5/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= github.com/ccoveille/go-safecast/v2 v2.0.0 h1:+5eyITXAUj3wMjad6cRVJKGnC7vDS55zk0INzJagub0= github.com/ccoveille/go-safecast/v2 v2.0.0/go.mod h1:JIYA4CAR33blIDuE6fSwCp2sz1oOBahXnvmdBhOAABs= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc= github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo= github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgraph-io/badger v1.6.2 h1:mNw0qs90GVgGGWylh0umH5iag1j6n/PeJtNvL6KY/x8= github.com/dgraph-io/badger v1.6.2/go.mod h1:JW2yswe3V058sS0kZ2h/AXeDSqFjxnZcRrVH//y2UQE= github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o= github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk= github.com/dgraph-io/ristretto v0.0.2/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= github.com/dgraph-io/ristretto v0.2.0 h1:XAfl+7cmoUDWW/2Lx8TGZQjjxIQ2Ley9DSf52dru4WE= github.com/dgraph-io/ristretto v0.2.0/go.mod h1:8uBHCU/PBV4Ag0CJrP47b9Ofby5dqWNh4FicAdoqFNU= github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38= github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dunglas/caddy-cbrotli v1.0.1 h1:mkg7EB1GmoyfBt3kY3mq4o/0bfnBeq7ZLQjmVmdBE3Y= github.com/dunglas/caddy-cbrotli v1.0.1/go.mod h1:uXABy3tjy1FABF+3JWKVh1ajFvIO/kfpwHaeZGSBaAY= github.com/dunglas/httpsfv v1.1.0 h1:Jw76nAyKWKZKFrpMMcL76y35tOpYHqQPzHQiwDvpe54= github.com/dunglas/httpsfv v1.1.0/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg= github.com/dunglas/mercure v0.21.11 h1:4Sd/Q77j8uh9SI5D9ZMg5sePlWs336+9CKxDQC1FV34= github.com/dunglas/mercure v0.21.11/go.mod h1:WPMgfqonUiO1qB+W8Tya63Ngag9ZwplGMXSOy8P/uMg= github.com/dunglas/mercure/caddy v0.21.11 h1:WnasC7EiqBPAB0CpBEPrm7vLiuL7o3BOVmfGDghnyVM= github.com/dunglas/mercure/caddy v0.21.11/go.mod h1:MlGm4jbpBV+9nizn03PDejTEM916z3WDP9zO/Yw8OYQ= github.com/dunglas/skipfilter v1.0.0 h1:JG9SgGg4n6BlFwuTYzb9RIqjH7PfwszvWehanrYWPF4= github.com/dunglas/skipfilter v1.0.0/go.mod h1:ryhr8j7CAHSjzeN7wI6YEuwoArQ3OQmRqWWVCEAfb9w= github.com/dunglas/vulcain v1.4.0 h1:uGMTLKmw53yJNKBwCtD3GOmnmGw4SfsIqYfb3NEKvbA= github.com/dunglas/vulcain v1.4.0/go.mod h1:WJjUJ/anaMlV4JWUCLNTNkviPFQL817yaVW5ErfiaMY= github.com/dunglas/vulcain/caddy v1.4.0 h1:u377qYQwDKRA2/CcZ7yIbRehuY+AjQM5xpkIyynsn1c= github.com/dunglas/vulcain/caddy v1.4.0/go.mod h1:qu6VV33pP42D8tIZDURE0ngt2MBR9OE34lCeMBo8caM= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be h1:vqHrvilasyJcnru/0Z4FoojsQJUIfXGVplte7JtupfY= github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be/go.mod h1:PmV4IVmBJVqT2NcfTGN4+sZ+qGe3PA0qkphAtOHeFG0= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ= github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE= github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA= github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0= github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo= github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM= github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0= github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/brotli/go/cbrotli v1.1.0 h1:YwHD/rwSgUSL4b2S3ZM2jnNymm+tmwKQqjUIC63nmHU= github.com/google/brotli/go/cbrotli v1.1.0/go.mod h1:nOPhAkwVliJdNTkj3gXpljmWhjc4wCaVqbMJcPKWP4s= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/cel-go v0.27.0 h1:e7ih85+4qVrBuqQWTW4FKSqZYokVuc3HnhH5keboFTo= github.com/google/cel-go v0.27.0/go.mod h1:tTJ11FWqnhw5KKpnWpvW9CJC3Y9GK4EIS0WXnBbebzw= github.com/google/certificate-transparency-go v1.0.21/go.mod h1:QeJfpSbVSfYc7RgB3gJFj9cbuQMMchQxrWXz8Ruopmg= github.com/google/certificate-transparency-go v1.3.3 h1:hq/rSxztSkXN2tx/3jQqF6Xc0O565UQPdHrOWvZwybo= github.com/google/certificate-transparency-go v1.3.3/go.mod h1:iR17ZgSaXRzSa5qvjFl8TnVD5h8ky2JMVio+dzoKMgA= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws= github.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ= github.com/google/go-tspi v0.3.0 h1:ADtq8RKfP+jrTyIWIZDIYcKOMecRqNJFOew2IT0Inus= github.com/google/go-tspi v0.3.0/go.mod h1:xfMGI3G0PhxCdNVcYr1C4C+EizojDg/TXuX5by8CiHI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8= github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= github.com/googleapis/gax-go/v2 v2.17.0 h1:RksgfBpxqff0EZkDWYuz9q/uWsTVz+kf43LsZ1J6SMc= github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo= github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c= github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU= github.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk= github.com/letsencrypt/pebble/v2 v2.10.0 h1:Wq6gYXlsY6ubqI3hhxsTzdyotvfdjFBxuwYqCLCnj/U= github.com/letsencrypt/pebble/v2 v2.10.0/go.mod h1:Sk8cmUIPcIdv2nINo+9PB4L+ZBhzY+F9A1a/h/xmWiQ= github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U= github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8= github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/maypok86/otter/v2 v2.3.0 h1:8H8AVVFUSzJwIegKwv1uF5aGitTY+AIrtktg7OcLs8w= github.com/maypok86/otter/v2 v2.3.0/go.mod h1:XgIdlpmL6jYz882/CAx1E4C1ukfgDKSaw4mWq59+7l8= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mholt/acmez/v3 v3.1.6 h1:eGVQNObP0pBN4sxqrXeg7MYqTOWyoiYpQqITVWlrevk= github.com/mholt/acmez/v3 v3.1.6/go.mod h1:5nTPosTGosLxF3+LU4ygbgMRFDhbAVpqMI4+a4aHLBY= github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc= github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM= github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY= github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c= github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/peterbourgon/diskv/v3 v3.0.1 h1:x06SQA46+PKIUftmEujdwSEpIx8kR+M9eLYsUxeYveU= github.com/peterbourgon/diskv/v3 v3.0.1/go.mod h1:kJ5Ny7vLdARGU3WUuy6uzO6T0nb/2gWcT1JiBvRmb5o= github.com/pires/go-proxyproto v0.11.0 h1:gUQpS85X/VJMdUsYyEgyn59uLJvGqPhJV5YvG68wXH4= github.com/pires/go-proxyproto v0.11.0/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos= github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM= github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= github.com/schollz/jsonstore v1.1.0 h1:WZBDjgezFS34CHI+myb4s8GGpir3UMpy7vWoCeO0n6E= github.com/schollz/jsonstore v1.1.0/go.mod h1:15c6+9guw8vDRyozGjN3FoILt0wpruJk9Pi66vjaZfg= github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/slackhq/nebula v1.10.3 h1:EstYj8ODEcv6T0R9X5BVq1zgWZnyU5gtPzk99QF1PMU= github.com/slackhq/nebula v1.10.3/go.mod h1:IL5TUQm4x9IFx2kCKPYm1gP47pwd5b8QGnnBH2RHnvs= github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262 h1:unQFBIznI+VYD1/1fApl1A+9VcBk+9dcqGfnePY87LY= github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262/go.mod h1:MyOHs9Po2fbM1LHej6sBUT8ozbxmMOFG+E+rx/GSGuc= github.com/smallstep/certificates v0.30.0-rc3 h1:Lx/NNJ4n+L3Pyx5NtVRGXeqviPPXTFFGLRiC1fCwU50= github.com/smallstep/certificates v0.30.0-rc3/go.mod h1:e5/ylYYpvnjCVZz6RpyOkpTe73EGPYoL+8TZZ5EtLjI= github.com/smallstep/cli-utils v0.12.2 h1:lGzM9PJrH/qawbzMC/s2SvgLdJPKDWKwKzx9doCVO+k= github.com/smallstep/cli-utils v0.12.2/go.mod h1:uCPqefO29goHLGqFnwk0i8W7XJu18X3WHQFRtOm/00Y= github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca h1:VX8L0r8vybH0bPeaIxh4NQzafKQiqvlOn8pmOXbFLO4= github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca/go.mod h1:vNAduivU014fubg6ewygkAvQC0IQVXqdc8vaGl/0er4= github.com/smallstep/linkedca v0.25.0 h1:txT9QHGbCsJq0MhAghBq7qhurGY727tQuqUi+n4BVBo= github.com/smallstep/linkedca v0.25.0/go.mod h1:Q3jVAauFKNlF86W5/RFtgQeyDKz98GL/KN3KG4mJOvc= github.com/smallstep/nosql v0.7.0 h1:YiWC9ZAHcrLCrayfaF+QJUv16I2bZ7KdLC3RpJcnAnE= github.com/smallstep/nosql v0.7.0/go.mod h1:H5VnKMCbeq9QA6SRY5iqPylfxLfYcLwvUff3onQ8+HU= github.com/smallstep/pkcs7 v0.2.1 h1:6Kfzr/QizdIuB6LSv8y1LJdZ3aPSfTNhTLqAx9CTLfA= github.com/smallstep/pkcs7 v0.2.1/go.mod h1:RcXHsMfL+BzH8tRhmrF1NkkpebKpq3JEM66cOFxanf0= github.com/smallstep/scep v0.0.0-20250318231241-a25cabb69492 h1:k23+s51sgYix4Zgbvpmy+1ZgXLjr4ZTkBTqXmpnImwA= github.com/smallstep/scep v0.0.0-20250318231241-a25cabb69492/go.mod h1:QQhwLqCS13nhv8L5ov7NgusowENUtXdEzdytjmJHdZQ= github.com/smallstep/truststore v0.13.0 h1:90if9htAOblavbMeWlqNLnO9bsjjgVv2hQeQJCi/py4= github.com/smallstep/truststore v0.13.0/go.mod h1:3tmMp2aLKZ/OA/jnFUB0cYPcho402UG2knuJoPh4j7A= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4= github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55/go.mod h1:4k4QO+dQ3R5FofL+SanAUZe+/QfeK0+OIuwDIRu2vSg= github.com/tailscale/tscert v0.0.0-20251216020129-aea342f6d747 h1:RnBbFMmodYzhC6adOjTbtUQXyzV8dcvKYbolzs6Qch0= github.com/tailscale/tscert v0.0.0-20251216020129-aea342f6d747/go.mod h1:ejPAJui3kVK4u5TgMtqtXlWf5HnKh9fLy5kvpaeuas0= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM= github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbWU= github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/urfave/cli v1.22.17 h1:SYzXoiPfQjHBbkYxbew5prZHS1TOLT3ierW8SYLqtVQ= github.com/urfave/cli v1.22.17/go.mod h1:b0ht0aqgH/6pBYzzxURyrM4xXNgsoT/n2ZzwQiEhNVo= github.com/woodsbury/decimal128 v1.4.0 h1:xJATj7lLu4f2oObouMt2tgGiElE5gO6mSWUjQsBgUlc= github.com/woodsbury/decimal128 v1.4.0/go.mod h1:BP46FUrVjVhdTbKT+XuQh2xfQaGki9LMIRJSFuh6THU= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.15/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.16 h1:n+CJdUxaFMiDUNnWC3dMWCIQJSkxH4uz3ZwQBkAlVNE= github.com/yuin/goldmark v1.7.16/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc h1:+IAOyRda+RLrxa1WC7umKOZRsGq4QrFFMYApOeHzQwQ= github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc/go.mod h1:ovIvrum6DQJA4QsJSovrkC4saKHQVs7TvcaeO8AIl5I= github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/bridges/prometheus v0.67.0 h1:dkBzNEAIKADEaFnuESzcXvpd09vxvDZsOjx11gjUqLk= go.opentelemetry.io/contrib/bridges/prometheus v0.67.0/go.mod h1:Z5RIwRkZgauOIfnG5IpidvLpERjhTninpP1dTG2jTl4= go.opentelemetry.io/contrib/exporters/autoexport v0.67.0 h1:4fnRcNpc6YFtG3zsFw9achKn3XgmxPxuMuqIL5rE8e8= go.opentelemetry.io/contrib/exporters/autoexport v0.67.0/go.mod h1:qTvIHMFKoxW7HXg02gm6/Wofhq5p3Ib/A/NNt1EoBSQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= go.opentelemetry.io/contrib/propagators/autoprop v0.67.0 h1:XhcQRf4MeqwQw96FcnatDAj6gwE19SUrWZ1VwNg77iE= go.opentelemetry.io/contrib/propagators/autoprop v0.67.0/go.mod h1:7OK06SuNIBIlc5Uq3JGQEsKHuXw29t9OJemvDYyP1dk= go.opentelemetry.io/contrib/propagators/aws v1.42.0 h1:Kbr3xDxs6kcxp5ThXTKWK2OtwLhNoXBVtqguNYcsZL0= go.opentelemetry.io/contrib/propagators/aws v1.42.0/go.mod h1:Jzw9hZHtxdpCN7x8S17UH59X/EiFivp6VXLs9bdM1OQ= go.opentelemetry.io/contrib/propagators/b3 v1.42.0 h1:B2Pew5ufEtgkjLF+tSkXjgYZXQr9m7aCm1wLKB0URbU= go.opentelemetry.io/contrib/propagators/b3 v1.42.0/go.mod h1:iPgUcSEF5DORW6+yNbdw/YevUy+QqJ508ncjhrRSCjc= go.opentelemetry.io/contrib/propagators/jaeger v1.42.0 h1:jP8unWI6q5kcb3gpGLjKDGaUa+JW+nHKWvpS/q+YuWA= go.opentelemetry.io/contrib/propagators/jaeger v1.42.0/go.mod h1:xd89e/pUyPatUP1C4z1UknD9jHptESO99tWyvd4mWD4= go.opentelemetry.io/contrib/propagators/ot v1.42.0 h1:uQjD1NNqX1+DfcAoWParPt1egNg9vC9gH4xarJ9Khxo= go.opentelemetry.io/contrib/propagators/ot v1.42.0/go.mod h1:yw/c2TCmQLIv109HBOCn6NlJ8Dp7MNfjMcqQZRnAMmg= go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc= go.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs= go.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro= go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s= go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs= go.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg= go.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI= go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= go.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw= go.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk= go.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA= go.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw= go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.step.sm/crypto v0.76.2 h1:JJ/yMcs/rmcCAwlo+afrHjq74XBFRTJw5B2y4Q4Z4c4= go.step.sm/crypto v0.76.2/go.mod h1:m6KlB/HzIuGFep0UWI5e0SYi38UxpoKeCg6qUaHV6/Q= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541 h1:FmKxj9ocLKn45jiR2jQMwCVhDvaK7fKQFzfuT9GvyK8= golang.org/x/crypto/x509roots/fallback v0.0.0-20260213171211-a408498e5541/go.mod h1:+UoQFNBq2p2wO+Q6ddVtYc25GZ6VNdOMyyrd4nrqrKs= golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0= golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= google.golang.org/api v0.270.0 h1:4rJZbIuWSTohczG9mG2ukSDdt9qKx4sSSHIydTN26L4= google.golang.org/api v0.270.0/go.mod h1:5+H3/8DlXpQWrSz4RjGGwz5HfJAQSEI8Bc6JqQNH77U= google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM= google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4= google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng= google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU= google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.1 h1:/WILD1UcXj/ujCxgoL/DvRgt2CP3txG8+FwkUbb9110= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.1/go.mod h1:YNKnb2OAApgYn2oYY47Rn7alMr1zWjb2U8Q0aoGWiNc= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM= howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= ================================================ FILE: caddy/hotreload-skip.go ================================================ //go:build nowatcher || nomercure package caddy import ( "errors" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) type hotReloadContext struct { } func (_ *FrankenPHPModule) configureHotReload(_ *FrankenPHPApp) error { return nil } func (_ *FrankenPHPModule) unmarshalHotReload(d *caddyfile.Dispenser) error { return errors.New("hot reload support disabled") } ================================================ FILE: caddy/hotreload.go ================================================ //go:build !nowatcher && !nomercure package caddy import ( "bytes" "encoding/gob" "errors" "fmt" "hash/fnv" "net/url" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/dunglas/frankenphp" ) const defaultHotReloadPattern = "./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}" type hotReloadContext struct { // HotReload specifies files to watch for file changes to trigger hot reloads updates. Supports the glob syntax. HotReload *hotReloadConfig `json:"hot_reload,omitempty"` } type hotReloadConfig struct { Topic string `json:"topic"` Watch []string `json:"watch"` } func (f *FrankenPHPModule) configureHotReload(app *FrankenPHPApp) error { if f.HotReload == nil { return nil } if f.mercureHub == nil { return errors.New("unable to enable hot reloading: no Mercure hub configured") } if len(f.HotReload.Watch) == 0 { f.HotReload.Watch = []string{defaultHotReloadPattern} } if f.HotReload.Topic == "" { uid, err := uniqueID(f) if err != nil { return err } f.HotReload.Topic = "https://frankenphp.dev/hot-reload/" + uid } app.opts = append(app.opts, frankenphp.WithHotReload(f.HotReload.Topic, f.mercureHub, f.HotReload.Watch)) f.preparedEnv["FRANKENPHP_HOT_RELOAD\x00"] = "/.well-known/mercure?topic=" + url.QueryEscape(f.HotReload.Topic) return nil } func (f *FrankenPHPModule) unmarshalHotReload(d *caddyfile.Dispenser) error { f.HotReload = &hotReloadConfig{ Watch: d.RemainingArgs(), } for d.NextBlock(1) { switch v := d.Val(); v { case "topic": if !d.NextArg() { return d.ArgErr() } if f.HotReload == nil { f.HotReload = &hotReloadConfig{} } f.HotReload.Topic = d.Val() case "watch": patterns := d.RemainingArgs() if len(patterns) == 0 { return d.ArgErr() } f.HotReload.Watch = append(f.HotReload.Watch, patterns...) default: return wrongSubDirectiveError("hot_reload", "topic, watch", v) } } return nil } func uniqueID(s any) (string, error) { var b bytes.Buffer if err := gob.NewEncoder(&b).Encode(s); err != nil { return "", fmt.Errorf("unable to generate unique name: %w", err) } h := fnv.New64a() if _, err := h.Write(b.Bytes()); err != nil { return "", fmt.Errorf("unable to generate unique name: %w", err) } return fmt.Sprintf("%016x", h.Sum64()), nil } ================================================ FILE: caddy/hotreload_test.go ================================================ //go:build !nowatcher && !nomercure package caddy_test import ( "context" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "testing" "github.com/caddyserver/caddy/v2/caddytest" "github.com/stretchr/testify/require" ) func TestHotReload(t *testing.T) { const topic = "https://frankenphp.dev/hot-reload/test" u := "/.well-known/mercure?topic=" + url.QueryEscape(topic) tmpDir := t.TempDir() indexFile := filepath.Join(tmpDir, "index.php") tester := caddytest.NewTester(t) tester.InitServer(` { debug skip_install_trust admin localhost:2999 } http://localhost:`+testPort+` { mercure { transport local subscriber_jwt TestKey anonymous } php_server { root `+tmpDir+` hot_reload { topic `+topic+` watch `+tmpDir+`/*.php } } `, "caddyfile") var connected, received sync.WaitGroup connected.Add(1) received.Go(func() { cx, cancel := context.WithCancel(t.Context()) req, _ := http.NewRequest(http.MethodGet, "http://localhost:"+testPort+u, nil) req = req.WithContext(cx) resp := tester.AssertResponseCode(req, http.StatusOK) connected.Done() var receivedBody strings.Builder buf := make([]byte, 1024) for { _, err := resp.Body.Read(buf) require.NoError(t, err) receivedBody.Write(buf) if strings.Contains(receivedBody.String(), "index.php") { cancel() break } } require.NoError(t, resp.Body.Close()) }) connected.Wait() require.NoError(t, os.WriteFile(indexFile, []byte("= 2 && args[0] == "-r" { status = frankenphp.ExecutePHPCode(args[1]) } else { status = frankenphp.ExecuteScriptCLI(args[0], args) } os.Exit(status) return status, nil } ================================================ FILE: caddy/php-server.go ================================================ package caddy import ( "encoding/json" "log" "log/slog" "net/http" "os" "strconv" "strings" "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" caddycmd "github.com/caddyserver/caddy/v2/cmd" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/caddyserver/caddy/v2/modules/caddyhttp/encode" "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver" "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite" "github.com/caddyserver/certmagic" "github.com/dunglas/frankenphp" "github.com/spf13/cobra" ) func init() { caddycmd.RegisterCommand(caddycmd.Command{ Name: "php-server", Usage: "[--domain=] [--root=] [--listen=] [--worker=/path/to/worker.php<,nb-workers>] [--watch[=]]... [--access-log] [--debug] [--no-compress] [--mercure]", Short: "Spins up a production-ready PHP server", Long: ` A simple but production-ready PHP server. Useful for quick deployments, demos, and development. The listener's socket address can be customized with the --listen flag. If a domain name is specified with --domain, the default listener address will be changed to the HTTPS port and the server will use HTTPS. If using a public domain, ensure A/AAAA records are properly configured before using this option. For more advanced use cases, see https://github.com/php/frankenphp/blob/main/docs/config.md`, CobraFunc: func(cmd *cobra.Command) { cmd.Flags().StringP("domain", "d", "", "Domain name at which to serve the files") cmd.Flags().StringP("root", "r", "", "The path to the root of the site") cmd.Flags().StringP("listen", "l", "", "The address to which to bind the listener") cmd.Flags().StringArrayP("worker", "w", []string{}, "Worker script") cmd.Flags().StringArray("watch", []string{}, "Glob pattern of directories and files to watch for changes") cmd.Flags().BoolP("access-log", "a", false, "Enable the access log") cmd.Flags().BoolP("debug", "v", false, "Enable verbose debug logs") cmd.Flags().BoolP("mercure", "m", false, "Enable the built-in Mercure.rocks hub") cmd.Flags().Bool("no-compress", false, "Disable Zstandard, Brotli and Gzip compression") cmd.Flags().Lookup("watch").NoOptDefVal = defaultWatchPattern cmd.RunE = caddycmd.WrapCommandFuncForCobra(cmdPHPServer) }, }) } // cmdPHPServer is freely inspired from the file-server command of the Caddy server (Apache License 2.0, Matthew Holt and The Caddy Authors) func cmdPHPServer(fs caddycmd.Flags) (int, error) { caddy.TrapSignals() domain := fs.String("domain") root := fs.String("root") listen := fs.String("listen") accessLog := fs.Bool("access-log") debug := fs.Bool("debug") compress := !fs.Bool("no-compress") mercure := fs.Bool("mercure") workers, err := fs.GetStringArray("worker") if err != nil { panic(err) } watch, err := fs.GetStringArray("watch") if err != nil { panic(err) } if frankenphp.EmbeddedAppPath != "" { if err := os.Chdir(frankenphp.EmbeddedAppPath); err != nil { return caddy.ExitCodeFailedStartup, err } } var workersOption []workerConfig if len(workers) != 0 { workersOption = make([]workerConfig, 0, len(workers)) for _, worker := range workers { parts := strings.SplitN(worker, ",", 2) var num uint64 if len(parts) > 1 { num, _ = strconv.ParseUint(parts[1], 10, 32) } workersOption = append(workersOption, workerConfig{FileName: parts[0], Num: int(num)}) } workersOption[0].Watch = watch } if frankenphp.EmbeddedAppPath != "" { if _, err := os.Stat("php.ini"); err == nil { iniScanDir := os.Getenv("PHP_INI_SCAN_DIR") if err := os.Setenv("PHP_INI_SCAN_DIR", iniScanDir+":"+frankenphp.EmbeddedAppPath); err != nil { return caddy.ExitCodeFailedStartup, err } } if _, err := os.Stat("Caddyfile"); err == nil { config, _, _, err := caddycmd.LoadConfig("Caddyfile", "caddyfile") if err != nil { return caddy.ExitCodeFailedStartup, err } if err = caddy.Load(config, true); err != nil { return caddy.ExitCodeFailedStartup, err } select {} } if root == "" { root = defaultDocumentRoot } } const indexFile = "index.php" extensions := []string{".php"} tryFiles := []string{"{http.request.uri.path}", "{http.request.uri.path}/" + indexFile, indexFile} rrs := true phpHandler := FrankenPHPModule{ Root: root, SplitPath: extensions, ResolveRootSymlink: &rrs, } // route to redirect to canonical path if index PHP file redirMatcherSet := caddy.ModuleMap{ "file": caddyconfig.JSON(fileserver.MatchFile{ Root: root, TryFiles: []string{"{http.request.uri.path}/" + indexFile}, }, nil), "not": caddyconfig.JSON(caddyhttp.MatchNot{ MatcherSetsRaw: []caddy.ModuleMap{ { "path": caddyconfig.JSON(caddyhttp.MatchPath{"*/"}, nil), }, }, }, nil), } redirHandler := caddyhttp.StaticResponse{ StatusCode: caddyhttp.WeakString(strconv.Itoa(http.StatusPermanentRedirect)), Headers: http.Header{"Location": []string{"{http.request.orig_uri.path}/"}}, } redirRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(redirHandler, "handler", "static_response", nil)}, } // route to rewrite to PHP index file rewriteMatcherSet := caddy.ModuleMap{ "file": caddyconfig.JSON(fileserver.MatchFile{ Root: root, TryFiles: tryFiles, SplitPath: extensions, }, nil), } rewriteHandler := rewrite.Rewrite{ URI: "{http.matchers.file.relative}", } rewriteRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{rewriteMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rewriteHandler, "handler", "rewrite", nil)}, } // route to actually pass requests to PHP files; // match only requests that are for PHP files var pathList []string for _, ext := range extensions { pathList = append(pathList, "*"+ext) } phpMatcherSet := caddy.ModuleMap{ "path": caddyconfig.JSON(pathList, nil), } // create the PHP route which is // conditional on matching PHP files phpRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{phpMatcherSet}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(phpHandler, "handler", "php", nil)}, } fileRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(fileserver.FileServer{Root: root}, "handler", "file_server", nil)}, } subroute := caddyhttp.Subroute{ Routes: caddyhttp.RouteList{redirRoute, rewriteRoute, phpRoute, fileRoute}, } if compress { gzip, err := caddy.GetModule("http.encoders.gzip") if err != nil { return caddy.ExitCodeFailedStartup, err } br, err := caddy.GetModule("http.encoders.br") if err != nil && brotli { return caddy.ExitCodeFailedStartup, err } zstd, err := caddy.GetModule("http.encoders.zstd") if err != nil { return caddy.ExitCodeFailedStartup, err } var ( encodings caddy.ModuleMap prefer []string ) if brotli { encodings = caddy.ModuleMap{ "zstd": caddyconfig.JSON(zstd.New(), nil), "br": caddyconfig.JSON(br.New(), nil), "gzip": caddyconfig.JSON(gzip.New(), nil), } prefer = []string{"zstd", "br", "gzip"} } else { encodings = caddy.ModuleMap{ "zstd": caddyconfig.JSON(zstd.New(), nil), "gzip": caddyconfig.JSON(gzip.New(), nil), } prefer = []string{"zstd", "gzip"} } encodeRoute := caddyhttp.Route{ MatcherSetsRaw: []caddy.ModuleMap{}, HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(encode.Encode{ EncodingsRaw: encodings, Prefer: prefer, }, "handler", "encode", nil)}, } subroute.Routes = append(caddyhttp.RouteList{encodeRoute}, subroute.Routes...) } if mercure { mercureRoute, err := createMercureRoute() if err != nil { return caddy.ExitCodeFailedStartup, err } subroute.Routes = append(caddyhttp.RouteList{mercureRoute}, subroute.Routes...) } route := caddyhttp.Route{ HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)}, } if domain != "" { route.MatcherSetsRaw = []caddy.ModuleMap{ { "host": caddyconfig.JSON(caddyhttp.MatchHost{domain}, nil), }, } } server := &caddyhttp.Server{ ReadHeaderTimeout: caddy.Duration(10 * time.Second), IdleTimeout: caddy.Duration(30 * time.Second), MaxHeaderBytes: 1024 * 10, Routes: caddyhttp.RouteList{route}, } if listen == "" { if domain == "" { listen = ":80" } else { listen = ":" + strconv.Itoa(certmagic.HTTPSPort) } } server.Listen = []string{listen} if accessLog { server.Logs = &caddyhttp.ServerLogConfig{} } httpApp := caddyhttp.App{ Servers: map[string]*caddyhttp.Server{"php": server}, } var f bool cfg := &caddy.Config{ Admin: &caddy.AdminConfig{ Disabled: true, Config: &caddy.ConfigSettings{ Persist: &f, }, }, AppsRaw: caddy.ModuleMap{ "http": caddyconfig.JSON(httpApp, nil), "frankenphp": caddyconfig.JSON(FrankenPHPApp{Workers: workersOption}, nil), }, } if debug { cfg.Logging = &caddy.Logging{ Logs: map[string]*caddy.CustomLog{ "default": { BaseLog: caddy.BaseLog{Level: slog.LevelDebug.String()}, }, }, } } err = caddy.Run(cfg) if err != nil { return caddy.ExitCodeFailedStartup, err } log.Printf("Caddy serving PHP app on %s", listen) select {} } ================================================ FILE: caddy/watcher_test.go ================================================ //go:build !nowatcher package caddy_test import ( "net/http" "testing" "github.com/caddyserver/caddy/v2/caddytest" ) func TestWorkerWithInactiveWatcher(t *testing.T) { tester := caddytest.NewTester(t) tester.InitServer(` { skip_install_trust admin localhost:2999 http_port `+testPort+` frankenphp { worker { file ../testdata/worker-with-counter.php num 1 watch ./**/*.php } } } localhost:`+testPort+` { root ../testdata rewrite worker-with-counter.php php } `, "caddyfile") tester.AssertGetResponse("http://localhost:"+testPort, http.StatusOK, "requests:1") tester.AssertGetResponse("http://localhost:"+testPort, http.StatusOK, "requests:2") } ================================================ FILE: caddy/workerconfig.go ================================================ package caddy import ( "net/http" "path" "path/filepath" "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/internal/fastabs" ) // workerConfig represents the "worker" directive in the Caddyfile // it can appear in the "frankenphp", "php_server" and "php" directives // // frankenphp { // worker { // name "my-worker" // file "my-worker.php" // } // } type workerConfig struct { mercureContext // Name for the worker. Default: the filename for FrankenPHPApp workers, always prefixed with "m#" for FrankenPHPModule workers. Name string `json:"name,omitempty"` // FileName sets the path to the worker script. FileName string `json:"file_name,omitempty"` // Num sets the number of workers to start. Num int `json:"num,omitempty"` // MaxThreads sets the maximum number of threads for this worker. MaxThreads int `json:"max_threads,omitempty"` // Env sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. Env map[string]string `json:"env,omitempty"` // Directories to watch for file changes Watch []string `json:"watch,omitempty"` // The path to match against the worker MatchPath []string `json:"match_path,omitempty"` // MaxConsecutiveFailures sets the maximum number of consecutive failures before panicking (defaults to 6, set to -1 to never panick) MaxConsecutiveFailures int `json:"max_consecutive_failures,omitempty"` options []frankenphp.WorkerOption requestOptions []frankenphp.RequestOption absFileName string matchRelPath string // pre-computed relative URL path for fast matching } func unmarshalWorker(d *caddyfile.Dispenser) (workerConfig, error) { wc := workerConfig{} if d.NextArg() { wc.FileName = d.Val() } if d.NextArg() { if d.Val() == "watch" { wc.Watch = append(wc.Watch, defaultWatchPattern) } else { v, err := strconv.ParseUint(d.Val(), 10, 32) if err != nil { return wc, err } wc.Num = int(v) } } if d.NextArg() { return wc, d.Errf(`FrankenPHP: too many "worker" arguments: %s`, d.Val()) } for d.NextBlock(1) { switch v := d.Val(); v { case "name": if !d.NextArg() { return wc, d.ArgErr() } wc.Name = d.Val() case "file": if !d.NextArg() { return wc, d.ArgErr() } wc.FileName = d.Val() case "num": if !d.NextArg() { return wc, d.ArgErr() } v, err := strconv.ParseUint(d.Val(), 10, 32) if err != nil { return wc, d.WrapErr(err) } wc.Num = int(v) case "max_threads": if !d.NextArg() { return wc, d.ArgErr() } v, err := strconv.ParseUint(d.Val(), 10, 32) if err != nil { return wc, d.WrapErr(err) } wc.MaxThreads = int(v) case "env": args := d.RemainingArgs() if len(args) != 2 { return wc, d.ArgErr() } if wc.Env == nil { wc.Env = make(map[string]string) } wc.Env[args[0]] = args[1] case "watch": patterns := d.RemainingArgs() if len(patterns) == 0 { // the default if the watch directory is left empty: wc.Watch = append(wc.Watch, defaultWatchPattern) } else { wc.Watch = append(wc.Watch, patterns...) } case "match": // provision the path so it's identical to Caddy match rules // see: https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/matchers.go caddyMatchPath := (caddyhttp.MatchPath)(d.RemainingArgs()) if err := caddyMatchPath.Provision(caddy.Context{}); err != nil { return wc, d.WrapErr(err) } wc.MatchPath = caddyMatchPath case "max_consecutive_failures": if !d.NextArg() { return wc, d.ArgErr() } v, err := strconv.Atoi(d.Val()) if err != nil { return wc, d.WrapErr(err) } if v < -1 { return wc, d.Errf("max_consecutive_failures must be >= -1") } wc.MaxConsecutiveFailures = v default: return wc, wrongSubDirectiveError("worker", "name, file, num, env, watch, match, max_consecutive_failures, max_threads", v) } } if wc.FileName == "" { return wc, d.Err(`the "file" argument must be specified`) } if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(wc.FileName) { wc.FileName = filepath.Join(frankenphp.EmbeddedAppPath, wc.FileName) } return wc, nil } func (wc *workerConfig) inheritEnv(env map[string]string) { if wc.Env == nil { wc.Env = make(map[string]string, len(env)) } for k, v := range env { // do not overwrite existing environment variables if _, exists := wc.Env[k]; !exists { wc.Env[k] = v } } } func (wc *workerConfig) matchesPath(r *http.Request, documentRoot string) bool { // try to match against a pattern if one is assigned if len(wc.MatchPath) != 0 { return (caddyhttp.MatchPath)(wc.MatchPath).Match(r) } // fast path: compare the request URL path against the pre-computed relative path if wc.matchRelPath != "" { reqPath := r.URL.Path if reqPath == wc.matchRelPath { return true } // ensure leading slash for relative paths (see #2166) if reqPath == "" || reqPath[0] != '/' { reqPath = "/" + reqPath } return path.Clean(reqPath) == wc.matchRelPath } // fallback when documentRoot is dynamic (contains placeholders) fullPath, _ := fastabs.FastAbs(filepath.Join(documentRoot, r.URL.Path)) return fullPath == wc.absFileName } ================================================ FILE: cgi.go ================================================ package frankenphp // #cgo nocallback frankenphp_register_server_vars // #cgo nocallback frankenphp_register_variable_safe // #cgo nocallback frankenphp_register_known_variable // #cgo nocallback frankenphp_init_persistent_string // #cgo noescape frankenphp_register_server_vars // #cgo noescape frankenphp_register_variable_safe // #cgo noescape frankenphp_register_known_variable // #cgo noescape frankenphp_init_persistent_string // #include "frankenphp.h" // #include import "C" import ( "context" "crypto/tls" "net" "net/http" "path/filepath" "strings" "unicode/utf8" "unsafe" "github.com/dunglas/frankenphp/internal/phpheaders" "golang.org/x/text/language" "golang.org/x/text/search" ) // cStringHTTPMethods caches C string versions of common HTTP methods // to avoid allocations in pinCString on every request. var cStringHTTPMethods = map[string]*C.char{ "GET": C.CString("GET"), "HEAD": C.CString("HEAD"), "POST": C.CString("POST"), "PUT": C.CString("PUT"), "DELETE": C.CString("DELETE"), "CONNECT": C.CString("CONNECT"), "OPTIONS": C.CString("OPTIONS"), "TRACE": C.CString("TRACE"), "PATCH": C.CString("PATCH"), } // computeKnownVariables returns a set of CGI environment variables for the request. // // TODO: handle this case https://github.com/caddyserver/caddy/issues/3718 // Inspired by https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go func addKnownVariablesToServer(fc *frankenPHPContext, trackVarsArray *C.zval) { request := fc.request // Separate remote IP and port; more lenient than net.SplitHostPort var ip, port string if idx := strings.LastIndex(request.RemoteAddr, ":"); idx > -1 { ip = request.RemoteAddr[:idx] port = request.RemoteAddr[idx+1:] } else { ip = request.RemoteAddr } // Remove [] from IPv6 addresses if len(ip) > 0 && ip[0] == '[' { ip = ip[1 : len(ip)-1] } var rs, https, sslProtocol *C.zend_string var sslCipher string if request.TLS == nil { rs = C.frankenphp_strings.httpLowercase https = C.frankenphp_strings.empty sslProtocol = C.frankenphp_strings.empty sslCipher = "" } else { rs = C.frankenphp_strings.httpsLowercase https = C.frankenphp_strings.on // and pass the protocol details in a manner compatible with Apache's mod_ssl // (which is why these have an SSL_ prefix and not TLS_). sslProtocol = tlsProtocol(request.TLS.Version) if request.TLS.CipherSuite != 0 { sslCipher = tls.CipherSuiteName(request.TLS.CipherSuite) } } reqHost, reqPort, _ := net.SplitHostPort(request.Host) if reqHost == "" { // whatever, just assume there was no port reqHost = request.Host } if reqPort == "" { // compliance with the CGI specification requires that // the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client // even if the port is the default port for the scheme and could otherwise be omitted from a URI. // https://tools.ietf.org/html/rfc3875#section-4.1.15 switch rs { case C.frankenphp_strings.httpsLowercase: reqPort = "443" case C.frankenphp_strings.httpLowercase: reqPort = "80" } } serverPort := reqPort contentLength := request.Header.Get("Content-Length") var requestURI string if fc.originalRequest != nil { requestURI = fc.originalRequest.URL.RequestURI() } else { requestURI = fc.requestURI } requestPath := ensureLeadingSlash(request.URL.Path) C.frankenphp_register_server_vars(trackVarsArray, C.frankenphp_server_vars{ // approximate total length to avoid array re-hashing: // 28 CGI vars + headers + environment total_num_vars: C.size_t(28 + len(request.Header) + len(fc.env) + lengthOfEnv), // CGI vars with variable values remote_addr: toUnsafeChar(ip), remote_addr_len: C.size_t(len(ip)), remote_host: toUnsafeChar(ip), remote_host_len: C.size_t(len(ip)), remote_port: toUnsafeChar(port), remote_port_len: C.size_t(len(port)), document_root: toUnsafeChar(fc.documentRoot), document_root_len: C.size_t(len(fc.documentRoot)), path_info: toUnsafeChar(fc.pathInfo), path_info_len: C.size_t(len(fc.pathInfo)), php_self: toUnsafeChar(requestPath), php_self_len: C.size_t(len(requestPath)), document_uri: toUnsafeChar(fc.docURI), document_uri_len: C.size_t(len(fc.docURI)), script_filename: toUnsafeChar(fc.scriptFilename), script_filename_len: C.size_t(len(fc.scriptFilename)), script_name: toUnsafeChar(fc.scriptName), script_name_len: C.size_t(len(fc.scriptName)), server_name: toUnsafeChar(reqHost), server_name_len: C.size_t(len(reqHost)), server_port: toUnsafeChar(serverPort), server_port_len: C.size_t(len(serverPort)), content_length: toUnsafeChar(contentLength), content_length_len: C.size_t(len(contentLength)), server_protocol: toUnsafeChar(request.Proto), server_protocol_len: C.size_t(len(request.Proto)), http_host: toUnsafeChar(request.Host), http_host_len: C.size_t(len(request.Host)), request_uri: toUnsafeChar(requestURI), request_uri_len: C.size_t(len(requestURI)), ssl_cipher: toUnsafeChar(sslCipher), ssl_cipher_len: C.size_t(len(sslCipher)), // CGI vars with known values request_scheme: rs, // "http" or "https" ssl_protocol: sslProtocol, // values from tlsProtocol https: https, // "on" or empty }) } func addHeadersToServer(ctx context.Context, request *http.Request, trackVarsArray *C.zval) { for field, val := range request.Header { if k := commonHeaders[field]; k != nil { v := strings.Join(val, ", ") C.frankenphp_register_known_variable(k, toUnsafeChar(v), C.size_t(len(v)), trackVarsArray) continue } // if the header name could not be cached, it needs to be registered safely // this is more inefficient but allows additional sanitizing by PHP k := phpheaders.GetUnCommonHeader(ctx, field) v := strings.Join(val, ", ") C.frankenphp_register_variable_safe(toUnsafeChar(k), toUnsafeChar(v), C.size_t(len(v)), trackVarsArray) } } func addPreparedEnvToServer(fc *frankenPHPContext, trackVarsArray *C.zval) { for k, v := range fc.env { C.frankenphp_register_variable_safe(toUnsafeChar(k), toUnsafeChar(v), C.size_t(len(v)), trackVarsArray) } fc.env = nil } //export go_register_server_variables func go_register_server_variables(threadIndex C.uintptr_t, trackVarsArray *C.zval) { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() if fc.request != nil { addKnownVariablesToServer(fc, trackVarsArray) addHeadersToServer(thread.context(), fc.request, trackVarsArray) } // The Prepared Environment is registered last and can overwrite any previous values addPreparedEnvToServer(fc, trackVarsArray) } // splitCgiPath splits the request path into SCRIPT_NAME, SCRIPT_FILENAME, PATH_INFO, DOCUMENT_URI func splitCgiPath(fc *frankenPHPContext) { path := fc.request.URL.Path splitPath := fc.splitPath if splitPath == nil { splitPath = []string{".php"} } if splitPos := splitPos(path, splitPath); splitPos > -1 { fc.docURI = path[:splitPos] fc.pathInfo = path[splitPos:] // Strip PATH_INFO from SCRIPT_NAME fc.scriptName = strings.TrimSuffix(path, fc.pathInfo) // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875 // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13 if fc.scriptName != "" && !strings.HasPrefix(fc.scriptName, "/") { fc.scriptName = "/" + fc.scriptName } } // TODO: is it possible to delay this and avoid saving everything in the context? // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName) fc.worker = workersByPath[fc.scriptFilename] } var splitSearchNonASCII = search.New(language.Und, search.IgnoreCase) // splitPos returns the index where path should be split based on splitPath. // example: if splitPath is [".php"] // "/path/to/script.php/some/path": ("/path/to/script.php", "/some/path") func splitPos(path string, splitPath []string) int { if len(splitPath) == 0 { return 0 } pathLen := len(path) // We are sure that split strings are all ASCII-only and lower-case because of validation and normalization in WithRequestSplitPath for _, split := range splitPath { splitLen := len(split) for i := 0; i < pathLen; i++ { if path[i] >= utf8.RuneSelf { if _, end := splitSearchNonASCII.IndexString(path, split); end > -1 { return end } break } if i+splitLen > pathLen { continue } match := true for j := 0; j < splitLen; j++ { c := path[i+j] if c >= utf8.RuneSelf { if _, end := splitSearchNonASCII.IndexString(path, split); end > -1 { return end } break } if 'A' <= c && c <= 'Z' { c += 'a' - 'A' } if c != split[j] { match = false break } } if match { return i + splitLen } } } return -1 } // go_update_request_info updates the sapi_request_info struct // See: https://github.com/php/php-src/blob/345e04b619c3bc11ea17ee02cdecad6ae8ce5891/main/SAPI.h#L72 // //export go_update_request_info func go_update_request_info(threadIndex C.uintptr_t, info *C.sapi_request_info) *C.char { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() request := fc.request if request == nil { return nil } if m, ok := cStringHTTPMethods[request.Method]; ok { info.request_method = m } else { info.request_method = thread.pinCString(request.Method) } info.query_string = thread.pinCString(request.URL.RawQuery) info.content_length = C.zend_long(request.ContentLength) if contentType := request.Header.Get("Content-Type"); contentType != "" { info.content_type = thread.pinCString(contentType) } if fc.pathInfo != "" { info.path_translated = thread.pinCString(sanitizedPathJoin(fc.documentRoot, fc.pathInfo)) // See: http://www.oreilly.com/openbook/cgi/ch02_04.html } info.request_uri = thread.pinCString(fc.requestURI) info.proto_num = C.int(request.ProtoMajor*1000 + request.ProtoMinor) authorizationHeader := request.Header.Get("Authorization") if authorizationHeader == "" { return nil } return thread.pinCString(authorizationHeader) } // SanitizedPathJoin performs filepath.Join(root, reqPath) that // is safe against directory traversal attacks. It uses logic // similar to that in the Go standard library, specifically // in the implementation of http.Dir. The root is assumed to // be a trusted path, but reqPath is not; and the output will // never be outside of root. The resulting path can be used // with the local file system. // // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go // Copyright 2015 Matthew Holt and The Caddy Authors func sanitizedPathJoin(root, reqPath string) string { if root == "" { root = "." } path := filepath.Join(root, filepath.Clean("/"+reqPath)) // filepath.Join also cleans the path, and cleaning strips // the trailing slash, so we need to re-add it afterward. // if the length is 1, then it's a path to the root, // and that should return ".", so we don't append the separator. if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 { path += separator } return path } const separator = string(filepath.Separator) func ensureLeadingSlash(path string) string { if path == "" || path[0] == '/' { return path } return "/" + path } // toUnsafeChar returns a *C.char pointing at the backing bytes the Go string. // If C does not store the string, it may be passed directly in a Cgo call (most efficient). // If C stores the string, it must be pinned explicitly instead (inefficient). // C may never modify the string. func toUnsafeChar(s string) *C.char { return (*C.char)(unsafe.Pointer(unsafe.StringData(s))) } // initialize a global zend_string that must never be freed and is ignored by GC func newPersistentZendString(str string) *C.zend_string { return C.frankenphp_init_persistent_string(toUnsafeChar(str), C.size_t(len(str))) } // Protocol versions, in Apache mod_ssl format: https://httpd.apache.org/docs/current/mod/mod_ssl.html // Note that these are slightly different from SupportedProtocols in caddytls/config.go func tlsProtocol(proto uint16) *C.zend_string { switch proto { case tls.VersionTLS10: return C.frankenphp_strings.tls1 case tls.VersionTLS11: return C.frankenphp_strings.tls11 case tls.VersionTLS12: return C.frankenphp_strings.tls12 case tls.VersionTLS13: return C.frankenphp_strings.tls13 default: return C.frankenphp_strings.empty } } ================================================ FILE: cgi_test.go ================================================ package frankenphp import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestEnsureLeadingSlash(t *testing.T) { t.Parallel() tests := []struct { input string expected string }{ {"/index.php", "/index.php"}, {"index.php", "/index.php"}, {"/", "/"}, {"", ""}, {"/path/to/script.php", "/path/to/script.php"}, {"path/to/script.php", "/path/to/script.php"}, {"/index.php/path/info", "/index.php/path/info"}, {"index.php/path/info", "/index.php/path/info"}, } for _, tt := range tests { t.Run(tt.input+"-"+tt.expected, func(t *testing.T) { t.Parallel() assert.Equal(t, tt.expected, ensureLeadingSlash(tt.input), "ensureLeadingSlash(%q)", tt.input) }) } } func TestSplitPos(t *testing.T) { tests := []struct { name string path string splitPath []string wantPos int }{ { name: "simple php extension", path: "/path/to/script.php", splitPath: []string{".php"}, wantPos: 19, }, { name: "php extension with path info", path: "/path/to/script.php/some/path", splitPath: []string{".php"}, wantPos: 19, }, { name: "case insensitive match", path: "/path/to/script.PHP", splitPath: []string{".php"}, wantPos: 19, }, { name: "mixed case match", path: "/path/to/script.PhP/info", splitPath: []string{".php"}, wantPos: 19, }, { name: "no match", path: "/path/to/script.txt", splitPath: []string{".php"}, wantPos: -1, }, { name: "empty split path", path: "/path/to/script.php", splitPath: []string{}, wantPos: 0, }, { name: "multiple split paths first match", path: "/path/to/script.php", splitPath: []string{".php", ".phtml"}, wantPos: 19, }, { name: "multiple split paths second match", path: "/path/to/script.phtml", splitPath: []string{".php", ".phtml"}, wantPos: 21, }, // Unicode case-folding tests (security fix for GHSA-g966-83w7-6w38) // U+023A (Ⱥ) lowercases to U+2C65 (ⱥ), which has different UTF-8 byte length // Ⱥ: 2 bytes (C8 BA), ⱥ: 3 bytes (E2 B1 A5) { name: "unicode path with case-folding length expansion", path: "/ȺȺȺȺshell.php", splitPath: []string{".php"}, wantPos: 18, // correct position in original string }, { name: "unicode path with extension after expansion chars", path: "/ȺȺȺȺshell.php/path/info", splitPath: []string{".php"}, wantPos: 18, }, { name: "unicode in filename with multiple php occurrences", path: "/ȺȺȺȺshell.php.txt.php", splitPath: []string{".php"}, wantPos: 18, // should match first .php, not be confused by byte offset shift }, { name: "unicode case insensitive extension", path: "/ȺȺȺȺshell.PHP", splitPath: []string{".php"}, wantPos: 18, }, { name: "unicode in middle of path", path: "/path/Ⱥtest/script.php", splitPath: []string{".php"}, wantPos: 23, // Ⱥ is 2 bytes, so path is 23 bytes total, .php ends at byte 23 }, { name: "unicode only in directory not filename", path: "/Ⱥ/script.php", splitPath: []string{".php"}, wantPos: 14, }, // Additional Unicode characters that expand when lowercased // U+0130 (İ - Turkish capital I with dot) lowercases to U+0069 + U+0307 { name: "turkish capital I with dot", path: "/İtest.php", splitPath: []string{".php"}, wantPos: 11, }, // Ensure standard ASCII still works correctly { name: "ascii only path with case variation", path: "/PATH/TO/SCRIPT.PHP/INFO", splitPath: []string{".php"}, wantPos: 19, }, { name: "path at root", path: "/index.php", splitPath: []string{".php"}, wantPos: 10, }, { name: "extension in middle of filename", path: "/test.php.bak", splitPath: []string{".php"}, wantPos: 9, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotPos := splitPos(tt.path, tt.splitPath) assert.Equal(t, tt.wantPos, gotPos, "splitPos(%q, %v)", tt.path, tt.splitPath) // Verify that the split produces valid substrings if gotPos > 0 && gotPos <= len(tt.path) { scriptName := tt.path[:gotPos] pathInfo := tt.path[gotPos:] // The script name should end with one of the split extensions (case-insensitive) hasValidEnding := false for _, split := range tt.splitPath { if strings.HasSuffix(strings.ToLower(scriptName), split) { hasValidEnding = true break } } assert.True(t, hasValidEnding, "script name %q should end with one of %v", scriptName, tt.splitPath) // Original path should be reconstructable assert.Equal(t, tt.path, scriptName+pathInfo, "path should be reconstructable from split parts") } }) } } // TestSplitPosUnicodeSecurityRegression specifically tests the vulnerability // described in GHSA-g966-83w7-6w38 where Unicode case-folding caused // incorrect SCRIPT_NAME/PATH_INFO splitting func TestSplitPosUnicodeSecurityRegression(t *testing.T) { // U+023A: Ⱥ (UTF-8: C8 BA). Lowercase is ⱥ (UTF-8: E2 B1 A5), longer in bytes. path := "/ȺȺȺȺshell.php.txt.php" split := []string{".php"} pos := splitPos(path, split) // The vulnerable code would return 22 (computed on lowercased string) // The correct code should return 18 (position in original string) expectedPos := strings.Index(path, ".php") + len(".php") assert.Equal(t, expectedPos, pos, "split position should match first .php in original string") assert.Equal(t, 18, pos, "split position should be 18, not 22") if pos > 0 && pos <= len(path) { scriptName := path[:pos] pathInfo := path[pos:] assert.Equal(t, "/ȺȺȺȺshell.php", scriptName, "script name should be the path up to first .php") assert.Equal(t, ".txt.php", pathInfo, "path info should be the remainder after first .php") } } ================================================ FILE: cgo.go ================================================ package frankenphp // #cgo darwin pkg-config: libxml-2.0 // #cgo unix CFLAGS: -Wall -Werror // #cgo linux CFLAGS: -D_GNU_SOURCE // #cgo unix LDFLAGS: -lphp -lm -lutil // #cgo linux LDFLAGS: -ldl -lresolv // #cgo darwin LDFLAGS: -Wl,-rpath,/usr/local/lib -liconv -ldl // #cgo windows CFLAGS: -D_WINDOWS -DWINDOWS=1 -DZEND_WIN32=1 -DPHP_WIN32=1 -DWIN32 -D_MBCS -D_USE_MATH_DEFINES -DNDebug -DNDEBUG -DZEND_DEBUG=0 -DZTS=1 -DFD_SETSIZE=256 // #cgo windows LDFLAGS: -lpthreadVC3 import "C" ================================================ FILE: cli.go ================================================ package frankenphp // #include "frankenphp.h" import "C" import "unsafe" // ExecuteScriptCLI executes the PHP script passed as parameter. // It returns the exit status code of the script. func ExecuteScriptCLI(script string, args []string) int { // Ensure extensions are registered before CLI execution registerExtensions() cScript := C.CString(script) defer C.free(unsafe.Pointer(cScript)) argc, argv := convertArgs(args) defer freeArgs(argv) return int(C.frankenphp_execute_script_cli(cScript, argc, (**C.char)(unsafe.Pointer(&argv[0])), false)) } func ExecutePHPCode(phpCode string) int { // Ensure extensions are registered before CLI execution registerExtensions() cCode := C.CString(phpCode) defer C.free(unsafe.Pointer(cCode)) return int(C.frankenphp_execute_script_cli(cCode, 0, nil, true)) } ================================================ FILE: cli_test.go ================================================ package frankenphp_test import ( "errors" "log" "os" "os/exec" "testing" "github.com/dunglas/frankenphp" "github.com/stretchr/testify/assert" ) func TestExecuteScriptCLI(t *testing.T) { if _, err := os.Stat("internal/testcli/testcli"); err != nil { t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") } cmd := exec.Command("internal/testcli/testcli", "testdata/command.php", "foo", "bar") stdoutStderr, err := cmd.CombinedOutput() assert.Error(t, err) var exitError *exec.ExitError if errors.As(err, &exitError) { assert.Equal(t, 3, exitError.ExitCode()) } stdoutStderrStr := string(stdoutStderr) assert.Contains(t, stdoutStderrStr, `"foo"`) assert.Contains(t, stdoutStderrStr, `"bar"`) assert.Contains(t, stdoutStderrStr, "From the CLI") } func TestExecuteCLICode(t *testing.T) { if _, err := os.Stat("internal/testcli/testcli"); err != nil { t.Skip("internal/testcli/testcli has not been compiled, run `cd internal/testcli/ && go build`") } cmd := exec.Command("internal/testcli/testcli", "-r", "echo 'Hello World';") stdoutStderr, err := cmd.CombinedOutput() assert.NoError(t, err) stdoutStderrStr := string(stdoutStderr) assert.Equal(t, stdoutStderrStr, `Hello World`) } func ExampleExecuteScriptCLI() { if len(os.Args) <= 1 { log.Println("Usage: my-program script.php") os.Exit(1) } os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args)) } ================================================ FILE: context.go ================================================ package frankenphp import ( "context" "errors" "fmt" "log/slog" "net/http" "os" "strconv" "strings" "time" ) // frankenPHPContext provides contextual information about the Request to handle. type frankenPHPContext struct { mercureContext documentRoot string splitPath []string env PreparedEnv logger *slog.Logger request *http.Request originalRequest *http.Request worker *worker docURI string pathInfo string scriptName string scriptFilename string requestURI string // Whether the request is already closed by us isDone bool responseWriter http.ResponseWriter responseController *http.ResponseController handlerParameters any handlerReturn any done chan any startedAt time.Time } type contextHolder struct { ctx context.Context frankenPHPContext *frankenPHPContext } // fromContext extracts the frankenPHPContext from a context. func fromContext(ctx context.Context) (fctx *frankenPHPContext, ok bool) { fctx, ok = ctx.Value(contextKey).(*frankenPHPContext) return } func newFrankenPHPContext() *frankenPHPContext { return &frankenPHPContext{ done: make(chan any), startedAt: time.Now(), } } // NewRequestWithContext creates a new FrankenPHP request context. func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error) { fc := newFrankenPHPContext() fc.request = r for _, o := range opts { if err := o(fc); err != nil { return nil, err } } if fc.logger == nil { fc.logger = globalLogger } if fc.documentRoot == "" { if EmbeddedAppPath != "" { fc.documentRoot = EmbeddedAppPath } else { var err error if fc.documentRoot, err = os.Getwd(); err != nil { return nil, err } } } // If a worker is already assigned explicitly, use its filename and skip parsing path variables if fc.worker != nil { fc.scriptFilename = fc.worker.fileName } else { // If no worker was assigned, split the path into the "traditional" CGI path variables. // This needs to already happen here in case a worker script still matches the path. splitCgiPath(fc) } fc.requestURI = r.URL.RequestURI() c := context.WithValue(r.Context(), contextKey, fc) return r.WithContext(c), nil } // newDummyContext creates a fake context from a request path func newDummyContext(requestPath string, opts ...RequestOption) (*frankenPHPContext, error) { r, err := http.NewRequestWithContext(globalCtx, http.MethodGet, requestPath, nil) if err != nil { return nil, err } fr, err := NewRequestWithContext(r, opts...) if err != nil { return nil, err } fc, _ := fromContext(fr.Context()) return fc, nil } // closeContext sends the response to the client func (fc *frankenPHPContext) closeContext() { if fc.isDone { return } close(fc.done) fc.isDone = true } // validate checks if the request should be outright rejected func (fc *frankenPHPContext) validate() error { if strings.Contains(fc.request.URL.Path, "\x00") { fc.reject(ErrInvalidRequestPath) return ErrInvalidRequestPath } contentLengthStr := fc.request.Header.Get("Content-Length") if contentLengthStr != "" { if contentLength, err := strconv.Atoi(contentLengthStr); err != nil || contentLength < 0 { e := fmt.Errorf("%w: %q", ErrInvalidContentLengthHeader, contentLengthStr) fc.reject(e) return e } } return nil } func (fc *frankenPHPContext) clientHasClosed() bool { if fc.request == nil { return false } select { case <-fc.request.Context().Done(): return true default: return false } } // reject sends a response with the given status code and error func (fc *frankenPHPContext) reject(err error) { if fc.isDone { return } re := &ErrRejected{} if !errors.As(err, re) { // Should never happen panic("only instance of ErrRejected can be passed to reject") } rw := fc.responseWriter if rw != nil { rw.WriteHeader(re.status) _, _ = rw.Write([]byte(err.Error())) if f, ok := rw.(http.Flusher); ok { f.Flush() } } fc.closeContext() } ================================================ FILE: debugstate.go ================================================ package frankenphp import ( "github.com/dunglas/frankenphp/internal/state" ) // EXPERIMENTAL: ThreadDebugState prints the state of a single PHP thread - debugging purposes only type ThreadDebugState struct { Index int Name string State string IsWaiting bool IsBusy bool WaitingSinceMilliseconds int64 } // EXPERIMENTAL: FrankenPHPDebugState prints the state of all PHP threads - debugging purposes only type FrankenPHPDebugState struct { ThreadDebugStates []ThreadDebugState ReservedThreadCount int } // EXPERIMENTAL: DebugState prints the state of all PHP threads - debugging purposes only func DebugState() FrankenPHPDebugState { fullState := FrankenPHPDebugState{ ThreadDebugStates: make([]ThreadDebugState, 0, len(phpThreads)), ReservedThreadCount: 0, } for _, thread := range phpThreads { if thread.state.Is(state.Reserved) { fullState.ReservedThreadCount++ continue } fullState.ThreadDebugStates = append(fullState.ThreadDebugStates, threadDebugState(thread)) } return fullState } // threadDebugState creates a small jsonable status message for debugging purposes func threadDebugState(thread *phpThread) ThreadDebugState { return ThreadDebugState{ Index: thread.threadIndex, Name: thread.name(), State: thread.state.Name(), IsWaiting: thread.state.IsInWaitingState(), IsBusy: !thread.state.IsInWaitingState(), WaitingSinceMilliseconds: thread.state.WaitTime(), } } ================================================ FILE: dev-alpine.Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 FROM golang:1.26-alpine ENV GOTOOLCHAIN=local ENV CFLAGS="-ggdb3" ENV PHPIZE_DEPS="\ autoconf \ dpkg-dev \ file \ g++ \ gcc \ libc-dev \ make \ pkgconfig \ re2c" SHELL ["/bin/ash", "-eo", "pipefail", "-c"] RUN apk add --no-cache \ $PHPIZE_DEPS \ argon2-dev \ brotli-dev \ curl-dev \ oniguruma-dev \ readline-dev \ libsodium-dev \ sqlite-dev \ openssl-dev \ libxml2-dev \ zlib-dev \ bison \ nss-tools \ # file watcher \ libstdc++ \ linux-headers \ # Dev tools \ git \ clang \ cmake \ llvm \ gdb \ valgrind \ neovim \ zsh \ libtool && \ echo 'set auto-load safe-path /' > /root/.gdbinit WORKDIR /usr/local/src/php RUN git clone --branch=PHP-8.5 https://github.com/php/php-src.git . && \ # --enable-embed is necessary to generate libphp.so, but we don't use this SAPI directly ./buildconf --force && \ EXTENSION_DIR=/usr/lib/frankenphp/modules ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers \ --with-config-file-path=/etc/frankenphp/php.ini \ --with-config-file-scan-dir=/etc/frankenphp/php.d \ --enable-debug && \ make -j"$(nproc)" && \ make install && \ ldconfig /etc/ld.so.conf.d && \ mkdir -p /etc/frankenphp/php.d && \ cp php.ini-development /etc/frankenphp/php.ini && \ echo "zend_extension=opcache.so" >> /etc/frankenphp/php.ini && \ echo "opcache.enable=1" >> /etc/frankenphp/php.ini && \ php --version # Install e-dant/watcher (necessary for file watching) WORKDIR /usr/local/src/watcher RUN git clone https://github.com/e-dant/watcher . && \ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && \ cmake --build build/ && \ cmake --install build WORKDIR /go/src/app COPY . . WORKDIR /go/src/app/caddy/frankenphp RUN ../../go.sh build -buildvcs=false WORKDIR /go/src/app CMD [ "zsh" ] ================================================ FILE: dev.Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 FROM golang:1.26 ENV GOTOOLCHAIN=local ENV CFLAGS="-ggdb3" ENV PHPIZE_DEPS="\ autoconf \ dpkg-dev \ file \ g++ \ gcc \ libc-dev \ make \ pkg-config \ re2c" SHELL ["/bin/bash", "-o", "pipefail", "-c"] # hadolint ignore=DL3009 RUN apt-get update && \ apt-get -y --no-install-recommends install \ $PHPIZE_DEPS \ libargon2-dev \ libbrotli-dev \ libcurl4-openssl-dev \ libonig-dev \ libreadline-dev \ libsodium-dev \ libsqlite3-dev \ libssl-dev \ libxml2-dev \ zlib1g-dev \ bison \ libnss3-tools \ # Dev tools \ git \ clang \ cmake \ llvm \ gdb \ valgrind \ neovim \ zsh \ libtool-bin && \ echo 'set auto-load safe-path /' > /root/.gdbinit && \ echo '* soft core unlimited' >> /etc/security/limits.conf \ && \ apt-get clean WORKDIR /usr/local/src/php RUN git clone --branch=PHP-8.5 https://github.com/php/php-src.git . && \ # --enable-embed is only necessary to generate libphp.so, we don't use this SAPI directly ./buildconf --force && \ EXTENSION_DIR=/usr/lib/frankenphp/modules ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers \ --with-config-file-path=/etc/frankenphp/php.ini \ --with-config-file-scan-dir=/etc/frankenphp/php.d \ --enable-debug && \ make -j"$(nproc)" && \ make install && \ ldconfig && \ mkdir -p /etc/frankenphp/php.d && \ cp php.ini-development /etc/frankenphp/php.ini && \ echo "zend_extension=opcache.so" >> /etc/frankenphp/php.ini && \ echo "opcache.enable=1" >> /etc/frankenphp/php.ini && \ php --version # Install e-dant/watcher (necessary for file watching) WORKDIR /usr/local/src/watcher RUN git clone https://github.com/e-dant/watcher . && \ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && \ cmake --build build/ && \ cmake --install build && \ cp build/libwatcher-c.so /usr/local/lib/libwatcher-c.so && \ ldconfig WORKDIR /go/src/app COPY --link . ./ WORKDIR /go/src/app/caddy/frankenphp RUN ../../go.sh build -buildvcs=false WORKDIR /go/src/app CMD [ "zsh" ] ================================================ FILE: docker-bake.hcl ================================================ variable "IMAGE_NAME" { default = "dunglas/frankenphp" } variable "VERSION" { default = "dev" } variable "PHP_VERSION" { default = "8.2,8.3,8.4,8.5" } variable "GO_VERSION" { default = "1.26" } variable "BASE_FINGERPRINT" { default = "" } variable "SPC_OPT_BUILD_ARGS" { default = "" } variable "SHA" {} variable "LATEST" { default = true } variable "CACHE" { default = "" } variable "CI" { # CI flag coming from the environment or --set; empty by default default = "" } variable DEFAULT_PHP_VERSION { default = "8.5" } function "tag" { params = [version, os, php-version, tgt] result = [ version == "" ? "" : "${IMAGE_NAME}:${trimprefix("${version}${tgt == "builder" ? "-builder" : ""}-php${php-version}-${os}", "latest-")}", php-version == DEFAULT_PHP_VERSION && os == "trixie" && version != "" ? "${IMAGE_NAME}:${trimprefix("${version}${tgt == "builder" ? "-builder" : ""}", "latest-")}" : "", php-version == DEFAULT_PHP_VERSION && version != "" ? "${IMAGE_NAME}:${trimprefix("${version}${tgt == "builder" ? "-builder" : ""}-${os}", "latest-")}" : "", os == "trixie" && version != "" ? "${IMAGE_NAME}:${trimprefix("${version}${tgt == "builder" ? "-builder" : ""}-php${php-version}", "latest-")}" : "", ] } # cleanTag ensures that the tag is a valid Docker tag # cleanTag ensures that the tag is a valid Docker tag # see https://github.com/distribution/distribution/blob/v2.8.2/reference/regexp.go#L37 function "clean_tag" { params = [tag] result = substr(regex_replace(regex_replace(tag, "[^\\w.-]", "-"), "^([^\\w])", "r$0"), 0, 127) } # semver adds semver-compliant tag if a semver version number is passed, or returns the revision itself # see https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string function "semver" { params = [rev] result = __semver(_semver(regexall("^v?(?P0|[1-9]\\d*)\\.(?P0|[1-9]\\d*)\\.(?P0|[1-9]\\d*)(?:-(?P(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?P[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$", rev))) } function "_semver" { params = [matches] result = length(matches) == 0 ? {} : matches[0] } function "__semver" { params = [v] result = v == {} ? [clean_tag(VERSION)] : v.prerelease == null ? [v.major, "${v.major}.${v.minor}", "${v.major}.${v.minor}.${v.patch}"] : ["${v.major}.${v.minor}.${v.patch}-${v.prerelease}"] } function "php_version" { params = [v] result = _php_version(v, regexall("(?P\\d+)\\.(?P\\d+)", v)[0]) } function "_php_version" { params = [v, m] result = "${m.major}.${m.minor}" == DEFAULT_PHP_VERSION ? [v, "${m.major}.${m.minor}", "${m.major}"] : [v, "${m.major}.${m.minor}"] } target "default" { name = "${tgt}-php-${replace(php-version, ".", "-")}-${os}" matrix = { os = ["trixie", "bookworm", "alpine"] php-version = split(",", PHP_VERSION) tgt = ["builder", "runner"] } contexts = { php-base = "docker-image://php:${php-version}-zts-${os}" golang-base = "docker-image://golang:${GO_VERSION}-${os}" } dockerfile = os == "alpine" ? "alpine.Dockerfile" : "Dockerfile" context = "./" target = tgt # arm/v6 is only available for Alpine: https://github.com/docker-library/golang/issues/502 platforms = os == "alpine" ? [ "linux/amd64", "linux/386", "linux/arm/v6", "linux/arm/v7", "linux/arm64", ] : [ "linux/amd64", "linux/386", "linux/arm/v7", "linux/arm64" ] tags = distinct(flatten( [for pv in php_version(php-version) : flatten([ LATEST ? tag("latest", os, pv, tgt) : [], tag(SHA == "" || VERSION != "dev" ? "" : "sha-${substr(SHA, 0, 7)}", os, pv, tgt), VERSION == "dev" ? [] : [for v in semver(VERSION) : tag(v, os, pv, tgt)] ]) ])) labels = { "org.opencontainers.image.created" = "${timestamp()}" "org.opencontainers.image.version" = VERSION "org.opencontainers.image.revision" = SHA "dev.frankenphp.base.fingerprint" = BASE_FINGERPRINT } args = { FRANKENPHP_VERSION = VERSION } secret = ["id=github-token,env=GITHUB_TOKEN"] } target "static-builder-musl" { contexts = { golang-base = "docker-image://golang:${GO_VERSION}-alpine" } dockerfile = "static-builder-musl.Dockerfile" context = "./" platforms = [ "linux/amd64", "linux/arm64", ] tags = distinct(flatten([ LATEST ? "${IMAGE_NAME}:static-builder-musl" : "", SHA == "" || VERSION != "dev" ? "" : "${IMAGE_NAME}:static-builder-musl-sha-${substr(SHA, 0, 7)}", VERSION == "dev" ? [] : [for v in semver(VERSION) : "${IMAGE_NAME}:static-builder-musl-${v}"] ])) labels = { "org.opencontainers.image.created" = "${timestamp()}" "org.opencontainers.image.version" = VERSION "org.opencontainers.image.revision" = SHA "dev.frankenphp.base.fingerprint" = BASE_FINGERPRINT } args = { FRANKENPHP_VERSION = VERSION CI = CI SPC_OPT_BUILD_ARGS = SPC_OPT_BUILD_ARGS } secret = ["id=github-token,env=GITHUB_TOKEN"] } target "static-builder-gnu" { dockerfile = "static-builder-gnu.Dockerfile" context = "./" platforms = [ "linux/amd64", "linux/arm64" ] tags = distinct(flatten([ LATEST ? "${IMAGE_NAME}:static-builder-gnu" : "", SHA == "" || VERSION != "dev" ? "" : "${IMAGE_NAME}:static-builder-gnu-sha-${substr(SHA, 0, 7)}", VERSION == "dev" ? [] : [for v in semver(VERSION) : "${IMAGE_NAME}:static-builder-gnu-${v}"] ])) labels = { "org.opencontainers.image.created" = "${timestamp()}" "org.opencontainers.image.version" = VERSION "org.opencontainers.image.revision" = SHA "dev.frankenphp.base.fingerprint" = BASE_FINGERPRINT } args = { FRANKENPHP_VERSION = VERSION GO_VERSION = GO_VERSION CI = CI SPC_OPT_BUILD_ARGS = SPC_OPT_BUILD_ARGS } secret = ["id=github-token,env=GITHUB_TOKEN"] } ================================================ FILE: docs/classic.md ================================================ # Using Classic Mode Without any additional configuration, FrankenPHP operates in classic mode. In this mode, FrankenPHP functions like a traditional PHP server, directly serving PHP files. This makes it a seamless drop-in replacement for PHP-FPM or Apache with mod_php. Similar to Caddy, FrankenPHP accepts an unlimited number of connections and uses a [fixed number of threads](config.md#caddyfile-config) to serve them. The number of accepted and queued connections is limited only by the available system resources. The PHP thread pool operates with a fixed number of threads initialized at startup, comparable to the static mode of PHP-FPM. It's also possible to let threads [scale automatically at runtime](performance.md#max_threads), similar to the dynamic mode of PHP-FPM. Queued connections will wait indefinitely until a PHP thread is available to serve them. To avoid this, you can use the max_wait_time [configuration](config.md#caddyfile-config) in FrankenPHP's global configuration to limit the duration a request can wait for a free PHP thread before being rejected. Additionally, you can set a reasonable [write timeout in Caddy](https://caddyserver.com/docs/caddyfile/options#timeouts). Each Caddy instance will only spin up one FrankenPHP thread pool, which will be shared across all `php_server` blocks. ================================================ FILE: docs/cn/CONTRIBUTING.md ================================================ # 贡献 ## 编译 PHP ### 使用 Docker (Linux) 构建开发环境 Docker 镜像: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` 该镜像包含常用的开发工具(Go、GDB、Valgrind、Neovim等)并使用以下 php 设置位置 - php.ini: `/etc/frankenphp/php.ini` 默认提供了一个带有开发预设的 php.ini 文件。 - 附加配置文件: `/etc/frankenphp/php.d/*.ini` - php 扩展: `/usr/lib/frankenphp/modules/` 如果你的 Docker 版本低于 23.0,则会因为 dockerignore [pattern issue](https://github.com/moby/moby/pull/42676) 而导致构建失败。将目录添加到 `.dockerignore`。 ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### 不使用 Docker (Linux 和 macOS) [按照说明从源代码编译](https://frankenphp.dev/docs/compile/) 并传递 `--debug` 配置标志。 ## 运行测试套件 ```console go test -race -v ./... ``` ## Caddy 模块 使用 FrankenPHP Caddy 模块构建 Caddy: ```console cd caddy/frankenphp/ go build -tags nobadger,nomysql,nopgx cd ../../ ``` 使用 FrankenPHP Caddy 模块运行 Caddy: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` 服务器正在监听 `127.0.0.1:80`: > [!NOTE] > 如果您正在使用 Docker,您必须绑定容器的 80 端口或者在容器内部执行命令。 ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## 最小测试服务器 构建最小测试服务器: ```console cd internal/testserver/ go build cd ../../ ``` 运行测试服务器: ```console cd testdata/ ../internal/testserver/testserver ``` 服务器正在监听 `127.0.0.1:8080`: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## 本地构建 Docker 镜像 打印 bake 计划: ```console docker buildx bake -f docker-bake.hcl --print ``` 本地构建 amd64 的 FrankenPHP 镜像: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` 本地构建 arm64 的 FrankenPHP 镜像: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` 从头开始为 arm64 和 amd64 构建 FrankenPHP 镜像并推送到 Docker Hub: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## 使用静态构建调试分段错误 1. 从 GitHub 下载 FrankenPHP 二进制文件的调试版本或创建包含调试符号的自定义静态构建: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. 将当前版本的 `frankenphp` 替换为 debug FrankenPHP 可执行文件 3. 照常启动 FrankenPHP(或者,你可以直接使用 GDB 启动 FrankenPHP: `gdb --args frankenphp run`) 4. 使用 GDB 附加到进程: ```console gdb -p `pidof frankenphp` ``` 5. 如有必要,请在 GDB shell 中输入 `continue` 6. 使 FrankenPHP 崩溃 7. 在 GDB shell 中输入 `bt` 8. 复制输出 ## 在 GitHub Actions 中调试分段错误 1. 打开 `.github/workflows/tests.yml` 2. 启用 PHP 调试符号 ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. 启用 `tmate` 以连接到容器 ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. 连接到容器 5. 打开 `frankenphp.go` 6. 启用 `cgosymbolizer` ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. 下载模块: `go get` 8. 在容器中,可以使用 GDB 和以下: ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. 当错误修复后,恢复所有这些更改 ## 其他开发资源 - [PHP 嵌入 uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [PHP 嵌入 NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [PHP 嵌入 Go (go-php)](https://github.com/deuill/go-php) - [PHP 嵌入 Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [PHP 嵌入 C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [扩展和嵌入 PHP 作者:Sara Golemon](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [TSRMLS_CC到底是什么?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [SDL 绑定](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Docker 相关资源 - [Bake 文件定义](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## 有用的命令 ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## 翻译文档 要将文档和网站翻译成新语言,请按照下列步骤操作: 1. 在此存储库的 `docs/` 目录中创建一个以语言的 2 个字符的 ISO 代码命名的新目录 2. 将 `docs/` 目录根目录中的所有 `.md` 文件复制到新目录中(始终使用英文版本作为翻译源,因为它始终是最新的) 3. 将 `README.md` 和 `CONTRIBUTING.md` 文件从根目录复制到新目录 4. 翻译文件的内容,但不要更改文件名,也不要翻译以 `> [!` 开头的字符串(这是 GitHub 的特殊标记) 5. 创建翻译的拉取请求 6. 在 [站点存储库](https://github.com/dunglas/frankenphp-website/tree/main) 中,复制并翻译 `content/`、`data/` 和 `i18n/` 目录中的翻译文件 7. 转换创建的 YAML 文件中的值 8. 在站点存储库上打开拉取请求 ================================================ FILE: docs/cn/README.md ================================================ # FrankenPHP: 适用于 PHP 的现代应用服务器

FrankenPHP

FrankenPHP 是建立在 [Caddy](https://caddyserver.com/) Web 服务器之上的现代 PHP 应用程序服务器。 FrankenPHP 凭借其令人惊叹的功能为你的 PHP 应用程序提供了超能力:[早期提示](early-hints.md)、[worker 模式](worker.md)、[实时功能](mercure.md)、自动 HTTPS、HTTP/2 和 HTTP/3 支持...... FrankenPHP 可与任何 PHP 应用程序一起使用,并且由于提供了与 worker 模式的集成,使你的 Symfony 和 Laravel 项目比以往任何时候都更快。 FrankenPHP 也可以用作独立的 Go 库,将 PHP 嵌入到任何使用 `net/http` 的应用程序中。 [**了解更多** _frankenphp.dev_](https://frankenphp.dev/cn/) 以及查看此演示文稿: Slides ## 开始 在 Windows 上,请使用 [WSL](https://learn.microsoft.com/windows/wsl/) 运行 FrankenPHP。 ### 安装脚本 你可以将以下命令复制到终端中,自动安装适用于你平台的版本: ```console curl https://frankenphp.dev/install.sh | sh ``` ### 独立二进制 我们为 Linux 和 macOS 提供用于开发的 FrankenPHP 静态二进制文件, 包含 [PHP 8.4](https://www.php.net/releases/8.4/zh.php) 以及大多数常用 PHP 扩展。 [下载 FrankenPHP](https://github.com/dunglas/frankenphp/releases) **安装扩展:** 常见扩展已内置,无法再安装更多扩展。 ### rpm 软件包 我们的维护者为所有使用 `dnf` 的系统提供 rpm 包。安装方式: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 可用 8.2-8.5 sudo dnf install frankenphp ``` **安装扩展:** `sudo dnf install php-zts-` 对于默认不可用的扩展,请使用 [PIE](https://github.com/php/pie): ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### deb 软件包 我们的维护者为所有使用 `apt` 的系统提供 deb 包。安装方式: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **安装扩展:** `sudo apt install php-zts-` 对于默认不可用的扩展,请使用 [PIE](https://github.com/php/pie): ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker 此外,还可以使用 [Docker 镜像](https://frankenphp.dev/docs/docker/): ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` 访问 `https://localhost`, 并享受吧! > [!TIP] > > 不要尝试使用 `https://127.0.0.1`。使用 `https://localhost` 并接受自签名证书。 > 使用 [`SERVER_NAME` 环境变量](config.md#environment-variables) 更改要使用的域。 ### Homebrew FrankenPHP 也作为 [Homebrew](https://brew.sh) 软件包提供,适用于 macOS 和 Linux 系统。 安装方法: ```console brew install dunglas/frankenphp/frankenphp ``` **安装扩展:** 使用 [PIE](https://github.com/php/pie)。 ### 用法 要提供当前目录的内容,请运行: ```console frankenphp php-server ``` 你还可以使用以下命令运行命令行脚本: ```console frankenphp php-cli /path/to/your/script.php ``` 对于 deb 和 rpm 软件包,还可以启动 systemd 服务: ```console sudo systemctl start frankenphp ``` ## 文档 - [Classic 模式](classic.md) - [worker 模式](worker.md) - [早期提示支持(103 HTTP status code)](early-hints.md) - [实时功能](mercure.md) - [高效地服务大型静态文件](x-sendfile.md) - [配置](config.md) - [用 Go 编写 PHP 扩展](extensions.md) - [Docker 镜像](docker.md) - [在生产环境中部署](production.md) - [性能优化](performance.md) - [创建独立、可自行执行的 PHP 应用程序](embed.md) - [创建静态二进制文件](static.md) - [从源代码编译](compile.md) - [Laravel 集成](laravel.md) - [已知问题](known-issues.md) - [演示应用程序 (Symfony) 和性能测试](https://github.com/dunglas/frankenphp-demo) - [Go 库文档](https://pkg.go.dev/github.com/dunglas/frankenphp) - [贡献和调试](https://frankenphp.dev/docs/contributing/) ## 示例和框架 - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/distribution/) - [Laravel](laravel.md) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/cn/classic.md ================================================ # 使用经典模式 在没有任何额外配置的情况下,FrankenPHP 以经典模式运行。在此模式下,FrankenPHP 的功能类似于传统的 PHP 服务器,直接提供 PHP 文件服务。这使其成为 PHP-FPM 或 Apache with mod_php 的无缝替代品。 与 Caddy 类似,FrankenPHP 接受无限数量的连接,并使用[固定数量的线程](config.md#caddyfile-配置)来为它们提供服务。接受和排队的连接数量仅受可用系统资源的限制。 PHP 线程池使用在启动时初始化的固定数量的线程运行,类似于 PHP-FPM 的静态模式。也可以让线程在[运行时自动扩展](performance.md#max_threads),类似于 PHP-FPM 的动态模式。 排队的连接将无限期等待,直到有 PHP 线程可以为它们提供服务。为了避免这种情况,你可以在 FrankenPHP 的全局配置中使用 max_wait_time [配置](config.md#caddyfile-配置)来限制请求可以等待空闲的 PHP 线程的时间,超时后将被拒绝。 此外,你还可以在 Caddy 中设置合理的[写超时](https://caddyserver.com/docs/caddyfile/options#timeouts)。 每个 Caddy 实例只会启动一个 FrankenPHP 线程池,该线程池将在所有 `php_server` 块之间共享。 ================================================ FILE: docs/cn/compile.md ================================================ # 从源代码编译 本文档解释了如何创建一个 FrankenPHP 构建,它将 PHP 加载为一个动态库。 这是推荐的方法。 或者,你也可以 [编译静态版本](static.md)。 ## 安装 PHP FrankenPHP 支持 PHP 8.2 及更高版本。 ### 使用 Homebrew (Linux 和 Mac) 安装与 FrankenPHP 兼容的 libphp 版本的最简单方法是使用 [Homebrew PHP](https://github.com/shivammathur/homebrew-php) 提供的 ZTS 包。 首先,如果尚未安装,请安装 [Homebrew](https://brew.sh)。 然后,安装 PHP 的 ZTS 变体、Brotli(可选,用于压缩支持)和 watcher(可选,用于文件更改检测): ```console brew install shivammathur/php/php-zts brotli watcher brew link --overwrite --force shivammathur/php/php-zts ``` ### 通过编译 PHP 或者,你可以按照以下步骤,使用 FrankenPHP 所需的选项从源代码编译 PHP。 首先,[获取 PHP 源代码](https://www.php.net/downloads.php) 并提取它们: ```console tar xf php-* cd php-*/ ``` 然后,运行适用于你平台的 `configure` 脚本。 以下 `./configure` 标志是必需的,但你可以添加其他标志,例如编译扩展或附加功能。 #### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` #### Mac 使用 [Homebrew](https://brew.sh/) 包管理器安装所需的和可选的依赖项: ```console brew install libiconv bison brotli re2c pkg-config watcher echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` 然后运行 `./configure` 脚本: ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` #### 编译 PHP 最后,编译并安装 PHP: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## 安装可选依赖项 某些 FrankenPHP 功能依赖于必须安装的可选系统依赖项。 或者,可以通过向 Go 编译器传递构建标签来禁用这些功能。 | 功能 | 依赖项 | 用于禁用的构建标签 | | --------------------- | --------------------------------------------------------------------- | ------------------ | | Brotli 压缩 | [Brotli](https://github.com/google/brotli) | nobrotli | | 文件更改时重启 worker | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | ## 编译 Go 应用 你现在可以构建最终的二进制文件。 ### 使用 xcaddy 推荐的方法是使用 [xcaddy](https://github.com/caddyserver/xcaddy) 来编译 FrankenPHP。 `xcaddy` 还允许轻松添加 [自定义 Caddy 模块](https://caddyserver.com/docs/modules/) 和 FrankenPHP 扩展: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # 在这里添加额外的 Caddy 模块和 FrankenPHP 扩展 ``` > [!TIP] > > 如果你的系统基于 musl libc(Alpine Linux 上默认使用)并搭配 Symfony 使用, > 你可能需要增加默认堆栈大小。 > 否则,你可能会收到如下错误 `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression` > > 请将 `XCADDY_GO_BUILD_FLAGS` 环境变量更改为如下类似的值 > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (根据你的应用需求更改堆栈大小)。 ### 不使用 xcaddy 或者,可以通过直接使用 `go` 命令来编译 FrankenPHP 而不使用 `xcaddy`: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/cn/config.md ================================================ # 配置 FrankenPHP、Caddy 以及 [Mercure](mercure.md) 和 [Vulcain](https://vulcain.rocks) 模块可以使用 [Caddy 支持的格式](https://caddyserver.com/docs/getting-started#your-first-config) 进行配置。 最常见的格式是 `Caddyfile`,它是一种简单、易读的文本格式。默认情况下,FrankenPHP 会在当前目录中查找 `Caddyfile`。你可以使用 `-c` 或 `--config` 选项指定自定义路径。 以下是用于服务 PHP 应用程序的最小 `Caddyfile` 示例: ```caddyfile # 响应的主机名 localhost # 可选:提供文件的目录,否则默认为当前目录 #root public/ php_server ``` 一个更高级的 `Caddyfile`,支持更多功能并提供方便的环境变量,可以在 [FrankenPHP 仓库中](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile)找到,并随 Docker 镜像提供。 PHP 本身可以[使用 `php.ini` 文件](https://www.php.net/manual/en/configuration.file.php)进行配置。 根据你的安装方法,FrankenPHP 和 PHP 解释器将在以下位置查找配置文件。 ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: 主配置文件 - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: 自动加载的附加配置文件 PHP: - `php.ini`: `/usr/local/etc/php/php.ini`(默认情况下不提供 `php.ini`) - 附加配置文件: `/usr/local/etc/php/conf.d/*.ini` - PHP 扩展: `/usr/local/lib/php/extensions/no-debug-zts-/` - 你应该复制 PHP 项目提供的官方模板: ```dockerfile FROM dunglas/frankenphp # 生产环境: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # 或开发环境: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## RPM 和 Debian 包 FrankenPHP: - `/etc/frankenphp/Caddyfile`: 主配置文件 - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: 自动加载的附加配置文件 PHP: - `php.ini`: `/etc/php-zts/php.ini`(默认情况下提供带有生产预设的 `php.ini` 文件) - 附加配置文件: `/etc/php-zts/conf.d/*.ini` ## 静态二进制文件 FrankenPHP: - 在当前工作目录: `Caddyfile` PHP: - `php.ini`: 执行 `frankenphp run` 或 `frankenphp php-server` 的目录,然后是 `/etc/frankenphp/php.ini` - 附加配置文件: `/etc/frankenphp/php.d/*.ini` - PHP 扩展: 无法加载,将它们打包在二进制文件本身中 - 复制 [PHP 源代码](https://github.com/php/php-src/) 中提供的 `php.ini-production` 或 `php.ini-development` 中的一个。 ## Caddyfile 配置 可以在站点块中使用 `php_server` 或 `php` [HTTP 指令](https://caddyserver.com/docs/caddyfile/concepts#directives) 来为你的 PHP 应用程序提供服务。 最小示例: ```caddyfile localhost { # 启用压缩(可选) encode zstd br gzip # 在当前目录中执行 PHP 文件并提供资源服务 php_server } ``` 你还可以使用 `frankenphp` [全局选项](https://caddyserver.com/docs/caddyfile/concepts#global-options) 显式配置 FrankenPHP: ```caddyfile { frankenphp { num_threads # 设置要启动的 PHP 线程数量。默认:可用 CPU 数量的 2 倍。 max_threads # 限制可以在运行时启动的额外 PHP 线程的数量。默认值:num_threads。可以设置为 'auto'。 max_wait_time # 设置请求在超时之前可以等待的最大时间,直到找到一个空闲的 PHP 线程。 默认:禁用。 max_idle_time # 设置一个自动扩展的线程在被停用之前可以空闲的最长时间。默认:5s。 php_ini # 设置一个 php.ini 指令。可以多次使用以设置多个指令。 worker { file # 设置工作脚本的路径。 num # 设置要启动的 PHP 线程数量,默认为可用 CPU 数量的 2 倍。 env # 设置一个额外的环境变量为给定的值。可以多次指定以设置多个环境变量。 watch # 设置要监视文件更改的路径。可以为多个路径多次指定。 name # 设置worker的名称,用于日志和指标。默认值:worker文件的绝对路径。 max_consecutive_failures # 设置在工人被视为不健康之前的最大连续失败次数,-1意味着工人将始终重新启动。默认值:6。 } } } # ... ``` 或者,您可以使用 `worker` 选项的一行简短形式: ```caddyfile { frankenphp { worker } } # ... ``` 如果您在同一服务器上服务多个应用程序,您还可以定义多个工作线程: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # 允许更好的缓存 worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` 使用 `php_server` 指令通常是您需要的, 但是如果你需要完全控制,你可以使用更低级的 `php` 指令。 `php` 指令将所有输入传递给 PHP,而不是先检查是否 是一个PHP文件。在[性能页面](performance.md#try_files)中了解更多关于它的信息。 使用 `php_server` 指令等同于以下配置: ```caddyfile route { # 为目录请求添加尾斜杠 @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # 如果请求的文件不存在,则尝试 index 文件 @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` `php_server` 和 `php` 指令有以下选项: ```caddyfile php_server [] { root # 将根文件夹设置为站点。默认值:`root` 指令。 split_path # 设置用于将 URI 分割成两部分的子字符串。第一个匹配的子字符串将用来将 "路径信息" 与路径分开。第一部分后缀为匹配的子字符串,并将被视为实际资源(CGI 脚本)名称。第二部分将被设置为脚本使用的 PATH_INFO。默认值:`.php`。 resolve_root_symlink false # 禁用通过评估符号链接(如果存在)将 `root` 目录解析为其实际值(默认启用)。 env # 设置一个额外的环境变量为给定的值。可以多次指定以设置多个环境变量。 file_server off # 禁用内置的 file_server 指令。 worker { # 为此服务器创建特定的worker。可以多次指定以创建多个workers。 file # 设置工作脚本的路径,可以相对于 php_server 根目录 num # 设置要启动的 PHP 线程数,默认为可用 CPU 数量的 2 倍 name # 为worker设置名称,用于日志和指标。默认值:worker文件的绝对路径。定义在 php_server 块中时,始终以 m# 开头。 watch # 设置要监视文件更改的路径。可以为多个路径多次指定。 env # 设置一个额外的环境变量为给定值。可以多次指定以设置多个环境变量。此工作进程的环境变量也从 php_server 父进程继承,但可以在此处覆盖。 match # 将worker匹配到路径模式。覆盖 try_files,并且只能在 php_server 指令中使用。 } worker # 也可以像在全局 frankenphp 块中那样使用简短形式。 } ``` ### 监控文件变化 由于 workers 只会启动您的应用程序一次并将其保留在内存中, 因此对您的 PHP 文件的任何更改不会立即反映出来。 Workers 可以通过 `watch` 指令在文件更改时重新启动。 这对开发环境很有用。 ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` 此功能通常与[热重载](hot-reload.md)结合使用。 如果没有指定 `watch` 目录,它将回退到 `./**/*.{env,php,twig,yaml,yml}`, 这将监视启动 FrankenPHP 进程的目录及其子目录中的所有 `.env`、`.php`、`.twig`、`.yaml` 和 `.yml` 文件。 你也可以通过 [shell 文件名模式](https://pkg.go.dev/path/filepath#Match) 指定一个或多个目录: ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # 监视 /path/to/app 所有子目录中的所有文件 watch /path/to/app/*.php # 监视位于/path/to/app中的以.php结尾的文件 watch /path/to/app/**/*.php # 监视 /path/to/app 及子目录中的 PHP 文件 watch /path/to/app/**/*.{php,twig} # 在/path/to/app及其子目录中监视PHP和Twig文件 } } } ``` - `**` 模式表示递归监视 - 目录也可以是相对的(相对于FrankenPHP进程启动的位置) - 如果您定义了多个workers,当文件发生更改时,将重新启动所有workers。 - 小心查看在运行时创建的文件(如日志),因为它们可能导致不必要的工作进程重启。 文件监视器基于[e-dant/watcher](https://github.com/e-dant/watcher)。 ## 将 worker 匹配到一条路径 在传统的PHP应用程序中,脚本总是放在公共目录中。 这对于工作脚本也是如此,这些脚本被视为任何其他PHP脚本。 如果您想将工作脚本放在公共目录外,可以通过 `match` 指令来实现。 `match` 指令是 `try_files` 的一种优化替代方案,仅在 `php_server` 和 `php` 内部可用。 以下示例将始终在公共目录中提供文件(如果存在),否则会将请求转发给与路径模式匹配的 worker。 ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # 文件可以在公共路径之外 match /api/* # 所有以 /api/ 开头的请求将由此 worker 处理 } } } } ``` ## 环境变量 可以使用以下环境变量在不修改 `Caddyfile` 的情况下注入 Caddy 指令: - `SERVER_NAME`: 更改[监听的地址](https://caddyserver.com/docs/caddyfile/concepts#addresses),提供的宿主名也将用于生成的TLS证书。 - `SERVER_ROOT`: 更改网站的根目录,默认为 `public/` - `CADDY_GLOBAL_OPTIONS`: 注入[全局选项](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG`: 在 `frankenphp` 指令下注入配置 至于 FPM 和 CLI SAPIs,环境变量默认在 `$_SERVER` 超全局中暴露。 `variables_order` PHP 指令中 `S` 的值始终等于 `ES`,无论 `E` 在该指令中的其他位置如何。 ## PHP 配置 为了加载[附加的 PHP 配置文件](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan),可以使用 `PHP_INI_SCAN_DIR` 环境变量。设置后,PHP 将加载给定目录中所有带有 `.ini` 扩展名的文件。 您还可以通过在 `Caddyfile` 中使用 `php_ini` 指令来更改 PHP 配置: ```caddyfile { frankenphp { php_ini memory_limit 256M # 或者 php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### 禁用 HTTPS 默认情况下,FrankenPHP 会自动为所有主机名(包括 `localhost`)启用 HTTPS。 如果你想禁用 HTTPS(例如在开发环境中),你可以将 `SERVER_NAME` 环境变量设置为 `http://` 或 `:80`: 或者,你可以使用 [Caddy 文档](https://caddyserver.com/docs/automatic-https#activation) 中描述的所有其他方法。 如果你想将 HTTPS 与 `127.0.0.1` IP 地址而不是 `localhost` 主机名一起使用,请阅读[已知问题](known-issues.md#using-https127001-with-docker)部分。 ### 全双工 (HTTP/1) 在使用 HTTP/1.x 时,可能希望启用全双工模式,以便在整个请求体被读取之前允许写入响应。(例如:[Mercure](mercure.md)、WebSocket、Server-Sent Events 等) 这是一个可选配置,需要添加到 `Caddyfile` 中的全局选项中: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > 启用此选项可能导致不支持全双工的旧 HTTP/1.x 客户端死锁。 > 这也可以通过 `CADDY_GLOBAL_OPTIONS` 环境变量配置来实现: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` 您可以在[Caddy文档](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex)中找到有关此设置的更多信息。 ## 启用调试模式 使用Docker镜像时,将`CADDY_GLOBAL_OPTIONS`环境变量设置为`debug`以启用调试模式: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Shell 补全 FrankenPHP 提供对 Bash、Zsh、Fish 和 PowerShell 的内置 shell 补全支持。这为所有命令(包括 `php-server`、`php-cli` 和 `extension-init` 等自定义命令)及其标志启用了自动补全。 ### Bash 要在当前 shell 会话中加载补全: ```console source <(frankenphp completion bash) ``` 要为每个新会话加载补全,运行: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh 如果您的环境中尚未启用 shell 补全,您将需要启用它。您可以执行以下命令一次: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` 要为每个会话加载补全,请执行一次: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` 您需要启动一个新的 shell 会话才能使此设置生效。 ### Fish 要在当前 shell 会话中加载补全: ```console frankenphp completion fish | source ``` 要为每个新会话加载补全,请执行一次: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell 要在当前 shell 会话中加载补全: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` 要为每个新会话加载补全,请执行一次: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` 您需要启动一个新的 shell 会话才能使此设置生效。 您需要启动一个新的 shell 会话才能使此设置生效。 ================================================ FILE: docs/cn/docker.md ================================================ # 构建自定义 Docker 镜像 [FrankenPHP Docker 镜像](https://hub.docker.com/r/dunglas/frankenphp) 基于 [官方 PHP 镜像](https://hub.docker.com/_/php/)。 提供适用于流行架构的 Debian 和 Alpine Linux 变体。 推荐使用 Debian 变体。 提供 PHP 8.2、8.3、8.4 和 8.5 的变体。 标签遵循此模式:`dunglas/frankenphp:-php-` - `` 和 `` 分别是 FrankenPHP 和 PHP 的版本号,范围从主版本(例如 `1`)、次版本(例如 `1.2`)到补丁版本(例如 `1.2.3`)。 - `` 要么是 `trixie`(用于 Debian Trixie),`bookworm`(用于 Debian Bookworm),要么是 `alpine`(用于 Alpine 的最新稳定版本)。 [浏览标签](https://hub.docker.com/r/dunglas/frankenphp/tags)。 ## 如何使用镜像 在项目中创建 `Dockerfile`: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` 然后运行以下命令以构建并运行 Docker 镜像: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## 如何调整配置 为了方便,镜像中提供了一个包含有用环境变量的[默认 `Caddyfile`](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile)。 ## 如何安装更多 PHP 扩展 [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) 脚本在基础镜像中提供。 添加额外的 PHP 扩展很简单: ```dockerfile FROM dunglas/frankenphp # 在此处添加其他扩展: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## 如何安装更多 Caddy 模块 FrankenPHP 建立在 Caddy 之上,所有 [Caddy 模块](https://caddyserver.com/docs/modules/) 都可以与 FrankenPHP 一起使用。 安装自定义 Caddy 模块的最简单方法是使用 [xcaddy](https://github.com/caddyserver/xcaddy): ```dockerfile FROM dunglas/frankenphp:builder AS builder # 在构建器镜像中复制 xcaddy COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # 必须启用 CGO 才能构建 FrankenPHP RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure 和 Vulcain 包含在官方版本中,如果不需要你可以删除它们 --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # 在此处添加额外的 Caddy 模块 FROM dunglas/frankenphp AS runner # 将官方二进制文件替换为包含自定义模块的二进制文件 COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` FrankenPHP 提供的[构建器镜像](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder)适用于所有版本的 FrankenPHP 和 PHP,同时支持 Debian 和 Alpine。 > [!TIP] > > 如果你正在使用 Alpine Linux 和 Symfony,你可能需要[增加默认堆栈大小](compile.md#using-xcaddy)。 ## 默认启用 worker 模式 设置 `FRANKENPHP_CONFIG` 环境变量以使用 worker 脚本启动 FrankenPHP: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## 在开发中使用卷 要使用 FrankenPHP 轻松开发,请从包含应用程序源代码的主机挂载目录作为 Docker 容器中的卷: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > `--tty` 选项允许使用易读的日志,而不是 JSON 日志。 使用 Docker Compose: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # 如果要使用自定义 Dockerfile,请取消注释以下行 #build: . # 如果要在生产环境中运行,请取消注释以下行 # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # 在生产环境中注释以下行,它允许在开发环境中使用易读日志 tty: true # Caddy 证书和配置所需的数据卷 volumes: caddy_data: caddy_config: ``` ## 以非 root 用户身份运行 FrankenPHP 可以在 Docker 中以非 root 用户身份运行。 下面是一个示例 `Dockerfile`: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # 在基于 Alpine 的发行版使用 "adduser -D ${USER}" useradd ${USER}; \ # 添加绑定到 80 和 443 端口的额外能力 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # 赋予 /config/caddy 和 /data/caddy 目录的写入权限 chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### 在不使用能力的情况下运行 即使在无根运行时,FrankenPHP 也需要 `CAP_NET_BIND_SERVICE` 能力来将 Web 服务器绑定到特权端口(80 和 443)。 如果你在非特权端口(1024 及以上)上公开 FrankenPHP,则可以以非 root 用户身份运行 Web 服务器,并且不需要任何能力: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # 在基于 Alpine 的发行版使用 "adduser -D ${USER}" useradd ${USER}; \ # 移除默认能力 setcap -r /usr/local/bin/frankenphp; \ # 赋予 /config/caddy 和 /data/caddy 目录的写入权限 chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` 接下来,设置 `SERVER_NAME` 环境变量以使用非特权端口。 示例:`:8000` ## 更新 Docker 镜像会在以下情况下构建: - 发布新的版本后 - 每日 UTC 时间上午 4 点,如果新的官方 PHP 镜像可用 ## 强化镜像 为了进一步减少 FrankenPHP Docker 镜像的攻击面和大小,还可以基于 [Google distroless](https://github.com/GoogleContainerTools/distroless) 或 [Docker hardened](https://www.docker.com/products/hardened-images) 镜像构建它们。 > [!WARNING] > 这些最小化的基础镜像不包含 shell 或包管理器,这使得调试更加困难。因此,仅在安全性优先级很高的情况下,才推荐将其用于生产环境。 当添加额外的 PHP 扩展时,你需要一个中间构建阶段: ```dockerfile FROM dunglas/frankenphp AS builder # 在此处添加额外的 PHP 扩展 RUN install-php-extensions pdo_mysql pdo_pgsql #... # 将 frankenphp 和所有已安装扩展的共享库复制到临时位置 # 你也可以通过分析 frankenphp 二进制文件和每个扩展 .so 文件的 ldd 输出手动执行此步骤 RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Distroless debian 基础镜像,确保它与基础镜像使用相同的 debian 版本 FROM gcr.io/distroless/base-debian13 # Docker hardened 镜像替代方案 # FROM dhi.io/debian:13 # 你的应用程序和 Caddyfile 要复制到容器中的位置 ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # 将你的应用程序复制到 /app # 为了进一步强化,请确保只有可写路径由非 root 用户拥有 COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # 复制 frankenphp 和必要的库 COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # 复制 php.ini 配置文件 COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Caddy 数据目录——即使在只读根文件系统上,也必须对非 root 用户可写 ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # 运行 frankenphp 并使用提供的 Caddyfile 的入口点 ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## 开发版本 开发版本可在 [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev) Docker 仓库中获取。 每次将新的提交推送到 GitHub 仓库的主分支时,都会触发一次新的构建。 `latest*` 标签指向 `main` 分支的 HEAD。形式为 `sha-` 的标签也可用。 ================================================ FILE: docs/cn/early-hints.md ================================================ # 早期提示 FrankenPHP 原生支持 [103 Early Hints 状态码](https://developer.chrome.com/blog/early-hints/)。 使用早期提示可以将网页的加载时间缩短 30%。 ```php ; rel=preload; as=style'); headers_send(103); // 慢速算法和 SQL 查询 echo <<<'HTML' Hello FrankenPHP HTML; ``` 早期提示由普通模式和 [worker](worker.md) 模式支持。 ================================================ FILE: docs/cn/embed.md ================================================ # PHP 应用程序作为独立二进制文件 FrankenPHP 能够将 PHP 应用程序的源代码和资源文件嵌入到静态的、独立的二进制文件中。 由于这个特性,PHP 应用程序可以作为独立的二进制文件分发,包括应用程序本身、PHP 解释器和生产级 Web 服务器 Caddy。 了解有关此功能的更多信息 [Kévin 在 SymfonyCon 上的演讲](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/)。 有关嵌入 Laravel 应用程序,请[阅读此特定文档条目](laravel.md#laravel-apps-as-standalone-binaries)。 ## 准备你的应用 在创建独立二进制文件之前,请确保应用已准备好进行打包。 例如,你可能希望: - 给应用安装生产环境的依赖 - 导出 autoloader - 如果可能,为应用启用生产模式 - 丢弃不需要的文件,例如 `.git` 或测试文件,以减小最终二进制文件的大小 例如,对于 Symfony 应用程序,你可以使用以下命令: ```console # 导出项目以避免 .git/ 等目录 mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # 设置适当的环境变量 echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # 删除测试和其他不需要的文件以节省空间 # 或者,将这些文件添加到您的 .gitattributes 文件中,并设置 export-ignore 属性 rm -Rf tests/ # 安装依赖项 composer install --ignore-platform-reqs --no-dev -a # 优化 .env composer dump-env prod ``` ### 自定义配置 要自定义[配置](config.md),您可以放置一个 `Caddyfile` 以及一个 `php.ini` 文件 在应用程序的主目录中嵌入(在之前的示例中是`$TMPDIR/my-prepared-app`)。 ## 创建 Linux 二进制文件 创建 Linux 二进制文件的最简单方法是使用我们提供的基于 Docker 的构建器。 1. 在准备好的应用的存储库中创建一个名为 `static-build.Dockerfile` 的文件。 ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # 如果你打算在 glibc 系统上运行该二进制文件,请使用 static-builder-gnu # 复制应用代码 WORKDIR /go/src/app/dist/app COPY . . # 构建静态二进制文件 WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > 某些 `.dockerignore` 文件(例如默认的 [Symfony Docker `.dockerignore`](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > 会忽略 `vendor/` 文件夹和 `.env` 文件。在构建之前,请务必调整或删除 `.dockerignore` 文件。 2. 构建: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. 提取二进制文件 ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` 生成的二进制文件是当前目录中名为 `my-app` 的文件。 ## 为其他操作系统创建二进制文件 如果你不想使用 Docker,或者想要构建 macOS 二进制文件,你可以使用我们提供的 shell 脚本: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` 在 `dist/` 目录中生成的二进制文件名称为 `frankenphp--`。 ## 使用二进制文件 就是这样!`my-app` 文件(或其他操作系统上的 `dist/frankenphp--`)包含你的独立应用程序! 若要启动 Web 应用,请执行: ```console ./my-app php-server ``` 如果你的应用包含 [worker 脚本](worker.md),请使用如下命令启动 worker: ```console ./my-app php-server --worker public/index.php ``` 要启用 HTTPS(自动创建 Let's Encrypt 证书)、HTTP/2 和 HTTP/3,请指定要使用的域名: ```console ./my-app php-server --domain localhost ``` 你还可以运行二进制文件中嵌入的 PHP CLI 脚本: ```console ./my-app php-cli bin/console ``` ## PHP Extensions 默认情况下,脚本将构建您项目的 `composer.json` 文件中所需的扩展(如果有的话)。 如果 `composer.json` 文件不存在,将构建默认扩展,如 [静态构建条目](static.md) 中所述。 要自定义扩展,请使用 `PHP_EXTENSIONS` 环境变量。 ## 自定义构建 [阅读静态构建文档](static.md) 查看如何自定义二进制文件(扩展、PHP 版本等)。 ## 分发二进制文件 在Linux上,创建的二进制文件使用[UPX](https://upx.github.io)进行压缩。 在Mac上,您可以在发送文件之前压缩它以减小文件大小。 我们推荐使用 `xz`。 ================================================ FILE: docs/cn/extension-workers.md ================================================ # 扩展 Worker 扩展 Worker 使您的 [FrankenPHP 扩展](https://frankenphp.dev/docs/extensions/) 能够管理专用的 PHP 线程池,用于执行后台任务、处理异步事件或实现自定义协议。适用于队列系统、事件监听器、调度器等。 ## 注册 Worker ### 静态注册 如果您的 worker 不需要用户配置(固定的脚本路径、固定的线程数),您可以直接在 `init()` 函数中注册 worker。 ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // 与 worker 池通信的全局句柄 var worker frankenphp.Workers func init() { // 模块加载时注册 worker。 worker = caddy.RegisterWorkers( "my-internal-worker", // 唯一名称 "worker.php", // 脚本路径(相对于执行目录或绝对路径) 2, // 固定线程数 // 可选的生命周期钩子 frankenphp.WithWorkerOnServerStartup(func() { // 全局设置逻辑... }), ) } ``` ### 在 Caddy 模块中(用户可配置) 如果您计划共享您的扩展(例如通用的队列或事件监听器),您应该将其封装在一个 Caddy 模块中。这允许用户通过 `Caddyfile` 配置脚本路径和线程数。这需要实现 `caddy.Provisioner` 接口并解析 Caddyfile ([查看示例](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go))。 ### 在纯 Go 应用程序中(嵌入式) 如果您 [在没有 Caddy 的标准 Go 应用程序中嵌入 FrankenPHP](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP),您可以在初始化选项时使用 `frankenphp.WithExtensionWorkers` 注册扩展 worker。 ## 与 Worker 交互 一旦 worker 池激活,您就可以向其分派任务。这可以在 [导出到 PHP 的原生函数](https://frankenphp.dev/docs/extensions/#writing-the-extension) 中完成,也可以从任何 Go 逻辑中完成,例如 cron 调度器、事件监听器 (MQTT、Kafka) 或任何其他 goroutine。 ### 无头模式:`SendMessage` 使用 `SendMessage` 将原始数据直接传递给您的 worker 脚本。这非常适合队列或简单命令。 #### 示例:一个异步队列扩展 ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. 确保 worker 已准备就绪 if worker == nil { return false } // 2. 分派给后台 worker _, err := worker.SendMessage( context.Background(), // 标准 Go 上下文 unsafe.Pointer(data), // 要传递给 worker 的数据 nil, // 可选的 http.ResponseWriter ) return err == nil } ``` ### HTTP 模拟:`SendRequest` 如果您的扩展需要调用一个期望标准 Web 环境(填充 `$_SERVER`、`$_GET` 等)的 PHP 脚本,请使用 `SendRequest`。 ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. 准备请求和记录器 url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. 分派给 worker if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. 返回捕获的响应 return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Worker 脚本 PHP worker 脚本在一个循环中运行,可以处理原始消息和 HTTP 请求。 ```php [!TIP] > 如果你想了解如何从头开始在 Go 中编写扩展,可以阅读下面的手动实现部分,该部分演示了如何在不使用生成器的情况下在 Go 中编写 PHP 扩展。 请记住,此工具**不是功能齐全的扩展生成器**。它旨在帮助你在 Go 中编写简单的扩展,但它不提供 PHP 扩展的最高级功能。如果你需要编写更**复杂和优化**的扩展,你可能需要编写一些 C 代码或直接使用 CGO。 ### 先决条件 正如下面的手动实现部分所涵盖的,你需要[获取 PHP 源代码](https://www.php.net/downloads.php)并创建一个新的 Go 模块。 #### 创建新模块并获取 PHP 源代码 在 Go 中编写 PHP 扩展的第一步是创建一个新的 Go 模块。你可以使用以下命令: ```console go mod init github.com/my-account/my-module ``` 第二步是为后续步骤[获取 PHP 源代码](https://www.php.net/downloads.php)。获取后,将它们解压到你选择的目录中,不要放在你的 Go 模块内: ```console tar xf php-* ``` ### 编写扩展 现在一切都设置好了,可以在 Go 中编写你的原生函数。创建一个名为 `stringext.go` 的新文件。我们的第一个函数将接受一个字符串作为参数,重复次数,一个布尔值来指示是否反转字符串,并返回结果字符串。这应该看起来像这样: ```go import ( "C" "github.com/dunglas/frankenphp" "strings" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` 这里有两个重要的事情要注意: - 指令注释 `//export_php:function` 定义了 PHP 中的函数签名。这是生成器知道如何使用正确的参数和返回类型生成 PHP 函数的方式; - 函数必须返回 `unsafe.Pointer`。FrankenPHP 提供了一个 API 来帮助你在 C 和 Go 之间进行类型转换。 虽然第一点不言自明,但第二点可能更难理解。让我们在下一节中深入了解类型转换。 ### 类型转换 虽然一些变量类型在 C/PHP 和 Go 之间具有相同的内存表示,但某些类型需要更多逻辑才能直接使用。这可能是编写扩展时最困难的部分,因为它需要了解 Zend 引擎的内部结构以及变量在 PHP 中的内部存储方式。此表总结了你需要知道的内容: | PHP 类型 | Go 类型 | 直接转换 | C 到 Go 助手 | Go 到 C 助手 | 类方法支持 | | ------------------ | ------------------- | -------- | --------------------- | ---------------------- | ---------- | | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | frankenphp.GoString() | frankenphp.PHPString() | ✅ | | `array` | `*frankenphp.Array` | ❌ | frankenphp.GoArray() | frankenphp.PHPArray() | ✅ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `object` | `struct` | ❌ | _尚未实现_ | _尚未实现_ | ❌ | > [!NOTE] > 此表尚不详尽,将随着 FrankenPHP 类型 API 变得更加完整而完善。 > > 特别是对于类方法,目前支持原始类型和数组。对象尚不能用作方法参数或返回类型。 如果你参考上一节的代码片段,你可以看到助手用于转换第一个参数和返回值。我们的 `repeat_this()` 函数的第二和第三个参数不需要转换,因为底层类型的内存表示对于 C 和 Go 都是相同的。 #### 处理数组 FrankenPHP 通过 `frankenphp.Array` 类型为 PHP 数组提供原生支持。此类型表示 PHP 索引数组(列表)和关联数组(哈希映射),具有有序的键值对。 **在 Go 中创建和操作数组:** ```go //export_php:function process_data(array $input): array func process_data(arr *C.zval) unsafe.Pointer { // 将 PHP 数组转换为 Go goArray := frankenphp.GoArray(unsafe.Pointer(arr)) result := &frankenphp.Array{} result.SetInt(0, "first") result.SetInt(1, "second") result.Append("third") // 自动分配下一个整数键 result.SetString("name", "John") result.SetString("age", int64(30)) for i := uint32(0); i < goArray.Len(); i++ { key, value := goArray.At(i) if key.Type == frankenphp.PHPStringKey { result.SetString("processed_"+key.Str, value) } else { result.SetInt(key.Int+100, value) } } // 转换回 PHP 数组 return frankenphp.PHPArray(result) } ``` **`frankenphp.Array` 的关键特性:** - **有序键值对** - 像 PHP 数组一样维护插入顺序 - **混合键类型** - 在同一数组中支持整数和字符串键 - **类型安全** - `PHPKey` 类型确保正确的键处理 - **自动列表检测** - 转换为 PHP 时,自动检测数组应该是打包列表还是哈希映射 - **不支持对象** - 目前,只有标量类型和数组可以用作值。提供对象将导致 PHP 数组中的 `null` 值。 **可用方法:** - `SetInt(key int64, value any)` - 使用整数键设置值 - `SetString(key string, value any)` - 使用字符串键设置值 - `Append(value any)` - 使用下一个可用整数键添加值 - `Len() uint32` - 获取元素数量 - `At(index uint32) (PHPKey, any)` - 获取索引处的键值对 - `frankenphp.PHPArray(arr *frankenphp.Array) unsafe.Pointer` - 转换为 PHP 数组 ### 声明原生 PHP 类 生成器支持将 Go 结构体声明为**不透明类**,可用于创建 PHP 对象。你可以使用 `//export_php:class` 指令注释来定义 PHP 类。例如: ```go //export_php:class User type UserStruct struct { Name string Age int } ``` #### 什么是不透明类? **不透明类**是内部结构(属性)对 PHP 代码隐藏的类。这意味着: - **无直接属性访问**:你不能直接从 PHP 读取或写入属性(`$user->name` 不起作用) - **仅方法接口** - 所有交互必须通过你定义的方法进行 - **更好的封装** - 内部数据结构完全由 Go 代码控制 - **类型安全** - 没有 PHP 代码使用错误类型破坏内部状态的风险 - **更清晰的 API** - 强制设计适当的公共接口 这种方法提供了更好的封装,并防止 PHP 代码意外破坏 Go 对象的内部状态。与对象的所有交互都必须通过你明确定义的方法进行。 #### 为类添加方法 由于属性不能直接访问,你**必须定义方法**来与不透明类交互。使用 `//export_php:method` 指令来定义行为: ```go //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### 可空参数 生成器支持在 PHP 签名中使用 `?` 前缀的可空参数。当参数可空时,它在你的 Go 函数中变成指针,允许你检查值在 PHP 中是否为 `null`: ```go //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // 检查是否提供了 name(不为 null) if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // 检查是否提供了 age(不为 null) if age != nil { us.Age = int(*age) } // 检查是否提供了 active(不为 null) if active != nil { us.Active = *active } } ``` **关于可空参数的要点:** - **可空原始类型**(`?int`、`?float`、`?bool`)在 Go 中变成指针(`*int64`、`*float64`、`*bool`) - **可空字符串**(`?string`)仍然是 `*C.zend_string`,但可以是 `nil` - **在解引用指针值之前检查 `nil`** - **PHP `null` 变成 Go `nil`** - 当 PHP 传递 `null` 时,你的 Go 函数接收 `nil` 指针 > [!WARNING] > 目前,类方法有以下限制。**不支持对象**作为参数类型或返回类型。**完全支持数组**作为参数和返回类型。支持的类型:`string`、`int`、`float`、`bool`、`array` 和 `void`(用于返回类型)。**完全支持可空参数类型**,适用于所有标量类型(`?string`、`?int`、`?float`、`?bool`)。 生成扩展后,你将被允许在 PHP 中使用类及其方法。请注意,你**不能直接访问属性**: ```php setAge(25); echo $user->getName(); // 输出:(空,默认值) echo $user->getAge(); // 输出:25 $user->setNamePrefix("Employee"); // ✅ 这也可以工作 - 可空参数 $user->updateInfo("John", 30, true); // 提供所有参数 $user->updateInfo("Jane", null, false); // Age 为 null $user->updateInfo(null, 25, null); // Name 和 active 为 null // ❌ 这不会工作 - 直接属性访问 // echo $user->name; // 错误:无法访问私有属性 // $user->age = 30; // 错误:无法访问私有属性 ``` 这种设计确保你的 Go 代码完全控制如何访问和修改对象的状态,提供更好的封装和类型安全。 ### 声明常量 生成器支持使用两个指令将 Go 常量导出到 PHP:`//export_php:const` 用于全局常量,`//export_php:classconst` 用于类常量。这允许你在 Go 和 PHP 代码之间共享配置值、状态代码和其他常量。 #### 全局常量 使用 `//export_php:const` 指令创建全局 PHP 常量: ```go //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const STATUS_OK = iota //export_php:const const STATUS_ERROR = iota ``` #### 类常量 使用 `//export_php:classconst ClassName` 指令创建属于特定 PHP 类的常量: ```go //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const STATE_PENDING = iota //export_php:classconst Order const STATE_PROCESSING = iota //export_php:classconst Order const STATE_COMPLETED = iota ``` 类常量在 PHP 中使用类名作用域访问: ```php getName(); // "John Doe" echo My\Extension\STATUS_ACTIVE; // 1 ``` #### 重要说明 - 每个文件只允许**一个**命名空间指令。如果找到多个命名空间指令,生成器将返回错误。 - 命名空间适用于文件中的**所有**导出符号:函数、类、方法和常量。 - 命名空间名称遵循 PHP 命名空间约定,使用反斜杠(`\`)作为分隔符。 - 如果没有声明命名空间,符号将照常导出到全局命名空间。 ### 生成扩展 这就是魔法发生的地方,现在可以生成你的扩展。你可以使用以下命令运行生成器: ```console GEN_STUB_SCRIPT=php-src/build/gen_stub.php frankenphp extension-init my_extension.go ``` > [!NOTE] > 不要忘记将 `GEN_STUB_SCRIPT` 环境变量设置为你之前下载的 PHP 源代码中 `gen_stub.php` 文件的路径。这是在手动实现部分中提到的同一个 `gen_stub.php` 脚本。 如果一切顺利,应该创建了一个名为 `build` 的新目录。此目录包含扩展的生成文件,包括带有生成的 PHP 函数存根的 `my_extension.go` 文件。 ### 将生成的扩展集成到 FrankenPHP 中 我们的扩展现在已准备好编译并集成到 FrankenPHP 中。为此,请参阅 FrankenPHP [编译文档](compile.md)以了解如何编译 FrankenPHP。使用 `--with` 标志添加模块,指向你的模块路径: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module/build ``` 请注意,你指向在生成步骤中创建的 `/build` 子目录。但是,这不是强制性的:你也可以将生成的文件复制到你的模块目录并直接指向它。 ### 测试你的生成扩展 你可以创建一个 PHP 文件来测试你创建的函数和类。例如,创建一个包含以下内容的 `index.php` 文件: ```php process('Hello World', StringProcessor::MODE_LOWERCASE); // "hello world" echo $processor->process('Hello World', StringProcessor::MODE_UPPERCASE); // "HELLO WORLD" ``` 一旦你按照上一节所示将扩展集成到 FrankenPHP 中,你就可以使用 `./frankenphp php-server` 运行此测试文件,你应该看到你的扩展正在工作。 ## 手动实现 如果你想了解扩展的工作原理或需要完全控制你的扩展,你可以手动编写它们。这种方法给你完全的控制,但需要更多的样板代码。 ### 基本函数 我们将看到如何在 Go 中编写一个简单的 PHP 扩展,定义一个新的原生函数。此函数将从 PHP 调用,并将触发一个在 Caddy 日志中记录消息的协程。此函数不接受任何参数并且不返回任何内容。 #### 定义 Go 函数 在你的模块中,你需要定义一个新的原生函数,该函数将从 PHP 调用。为此,创建一个你想要的名称的文件,例如 `extension.go`,并添加以下代码: ```go package ext_go //#include "extension.h" import "C" import ( "unsafe" "github.com/caddyserver/caddy/v2" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { caddy.Log().Info("Hello from a goroutine!") }() } ``` `frankenphp.RegisterExtension()` 函数通过处理内部 PHP 注册逻辑简化了扩展注册过程。`go_print_something` 函数使用 `//export` 指令表示它将在我们将编写的 C 代码中可访问,这要归功于 CGO。 在此示例中,我们的新函数将触发一个在 Caddy 日志中记录消息的协程。 #### 定义 PHP 函数 为了允许 PHP 调用我们的函数,我们需要定义相应的 PHP 函数。为此,我们将创建一个存根文件,例如 `extension.stub.php`,其中包含以下代码: ```php extern zend_module_entry ext_module_entry; #endif ``` 接下来,创建一个名为 `extension.c` 的文件,该文件将执行以下步骤: - 包含 PHP 头文件; - 声明我们的新原生 PHP 函数 `go_print()`; - 声明扩展元数据。 让我们首先包含所需的头文件: ```c #include #include "extension.h" #include "extension_arginfo.h" // 包含 Go 导出的符号 #include "_cgo_export.h" ``` 然后我们将 PHP 函数定义为原生语言函数: ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` 在这种情况下,我们的函数不接受参数并且不返回任何内容。它只是调用我们之前定义的 Go 函数,使用 `//export` 指令导出。 最后,我们在 `zend_module_entry` 结构中定义扩展的元数据,例如其名称、版本和属性。这些信息对于 PHP 识别和加载我们的扩展是必需的。请注意,`ext_functions` 是指向我们定义的 PHP 函数的指针数组,它由 `gen_stub.php` 脚本在 `extension_arginfo.h` 文件中自动生成。 扩展注册由我们在 Go 代码中调用的 FrankenPHP 的 `RegisterExtension()` 函数自动处理。 ### 高级用法 现在我们知道了如何在 Go 中创建基本的 PHP 扩展,让我们复杂化我们的示例。我们现在将创建一个 PHP 函数,该函数接受一个字符串作为参数并返回其大写版本。 #### 定义 PHP 函数存根 为了定义新的 PHP 函数,我们将修改我们的 `extension.stub.php` 文件以包含新的函数签名: ```php [!TIP] > 不要忽视函数的文档!你可能会与其他开发人员共享扩展存根,以记录如何使用你的扩展以及哪些功能可用。 通过使用 `gen_stub.php` 脚本重新生成存根文件,`extension_arginfo.h` 文件应该如下所示: ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` 我们可以看到 `go_upper` 函数定义了一个 `string` 类型的参数和一个 `string` 的返回类型。 #### Go 和 PHP/C 之间的类型转换 你的 Go 函数不能直接接受 PHP 字符串作为参数。你需要将其转换为 Go 字符串。幸运的是,FrankenPHP 提供了助手函数来处理 PHP 字符串和 Go 字符串之间的转换,类似于我们在生成器方法中看到的。 头文件保持简单: ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` 我们现在可以在我们的 `extension.c` 文件中编写 Go 和 C 之间的桥梁。我们将 PHP 字符串直接传递给我们的 Go 函数: ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` 你可以在 [PHP 内部手册](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters) 的专门页面中了解更多关于 `ZEND_PARSE_PARAMETERS_START` 和参数解析的信息。在这里,我们告诉 PHP 我们的函数接受一个 `string` 类型的强制参数作为 `zend_string`。然后我们将此字符串直接传递给我们的 Go 函数,并使用 `RETVAL_STR` 返回结果。 只剩下一件事要做:在 Go 中实现 `go_upper` 函数。 #### 实现 Go 函数 我们的 Go 函数将接受 `*C.zend_string` 作为参数,使用 FrankenPHP 的助手函数将其转换为 Go 字符串,处理它,并将结果作为新的 `*C.zend_string` 返回。助手函数为我们处理所有内存管理和转换复杂性。 ```go import "strings" //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` 这种方法比手动内存管理更清洁、更安全。FrankenPHP 的助手函数自动处理 PHP 的 `zend_string` 格式和 Go 字符串之间的转换。`PHPString()` 中的 `false` 参数表示我们想要创建一个新的非持久字符串(在请求结束时释放)。 > [!TIP] > 在此示例中,我们不执行任何错误处理,但你应该始终检查指针不是 `nil` 并且数据在 Go 函数中使用之前是有效的。 ### 将扩展集成到 FrankenPHP 中 我们的扩展现在已准备好编译并集成到 FrankenPHP 中。为此,请参阅 FrankenPHP [编译文档](compile.md)以了解如何编译 FrankenPHP。使用 `--with` 标志添加模块,指向你的模块路径: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module ``` 就是这样!你的扩展现在集成到 FrankenPHP 中,可以在你的 PHP 代码中使用。 ### 测试你的扩展 将扩展集成到 FrankenPHP 后,你可以为你实现的函数创建一个包含示例的 `index.php` 文件: ```php [!WARNING] > > 此功能仅适用于**开发环境**。 > 请勿在生产环境中启用 `hot_reload`,因为此功能不安全(会暴露敏感的内部细节)并且会降低应用程序的速度。 > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` 默认情况下,FrankenPHP 会监控当前工作目录中匹配此全局模式的所有文件:`./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` 可以通过全局语法显式设置要监控的文件: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` 使用 `hot_reload` 的长格式来指定要使用的 Mercure 主题以及要监控的目录或文件: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## 客户端集成 尽管服务器检测到更改,但浏览器需要订阅这些事件才能更新页面。 FrankenPHP 通过 `$_SERVER['FRANKENPHP_HOT_RELOAD']` 环境变量公开用于订阅文件更改的 Mercure Hub URL。 还提供了一个方便的 JavaScript 库 [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload) 来处理客户端逻辑。 要使用它,请将以下内容添加到您的主布局中: ```php FrankenPHP Hot Reload ``` 该库将自动订阅 Mercure hub,在检测到文件更改时在后台获取当前 URL,并修改 DOM。 它作为 [npm](https://www.npmjs.com/package/frankenphp-hot-reload) 包和在 [GitHub](https://github.com/dunglas/frankenphp-hot-reload) 上提供。 或者,您可以通过使用 `EventSource` 原生 JavaScript 类直接订阅 Mercure hub 来实现自己的客户端逻辑。 ### 保留现有 DOM 节点 在极少数情况下,例如使用开发工具([如 Symfony web 调试工具栏](https://github.com/symfony/symfony/pull/62970))时, 您可能希望保留特定的 DOM 节点。 为此,请将 `data-frankenphp-hot-reload-preserve` 属性添加到相关的 HTML 元素: ```html
``` ## Worker 模式 如果您的应用程序在 [Worker 模式](https://frankenphp.dev/docs/worker/)下运行,您的应用程序脚本会保留在内存中。 这意味着即使浏览器重新加载,您对 PHP 代码的更改也不会立即反映。 为了获得最佳的开发者体验,您应该将 `hot_reload` 与 [worker 指令中的 `watch` 子指令](config.md#watching-for-file-changes)结合使用。 - `hot_reload`:文件更改时刷新**浏览器** - `worker.watch`:文件更改时重启 worker ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## 工作原理 1. **监控**:FrankenPHP 使用底层 [e-dant/watcher 库](https://github.com/e-dant/watcher)(我们贡献了 Go 绑定)监控文件系统中的修改。 2. **重启 (Worker 模式)**:如果 worker 配置中启用了 `watch`,PHP worker 将重新启动以加载新代码。 3. **推送**:包含更改文件列表的 JSON 有效载荷被发送到内置的 [Mercure hub](https://mercure.rocks)。 4. **接收**:浏览器通过 JavaScript 库监听,接收 Mercure 事件。 5. **更新**: - 如果检测到 **Idiomorph**,它会获取更新的内容并修改当前的 HTML 以匹配新状态,即时应用更改而不会丢失状态。 - 否则,将调用 `window.location.reload()` 来刷新页面。 ================================================ FILE: docs/cn/known-issues.md ================================================ # 已知问题 ## 不支持的 PHP 扩展 已知以下扩展与 FrankenPHP 不兼容: | 名称 | 原因 | 替代方案 | | ----------------------------------------------------------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/en/imap.installation.php) | 不安全的线程 | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | 不安全的线程 | - | ## 有缺陷的 PHP 扩展 以下扩展在与 FrankenPHP 一起使用时已知存在错误和意外行为: | 名称 | 问题 | | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [ext-openssl](https://www.php.net/manual/en/book.openssl.php) | 在使用静态构建的 FrankenPHP(使用 musl libc 构建)时,在重负载下 OpenSSL 扩展可能会崩溃。一个解决方法是使用动态链接的构建(如 Docker 镜像中使用的版本)。此错误正在由 PHP 跟踪。[查看问题](https://github.com/php/php-src/issues/13648)。 | ## get_browser [get_browser()](https://www.php.net/manual/en/function.get-browser.php) 函数在一段时间后似乎表现不佳。解决方法是缓存(例如使用 [APCu](https://www.php.net/manual/zh/book.apcu.php))每个 User-Agent,因为它们是不变的。 ## 独立的二进制和基于 Alpine 的 Docker 镜像 独立的二进制文件和基于 Alpine 的 Docker 镜像 (`dunglas/frankenphp:*-alpine`) 使用的是 [musl libc](https://musl.libc.org/) 而不是 [glibc and friends](https://www.etalabs.net/compare_libcs.html),为的是保持较小的二进制大小。这可能会导致一些兼容性问题。特别是,glob 标志 `GLOB_BRACE` [不可用](https://www.php.net/manual/en/function.glob.php)。 ## 在 Docker 中使用 `https://127.0.0.1` 默认情况下,FrankenPHP 会为 `localhost` 生成一个 TLS 证书。 这是本地开发最简单且推荐的选项。 如果确实想使用 `127.0.0.1` 作为主机,可以通过将服务器名称设置为 `127.0.0.1` 来配置它以为其生成证书。 如果你使用 Docker,因为 [Docker 网络](https://docs.docker.com/network/) 问题,只做这些是不够的。 你将收到类似于以下内容的 TLS 错误 `curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`。 如果你使用的是 Linux,解决方案是使用 [使用宿主机网络](https://docs.docker.com/network/network-tutorial-host/): ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` Mac 和 Windows 不支持 Docker 使用宿主机网络。在这些平台上,你必须猜测容器的 IP 地址并将其包含在服务器名称中。 运行 `docker network inspect bridge` 并查看 `Containers`,找到 `IPv4Address` 当前分配的最后一个 IP 地址,并增加 1。如果没有容器正在运行,则第一个分配的 IP 地址通常为 `172.17.0.2`。 然后将其包含在 `SERVER_NAME` 环境变量中: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > 请务必将 `172.17.0.3` 替换为将分配给容器的 IP。 你现在应该能够从主机访问 `https://127.0.0.1`。 如果不是这种情况,请在调试模式下启动 FrankenPHP 以尝试找出问题: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Composer 脚本引用 `@php` [Composer 脚本](https://getcomposer.org/doc/articles/scripts.md) 可能想要执行一个 PHP 二进制文件来完成一些任务,例如在 [Laravel 项目](laravel.md) 中运行 `@php artisan package:discover --ansi`。这 [目前失败](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) 的原因有两个: - Composer 不知道如何调用 FrankenPHP 二进制文件; - Composer 可以在命令中使用 `-d` 标志添加 PHP 设置,而 FrankenPHP 目前尚不支持。 作为一种变通方法,我们可以在 `/usr/local/bin/php` 中创建一个 Shell 脚本,该脚本会去掉不支持的参数,然后调用 FrankenPHP: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` 然后将环境变量 `PHP_BINARY` 设置为我们 `php` 脚本的路径,并运行 Composer: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## 使用静态二进制文件排查 TLS/SSL 问题 在使用静态二进制文件时,您可能会遇到以下与TLS相关的错误,例如在使用STARTTLS发送电子邮件时: ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` 由于静态二进制不捆绑 TLS 证书,因此您需要将 OpenSSL 指向本地 CA 证书安装。 检查 [`openssl_get_cert_locations()`](https://www.php.net/manual/en/function.openssl-get-cert-locations.php) 的输出, 以找到 CA 证书必须安装的位置,并将它们存储在该位置。 > [!WARNING] > > Web 和命令行界面可能有不同的设置。 > 确保在适当的上下文中运行 `openssl_get_cert_locations()`。 [从Mozilla提取的CA证书可以在curl网站上下载](https://curl.se/docs/caextract.html)。 或者,许多发行版,包括 Debian、Ubuntu 和 Alpine,提供名为 `ca-certificates` 的软件包,其中包含这些证书。 还可以使用 `SSL_CERT_FILE` 和 `SSL_CERT_DIR` 来提示 OpenSSL 在哪里查找 CA 证书: ```console # Set TLS certificates environment variables export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/cn/laravel.md ================================================ # Laravel ## Docker 使用 FrankenPHP 为 [Laravel](https://laravel.com) Web 应用程序提供服务就像将项目挂载到官方 Docker 镜像的 `/app` 目录中一样简单。 从 Laravel 应用程序的主目录运行以下命令: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` 尽情享受吧! ## 本地安装 或者,你可以从本地机器上使用 FrankenPHP 运行 Laravel 项目: 1. [下载与你的系统相对应的二进制文件](https://github.com/php/frankenphp/releases) 2. 将以下配置添加到 Laravel 项目根目录中名为 `Caddyfile` 的文件中: ```caddyfile { frankenphp } # 服务器的域名 localhost { # 将 webroot 设置为 public/ 目录 root public/ # 启用压缩(可选) encode zstd br gzip # 执行当前目录中的 PHP 文件并提供资源 php_server { try_files {path} index.php } } ``` 3. 从 Laravel 项目的根目录启动 FrankenPHP:`frankenphp run` ## Laravel Octane Octane 可以通过 Composer 包管理器安装: ```console composer require laravel/octane ``` 安装 Octane 后,你可以执行 `octane:install` Artisan 命令,该命令会将 Octane 的配置文件安装到你的应用程序中: ```console php artisan octane:install --server=frankenphp ``` Octane 服务可以通过 `octane:frankenphp` Artisan 命令启动。 ```console php artisan octane:frankenphp ``` `octane:frankenphp` 命令可以采用以下选项: - `--host`: 服务器应绑定到的 IP 地址(默认值: `127.0.0.1`) - `--port`: 服务器应可用的端口(默认值: `8000`) - `--admin-port`: 管理服务器应可用的端口(默认值: `2019`) - `--workers`: 应可用于处理请求的 worker 数(默认值: `auto`) - `--max-requests`: 在 worker 重启之前要处理的请求数(默认值: `500`) - `--caddyfile`:FrankenPHP `Caddyfile` 文件的路径(默认: [Laravel Octane 中的存根 `Caddyfile`](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: 开启 HTTPS、HTTP/2 和 HTTP/3,自动生成和延长证书 - `--http-redirect`: 启用 HTTP 到 HTTPS 重定向(仅在使用 `--https` 时启用) - `--watch`: 修改应用程序时自动重新加载服务器 - `--poll`: 在监视时使用文件系统轮询,以便通过网络监视文件 - `--log-level`: 在指定日志级别或高于指定日志级别的日志消息 > [!TIP] > 要获取结构化的 JSON 日志(在使用日志分析解决方案时非常有用),请明确传递 `--log-level` 选项。 你可以了解更多关于 [Laravel Octane 官方文档](https://laravel.com/docs/octane)。 ## Laravel 应用程序作为独立的可执行文件 使用[FrankenPHP 的应用嵌入功能](embed.md),可以将 Laravel 应用程序作为 独立的二进制文件分发。 按照以下步骤将您的Laravel应用程序打包为Linux的独立二进制文件: 1. 在您的应用程序的存储库中创建一个名为 `static-build.Dockerfile` 的文件: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # 如果你打算在 musl-libc 系统上运行该二进制文件,请使用 static-builder-musl # 复制你的应用 WORKDIR /go/src/app/dist/app COPY . . # 删除测试和其他不必要的文件以节省空间 # 或者,将这些文件添加到 .dockerignore 文件中 RUN rm -Rf tests/ # 复制 .env 文件 RUN cp .env.example .env # 将 APP_ENV 和 APP_DEBUG 更改为适合生产环境 RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # 根据需要对您的 .env 文件进行其他更改 # 安装依赖项 RUN composer install --ignore-platform-reqs --no-dev -a # 构建静态二进制文件 WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > 一些 `.dockerignore` 文件 > 将忽略 `vendor/` 目录和 `.env` 文件。在构建之前,请确保调整或删除 `.dockerignore` 文件。 2. 构建: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. 提取二进制: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. 填充缓存: ```console frankenphp php-cli artisan optimize ``` 5. 运行数据库迁移(如果有的话): ```console frankenphp php-cli artisan migrate ``` 6. 生成应用程序的密钥: ```console frankenphp php-cli artisan key:generate ``` 7. 启动服务器: ```console frankenphp php-server ``` 您的应用程序现在准备好了! 了解有关可用选项的更多信息,以及如何为其他操作系统构建二进制文件,请参见 [应用程序嵌入](embed.md) 文档。 ### 更改存储路径 默认情况下,Laravel 将上传的文件、缓存、日志等存储在应用程序的 `storage/` 目录中。 这不适合嵌入式应用,因为每个新版本将被提取到不同的临时目录中。 设置 `LARAVEL_STORAGE_PATH` 环境变量(例如,在 `.env` 文件中)或调用 `Illuminate\Foundation\Application::useStoragePath()` 方法以使用临时目录之外的目录。 ### 使用独立二进制文件运行 Octane 甚至可以将 Laravel Octane 应用打包为独立的二进制文件! 为此,[正确安装 Octane](#laravel-octane) 并遵循 [前一部分](#laravel-应用程序作为独立的可执行文件) 中描述的步骤。 然后,通过 Octane 在工作模式下启动 FrankenPHP,运行: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > 为了使命令有效,独立二进制文件**必须**命名为 `frankenphp` > 因为 Octane 需要一个名为 `frankenphp` 的程序在路径中可用。 ================================================ FILE: docs/cn/mercure.md ================================================ # 实时 FrankenPHP 配备了内置的 [Mercure](https://mercure.rocks) 中心! Mercure 允许将事件实时推送到所有连接的设备:它们将立即收到 JavaScript 事件。 无需 JS 库或 SDK! ![Mercure](../mercure-hub.png) 要启用 Mercure Hub,请按照 [Mercure 网站](https://mercure.rocks/docs/hub/config) 中的说明更新 `Caddyfile`。 Mercure hub 的路径是`/.well-known/mercure`. 在 Docker 中运行 FrankenPHP 时,完整的发送 URL 将类似于 `http://php/.well-known/mercure` (其中 `php` 是运行 FrankenPHP 的容器名称)。 要从你的代码中推送 Mercure 更新,我们推荐 [Symfony Mercure Component](https://symfony.com/components/Mercure)(不需要 Symfony 框架来使用)。 ================================================ FILE: docs/cn/metrics.md ================================================ # 指标 当启用 [Caddy 指标](https://caddyserver.com/docs/metrics) 时,FrankenPHP 公开以下指标: - `frankenphp_total_threads`:PHP 线程的总数。 - `frankenphp_busy_threads`:当前正在处理请求的 PHP 线程数(运行中的 worker 始终占用一个线程)。 - `frankenphp_queue_depth`:常规排队请求的数量 - `frankenphp_total_workers{worker="[worker_name]"}`:worker 的总数。 - `frankenphp_busy_workers{worker="[worker_name]"}`:当前正在处理请求的 worker 数量。 - `frankenphp_worker_request_time{worker="[worker_name]"}`:所有 worker 处理请求所花费的时间。 - `frankenphp_worker_request_count{worker="[worker_name]"}`:所有 worker 处理的请求数量。 - `frankenphp_ready_workers{worker="[worker_name]"}`:至少调用过一次 `frankenphp_handle_request` 的 worker 数量。 - `frankenphp_worker_crashes{worker="[worker_name]"}`:worker 意外终止的次数。 - `frankenphp_worker_restarts{worker="[worker_name]"}`:worker 被故意重启的次数。 - `frankenphp_worker_queue_depth{worker="[worker_name]"}`:排队请求的数量。 对于 worker 指标,`[worker_name]` 占位符被 Caddyfile 中的 worker 名称替换,否则将使用 worker 文件的绝对路径。 ================================================ FILE: docs/cn/performance.md ================================================ # 性能 默认情况下,FrankenPHP 尝试在性能和易用性之间提供良好的折衷。 但是,通过使用适当的配置,可以大幅提高性能。 ## 线程和 Worker 数量 默认情况下,FrankenPHP 启动的线程和 worker(在 worker 模式下)数量是可用 CPU 核心数的 2 倍。 适当的值很大程度上取决于你的应用程序是如何编写的、它做什么以及你的硬件。 我们强烈建议更改这些值。为了获得最佳的系统稳定性,建议 `num_threads` x `memory_limit` < `available_memory`。 要找到正确的值,最好运行模拟真实流量的负载测试。 [k6](https://k6.io) 和 [Gatling](https://gatling.io) 是很好的工具。 要配置线程数,请使用 `php_server` 和 `php` 指令的 `num_threads` 选项。 要更改 worker 数量,请使用 `frankenphp` 指令的 `worker` 部分的 `num` 选项。 ### `max_threads` 虽然准确了解你的流量情况总是更好,但现实应用往往更加 不可预测。`max_threads` [配置](config.md#caddyfile-config) 允许 FrankenPHP 在运行时自动生成额外线程,直到指定的限制。 `max_threads` 可以帮助你确定需要多少线程来处理你的流量,并可以使服务器对延迟峰值更具弹性。 如果设置为 `auto`,限制将基于你的 `php.ini` 中的 `memory_limit` 进行估算。如果无法这样做, `auto` 将默认为 2x `num_threads`。请记住,`auto` 可能会严重低估所需的线程数。 `max_threads` 类似于 PHP FPM 的 [pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children)。主要区别是 FrankenPHP 使用线程而不是 进程,并根据需要自动在不同的 worker 脚本和"经典模式"之间委派它们。 ## Worker 模式 启用 [worker 模式](worker.md) 大大提高了性能, 但你的应用必须适配以兼容此模式: 你需要创建一个 worker 脚本并确保应用不会泄漏内存。 ## 不要使用 musl 官方 Docker 镜像的 Alpine Linux 变体和我们提供的默认二进制文件使用 [musl libc](https://musl.libc.org)。 众所周知,当使用这个替代 C 库而不是传统的 GNU 库时,PHP [更慢](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381), 特别是在以 ZTS 模式(线程安全)编译时,这是 FrankenPHP 所必需的。在大量线程环境中,差异可能很显著。 另外,[一些错误只在使用 musl 时发生](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl)。 在生产环境中,我们建议使用链接到 glibc 的 FrankenPHP,并使用适当的优化级别进行编译。 这可以通过使用 Debian Docker 镜像、使用[我们的维护者提供的 .deb、.rpm 或 .apk 包](https://pkgs.henderkes.com),或通过[从源代码编译 FrankenPHP](compile.md) 来实现。 对于更精简或更安全的容器,你可能需要考虑使用[强化的 Debian 镜像](docker.md#hardening-images)而不是 Alpine。 ## Go 运行时配置 FrankenPHP 是用 Go 编写的。 一般来说,Go 运行时不需要任何特殊配置,但在某些情况下, 特定的配置可以提高性能。 你可能想要将 `GODEBUG` 环境变量设置为 `cgocheck=0`(FrankenPHP Docker 镜像中的默认值)。 如果你在容器(Docker、Kubernetes、LXC...)中运行 FrankenPHP 并限制容器的可用内存, 请将 `GOMEMLIMIT` 环境变量设置为可用内存量。 有关更多详细信息,[专门针对此主题的 Go 文档页面](https://pkg.go.dev/runtime#hdr-Environment_Variables) 是充分利用运行时的必读内容。 ## `file_server` 默认情况下,`php_server` 指令自动设置文件服务器来 提供存储在根目录中的静态文件(资产)。 此功能很方便,但有成本。 要禁用它,请使用以下配置: ```caddyfile php_server { file_server off } ``` ## `try_files` 除了静态文件和 PHP 文件外,`php_server` 还会尝试提供你应用程序的索引 和目录索引文件(`/path/` -> `/path/index.php`)。如果你不需要目录索引, 你可以通过明确定义 `try_files` 来禁用它们,如下所示: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # 在这里明确添加根目录允许更好的缓存 } ``` 这可以显著减少不必要的文件操作数量。 上述配置的 worker 等效项为: ```caddyfile route { php_server { # 如果完全不需要文件服务器,请使用 "php" 而不是 "php_server" root /root/to/your/app worker /path/to/worker.php { match * # 将所有请求直接发送到 worker } } } ``` 另一种具有 0 个不必要文件系统操作的方法是改用 `php` 指令并按路径将 文件与 PHP 分开。如果你的整个应用程序由一个入口文件提供服务,这种方法效果很好。 一个在 `/assets` 文件夹后面提供静态文件的示例[配置](config.md#caddyfile-config)可能如下所示: ```caddyfile route { @assets { path /assets/* } # /assets 后面的所有内容都由文件服务器处理 file_server @assets { root /root/to/your/app } # 不在 /assets 中的所有内容都由你的索引或 worker PHP 文件处理 rewrite index.php php { root /root/to/your/app # 在这里明确添加根目录允许更好的缓存 } } ``` ## 占位符 你可以在 `root` 和 `env` 指令中使用[占位符](https://caddyserver.com/docs/conventions#placeholders)。 但是,这会阻止缓存这些值,并带来显著的性能成本。 如果可能,请避免在这些指令中使用占位符。 ## `resolve_root_symlink` 默认情况下,如果文档根目录是符号链接,FrankenPHP 会自动解析它(这对于 PHP 正常工作是必要的)。 如果文档根目录不是符号链接,你可以禁用此功能。 ```caddyfile php_server { resolve_root_symlink false } ``` 如果 `root` 指令包含[占位符](https://caddyserver.com/docs/conventions#placeholders),这将提高性能。 在其他情况下,收益将可以忽略不计。 ## 日志 日志显然非常有用,但根据定义, 它需要 I/O 操作和内存分配,这会大大降低性能。 确保你[正确设置日志级别](https://caddyserver.com/docs/caddyfile/options#log), 并且只记录必要的内容。 ## PHP 性能 FrankenPHP 使用官方 PHP 解释器。 所有常见的 PHP 相关性能优化都适用于 FrankenPHP。 特别是: - 检查 [OPcache](https://www.php.net/manual/zh/book.opcache.php) 是否已安装、启用并正确配置 - 启用 [Composer 自动加载器优化](https://getcomposer.org/doc/articles/autoloader-optimization.md) - 确保 `realpath` 缓存对于你的应用程序需求足够大 - 使用[预加载](https://www.php.net/manual/zh/opcache.preloading.php) 有关更多详细信息,请阅读[专门的 Symfony 文档条目](https://symfony.com/doc/current/performance.html) (即使你不使用 Symfony,大多数提示也很有用)。 ## 拆分线程池 应用程序与慢速外部服务交互是很常见的,例如在高负载下往往不可靠或持续需要 10 秒以上才能响应的 API。 在这种情况下,将线程池拆分以拥有专用的“慢速”池可能会很有益。这可以防止慢速端点消耗所有服务器资源/线程,并限制指向慢速端点的请求并发性,类似于连接池。 ```caddyfile example.com { php_server { root /app/public # 你的应用程序根目录 worker index.php { match /slow-endpoint/* # 所有路径为 /slow-endpoint/* 的请求都由这个线程池处理 num 1 # 匹配 /slow-endpoint/* 的请求至少有 1 个线程 max_threads 20 # 如果需要,允许最多 20 个线程处理匹配 /slow-endpoint/* 的请求 } worker index.php { match * # 所有其他请求单独处理 num 1 # 其他请求至少有 1 个线程,即使慢速端点开始挂起 max_threads 20 # 如果需要,允许最多 20 个线程处理其他请求 } } } ``` 通常,也建议通过使用消息队列等相关机制,异步处理非常慢的端点。 ================================================ FILE: docs/cn/production.md ================================================ # 在生产环境中部署 在本教程中,我们将学习如何使用 Docker Compose 在单个服务器上部署 PHP 应用程序。 如果你使用的是 Symfony,请阅读 Symfony Docker 项目(使用 FrankenPHP)的 [在生产环境中部署](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md) 文档条目。 如果你使用的是 API Platform(同样使用 FrankenPHP),请参阅 [框架的部署文档](https://api-platform.com/docs/deployment/)。 ## 准备应用 首先,在 PHP 项目的根目录中创建一个 `Dockerfile`: ```dockerfile FROM dunglas/frankenphp # 请将 "your-domain-name.example.com" 替换为你的域名 ENV SERVER_NAME=your-domain-name.example.com # 如果要禁用 HTTPS,请改用以下值: #ENV SERVER_NAME=:80 # 如果你的项目不使用 "public" 目录作为 web 根目录,你可以在这里设置: # ENV SERVER_ROOT=web/ # 启用 PHP 生产配置 RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # 将项目的 PHP 文件复制到 public 目录中 COPY . /app/public # 如果你使用 Symfony 或 Laravel,你需要复制整个项目: #COPY . /app ``` 有关更多详细信息和选项,请参阅 [构建自定义 Docker 镜像](docker.md)。 要了解如何自定义配置,请安装 PHP 扩展和 Caddy 模块。 如果你的项目使用 Composer, 请务必将其包含在 Docker 镜像中并安装你的依赖。 然后,添加一个 `compose.yaml` 文件: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Caddy 证书和配置所需的挂载目录 volumes: caddy_data: caddy_config: ``` > [!NOTE] > > 前面的示例适用于生产用途。 > 在开发中,你可能希望使用挂载目录,不同的 PHP 配置和不同的 `SERVER_NAME` 环境变量值。 > > 见 [Symfony Docker](https://github.com/dunglas/symfony-docker) 项目 > (使用 FrankenPHP)作为使用多阶段镜像的更高级示例, > Composer、额外的 PHP 扩展等。 最后,如果你使用 Git,请提交这些文件并推送。 ## 准备服务器 若要在生产环境中部署应用程序,需要一台服务器。 在本教程中,我们将使用 DigitalOcean 提供的虚拟机,但任何 Linux 服务器都可以工作。 如果你已经有安装了 Docker 的 Linux 服务器,你可以直接跳到 [下一节](#配置域名)。 否则,请使用 [此会员链接](https://m.do.co/c/5d8aabe3ab80) 获得 200 美元的免费信用额度,创建一个帐户,然后单击“Create a Droplet”。 然后,单击“Choose an image”部分下的“Marketplace”选项卡,然后搜索名为“Docker”的应用程序。 这将配置已安装最新版本的 Docker 和 Docker Compose 的 Ubuntu 服务器! 出于测试目的,最便宜的就足够了。 对于实际的生产用途,你可能需要在“general purpose”部分中选择一个计划来满足你的需求。 ![使用 Docker 在 DigitalOcean 上部署 FrankenPHP](../digitalocean-droplet.png) 你可以保留其他设置的默认值,也可以根据需要进行调整。 不要忘记添加你的 SSH 密钥或创建密码,然后点击“完成并创建”按钮。 然后,在 Droplet 预配时等待几秒钟。 Droplet 准备就绪后,使用 SSH 进行连接: ```console ssh root@ ``` ## 配置域名 在大多数情况下,你需要将域名与你的网站相关联。 如果你还没有域名,则必须通过注册商购买。 然后为你的域名创建类型为 `A` 的 DNS 记录,指向服务器的 IP 地址: ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` DigitalOcean 域服务示例(“Networking” > “Domains”): ![在 DigitalOcean 上配置 DNS](../digitalocean-dns.png) > [!NOTE] > > Let's Encrypt 是 FrankenPHP 默认用于自动生成 TLS 证书的服务,不支持使用裸 IP 地址。使用域名是使用 Let's Encrypt 的必要条件。 ## 部署 使用 `git clone`、`scp` 或任何其他可能适合你需要的工具在服务器上复制你的项目。 如果使用 GitHub,则可能需要使用 [部署密钥](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys)。 部署密钥也 [由 GitLab 支持](https://docs.gitlab.com/ee/user/project/deploy_keys/)。 Git 示例: ```console git clone git@github.com:/.git ``` 进入包含项目 (``) 的目录,并在生产模式下启动应用: ```console docker compose up --wait ``` 你的服务器已启动并运行,并且已自动为你生成 HTTPS 证书。 去 `https://your-domain-name.example.com` 享受吧! > [!CAUTION] > > Docker 有一个缓存层,请确保每个部署都有正确的构建,或者使用 `--no-cache` 选项重新构建项目以避免缓存问题。 ## 在多个节点上部署 如果要在计算机集群上部署应用程序,可以使用 [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), 它与提供的 Compose 文件兼容。 要在 Kubernetes 上部署,请查看 [API 平台提供的 Helm 图表](https://api-platform.com/docs/deployment/kubernetes/),同样也使用 FrankenPHP。 ================================================ FILE: docs/cn/static.md ================================================ # 创建静态构建 与其使用本地安装的PHP库, 由于伟大的 [static-php-cli 项目](https://github.com/crazywhalecc/static-php-cli),创建一个静态或基本静态的 FrankenPHP 构建是可能的(尽管它的名字,这个项目支持所有的 SAPI,而不仅仅是 CLI)。 使用这种方法,我们可构建一个包含 PHP 解释器、Caddy Web 服务器和 FrankenPHP 的可移植二进制文件! 完全静态的本地可执行文件不需要任何依赖,并且可以在 [`scratch` Docker 镜像](https://docs.docker.com/build/building/base-images/#create-a-minimal-base-image-using-scratch) 上运行。 然而,它们无法加载动态 PHP 扩展(例如 Xdebug),并且由于使用了 musl libc,有一些限制。 大多数静态二进制文件只需要 `glibc` 并且可以加载动态扩展。 在可能的情况下,我们建议使用基于glibc的、主要是静态构建的版本。 FrankenPHP 还支持 [将 PHP 应用程序嵌入到静态二进制文件中](embed.md)。 ## Linux 我们提供了一个 Docker 镜像来构建 Linux 静态二进制文件: ### 基于musl的完全静态构建 对于一个在任何Linux发行版上运行且不需要依赖项的完全静态二进制文件,但不支持动态加载扩展: ```console docker buildx bake --load static-builder-musl docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-musl ``` 为了在高度并发的场景中获得更好的性能,请考虑使用 [mimalloc](https://github.com/microsoft/mimalloc) 分配器。 ```console docker buildx bake --load --set static-builder-musl.args.MIMALLOC=1 static-builder-musl ``` ### 基于glibc的,主要静态构建(支持动态扩展) 对于一个支持动态加载 PHP 扩展的二进制文件,同时又将所选扩展静态编译: ```console docker buildx bake --load static-builder-gnu docker cp $(docker create --name static-builder-gnu dunglas/frankenphp:static-builder-gnu):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-gnu ``` 该二进制文件支持所有glibc版本2.17及以上,但不支持基于musl的系统(如Alpine Linux)。 生成的主要是静态的(除了 `glibc`)二进制文件名为 `frankenphp`,并且可以在当前目录中找到。 如果你想在没有 Docker 的情况下构建静态二进制文件,请查看 macOS 说明,它也适用于 Linux。 ### 自定义扩展 默认情况下,大多数流行的 PHP 扩展都会被编译。 为了减少二进制文件的大小和减少攻击面,您可以选择使用 `PHP_EXTENSIONS` Docker ARG 构建的扩展列表。 例如,运行以下命令仅构建 `opcache` 扩展: ```console docker buildx bake --load --set static-builder-musl.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder-musl # ... ``` 若要将启用其他功能的库添加到已启用的扩展中,可以使用 `PHP_EXTENSION_LIBS` Docker 参数: ```console docker buildx bake \ --load \ --set static-builder-musl.args.PHP_EXTENSIONS=gd \ --set static-builder-musl.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder-musl ``` ### 额外的 Caddy 模块 要向 [xcaddy](https://github.com/caddyserver/xcaddy) 添加额外的 Caddy 模块或传递其他参数,请使用 `XCADDY_ARGS` Docker 参数: ```console docker buildx bake \ --load \ --set static-builder-musl.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder-musl ``` 在本例中,我们为 Caddy 添加了 [Souin](https://souin.io) HTTP 缓存模块,以及 [cbrotli](https://github.com/dunglas/caddy-cbrotli)、[Mercure](https://mercure.rocks) 和 [Vulcain](https://vulcain.rocks) 模块。 > [!TIP] > > 如果 `XCADDY_ARGS` 为空或未设置,则默认包含 cbrotli、Mercure 和 Vulcain 模块。 > 如果自定义了 `XCADDY_ARGS` 的值,则必须显式地包含它们。 参见:[自定义构建](#自定义构建) ### GitHub Token 如果遇到了 GitHub API 速率限制,请在 `GITHUB_TOKEN` 的环境变量中设置 GitHub Personal Access Token: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS 运行以下脚本以创建适用于 macOS 的静态二进制文件(需要先安装 [Homebrew](https://brew.sh/)): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` 注意:此脚本也适用于 Linux(可能也适用于其他 Unix 系统),我们提供的用于构建静态二进制的 Docker 镜像也在内部使用这个脚本。 ## 自定义构建 以下环境变量可以传递给 `docker build` 和 `build-static.sh` 脚本来自定义静态构建: - `FRANKENPHP_VERSION`: 要使用的 FrankenPHP 版本 - `PHP_VERSION`: 要使用的 PHP 版本 - `PHP_EXTENSIONS`: 要构建的 PHP 扩展([支持的扩展列表](https://static-php.dev/zh/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: 要构建的额外库,为扩展添加额外的功能 - `XCADDY_ARGS`:传递给 [xcaddy](https://github.com/caddyserver/xcaddy) 的参数,例如用于添加额外的 Caddy 模块 - `EMBED`: 要嵌入二进制文件的 PHP 应用程序的路径 - `CLEAN`: 设置后,libphp 及其所有依赖项都是重新构建的(不使用缓存) - `NO_COMPRESS`: 不要使用UPX压缩生成的二进制文件 - `DEBUG_SYMBOLS`: 设置后,调试符号将被保留在二进制文件内 - `MIMALLOC`: (实验性,仅限Linux) 用[mimalloc](https://github.com/microsoft/mimalloc)替换musl的mallocng,以提高性能。我们仅建议在musl目标构建中使用此选项,对于glibc,建议禁用此选项,并在运行二进制文件时使用[`LD_PRELOAD`](https://microsoft.github.io/mimalloc/overrides.html)。 - `RELEASE`: (仅限维护者)设置后,生成的二进制文件将上传到 GitHub 上 ## 扩展 使用glibc或基于macOS的二进制文件,您可以动态加载PHP扩展。然而,这些扩展必须使用ZTS支持进行编译。 由于大多数软件包管理器目前不提供其扩展的 ZTS 版本,因此您必须自己编译它们。 为此,您可以构建并运行 `static-builder-gnu` Docker 容器,远程进入它,并使用 `./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config` 编译扩展。 关于 [Xdebug 扩展](https://xdebug.org) 的示例步骤: ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` 这将在当前目录中创建 `frankenphp` 和 `xdebug-zts.so`。 如果你将 `xdebug-zts.so` 移动到你的扩展目录中,添加 `zend_extension=xdebug-zts.so` 到你的 php.ini 并运行 FrankenPHP,它将加载 Xdebug。 ================================================ FILE: docs/cn/worker.md ================================================ # 使用 FrankenPHP Workers 启动一次应用程序并将其保存在内存中。 FrankenPHP 将在几毫秒内处理传入请求。 ## 启动 Worker 脚本 ### Docker 将 `FRANKENPHP_CONFIG` 环境变量的值设置为 `worker /path/to/your/worker/script.php`: ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### 独立二进制文件 使用 `php-server` 命令的 `--worker` 选项通过 worker 为当前目录的内容提供服务: ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` 如果你的 PHP 应用程序已[嵌入到二进制文件中](embed.md),你可以在应用程序的根目录中添加自定义的 `Caddyfile`。 它将被自动使用。 还可以使用 `--watch` 选项在[文件更改时重启 worker](config.md#watching-for-file-changes)。 如果 `/path/to/your/app/` 目录或子目录中任何以 `.php` 结尾的文件被修改,以下命令将触发重启: ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` 此功能通常与[热重载](hot-reload.md)结合使用。 ## Symfony Runtime > [!TIP] > 以下部分仅在 Symfony 7.4 之前是必需的,因为 Symfony 7.4 引入了对 FrankenPHP worker 模式的原生支持。 FrankenPHP 的 worker 模式由 [Symfony Runtime Component](https://symfony.com/doc/current/components/runtime.html) 支持。 要在 worker 中启动任何 Symfony 应用程序,请安装 [PHP Runtime](https://github.com/php-runtime/runtime) 的 FrankenPHP 包: ```console composer require runtime/frankenphp-symfony ``` 通过定义 `APP_RUNTIME` 环境变量来使用 FrankenPHP Symfony Runtime 启动你的应用服务器: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane 请参阅[专门的文档](laravel.md#laravel-octane)。 ## 自定义应用程序 以下示例展示了如何创建自己的 worker 脚本而不依赖第三方库: ```php boot(); // 在循环外的处理器以获得更好的性能(减少工作量) $handler = static function () use ($myApp) { try { // 当收到请求时调用, // 超全局变量、php://input 等都会被重置 echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` 仅在 worker 脚本结束时调用, // 这可能不是您所期望的,因此在此处捕获并处理异常 (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // 在发送 HTTP 响应后做一些事情 $myApp->terminate(); // 调用垃圾收集器以减少在页面生成过程中触发垃圾收集的可能性 gc_collect_cycles(); if (!$keepRunning) break; } // 清理 $myApp->shutdown(); ``` 然后,启动你的应用程序并使用 `FRANKENPHP_CONFIG` 环境变量配置你的 worker: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` 默认情况下,每个 CPU 启动 2 个 worker。 你也可以配置要启动的 worker 数量: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### 在处理一定数量的请求后重启 Worker 由于 PHP 最初不是为长时间运行的进程而设计的,仍有许多库和传统代码会泄漏内存。 在 worker 模式下使用此类代码的一个解决方法是在处理一定数量的请求后重启 worker 脚本: 前面的 worker 代码片段允许通过设置名为 `MAX_REQUESTS` 的环境变量来配置要处理的最大请求数。 ### 手动重启 Workers 虽然可以在[文件更改时重启 workers](config.md#watching-for-file-changes),但也可以通过 [Caddy admin API](https://caddyserver.com/docs/api) 优雅地重启所有 workers。如果在你的 [Caddyfile](config.md#caddyfile-config) 中启用了 admin,你可以通过简单的 POST 请求 ping 重启端点,如下所示: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Worker 故障 如果 worker 脚本因非零退出代码而崩溃,FrankenPHP 将使用指数退避策略重启它。 如果 worker 脚本保持运行的时间超过上次退避 × 2, 它将不会惩罚 worker 脚本并再次重启它。 但是,如果 worker 脚本在短时间内继续以非零退出代码失败 (例如,脚本中有拼写错误),FrankenPHP 将崩溃并出现错误:`too many consecutive failures`。 可以在你的 [Caddyfile](config.md#caddyfile-config) 中使用 `max_consecutive_failures` 选项配置连续失败的次数: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## 超全局变量行为 [PHP 超全局变量](https://www.php.net/manual/zh/language.variables.superglobals.php)(`$_SERVER`、`$_ENV`、`$_GET`...) 行为如下: - 在第一次调用 `frankenphp_handle_request()` 之前,超全局变量包含绑定到 worker 脚本本身的值 - 在调用 `frankenphp_handle_request()` 期间和之后,超全局变量包含从处理的 HTTP 请求生成的值,每次调用 `frankenphp_handle_request()` 都会更改超全局变量的值 要在回调内访问 worker 脚本的超全局变量,必须复制它们并将副本导入到回调的作用域中: ```php > ~/.zshrc ``` Then run the configure script: ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` #### Compile PHP Finally, compile and install PHP: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Install Optional Dependencies Some FrankenPHP features depend on optional system dependencies that must be installed. Alternatively, these features can be disabled by passing build tags to the Go compiler. | Feature | Dependency | Build tag to disable it | | ------------------------------ | ------------------------------------------------------------------------------------------------------------ | ----------------------- | | Brotli compression | [Brotli](https://github.com/google/brotli) | nobrotli | | Restart workers on file change | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | | [Mercure](mercure.md) | [Mercure Go library](https://pkg.go.dev/github.com/dunglas/mercure) (automatically installed, AGPL licensed) | nomercure | ## Compile the Go App You can now build the final binary. ### Using xcaddy The recommended way is to use [xcaddy](https://github.com/caddyserver/xcaddy) to compile FrankenPHP. `xcaddy` also allows to easily add [custom Caddy modules](https://caddyserver.com/docs/modules/) and FrankenPHP extensions: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy \ --with github.com/dunglas/caddy-cbrotli # Add extra Caddy modules and FrankenPHP extensions here # optionally, if you would like to compile from your frankenphp sources: # --with github.com/dunglas/frankenphp=$(pwd) \ # --with github.com/dunglas/frankenphp/caddy=$(pwd)/caddy ``` > [!TIP] > > If you're using musl libc (the default on Alpine Linux) and Symfony, > you may need to increase the default stack size. > Otherwise, you may get errors like `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression` > > To do so, change the `XCADDY_GO_BUILD_FLAGS` environment variable to something like > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (change the stack size value according to your app needs). ### Without xcaddy Alternatively, it's possible to compile FrankenPHP without `xcaddy` by using the `go` command directly: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/config.md ================================================ # Configuration FrankenPHP, Caddy as well as the [Mercure](mercure.md) and [Vulcain](https://vulcain.rocks) modules can be configured using [the formats supported by Caddy](https://caddyserver.com/docs/getting-started#your-first-config). The most common format is the `Caddyfile`, which is a simple, human-readable text format. By default, FrankenPHP will look for a `Caddyfile` in the current directory. You can specify a custom path with the `-c` or `--config` option. A minimal `Caddyfile` to serve a PHP application is shown below: ```caddyfile # The hostname to respond to localhost # Optionally, the directory to serve files from, otherwise defaults to the current directory #root public/ php_server ``` A more advanced `Caddyfile` enabling more features and providing convenient environment variables is provided [in the FrankenPHP repository](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile), and with Docker images. PHP itself can be configured [using a `php.ini` file](https://www.php.net/manual/en/configuration.file.php). Depending on your installation method, FrankenPHP and the PHP interpreter will look for configuration files in locations described below. ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: the main configuration file - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: additional configuration files that are loaded automatically PHP: - `php.ini`: `/usr/local/etc/php/php.ini` (no `php.ini` is provided by default) - additional configuration files: `/usr/local/etc/php/conf.d/*.ini` - PHP extensions: `/usr/local/lib/php/extensions/no-debug-zts-/` - You should copy an official template provided by the PHP project: ```dockerfile FROM dunglas/frankenphp # Production: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Or development: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## RPM and Debian packages FrankenPHP: - `/etc/frankenphp/Caddyfile`: the main configuration file - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: additional configuration files that are loaded automatically PHP: - `php.ini`: `/etc/php-zts/php.ini` (a `php.ini` file with production presets is provided by default) - additional configuration files: `/etc/php-zts/conf.d/*.ini` ## Static binary FrankenPHP: - In the current working directory: `Caddyfile` PHP: - `php.ini`: The directory in which `frankenphp run` or `frankenphp php-server` is executed, then `/etc/frankenphp/php.ini` - additional configuration files: `/etc/frankenphp/php.d/*.ini` - PHP extensions: cannot be loaded, bundle them in the binary itself - copy one of `php.ini-production` or `php.ini-development` provided [in the PHP sources](https://github.com/php/php-src/). ## Caddyfile Config The `php_server` or the `php` [HTTP directives](https://caddyserver.com/docs/caddyfile/concepts#directives) may be used within the site blocks to serve your PHP app. Minimal example: ```caddyfile localhost { # Enable compression (optional) encode zstd br gzip # Execute PHP files in the current directory and serve assets php_server } ``` You can also explicitly configure FrankenPHP using the [global option](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp`: ```caddyfile { frankenphp { num_threads # Sets the number of PHP threads to start. Default: 2x the number of available CPUs. max_threads # Limits the number of additional PHP threads that can be started at runtime. Default: num_threads. Can be set to 'auto'. max_wait_time # Sets the maximum time a request may wait for a free PHP thread before timing out. Default: disabled. max_idle_time # Sets the maximum time an autoscaled thread may be idle before being deactivated. Default: 5s. php_ini # Set a php.ini directive. Can be used several times to set multiple directives. worker { file # Sets the path to the worker script. num # Sets the number of PHP threads to start, defaults to 2x the number of available CPUs. env # Sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. watch # Sets the path to watch for file changes. Can be specified more than once for multiple paths. name # Sets the name of the worker, used in logs and metrics. Default: absolute path of worker file max_consecutive_failures # Sets the maximum number of consecutive failures before the worker is considered unhealthy, -1 means the worker will always restart. Default: 6. } } } # ... ``` Alternatively, you may use the one-line short form of the `worker` option: ```caddyfile { frankenphp { worker } } # ... ``` You can also define multiple workers if you serve multiple apps on the same server: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # allows for better caching worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` Using the `php_server` directive is generally what you need, but if you need full control, you can use the lower-level `php` directive. The `php` directive passes all input to PHP, instead of first checking whether it's a PHP file or not. Read more about it in the [performance page](performance.md#try_files). Using the `php_server` directive is equivalent to this configuration: ```caddyfile route { # Add trailing slash for directory requests @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # If the requested file does not exist, try index files @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` The `php_server` and the `php` directives have the following options: ```caddyfile php_server [] { root # Sets the root folder to the site. Default: `root` directive. split_path # Sets the substrings for splitting the URI into two parts. The first matching substring will be used to split the "path info" from the path. The first piece is suffixed with the matching substring and will be assumed as the actual resource (CGI script) name. The second piece will be set to PATH_INFO for the script to use. Default: `.php` resolve_root_symlink false # Disables resolving the `root` directory to its actual value by evaluating a symbolic link, if one exists (enabled by default). env # Sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. file_server off # Disables the built-in file_server directive. worker { # Creates a worker specific to this server. Can be specified more than once for multiple workers. file # Sets the path to the worker script, can be relative to the php_server root num # Sets the number of PHP threads to start, defaults to 2x the number of available name # Sets the name for the worker, used in logs and metrics. Default: absolute path of worker file. Always starts with m# when defined in a php_server block. watch # Sets the path to watch for file changes. Can be specified more than once for multiple paths. env # Sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables. Environment variables for this worker are also inherited from the php_server parent, but can be overwritten here. match # match the worker to a path pattern. Overrides try_files and can only be used in the php_server directive. } worker # Can also use the short form like in the global frankenphp block. } ``` ### Watching for File Changes Since workers only boot your application once and keep it in memory, any changes to your PHP files will not be reflected immediately. Workers can instead be restarted on file changes via the `watch` directive. This is useful for development environments. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` This feature is often used in combination with [hot reload](hot-reload.md). If the `watch` directory is not specified, it will fall back to `./**/*.{env,php,twig,yaml,yml}`, which watches all `.env`, `.php`, `.twig`, `.yaml` and `.yml` files in the directory and subdirectories where the FrankenPHP process was started. You can instead also specify one or more directories via a [shell filename pattern](https://pkg.go.dev/path/filepath#Match): ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # watches all files in all subdirectories of /path/to/app watch /path/to/app/*.php # watches files ending in .php in /path/to/app watch /path/to/app/**/*.php # watches PHP files in /path/to/app and subdirectories watch /path/to/app/**/*.{php,twig} # watches PHP and Twig files in /path/to/app and subdirectories } } } ``` - The `**` pattern signifies recursive watching - Directories can also be relative (to where the FrankenPHP process is started from) - If you have multiple workers defined, all of them will be restarted when a file changes - Be wary about watching files that are created at runtime (like logs) since they might cause unwanted worker restarts. The file watcher is based on [e-dant/watcher](https://github.com/e-dant/watcher). ## Matching the Worker To a Path In traditional PHP applications, scripts are always placed in the public directory. This is also true for worker scripts, which are treated like any other PHP script. If you want to instead put the worker script outside the public directory, you can do so via the `match` directive. The `match` directive is an optimized alternative to `try_files` only available inside `php_server` and `php`. The following example will always serve a file in the public directory if present and otherwise forward the request to the worker matching the path pattern. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # file can be outside of public path match /api/* # all requests starting with /api/ will be handled by this worker } } } } ``` ## Environment Variables The following environment variables can be used to inject Caddy directives in the `Caddyfile` without modifying it: - `SERVER_NAME`: change [the addresses on which to listen](https://caddyserver.com/docs/caddyfile/concepts#addresses), the provided hostnames will also be used for the generated TLS certificate - `SERVER_ROOT`: change the root directory of the site, defaults to `public/` - `CADDY_GLOBAL_OPTIONS`: inject [global options](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG`: inject config under the `frankenphp` directive As for FPM and CLI SAPIs, environment variables are exposed by default in the `$_SERVER` superglobal. The `S` value of [the `variables_order` PHP directive](https://www.php.net/manual/en/ini.core.php#ini.variables-order) is always equivalent to `ES` regardless of the placement of `E` elsewhere in this directive. ## PHP config To load [additional PHP configuration files](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan), the `PHP_INI_SCAN_DIR` environment variable can be used. When set, PHP will load all the file with the `.ini` extension present in the given directories. You can also change the PHP configuration using the `php_ini` directive in the `Caddyfile`: ```caddyfile { frankenphp { php_ini memory_limit 256M # or php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### Disabling HTTPS By default, FrankenPHP will automatically enable HTTPS using for all the hostnames, including `localhost`. If you want to disable HTTPS (for example in a development environment), you can set the `SERVER_NAME` environment variable to `http://` or `:80`: Alternatively, you can use all other methods described in the [Caddy documentation](https://caddyserver.com/docs/automatic-https#activation). If you want to use HTTPS with the `127.0.0.1` IP address instead of the `localhost` hostname, please read the [known issues](known-issues.md#using-https127001-with-docker) section. ### Full Duplex (HTTP/1) When using HTTP/1.x, it may be desirable to enable full-duplex mode to allow writing a response before the entire body has been read. (for example: [Mercure](mercure.md), WebSocket, Server-Sent Events, etc.) This is an opt-in configuration that needs to be added to the global options in the `Caddyfile`: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > Enabling this option may cause old HTTP/1.x clients that don't support full-duplex to deadlock. > This can also be configured using the `CADDY_GLOBAL_OPTIONS` environment config: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` You can find more information about this setting in the [Caddy documentation](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex). ## Enable the Debug Mode When using the Docker image, set the `CADDY_GLOBAL_OPTIONS` environment variable to `debug` to enable the debug mode: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Shell Completion FrankenPHP provides built-in shell completion support for Bash, Zsh, Fish, and PowerShell. This enables autocompletion for all commands (including custom commands like `php-server`, `php-cli`, and `extension-init`) and their flags. ### Bash To load completions in your current shell session: ```console source <(frankenphp completion bash) ``` To load completions for every new session, run: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh If shell completion is not already enabled in your environment, you will need to enable it. You can execute the following once: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` To load completions for each session, execute once: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` You will need to start a new shell for this setup to take effect. ### Fish To load completions in your current shell session: ```console frankenphp completion fish | source ``` To load completions for every new session, execute once: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell To load completions in your current shell session: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` To load completions for every new session, execute once: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` You will need to start a new shell for this setup to take effect. You will need to start a new shell for this setup to take effect. ================================================ FILE: docs/docker.md ================================================ # Building Custom Docker Image [FrankenPHP Docker images](https://hub.docker.com/r/dunglas/frankenphp) are based on [official PHP images](https://hub.docker.com/_/php/). Debian and Alpine Linux variants are provided for popular architectures. Debian variants are recommended. Variants for PHP 8.2, 8.3, 8.4 and 8.5 are provided. The tags follow this pattern: `dunglas/frankenphp:-php-` - `` and `` are version numbers of FrankenPHP and PHP respectively, ranging from major (e.g. `1`), minor (e.g. `1.2`) to patch versions (e.g. `1.2.3`). - `` is either `trixie` (for Debian Trixie), `bookworm` (for Debian Bookworm), or `alpine` (for the latest stable version of Alpine). [Browse tags](https://hub.docker.com/r/dunglas/frankenphp/tags). ## How to Use The Images Create a `Dockerfile` in your project: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Then, run these commands to build and run the Docker image: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## How to Tweak the Configuration For convenience, [a default `Caddyfile`](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) containing useful environment variables is provided in the image. ## How to Install More PHP Extensions The [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) script is provided in the base image. Adding additional PHP extensions is straightforward: ```dockerfile FROM dunglas/frankenphp # add additional extensions here: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## How to Install More Caddy Modules FrankenPHP is built on top of Caddy, and all [Caddy modules](https://caddyserver.com/docs/modules/) can be used with FrankenPHP. The easiest way to install custom Caddy modules is to use [xcaddy](https://github.com/caddyserver/xcaddy): ```dockerfile FROM dunglas/frankenphp:builder AS builder # Copy xcaddy in the builder image COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # CGO must be enabled to build FrankenPHP RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure and Vulcain are included in the official build, but feel free to remove them --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Add extra Caddy modules here FROM dunglas/frankenphp AS runner # Replace the official binary by the one contained your custom modules COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` The `builder` image provided by FrankenPHP contains a compiled version of `libphp`. [Builders images](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) are provided for all versions of FrankenPHP and PHP, both for Debian and Alpine. > [!TIP] > > If you're using Alpine Linux and Symfony, > you may need to [increase the default stack size](compile.md#using-xcaddy). ## Enabling the Worker Mode by Default Set the `FRANKENPHP_CONFIG` environment variable to start FrankenPHP with a worker script: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Using a Volume in Development To develop easily with FrankenPHP, mount the directory from your host containing the source code of the app as a volume in the Docker container: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > The `--tty` option allows to have nice human-readable logs instead of JSON logs. With Docker Compose: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # uncomment the following line if you want to use a custom Dockerfile #build: . # uncomment the following line if you want to run this in a production environment # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # comment the following line in production, it allows to have nice human-readable logs in dev tty: true # Volumes needed for Caddy certificates and configuration volumes: caddy_data: caddy_config: ``` ## Running as a Non-Root User FrankenPHP can run as non-root user in Docker. Here is a sample `Dockerfile` doing this: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" for alpine based distros useradd ${USER}; \ # Add additional capability to bind to port 80 and 443 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # Give write access to /config/caddy and /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Running With No Capabilities Even when running rootless, FrankenPHP needs the `CAP_NET_BIND_SERVICE` capability to bind the web server on privileged ports (80 and 443). If you expose FrankenPHP on a non-privileged port (1024 and above), it's possible to run the webserver as a non-root user, and without the need for any capability: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" for alpine based distros useradd ${USER}; \ # Remove default capability setcap -r /usr/local/bin/frankenphp; \ # Give write access to /config/caddy and /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Next, set the `SERVER_NAME` environment variable to use an unprivileged port. Example: `:8000` ## Updates The Docker images are built: - when a new release is tagged - daily at 4 am UTC, if new versions of the official PHP images are available ## Hardening Images To further reduce the attack surface and size of your FrankenPHP Docker images, it's also possible to build them on top of a [Google distroless](https://github.com/GoogleContainerTools/distroless) or [Docker hardened](https://www.docker.com/products/hardened-images) image. > [!WARNING] > These minimal base images do not include a shell or package manager, which makes debugging more difficult. > They are therefore recommended only for production if security is a high priority. When adding additional PHP extensions, you will need an intermediate build stage: ```dockerfile FROM dunglas/frankenphp AS builder # Add additional PHP extensions here RUN install-php-extensions pdo_mysql pdo_pgsql #... # Copy shared libs of frankenphp and all installed extensions to temporary location # You can also do this step manually by analyzing ldd output of frankenphp binary and each extension .so file RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Distroless debian base image, make sure this is the same debian version as the base image FROM gcr.io/distroless/base-debian13 # Docker hardened image alternative # FROM dhi.io/debian:13 # Location of your app and Caddyfile to be copied into the container ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Copy your app into /app # For further hardening make sure only writable paths are owned by the nonroot user COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # Copy frankenphp and necessary libs COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # Copy php.ini configuration files COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Caddy data dirs — must be writable for nonroot, even on a read-only root filesystem ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # entrypoint to run frankenphp with the provided Caddyfile ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Development Versions Development versions are available in the [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev) Docker repository. A new build is triggered every time a commit is pushed to the main branch of the GitHub repository. The `latest*` tags point to the head of the `main` branch. Tags of the form `sha-` are also available. ================================================ FILE: docs/early-hints.md ================================================ # Early Hints FrankenPHP natively supports the [103 Early Hints status code](https://developer.chrome.com/blog/early-hints/). Using Early Hints can improve the load time of your web pages by 30%. ```php ; rel=preload; as=style'); headers_send(103); // your slow algorithms and SQL queries 🤪 echo <<<'HTML' Hello FrankenPHP HTML; ``` Early Hints are supported both by the normal and the [worker](worker.md) modes. ================================================ FILE: docs/embed.md ================================================ # PHP Apps As Standalone Binaries FrankenPHP has the ability to embed the source code and assets of PHP applications in a static, self-contained binary. Thanks to this feature, PHP applications can be distributed as standalone binaries that include the application itself, the PHP interpreter, and Caddy, a production-level web server. Learn more about this feature [in the presentation made by Kévin at SymfonyCon 2023](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/). For embedding Laravel applications, [read this specific documentation entry](laravel.md#laravel-apps-as-standalone-binaries). ## Preparing Your App Before creating the self-contained binary be sure that your app is ready for embedding. For instance, you likely want to: - Install the production dependencies of the app - Dump the autoloader - Enable the production mode of your application (if any) - Strip unneeded files such as `.git` or tests to reduce the size of your final binary For instance, for a Symfony app, you can use the following commands: ```console # Export the project to get rid of .git/, etc mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # Set proper environment variables echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Remove the tests and other unneeded files to save space # Alternatively, add these files with the export-ignore attribute in your .gitattributes file rm -Rf tests/ # Install the dependencies composer install --ignore-platform-reqs --no-dev -a # Optimize .env composer dump-env prod ``` ### Customizing the Configuration To customize [the configuration](config.md), you can put a `Caddyfile` as well as a `php.ini` file in the main directory of the app to be embedded (`$TMPDIR/my-prepared-app` in the previous example). ## Creating a Linux Binary The easiest way to create a Linux binary is to use the Docker-based builder we provide. 1. Create a file named `static-build.Dockerfile` in the repository of your app: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # If you intend to run the binary on musl-libc systems, use static-builder-musl instead # Copy your app WORKDIR /go/src/app/dist/app COPY . . # Build the static binary WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Some `.dockerignore` files (e.g. default [Symfony Docker `.dockerignore`](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > will ignore the `vendor/` directory and `.env` files. Be sure to adjust or remove the `.dockerignore` file before the build. 2. Build: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. Extract the binary: ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` The resulting binary is the file named `my-app` in the current directory. ## Creating a Binary for Other OSes If you don't want to use Docker, or want to build a macOS binary, use the shell script we provide: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` The resulting binary is the file named `frankenphp--` in the `dist/` directory. ## Using The Binary This is it! The `my-app` file (or `dist/frankenphp--` on other OSes) contains your self-contained app! To start the web app run: ```console ./my-app php-server ``` If your app contains a [worker script](worker.md), start the worker with something like: ```console ./my-app php-server --worker public/index.php ``` To enable HTTPS (a Let's Encrypt certificate is automatically created), HTTP/2, and HTTP/3, specify the domain name to use: ```console ./my-app php-server --domain localhost ``` You can also run the PHP CLI scripts embedded in your binary: ```console ./my-app php-cli bin/console ``` ## PHP Extensions By default, the script will build extensions required by the `composer.json` file of your project, if any. If the `composer.json` file doesn't exist, the default extensions are built, as documented in [the static builds entry](static.md). To customize the extensions, use the `PHP_EXTENSIONS` environment variable. ## Customizing The Build [Read the static build documentation](static.md) to see how to customize the binary (extensions, PHP version...). ## Distributing The Binary On Linux, the created binary is compressed using [UPX](https://upx.github.io). On Mac, to reduce the size of the file before sending it, you can compress it. We recommend `xz`. ================================================ FILE: docs/es/CONTRIBUTING.md ================================================ # Contribuir ## Compilar PHP ### Con Docker (Linux) Construya la imagen Docker de desarrollo: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` La imagen contiene las herramientas de desarrollo habituales (Go, GDB, Valgrind, Neovim...) y utiliza las siguientes ubicaciones de configuración de PHP: - php.ini: `/etc/frankenphp/php.ini` Se proporciona un archivo php.ini con ajustes preestablecidos de desarrollo por defecto. - archivos de configuración adicionales: `/etc/frankenphp/php.d/*.ini` - extensiones php: `/usr/lib/frankenphp/modules/` Si su versión de Docker es inferior a 23.0, la construcción fallará debido a un [problema de patrón](https://github.com/moby/moby/pull/42676) en `.dockerignore`. Agregue los directorios a `.dockerignore`: ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### Sin Docker (Linux y macOS) [Siga las instrucciones para compilar desde las fuentes](compile.md) y pase la bandera de configuración `--debug`. ## Ejecutar la suite de pruebas ```console go test -tags watcher -race -v ./... ``` ## Módulo Caddy Construir Caddy con el módulo FrankenPHP: ```console cd caddy/frankenphp/ go build -tags watcher,brotli,nobadger,nomysql,nopgx cd ../../ ``` Ejecutar Caddy con el módulo FrankenPHP: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` El servidor está configurado para escuchar en la dirección `127.0.0.1:80`: > [!NOTE] > > Si está usando Docker, deberá enlazar el puerto 80 del contenedor o ejecutar desde dentro del contenedor. ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## Servidor de prueba mínimo Construir el servidor de prueba mínimo: ```console cd internal/testserver/ go build cd ../../ ``` Iniciar el servidor de prueba: ```console cd testdata/ ../internal/testserver/testserver ``` El servidor está configurado para escuchar en la dirección `127.0.0.1:8080`: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Construir localmente las imágenes Docker Mostrar el plan de compilación: ```console docker buildx bake -f docker-bake.hcl --print ``` Construir localmente las imágenes FrankenPHP para amd64: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` Construir localmente las imágenes FrankenPHP para arm64: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` Construir desde cero las imágenes FrankenPHP para arm64 y amd64 y subirlas a Docker Hub: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## Depurar errores de segmentación con las compilaciones estáticas 1. Descargue la versión de depuración del binario FrankenPHP desde GitHub o cree su propia compilación estática incluyendo símbolos de depuración: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. Reemplace su versión actual de `frankenphp` por el ejecutable de depuración de FrankenPHP. 3. Inicie FrankenPHP como de costumbre (alternativamente, puede iniciar FrankenPHP directamente con GDB: `gdb --args frankenphp run`). 4. Adjunte el proceso con GDB: ```console gdb -p `pidof frankenphp` ``` 5. Si es necesario, escriba `continue` en el shell de GDB. 6. Haga que FrankenPHP falle. 7. Escriba `bt` en el shell de GDB. 8. Copie la salida. ## Depurar errores de segmentación en GitHub Actions 1. Abrir `.github/workflows/tests.yml` 2. Activar los símbolos de depuración de la biblioteca PHP: ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. Activar `tmate` para conectarse al contenedor: ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. Conectarse al contenedor. 5. Abrir `frankenphp.go`. 6. Activar `cgosymbolizer`: ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Descargar el módulo: `go get`. 8. Dentro del contenedor, puede usar GDB y similares: ```console go test -tags watcher -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. Cuando el error esté corregido, revierta todos los cambios. ## Recursos diversos para el desarrollo - [Integración de PHP en uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [Integración de PHP en NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [Integración de PHP en Go (go-php)](https://github.com/deuill/go-php) - [Integración de PHP en Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [Integración de PHP en C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Extending and Embedding PHP por Sara Golemon](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [¿Qué es TSRMLS_CC, exactamente?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [Integración de PHP en Mac](https://gist.github.com/jonnywang/61427ffc0e8dde74fff40f479d147db4) - [Bindings SDL](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Recursos relacionados con Docker - [Definición del archivo Bake](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Comando útil ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## Traducir la documentación Para traducir la documentación y el sitio a un nuevo idioma, siga estos pasos: 1. Cree un nuevo directorio con el código ISO de 2 caracteres del idioma en el directorio `docs/` de este repositorio. 2. Copie todos los archivos `.md` de la raíz del directorio `docs/` al nuevo directorio (siempre use la versión en inglés como fuente de traducción, ya que siempre está actualizada). 3. Copie los archivos `README.md` y `CONTRIBUTING.md` del directorio raíz al nuevo directorio. 4. Traduzca el contenido de los archivos, pero no cambie los nombres de los archivos, tampoco traduzca las cadenas que comiencen por `> [!` (es un marcado especial para GitHub). 5. Cree una Pull Request con las traducciones. 6. En el [repositorio del sitio](https://github.com/dunglas/frankenphp-website/tree/main), copie y traduzca los archivos de traducción en los directorios `content/`, `data/` y `i18n/`. 7. Traduzca los valores en el archivo YAML creado. 8. Abra una Pull Request en el repositorio del sitio. ================================================ FILE: docs/es/README.md ================================================ # FrankenPHP: el servidor de aplicaciones PHP moderno, escrito en Go

FrankenPHP

FrankenPHP es un servidor de aplicaciones moderno para PHP construido sobre el servidor web [Caddy](https://caddyserver.com/). FrankenPHP otorga superpoderes a tus aplicaciones PHP gracias a sus características de vanguardia: [_Early Hints_](early-hints.md), [modo worker](worker.md), [funcionalidades en tiempo real](mercure.md), HTTPS automático, soporte para HTTP/2 y HTTP/3... FrankenPHP funciona con cualquier aplicación PHP y hace que tus proyectos Laravel y Symfony sean más rápidos que nunca gracias a sus integraciones oficiales con el modo worker. FrankenPHP también puede usarse como una biblioteca Go autónoma que permite integrar PHP en cualquier aplicación usando `net/http`. Descubre más detalles sobre este servidor de aplicaciones en la grabación de esta conferencia dada en el Forum PHP 2022: Diapositivas ## Para Comenzar En Windows, usa [WSL](https://learn.microsoft.com/es-es/windows/wsl/) para ejecutar FrankenPHP. ### Script de instalación Puedes copiar esta línea en tu terminal para instalar automáticamente una versión adaptada a tu plataforma: ```console curl https://frankenphp.dev/install.sh | sh ``` ### Binario autónomo Proporcionamos binarios estáticos de FrankenPHP para desarrollo, para Linux y macOS, conteniendo [PHP 8.4](https://www.php.net/releases/8.4/es.php) y la mayoría de las extensiones PHP populares. [Descargar FrankenPHP](https://github.com/php/frankenphp/releases) **Instalación de extensiones:** Las extensiones más comunes están incluidas. No es posible instalar más. ### Paquetes rpm Nuestros mantenedores proponen paquetes rpm para todos los sistemas que usan `dnf`. Para instalar, ejecuta: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 8.2-8.5 disponibles sudo dnf install frankenphp ``` **Instalación de extensiones:** `sudo dnf install php-zts-` Para extensiones no disponibles por defecto, usa [PIE](https://github.com/php/pie): ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Paquetes deb Nuestros mantenedores proponen paquetes deb para todos los sistemas que usan `apt`. Para instalar, ejecuta: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **Instalación de extensiones:** `sudo apt install php-zts-` Para extensiones no disponibles por defecto, usa [PIE](https://github.com/php/pie): ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker Las [imágenes Docker](https://frankenphp.dev/docs/es/docker/) también están disponibles: ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Ve a `https://localhost`, ¡listo! > [!TIP] > > No intentes usar `https://127.0.0.1`. Usa `https://localhost` y acepta el certificado auto-firmado. > Usa [la variable de entorno `SERVER_NAME`](config.md#variables-de-entorno) para cambiar el dominio a usar. ### Homebrew FrankenPHP también está disponible como paquete [Homebrew](https://brew.sh) para macOS y Linux. Para instalarlo: ```console brew install dunglas/frankenphp/frankenphp ``` **Instalación de extensiones:** Usa [PIE](https://github.com/php/pie). ### Uso Para servir el contenido del directorio actual, ejecuta: ```console frankenphp php-server ``` También puedes ejecutar scripts en línea de comandos con: ```console frankenphp php-cli /ruta/a/tu/script.php ``` Para los paquetes deb y rpm, también puedes iniciar el servicio systemd: ```console sudo systemctl start frankenphp ``` ## Documentación - [El modo clásico](classic.md) - [El modo worker](worker.md) - [Soporte para Early Hints (código de estado HTTP 103)](early-hints.md) - [Tiempo real](mercure.md) - [Hot reloading](https://frankenphp.dev/docs/hot-reload/) - [Registro de actividad](https://frankenphp.dev/docs/logging/) - [Servir eficientemente archivos estáticos grandes](x-sendfile.md) - [Configuración](config.md) - [Escribir extensiones PHP en Go](extensions.md) - [Imágenes Docker](docker.md) - [Despliegue en producción](production.md) - [Optimización del rendimiento](performance.md) - [Crear aplicaciones PHP **autónomas**, auto-ejecutables](embed.md) - [Crear una compilación estática](static.md) - [Compilar desde las fuentes](compile.md) - [Monitoreo de FrankenPHP](metrics.md) - [Integración con WordPress](https://frankenphp.dev/docs/wordpress/) - [Integración con Laravel](laravel.md) - [Problemas conocidos](known-issues.md) - [Aplicación de demostración (Symfony) y benchmarks](https://github.com/dunglas/frankenphp-demo) - [Documentación de la biblioteca Go](https://pkg.go.dev/github.com/dunglas/frankenphp) - [Contribuir y depurar](CONTRIBUTING.md) ## Ejemplos y esqueletos - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/distribution/) - [Laravel](laravel.md) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/es/classic.md ================================================ # Usando el Modo Clásico Sin ninguna configuración adicional, FrankenPHP opera en modo clásico. En este modo, FrankenPHP funciona como un servidor PHP tradicional, sirviendo directamente archivos PHP. Esto lo convierte en un reemplazo directo para PHP-FPM o Apache con mod_php. Al igual que Caddy, FrankenPHP acepta un número ilimitado de conexiones y utiliza un [número fijo de hilos](config.md#caddyfile-config) para atenderlas. La cantidad de conexiones aceptadas y en cola está limitada únicamente por los recursos disponibles del sistema. El *pool* de hilos de PHP opera con un número fijo de hilos inicializados al inicio, comparable al modo estático de PHP-FPM. También es posible permitir que los hilos [escale automáticamente en tiempo de ejecución](performance.md#max_threads), similar al modo dinámico de PHP-FPM. Las conexiones en cola esperarán indefinidamente hasta que un hilo de PHP esté disponible para atenderlas. Para evitar esto, puedes usar la configuración `max_wait_time` en la [configuración global de FrankenPHP](config.md#caddyfile-config) para limitar la duración que una petición puede esperar por un hilo de PHP libre antes de ser rechazada. Adicionalmente, puedes establecer un [tiempo límite de escritura razonable en Caddy](https://caddyserver.com/docs/caddyfile/options#timeouts). Cada instancia de Caddy iniciará solo un *pool* de hilos de FrankenPHP, el cual será compartido entre todos los bloques `php_server`. ================================================ FILE: docs/es/compile.md ================================================ # Compilar desde fuentes Este documento explica cómo crear un binario de FrankenPHP que cargará PHP como una biblioteca dinámica. Esta es la forma recomendada. Alternativamente, también se pueden crear [compilaciones estáticas y mayormente estáticas](static.md). ## Instalar PHP FrankenPHP es compatible con PHP 8.2 y versiones superiores. ### Con Homebrew (Linux y Mac) La forma más sencilla de instalar una versión de libphp compatible con FrankenPHP es usar los paquetes ZTS proporcionados por [Homebrew PHP](https://github.com/shivammathur/homebrew-php). Primero, si no lo ha hecho ya, instale [Homebrew](https://brew.sh). Luego, instale la variante ZTS de PHP, Brotli (opcional, para soporte de compresión) y watcher (opcional, para detección de cambios en archivos): ```console brew install shivammathur/php/php-zts brotli watcher brew link --overwrite --force shivammathur/php/php-zts ``` ### Compilando PHP Alternativamente, puede compilar PHP desde las fuentes con las opciones necesarias para FrankenPHP siguiendo estos pasos. Primero, [obtenga las fuentes de PHP](https://www.php.net/downloads.php) y extráigalas: ```console tar xf php-* cd php-*/ ``` Luego, ejecute el script `configure` con las opciones necesarias para su plataforma. Las siguientes banderas de `./configure` son obligatorias, pero puede agregar otras, por ejemplo, para compilar extensiones o características adicionales. #### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` #### Mac Use el gestor de paquetes [Homebrew](https://brew.sh/) para instalar las dependencias requeridas y opcionales: ```console brew install libiconv bison brotli re2c pkg-config watcher echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` Luego ejecute el script de configuración: ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` #### Compilar PHP Finalmente, compile e instale PHP: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Instalar dependencias opcionales Algunas características de FrankenPHP dependen de dependencias opcionales del sistema que deben instalarse. Alternativamente, estas características pueden deshabilitarse pasando etiquetas de compilación al compilador Go. | Característica | Dependencia | Etiqueta de compilación para deshabilitarla | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | Compresión Brotli | [Brotli](https://github.com/google/brotli) | nobrotli | | Reiniciar workers al cambiar archivos | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | | [Mercure](mercure.md) | [Biblioteca Mercure Go](https://pkg.go.dev/github.com/dunglas/mercure) (instalada automáticamente, licencia AGPL) | nomercure | ## Compilar la aplicación Go Ahora puede construir el binario final. ### Usando xcaddy La forma recomendada es usar [xcaddy](https://github.com/caddyserver/xcaddy) para compilar FrankenPHP. `xcaddy` también permite agregar fácilmente [módulos personalizados de Caddy](https://caddyserver.com/docs/modules/) y extensiones de FrankenPHP: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy \ --with github.com/dunglas/caddy-cbrotli # Agregue módulos adicionales de Caddy y extensiones de FrankenPHP aquí # opcionalmente, si desea compilar desde sus fuentes de frankenphp: # --with github.com/dunglas/frankenphp=$(pwd) \ # --with github.com/dunglas/frankenphp/caddy=$(pwd)/caddy ``` > [!TIP] > > Si está usando musl libc (predeterminado en Alpine Linux) y Symfony, > es posible que deba aumentar el tamaño de pila predeterminado. > De lo contrario, podría obtener errores como `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression` > > Para hacerlo, cambie la variable de entorno `XCADDY_GO_BUILD_FLAGS` a algo como: > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (cambie el valor del tamaño de pila según las necesidades de su aplicación). ### Sin xcaddy Alternativamente, es posible compilar FrankenPHP sin `xcaddy` usando directamente el comando `go`: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/es/config.md ================================================ # Configuración FrankenPHP, Caddy así como los módulos [Mercure](mercure.md) y [Vulcain](https://vulcain.rocks) pueden configurarse usando [los formatos soportados por Caddy](https://caddyserver.com/docs/getting-started#your-first-config). El formato más común es el `Caddyfile`, que es un formato de texto simple y legible. Por defecto, FrankenPHP buscará un `Caddyfile` en el directorio actual. Puede especificar una ruta personalizada con la opción `-c` o `--config`. Un `Caddyfile` mínimo para servir una aplicación PHP se muestra a continuación: ```caddyfile # El nombre de host al que responder localhost # Opcionalmente, el directorio desde el que servir archivos, por defecto es el directorio actual #root public/ php_server ``` Un `Caddyfile` más avanzado que habilita más características y proporciona variables de entorno convenientes está disponible [en el repositorio de FrankenPHP](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile), y con las imágenes de Docker. PHP en sí puede configurarse [usando un archivo `php.ini`](https://www.php.net/manual/es/configuration.file.php). Dependiendo de su método de instalación, FrankenPHP y el intérprete de PHP buscarán archivos de configuración en las ubicaciones descritas a continuación. ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: el archivo de configuración principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: archivos de configuración adicionales que se cargan automáticamente PHP: - `php.ini`: `/usr/local/etc/php/php.ini` (no se proporciona ningún `php.ini` por defecto) - archivos de configuración adicionales: `/usr/local/etc/php/conf.d/*.ini` - extensiones de PHP: `/usr/local/lib/php/extensions/no-debug-zts-/` - Debe copiar una plantilla oficial proporcionada por el proyecto PHP: ```dockerfile FROM dunglas/frankenphp # Producción: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # O desarrollo: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## Paquetes RPM y Debian FrankenPHP: - `/etc/frankenphp/Caddyfile`: el archivo de configuración principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: archivos de configuración adicionales que se cargan automáticamente PHP: - `php.ini`: `/etc/php-zts/php.ini` (se proporciona un archivo `php.ini` con ajustes de producción por defecto) - archivos de configuración adicionales: `/etc/php-zts/conf.d/*.ini` ## Binario estático FrankenPHP: - En el directorio de trabajo actual: `Caddyfile` PHP: - `php.ini`: El directorio en el que se ejecuta `frankenphp run` o `frankenphp php-server`, luego `/etc/frankenphp/php.ini` - archivos de configuración adicionales: `/etc/frankenphp/php.d/*.ini` - extensiones de PHP: no pueden cargarse, debe incluirlas en el binario mismo - copie uno de `php.ini-production` o `php.ini-development` proporcionados [en las fuentes de PHP](https://github.com/php/php-src/). ## Configuración de Caddyfile Las directivas `php_server` o `php` [de HTTP](https://caddyserver.com/docs/caddyfile/concepts#directives) pueden usarse dentro de los bloques de sitio para servir su aplicación PHP. Ejemplo mínimo: ```caddyfile localhost { # Habilitar compresión (opcional) encode zstd br gzip # Ejecutar archivos PHP en el directorio actual y servir activos php_server } ``` También puede configurar explícitamente FrankenPHP usando la [opción global](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp`: ```caddyfile { frankenphp { num_threads # Establece el número de hilos de PHP para iniciar. Por defecto: 2x el número de CPUs disponibles. max_threads # Limita el número de hilos de PHP adicionales que pueden iniciarse en tiempo de ejecución. Por defecto: num_threads. Puede establecerse como 'auto'. max_wait_time # Establece el tiempo máximo que una solicitud puede esperar por un hilo de PHP libre antes de agotar el tiempo de espera. Por defecto: deshabilitado. php_ini # Establece una directiva php.ini. Puede usarse varias veces para establecer múltiples directivas. worker { file # Establece la ruta al script del worker. num # Establece el número de hilos de PHP para iniciar, por defecto es 2x el número de CPUs disponibles. env # Establece una variable de entorno adicional con el valor dado. Puede especificarse más de una vez para múltiples variables de entorno. watch # Establece la ruta para observar cambios en archivos. Puede especificarse más de una vez para múltiples rutas. name # Establece el nombre del worker, usado en logs y métricas. Por defecto: ruta absoluta del archivo del worker max_consecutive_failures # Establece el número máximo de fallos consecutivos antes de que el worker se considere no saludable, -1 significa que el worker siempre se reiniciará. Por defecto: 6. } } } # ... ``` Alternativamente, puede usar la forma corta de una línea de la opción `worker`: ```caddyfile { frankenphp { worker } } # ... ``` También puede definir múltiples workers si sirve múltiples aplicaciones en el mismo servidor: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # permite un mejor almacenamiento en caché worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` Usar la directiva `php_server` es generalmente lo que necesita, pero si necesita un control total, puede usar la directiva de bajo nivel `php`. La directiva `php` pasa toda la entrada a PHP, en lugar de verificar primero si es un archivo PHP o no. Lea más sobre esto en la [página de rendimiento](performance.md#try_files). Usar la directiva `php_server` es equivalente a esta configuración: ```caddyfile route { # Agrega barra final para solicitudes de directorio @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # Si el archivo solicitado no existe, intenta archivos índice @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # ¡FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` Las directivas `php_server` y `php` tienen las siguientes opciones: ```caddyfile php_server [] { root # Establece la carpeta raíz del sitio. Por defecto: directiva `root`. split_path # Establece las subcadenas para dividir la URI en dos partes. La primera subcadena coincidente se usará para dividir la "información de ruta" del path. La primera parte se sufija con la subcadena coincidente y se asumirá como el nombre del recurso real (script CGI). La segunda parte se establecerá como PATH_INFO para que el script la use. Por defecto: `.php` resolve_root_symlink false # Desactiva la resolución del directorio `root` a su valor real evaluando un enlace simbólico, si existe (habilitado por defecto). env # Establece una variable de entorno adicional con el valor dado. Puede especificarse más de una vez para múltiples variables de entorno. file_server off # Desactiva la directiva incorporada file_server. worker { # Crea un worker específico para este servidor. Puede especificarse más de una vez para múltiples workers. file # Establece la ruta al script del worker, puede ser relativa a la raíz de php_server num # Establece el número de hilos de PHP para iniciar, por defecto es 2x el número de CPUs disponibles. name # Establece el nombre para el worker, usado en logs y métricas. Por defecto: ruta absoluta del archivo del worker. Siempre comienza con m# cuando se define en un bloque php_server. watch # Establece la ruta para observar cambios en archivos. Puede especificarse más de una vez para múltiples rutas. env # Establece una variable de entorno adicional con el valor dado. Puede especificarse más de una vez para múltiples variables de entorno. Las variables de entorno para este worker también se heredan del php_server padre, pero pueden sobrescribirse aquí. match # hace coincidir el worker con un patrón de ruta. Anula try_files y solo puede usarse en la directiva php_server. } worker # También puede usar la forma corta como en el bloque global frankenphp. } ``` ### Observando cambios en archivos Dado que los workers solo inician su aplicación una vez y la mantienen en memoria, cualquier cambio en sus archivos PHP no se reflejará inmediatamente. Los workers pueden reiniciarse al cambiar archivos mediante la directiva `watch`. Esto es útil para entornos de desarrollo. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` Esta función se utiliza frecuentemente en combinación con [hot reload](hot-reload.md). Si el directorio `watch` no está especificado, retrocederá a `./**/*.{env,php,twig,yaml,yml}`, lo cual vigila todos los archivos `.env`, `.php`, `.twig`, `.yaml` y `.yml` en el directorio y subdirectorios donde se inició el proceso de FrankenPHP. También puede especificar uno o más directorios mediante un [patrón de nombres de ficheros de shell](https://pkg.go.dev/path/filepath#Match): ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # observa todos los archivos en todos los subdirectorios de /path/to/app watch /path/to/app/*.php # observa archivos que terminan en .php en /path/to/app watch /path/to/app/**/*.php # observa archivos PHP en /path/to/app y subdirectorios watch /path/to/app/**/*.{php,twig} # observa archivos PHP y Twig en /path/to/app y subdirectorios } } } ``` - El patrón `**` significa observación recursiva - Los directorios también pueden ser relativos (al lugar donde se inicia el proceso de FrankenPHP) - Si tiene múltiples workers definidos, todos ellos se reiniciarán cuando cambie un archivo - Tenga cuidado al observar archivos que se crean en tiempo de ejecución (como logs) ya que podrían causar reinicios no deseados de workers. El observador de archivos se basa en [e-dant/watcher](https://github.com/e-dant/watcher). ## Coincidencia del worker con una ruta En aplicaciones PHP tradicionales, los scripts siempre se colocan en el directorio público. Esto también es cierto para los scripts de workers, que se tratan como cualquier otro script PHP. Si desea colocar el script del worker fuera del directorio público, puede hacerlo mediante la directiva `match`. La directiva `match` es una alternativa optimizada a `try_files` solo disponible dentro de `php_server` y `php`. El siguiente ejemplo siempre servirá un archivo en el directorio público si está presente y de lo contrario reenviará la solicitud al worker que coincida con el patrón de ruta. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # el archivo puede estar fuera de la ruta pública match /api/* # todas las solicitudes que comiencen con /api/ serán manejadas por este worker } } } } ``` ## Variables de entorno Las siguientes variables de entorno pueden usarse para inyectar directivas de Caddy en el `Caddyfile` sin modificarlo: - `SERVER_NAME`: cambia [las direcciones en las que escuchar](https://caddyserver.com/docs/caddyfile/concepts#addresses), los nombres de host proporcionados también se usarán para el certificado TLS generado - `SERVER_ROOT`: cambia el directorio raíz del sitio, por defecto es `public/` - `CADDY_GLOBAL_OPTIONS`: inyecta [opciones globales](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG`: inyecta configuración bajo la directiva `frankenphp` Al igual que en FPM y SAPIs CLI, las variables de entorno se exponen por defecto en la superglobal `$_SERVER`. El valor `S` de [la directiva `variables_order` de PHP](https://www.php.net/manual/en/ini.core.php#ini.variables-order) siempre es equivalente a `ES` independientemente de la ubicación de `E` en otro lugar de esta directiva. ## Configuración de PHP Para cargar [archivos de configuración adicionales de PHP](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan), puede usarse la variable de entorno `PHP_INI_SCAN_DIR`. Cuando se establece, PHP cargará todos los archivos con la extensión `.ini` presentes en los directorios dados. También puede cambiar la configuración de PHP usando la directiva `php_ini` en el `Caddyfile`: ```caddyfile { frankenphp { php_ini memory_limit 256M # o php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### Deshabilitar HTTPS Por defecto, FrankenPHP habilitará automáticamente HTTPS para todos los nombres de host, incluyendo `localhost`. Si desea deshabilitar HTTPS (por ejemplo en un entorno de desarrollo), puede establecer la variable de entorno `SERVER_NAME` a `http://` o `:80`: Alternativamente, puede usar todos los otros métodos descritos en la [documentación de Caddy](https://caddyserver.com/docs/automatic-https#activation). Si desea usar HTTPS con la dirección IP `127.0.0.1` en lugar del nombre de host `localhost`, lea la sección de [problemas conocidos](known-issues.md#using-https127001-with-docker). ### Dúplex completo (HTTP/1) Al usar HTTP/1.x, puede ser deseable habilitar el modo dúplex completo para permitir escribir una respuesta antes de que se haya leído todo el cuerpo (por ejemplo: [Mercure](mercure.md), WebSocket, Eventos enviados por el servidor, etc.). Esta es una configuración opcional que debe agregarse a las opciones globales en el `Caddyfile`: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > Habilitar esta opción puede causar que clientes HTTP/1.x antiguos que no soportan dúplex completo se bloqueen. > Esto también puede configurarse usando la configuración de entorno `CADDY_GLOBAL_OPTIONS`: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` Puede encontrar más información sobre esta configuración en la [documentación de Caddy](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex). ## Habilitar el modo de depuración Al usar la imagen de Docker, establezca la variable de entorno `CADDY_GLOBAL_OPTIONS` a `debug` para habilitar el modo de depuración: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ================================================ FILE: docs/es/docker.md ================================================ # Construir una imagen Docker personalizada Las [imágenes Docker de FrankenPHP](https://hub.docker.com/r/dunglas/frankenphp) están basadas en [imágenes oficiales de PHP](https://hub.docker.com/_/php/). Se proporcionan variantes para Debian y Alpine Linux en arquitecturas populares. Se recomiendan las variantes de Debian. Se proporcionan variantes para PHP 8.2, 8.3, 8.4 y 8.5. Las etiquetas siguen este patrón: `dunglas/frankenphp:-php-` - `` y `` son los números de versión de FrankenPHP y PHP respectivamente, que van desde versiones principales (ej. `1`), menores (ej. `1.2`) hasta versiones de parche (ej. `1.2.3`). - `` es `trixie` (para Debian Trixie), `bookworm` (para Debian Bookworm) o `alpine` (para la última versión estable de Alpine). [Explorar etiquetas](https://hub.docker.com/r/dunglas/frankenphp/tags). ## Cómo usar las imágenes Cree un archivo `Dockerfile` en su proyecto: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Luego, ejecute estos comandos para construir y ejecutar la imagen Docker: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## Cómo ajustar la configuración Para mayor comodidad, se proporciona en la imagen un [archivo `Caddyfile` predeterminado](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) que contiene variables de entorno útiles. ## Cómo instalar más extensiones de PHP El script [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) está disponible en la imagen base. Agregar extensiones adicionales de PHP es sencillo: ```dockerfile FROM dunglas/frankenphp # agregue extensiones adicionales aquí: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Cómo instalar más módulos de Caddy FrankenPHP está construido sobre Caddy, y todos los [módulos de Caddy](https://caddyserver.com/docs/modules/) pueden usarse con FrankenPHP. La forma más fácil de instalar módulos personalizados de Caddy es usar [xcaddy](https://github.com/caddyserver/xcaddy): ```dockerfile FROM dunglas/frankenphp:builder AS builder # Copie xcaddy en la imagen del constructor COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # CGO debe estar habilitado para construir FrankenPHP RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure y Vulcain están incluidos en la compilación oficial, pero puede eliminarlos si lo desea --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Agregue módulos adicionales de Caddy aquí FROM dunglas/frankenphp AS runner # Reemplace el binario oficial por el que contiene sus módulos personalizados COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` La imagen `builder` proporcionada por FrankenPHP contiene una versión compilada de `libphp`. Se proporcionan [imágenes de constructor](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) para todas las versiones de FrankenPHP y PHP, tanto para Debian como para Alpine. > [!TIP] > > Si está usando Alpine Linux y Symfony, > es posible que deba [aumentar el tamaño de pila predeterminado](compile.md#using-xcaddy). ## Habilitar el modo Worker por defecto Establezca la variable de entorno `FRANKENPHP_CONFIG` para iniciar FrankenPHP con un script de worker: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Usar un volumen en desarrollo Para desarrollar fácilmente con FrankenPHP, monte el directorio de su host que contiene el código fuente de la aplicación como un volumen en el contenedor Docker: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > La opción `--tty` permite tener logs legibles en lugar de logs en formato JSON. Con Docker Compose: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # descomente la siguiente línea si desea usar un Dockerfile personalizado #build: . # descomente la siguiente línea si desea ejecutar esto en un entorno de producción # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # comente la siguiente línea en producción, permite tener logs legibles en desarrollo tty: true # Volúmenes necesarios para los certificados y configuración de Caddy volumes: caddy_data: caddy_config: ``` ## Ejecutar como usuario no root FrankenPHP puede ejecutarse como usuario no root en Docker. Aquí hay un ejemplo de `Dockerfile` que hace esto: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" para distribuciones basadas en alpine useradd ${USER}; \ # Agregar capacidad adicional para enlazar a los puertos 80 y 443 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # Dar acceso de escritura a /config/caddy y /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Ejecutar sin capacidades Incluso cuando se ejecuta sin root, FrankenPHP necesita la capacidad `CAP_NET_BIND_SERVICE` para enlazar el servidor web en puertos privilegiados (80 y 443). Si expone FrankenPHP en un puerto no privilegiado (1024 y superior), es posible ejecutar el servidor web como usuario no root, y sin necesidad de ninguna capacidad: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" para distribuciones basadas en alpine useradd ${USER}; \ # Eliminar la capacidad predeterminada setcap -r /usr/local/bin/frankenphp; \ # Dar acceso de escritura a /config/caddy y /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Luego, establezca la variable de entorno `SERVER_NAME` para usar un puerto no privilegiado. Ejemplo: `:8000` ## Actualizaciones Las imágenes Docker se construyen: - Cuando se etiqueta una nueva versión - Diariamente a las 4 am UTC, si hay nuevas versiones de las imágenes oficiales de PHP disponibles ## Endurecimiento de Imágenes Para reducir aún más la superficie de ataque y el tamaño de tus imágenes Docker de FrankenPHP, también es posible construirlas sobre una imagen [Google distroless](https://github.com/GoogleContainerTools/distroless) o [Docker hardened](https://www.docker.com/products/hardened-images). > [!WARNING] > Estas imágenes base mínimas no incluyen un shell ni gestor de paquetes, lo que hace que la depuración sea más difícil. > Por lo tanto, se recomiendan solo para producción si la seguridad es una alta prioridad. Cuando agregues extensiones PHP adicionales, necesitarás una etapa de construcción intermedia: ```dockerfile FROM dunglas/frankenphp AS builder # Agregar extensiones PHP adicionales aquí RUN install-php-extensions pdo_mysql pdo_pgsql #... # Copiar bibliotecas compartidas de frankenphp y todas las extensiones instaladas a una ubicación temporal # También puedes hacer este paso manualmente analizando la salida de ldd del binario frankenphp y cada archivo .so de extensión RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Imagen base distroless de Debian, asegúrate de que sea la misma versión de Debian que la imagen base FROM gcr.io/distroless/base-debian13 # Alternativa de imagen endurecida de Docker # FROM dhi.io/debian:13 # Ubicación de tu aplicación y Caddyfile que se copiará al contenedor ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Copiar tu aplicación en /app # Para mayor endurecimiento asegúrate de que solo las rutas escribibles sean propiedad del usuario nonroot COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # Copiar frankenphp y bibliotecas necesarias COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # Copiar archivos de configuración php.ini COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Directorios de datos de Caddy — deben ser escribibles para nonroot, incluso en un sistema de archivos raíz de solo lectura ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # punto de entrada para ejecutar frankenphp con el Caddyfile proporcionado ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Versiones de desarrollo Las versiones de desarrollo están disponibles en el [repositorio Docker `dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev). Se activa una nueva compilación cada vez que se envía un commit a la rama principal del repositorio de GitHub. Las etiquetas `latest*` apuntan a la cabeza de la rama `main`. También están disponibles etiquetas de la forma `sha-`. ================================================ FILE: docs/es/early-hints.md ================================================ # Early Hints (Pistas Tempranas) FrankenPHP soporta nativamente el [código de estado 103 Early Hints](https://developer.chrome.com/blog/early-hints/). El uso de Early Hints puede mejorar el tiempo de carga de sus páginas web hasta en un 30%. ```php ; rel=preload; as=style'); headers_send(103); // sus algoritmos lentos y consultas SQL 🤪 echo <<<'HTML' Hola FrankenPHP HTML; ``` Early Hints están soportados tanto en el modo normal como en el modo [worker](worker.md). ================================================ FILE: docs/es/embed.md ================================================ # Aplicaciones PHP como Binarios Autónomos FrankenPHP tiene la capacidad de incrustar el código fuente y los activos de aplicaciones PHP en un binario estático y autónomo. Gracias a esta característica, las aplicaciones PHP pueden distribuirse como binarios autónomos que incluyen la aplicación en sí, el intérprete de PHP y Caddy, un servidor web de nivel de producción. Obtenga más información sobre esta característica [en la presentación realizada por Kévin en SymfonyCon 2023](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/). Para incrustar aplicaciones Laravel, [lea esta entrada específica de documentación](laravel.md#laravel-apps-as-standalone-binaries). ## Preparando su Aplicación Antes de crear el binario autónomo, asegúrese de que su aplicación esté lista para ser incrustada. Por ejemplo, probablemente querrá: - Instalar las dependencias de producción de la aplicación - Volcar el autoload - Activar el modo de producción de su aplicación (si lo hay) - Eliminar archivos innecesarios como `.git` o pruebas para reducir el tamaño de su binario final Por ejemplo, para una aplicación Symfony, puede usar los siguientes comandos: ```console # Exportar el proyecto para deshacerse de .git/, etc. mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # Establecer las variables de entorno adecuadas echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Eliminar las pruebas y otros archivos innecesarios para ahorrar espacio # Alternativamente, agregue estos archivos con el atributo export-ignore en su archivo .gitattributes rm -Rf tests/ # Instalar las dependencias composer install --ignore-platform-reqs --no-dev -a # Optimizar .env composer dump-env prod ``` ### Personalizar la Configuración Para personalizar [la configuración](config.md), puede colocar un archivo `Caddyfile` así como un archivo `php.ini` en el directorio principal de la aplicación a incrustar (`$TMPDIR/my-prepared-app` en el ejemplo anterior). ## Crear un Binario para Linux La forma más fácil de crear un binario para Linux es usar el constructor basado en Docker que proporcionamos. 1. Cree un archivo llamado `static-build.Dockerfile` en el repositorio de su aplicación: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Si tiene la intención de ejecutar el binario en sistemas musl-libc, use static-builder-musl en su lugar # Copie su aplicación WORKDIR /go/src/app/dist/app COPY . . # Construya el binario estático WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Algunos archivos `.dockerignore` (por ejemplo, el [`.dockerignore` predeterminado de Symfony Docker](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > ignorarán el directorio `vendor/` y los archivos `.env`. Asegúrese de ajustar o eliminar el archivo `.dockerignore` antes de la construcción. 2. Construya: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. Extraiga el binario: ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` El binario resultante es el archivo llamado `my-app` en el directorio actual. ## Crear un Binario para Otros Sistemas Operativos Si no desea usar Docker o desea construir un binario para macOS, use el script de shell que proporcionamos: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` El binario resultante es el archivo llamado `frankenphp--` en el directorio `dist/`. ## Usar el Binario ¡Listo! El archivo `my-app` (o `dist/frankenphp--` en otros sistemas operativos) contiene su aplicación autónoma. Para iniciar la aplicación web, ejecute: ```console ./my-app php-server ``` Si su aplicación contiene un [script worker](worker.md), inicie el worker con algo como: ```console ./my-app php-server --worker public/index.php ``` Para habilitar HTTPS (se crea automáticamente un certificado de Let's Encrypt), HTTP/2 y HTTP/3, especifique el nombre de dominio a usar: ```console ./my-app php-server --domain localhost ``` También puede ejecutar los scripts CLI de PHP incrustados en su binario: ```console ./my-app php-cli bin/console ``` ## Extensiones de PHP Por defecto, el script construirá las extensiones requeridas por el archivo `composer.json` de su proyecto, si existe. Si el archivo `composer.json` no existe, se construirán las extensiones predeterminadas, como se documenta en [la entrada de compilaciones estáticas](static.md). Para personalizar las extensiones, use la variable de entorno `PHP_EXTENSIONS`. ## Personalizar la Compilación [Lea la documentación de compilación estática](static.md) para ver cómo personalizar el binario (extensiones, versión de PHP, etc.). ## Distribuir el Binario En Linux, el binario creado se comprime usando [UPX](https://upx.github.io). En Mac, para reducir el tamaño del archivo antes de enviarlo, puede comprimirlo. Recomendamos `xz`. ================================================ FILE: docs/es/extension-workers.md ================================================ # Extension Workers Los Extension Workers permiten que tu [extensión FrankenPHP](https://frankenphp.dev/docs/extensions/) gestione un pool dedicado de hilos PHP para ejecutar tareas en segundo plano, manejar eventos asíncronos o implementar protocolos personalizados. Útil para sistemas de colas, listeners de eventos, programadores, etc. ## Registrando el Worker ### Registro Estático Si no necesitas hacer que el worker sea configurable por el usuario (ruta de script fija, número fijo de hilos), simplemente puedes registrar el worker en la función `init()`. ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // Manejador global para comunicarse con el pool de workers var worker frankenphp.Workers func init() { // Registrar el worker cuando se carga el módulo. worker = caddy.RegisterWorkers( "my-internal-worker", // Nombre único "worker.php", // Ruta del script (relativa a la ejecución o absoluta) 2, // Número fijo de hilos // Hooks de ciclo de vida opcionales frankenphp.WithWorkerOnServerStartup(func() { // Lógica de configuración global... }), ) } ``` ### En un Módulo Caddy (Configurable por el usuario) Si planeas compartir tu extensión (como una cola genérica o listener de eventos), deberías envolverla en un módulo Caddy. Esto permite a los usuarios configurar la ruta del script y el número de hilos a través de su `Caddyfile`. Esto requiere implementar la interfaz `caddy.Provisioner` y analizar el Caddyfile ([ver un ejemplo](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)). ### En una Aplicación Go Pura (Embedding) Si estás [embebiendo FrankenPHP en una aplicación Go estándar sin caddy](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), puedes registrar extension workers usando `frankenphp.WithExtensionWorkers` al inicializar las opciones. ## Interactuando con Workers Una vez que el pool de workers está activo, puedes enviar tareas a él. Esto se puede hacer dentro de [funciones nativas exportadas a PHP](https://frankenphp.dev/docs/extensions/#writing-the-extension), o desde cualquier lógica Go como un programador cron, un listener de eventos (MQTT, Kafka), o cualquier otra goroutine. ### Modo Sin Cabeza: `SendMessage` Usa `SendMessage` para pasar datos sin procesar directamente a tu script worker. Esto es ideal para colas o comandos simples. #### Ejemplo: Una Extensión de Cola Asíncrona ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. Asegurar que el worker esté listo if worker == nil { return false } // 2. Enviar al worker en segundo plano _, err := worker.SendMessage( context.Background(), // Contexto estándar de Go unsafe.Pointer(data), // Datos para pasar al worker nil, // http.ResponseWriter opcional ) return err == nil } ``` ### Emulación HTTP: `SendRequest` Usa `SendRequest` si tu extensión necesita invocar un script PHP que espera un entorno web estándar (poblando `$_SERVER`, `$_GET`, etc.). ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. Preparar la solicitud y el grabador url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. Enviar al worker if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Devolver la respuesta capturada return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Script Worker El script worker PHP se ejecuta en un bucle y puede manejar tanto mensajes sin procesar como solicitudes HTTP. ```php [!TIP] > Si quieres entender cómo se pueden escribir extensiones en Go desde cero, puedes leer la sección de implementación manual a continuación que demuestra cómo escribir una extensión PHP en Go sin usar el generador. Ten en cuenta que esta herramienta **no es un generador de extensiones completo**. Está diseñada para ayudarte a escribir extensiones simples en Go, pero no proporciona las características más avanzadas de las extensiones PHP. Si necesitas escribir una extensión más **compleja y optimizada**, es posible que necesites escribir algo de código C o usar CGO directamente. ### Requisitos Previos Como se cubre en la sección de implementación manual a continuación, necesitas [obtener las fuentes de PHP](https://www.php.net/downloads.php) y crear un nuevo módulo Go. #### Crear un Nuevo Módulo y Obtener las Fuentes de PHP El primer paso para escribir una extensión PHP en Go es crear un nuevo módulo Go. Puedes usar el siguiente comando para esto: ```console go mod init ejemplo.com/ejemplo ``` El segundo paso es [obtener las fuentes de PHP](https://www.php.net/downloads.php) para los siguientes pasos. Una vez que las tengas, descomprímelas en el directorio de tu elección, no dentro de tu módulo Go: ```console tar xf php-* ``` ### Escribiendo la Extensión Todo está listo para escribir tu función nativa en Go. Crea un nuevo archivo llamado `stringext.go`. Nuestra primera función tomará una cadena como argumento, el número de veces para repetirla, un booleano para indicar si invertir la cadena, y devolverá la cadena resultante. Esto debería verse así: ```go package ejemplo // #include import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` Hay dos cosas importantes a tener en cuenta aquí: - Un comentario de directiva `//export_php:function` define la firma de la función en PHP. Así es como el generador sabe cómo generar la función PHP con los parámetros y tipo de retorno correctos; - La función debe devolver un `unsafe.Pointer`. FrankenPHP proporciona una API para ayudarte con la manipulación de tipos entre C y Go. Mientras que el primer punto se explica por sí mismo, el segundo puede ser más difícil de entender. Profundicemos en la manipulación de tipos en la siguiente sección. ### Manipulación de Tipos Aunque algunos tipos de variables tienen la misma representación en memoria entre C/PHP y Go, algunos tipos requieren más lógica para ser usados directamente. Esta es quizá la parte más difícil cuando se trata de escribir extensiones porque requiere entender los internos del motor Zend y cómo se almacenan las variables internamente en PHP. Esta tabla resume lo que necesitas saber: | Tipo PHP | Tipo Go | Conversión directa | Helper de C a Go | Helper de Go a C | Soporte para Métodos de Clase | |---------------------|--------------------------------|---------------------|---------------------------------------|----------------------------------------|-------------------------------| | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | `frankenphp.GoString()` | `frankenphp.PHPString()` | ✅ | | `array` | `frankenphp.AssociativeArray` | ❌ | `frankenphp.GoAssociativeArray()` | `frankenphp.PHPAssociativeArray()` | ✅ | | `array` | `map[string]any` | ❌ | `frankenphp.GoMap()` | `frankenphp.PHPMap()` | ✅ | | `array` | `[]any` | ❌ | `frankenphp.GoPackedArray()` | `frankenphp.PHPPackedArray()` | ✅ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `callable` | `*C.zval` | ❌ | - | frankenphp.CallPHPCallable() | ❌ | | `object` | `struct` | ❌ | _Aún no implementado_ | _Aún no implementado_ | ❌ | > [!NOTE] > > Esta tabla aún no es exhaustiva y se completará a medida que la API de tipos de FrankenPHP se vuelva más completa. > > Para métodos de clase específicamente, los tipos primitivos y los arrays están actualmente soportados. Los objetos aún no pueden usarse como parámetros de métodos o tipos de retorno. Si te refieres al fragmento de código de la sección anterior, puedes ver que se usan helpers para convertir el primer parámetro y el valor de retorno. El segundo y tercer parámetro de nuestra función `repeat_this()` no necesitan ser convertidos ya que la representación en memoria de los tipos subyacentes es la misma para C y Go. #### Trabajando con Arrays FrankenPHP proporciona soporte nativo para arrays PHP a través de `frankenphp.AssociativeArray` o conversión directa a un mapa o slice. `AssociativeArray` representa un [mapa hash](https://es.wikipedia.org/wiki/Tabla_hash) compuesto por un campo `Map: map[string]any` y un campo opcional `Order: []string` (a diferencia de los "arrays asociativos" de PHP, los mapas de Go no están ordenados). Si no se necesita orden o asociación, también es posible convertir directamente a un slice `[]any` o un mapa no ordenado `map[string]any`. **Creando y manipulando arrays en Go:** ```go package ejemplo // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:function process_data_ordered(array $input): array func process_data_ordered_map(arr *C.zend_array) unsafe.Pointer { // Convertir array asociativo PHP a Go manteniendo el orden associativeArray, err := frankenphp.GoAssociativeArray[any](unsafe.Pointer(arr)) if err != nil { // manejar error } // iterar sobre las entradas en orden for _, key := range associativeArray.Order { value, _ = associativeArray.Map[key] // hacer algo con key y value } // devolver un array ordenado // si 'Order' no está vacío, solo se respetarán los pares clave-valor en 'Order' return frankenphp.PHPAssociativeArray[string](frankenphp.AssociativeArray[string]{ Map: map[string]string{ "clave1": "valor1", "clave2": "valor2", }, Order: []string{"clave1", "clave2"}, }) } // export_php:function process_data_unordered(array $input): array func process_data_unordered_map(arr *C.zend_array) unsafe.Pointer { // Convertir array asociativo PHP a un mapa Go sin mantener el orden // ignorar el orden será más eficiente goMap, err := frankenphp.GoMap[any](unsafe.Pointer(arr)) if err != nil { // manejar error } // iterar sobre las entradas sin un orden específico for key, value := range goMap { // hacer algo con key y value } // devolver un array no ordenado return frankenphp.PHPMap(map[string]string { "clave1": "valor1", "clave2": "valor2", }) } // export_php:function process_data_packed(array $input): array func process_data_packed(arr *C.zend_array) unsafe.Pointer { // Convertir array empaquetado PHP a Go goSlice, err := frankenphp.GoPackedArray(unsafe.Pointer(arr)) if err != nil { // manejar error } // iterar sobre el slice en orden for index, value := range goSlice { // hacer algo con index y value } // devolver un array empaquetado return frankenphp.PHPPackedArray([]string{"valor1", "valor2", "valor3"}) } ``` **Características clave de la conversión de arrays:** - **Pares clave-valor ordenados** - Opción para mantener el orden del array asociativo - **Optimizado para múltiples casos** - Opción para prescindir del orden para un mejor rendimiento o convertir directamente a un slice - **Detección automática de listas** - Al convertir a PHP, detecta automáticamente si el array debe ser una lista empaquetada o un mapa hash - **Arrays Anidados** - Los arrays pueden estar anidados y convertirán automáticamente todos los tipos soportados (`int64`, `float64`, `string`, `bool`, `nil`, `AssociativeArray`, `map[string]any`, `[]any`) - **Objetos no soportados** - Actualmente, solo se pueden usar tipos escalares y arrays como valores. Proporcionar un objeto resultará en un valor `null` en el array PHP. ##### Métodos Disponibles: Empaquetados y Asociativos - `frankenphp.PHPAssociativeArray(arr frankenphp.AssociativeArray) unsafe.Pointer` - Convertir a un array PHP ordenado con pares clave-valor - `frankenphp.PHPMap(arr map[string]any) unsafe.Pointer` - Convertir un mapa a un array PHP no ordenado con pares clave-valor - `frankenphp.PHPPackedArray(slice []any) unsafe.Pointer` - Convertir un slice a un array PHP empaquetado con solo valores indexados - `frankenphp.GoAssociativeArray(arr unsafe.Pointer, ordered bool) frankenphp.AssociativeArray` - Convertir un array PHP a un `AssociativeArray` de Go ordenado (mapa con orden) - `frankenphp.GoMap(arr unsafe.Pointer) map[string]any` - Convertir un array PHP a un mapa Go no ordenado - `frankenphp.GoPackedArray(arr unsafe.Pointer) []any` - Convertir un array PHP a un slice Go - `frankenphp.IsPacked(zval *C.zend_array) bool` - Verificar si un array PHP está empaquetado (solo indexado) o es asociativo (pares clave-valor) ### Trabajando con Callables FrankenPHP proporciona una forma de trabajar con callables de PHP usando el helper `frankenphp.CallPHPCallable`. Esto te permite llamar a funciones o métodos de PHP desde código Go. Para mostrar esto, creemos nuestra propia función `array_map()` que toma un callable y un array, aplica el callable a cada elemento del array, y devuelve un nuevo array con los resultados: ```go // export_php:function my_array_map(array $data, callable $callback): array func my_array_map(arr *C.zend_array, callback *C.zval) unsafe.Pointer { goSlice, err := frankenphp.GoPackedArray[any](unsafe.Pointer(arr)) if err != nil { panic(err) } result := make([]any, len(goSlice)) for index, value := range goSlice { result[index] = frankenphp.CallPHPCallable(unsafe.Pointer(callback), []interface{}{value}) } return frankenphp.PHPPackedArray(result) } ``` Observa cómo usamos `frankenphp.CallPHPCallable()` para llamar al callable de PHP pasado como parámetro. Esta función toma un puntero al callable y un array de argumentos, y devuelve el resultado de la ejecución del callable. Puedes usar la sintaxis de callable a la que estás acostumbrado: ```php name` no funcionará) - **Interfaz solo de métodos** - Todas las interacciones deben pasar a través de los métodos que defines - **Mejor encapsulación** - La estructura de datos interna está completamente controlada por el código Go - **Seguridad de tipos** - Sin riesgo de que el código PHP corrompa el estado interno con tipos incorrectos - **API más limpia** - Obliga a diseñar una interfaz pública adecuada Este enfoque proporciona una mejor encapsulación y evita que el código PHP corrompa accidentalmente el estado interno de tus objetos Go. Todas las interacciones con el objeto deben pasar a través de los métodos que defines explícitamente. #### Añadiendo Métodos a las Clases Dado que las propiedades no son directamente accesibles, **debes definir métodos** para interactuar con tus clases opacas. Usa la directiva `//export_php:method` para definir el comportamiento: ```go package ejemplo // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### Parámetros Nulos El generador soporta parámetros nulos usando el prefijo `?` en las firmas de PHP. Cuando un parámetro es nulo, se convierte en un puntero en tu función Go, permitiéndote verificar si el valor era `null` en PHP: ```go package ejemplo // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // Verificar si se proporcionó name (no es null) if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // Verificar si se proporcionó age (no es null) if age != nil { us.Age = int(*age) } // Verificar si se proporcionó active (no es null) if active != nil { us.Active = *active } } ``` **Puntos clave sobre parámetros nulos:** - **Tipos primitivos nulos** (`?int`, `?float`, `?bool`) se convierten en punteros (`*int64`, `*float64`, `*bool`) en Go - **Strings nulos** (`?string`) permanecen como `*C.zend_string` pero pueden ser `nil` - **Verificar `nil`** antes de desreferenciar valores de puntero - **`null` de PHP se convierte en `nil` de Go** - cuando PHP pasa `null`, tu función Go recibe un puntero `nil` > [!CAUTION] > > Actualmente, los métodos de clase tienen las siguientes limitaciones. **Los objetos no están soportados** como tipos de parámetro o tipos de retorno. **Los arrays están completamente soportados** para ambos parámetros y tipos de retorno. Tipos soportados: `string`, `int`, `float`, `bool`, `array`, y `void` (para tipo de retorno). **Los tipos de parámetros nulos están completamente soportados** para todos los tipos escalares (`?string`, `?int`, `?float`, `?bool`). Después de generar la extensión, podrás usar la clase y sus métodos en PHP. Ten en cuenta que **no puedes acceder a las propiedades directamente**: ```php setAge(25); echo $user->getName(); // Salida: (vacío, valor por defecto) echo $user->getAge(); // Salida: 25 $user->setNamePrefix("Empleado"); // ✅ Esto también funciona - parámetros nulos $user->updateInfo("John", 30, true); // Todos los parámetros proporcionados $user->updateInfo("Jane", null, false); // Age es null $user->updateInfo(null, 25, null); // Name y active son null // ❌ Esto NO funcionará - acceso directo a propiedades // echo $user->name; // Error: No se puede acceder a la propiedad privada // $user->age = 30; // Error: No se puede acceder a la propiedad privada ``` Este diseño asegura que tu código Go tenga control completo sobre cómo se accede y modifica el estado del objeto, proporcionando una mejor encapsulación y seguridad de tipos. ### Declarando Constantes El generador soporta exportar constantes Go a PHP usando dos directivas: `//export_php:const` para constantes globales y `//export_php:classconst` para constantes de clase. Esto te permite compartir valores de configuración, códigos de estado y otras constantes entre código Go y PHP. #### Constantes Globales Usa la directiva `//export_php:const` para crear constantes globales de PHP: ```go package ejemplo //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const STATUS_OK = iota //export_php:const const STATUS_ERROR = iota ``` #### Constantes de Clase Usa la directiva `//export_php:classconst ClassName` para crear constantes que pertenecen a una clase PHP específica: ```go package ejemplo //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const STATE_PENDING = iota //export_php:classconst Order const STATE_PROCESSING = iota //export_php:classconst Order const STATE_COMPLETED = iota ``` Las constantes de clase son accesibles usando el ámbito del nombre de clase en PHP: ```php import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:const const STR_REVERSE = iota //export_php:const const STR_NORMAL = iota //export_php:classconst StringProcessor const MODE_LOWERCASE = 1 //export_php:classconst StringProcessor const MODE_UPPERCASE = 2 //export_php:function repeat_this(string $str, int $count, int $mode): string func repeat_this(s *C.zend_string, count int64, mode int) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if mode == STR_REVERSE { // invertir la cadena } if mode == STR_NORMAL { // no hacer nada, solo para mostrar la constante } return frankenphp.PHPString(result, false) } //export_php:class StringProcessor type StringProcessorStruct struct { // campos internos } //export_php:method StringProcessor::process(string $input, int $mode): string func (sp *StringProcessorStruct) Process(input *C.zend_string, mode int64) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(input)) switch mode { case MODE_LOWERCASE: str = strings.ToLower(str) case MODE_UPPERCASE: str = strings.ToUpper(str) } return frankenphp.PHPString(str, false) } ``` ### Usando Espacios de Nombres El generador soporta organizar las funciones, clases y constantes de tu extensión PHP bajo un espacio de nombres usando la directiva `//export_php:namespace`. Esto ayuda a evitar conflictos de nombres y proporciona una mejor organización para la API de tu extensión. #### Declarando un Espacio de Nombres Usa la directiva `//export_php:namespace` al inicio de tu archivo Go para colocar todos los símbolos exportados bajo un espacio de nombres específico: ```go //export_php:namespace Mi\Extensión package ejemplo import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function hello(): string func hello() string { return "Hola desde el espacio de nombres Mi\\Extensión!" } //export_php:class User type UserStruct struct { // campos internos } //export_php:method User::getName(): string func (u *UserStruct) GetName() unsafe.Pointer { return frankenphp.PHPString("John Doe", false) } //export_php:const const STATUS_ACTIVE = 1 ``` #### Usando la Extensión con Espacio de Nombres en PHP Cuando se declara un espacio de nombres, todas las funciones, clases y constantes se colocan bajo ese espacio de nombres en PHP: ```php getName(); // "John Doe" echo Mi\Extensión\STATUS_ACTIVE; // 1 ``` #### Notas Importantes - Solo se permite **una** directiva de espacio de nombres por archivo. Si se encuentran múltiples directivas de espacio de nombres, el generador devolverá un error. - El espacio de nombres se aplica a **todos** los símbolos exportados en el archivo: funciones, clases, métodos y constantes. - Los nombres de espacios de nombres siguen las convenciones de espacios de nombres de PHP usando barras invertidas (`\`) como separadores. - Si no se declara un espacio de nombres, los símbolos se exportan al espacio de nombres global como de costumbre. ### Generando la Extensión Aquí es donde ocurre la magia, y tu extensión ahora puede ser generada. Puedes ejecutar el generador con el siguiente comando: ```console GEN_STUB_SCRIPT=php-src/build/gen_stub.php frankenphp extension-init mi_extensión.go ``` > [!NOTE] > No olvides establecer la variable de entorno `GEN_STUB_SCRIPT` a la ruta del archivo `gen_stub.php` en las fuentes de PHP que descargaste anteriormente. Este es el mismo script `gen_stub.php` mencionado en la sección de implementación manual. Si todo salió bien, se debería haber creado un nuevo directorio llamado `build`. Este directorio contiene los archivos generados para tu extensión, incluyendo el archivo `mi_extensión.go` con los stubs de funciones PHP generadas. ### Integrando la Extensión Generada en FrankenPHP Nuestra extensión ahora está lista para ser compilada e integrada en FrankenPHP. Para hacerlo, consulta la documentación de [compilación de FrankenPHP](compile.md) para aprender cómo compilar FrankenPHP. Agrega el módulo usando la bandera `--with`, apuntando a la ruta de tu módulo: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/mi-cuenta/mi-módulo/build ``` Ten en cuenta que apuntas al subdirectorio `/build` que se creó durante el paso de generación. Sin embargo, esto no es obligatorio: también puedes copiar los archivos generados a tu directorio de módulo y apuntar a él directamente. ### Probando tu Extensión Generada Puedes crear un archivo PHP para probar las funciones y clases que has creado. Por ejemplo, crea un archivo `index.php` con el siguiente contenido: ```php process('Hola Mundo', StringProcessor::MODE_LOWERCASE); // "hola mundo" echo $processor->process('Hola Mundo', StringProcessor::MODE_UPPERCASE); // "HOLA MUNDO" ``` Una vez que hayas integrado tu extensión en FrankenPHP como se demostró en la sección anterior, puedes ejecutar este archivo de prueba usando `./frankenphp php-server`, y deberías ver tu extensión funcionando. ## Implementación Manual Si quieres entender cómo funcionan las extensiones o necesitas un control total sobre tu extensión, puedes escribirlas manualmente. Este enfoque te da control completo pero requiere más código repetitivo. ### Función Básica Veremos cómo escribir una extensión PHP simple en Go que define una nueva función nativa. Esta función será llamada desde PHP y desencadenará una goroutine que registra un mensaje en los logs de Caddy. Esta función no toma ningún parámetro y no devuelve nada. #### Definir la Función Go En tu módulo, necesitas definir una nueva función nativa que será llamada desde PHP. Para esto, crea un archivo con el nombre que desees, por ejemplo, `extension.go`, y agrega el siguiente código: ```go package ejemplo // #include "extension.h" import "C" import ( "log/slog" "unsafe" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { slog.Info("¡Hola desde una goroutine!") }() } ``` La función `frankenphp.RegisterExtension()` simplifica el proceso de registro de la extensión manejando la lógica interna de registro de PHP. La función `go_print_something` usa la directiva `//export` para indicar que será accesible en el código C que escribiremos, gracias a CGO. En este ejemplo, nuestra nueva función desencadenará una goroutine que registra un mensaje en los logs de Caddy. #### Definir la Función PHP Para permitir que PHP llame a nuestra función, necesitamos definir una función PHP correspondiente. Para esto, crearemos un archivo stub, por ejemplo, `extension.stub.php`, que contendrá el siguiente código: ```php extern zend_module_entry ext_module_entry; #endif ``` A continuación, crea un archivo llamado `extension.c` que realizará los siguientes pasos: - Incluir los encabezados de PHP; - Declarar nuestra nueva función nativa de PHP `go_print()`; - Declarar los metadatos de la extensión. Comencemos incluyendo los encabezados requeridos: ```c #include #include "extension.h" #include "extension_arginfo.h" // Contiene símbolos exportados por Go #include "_cgo_export.h" ``` Luego definimos nuestra función PHP como una función de lenguaje nativo: ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Funciones */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` En este caso, nuestra función no toma parámetros y no devuelve nada. Simplemente llama a la función Go que definimos anteriormente, exportada usando la directiva `//export`. Finalmente, definimos los metadatos de la extensión en una estructura `zend_module_entry`, como su nombre, versión y propiedades. Esta información es necesaria para que PHP reconozca y cargue nuestra extensión. Ten en cuenta que `ext_functions` es un array de punteros a las funciones PHP que definimos, y fue generado automáticamente por el script `gen_stub.php` en el archivo `extension_arginfo.h`. El registro de la extensión es manejado automáticamente por la función `RegisterExtension()` de FrankenPHP que llamamos en nuestro código Go. ### Uso Avanzado Ahora que sabemos cómo crear una extensión PHP básica en Go, compliquemos nuestro ejemplo. Ahora crearemos una función PHP que tome una cadena como parámetro y devuelva su versión en mayúsculas. #### Definir el Stub de la Función PHP Para definir la nueva función PHP, modificaremos nuestro archivo `extension.stub.php` para incluir la nueva firma de la función: ```php [!TIP] > ¡No descuides la documentación de tus funciones! Es probable que compartas tus stubs de extensión con otros desarrolladores para documentar cómo usar tu extensión y qué características están disponibles. Al regenerar el archivo stub con el script `gen_stub.php`, el archivo `extension_arginfo.h` debería verse así: ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` Podemos ver que la función `go_upper` está definida con un parámetro de tipo `string` y un tipo de retorno `string`. #### Manipulación de Tipos entre Go y PHP/C Tu función Go no puede aceptar directamente una cadena PHP como parámetro. Necesitas convertirla a una cadena Go. Afortunadamente, FrankenPHP proporciona funciones helper para manejar la conversión entre cadenas PHP y cadenas Go, similar a lo que vimos en el enfoque del generador. El archivo de encabezado sigue siendo simple: ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` Ahora podemos escribir el puente entre Go y C en nuestro archivo `extension.c`. Pasaremos la cadena PHP directamente a nuestra función Go: ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` Puedes aprender más sobre `ZEND_PARSE_PARAMETERS_START` y el análisis de parámetros en la página dedicada del [Libro de Internals de PHP](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters). Aquí, le decimos a PHP que nuestra función toma un parámetro obligatorio de tipo `string` como `zend_string`. Luego pasamos esta cadena directamente a nuestra función Go y devolvemos el resultado usando `RETVAL_STR`. Solo queda una cosa por hacer: implementar la función `go_upper` en Go. #### Implementar la Función Go Nuestra función Go tomará un `*C.zend_string` como parámetro, lo convertirá a una cadena Go usando la función helper de FrankenPHP, lo procesará y devolverá el resultado como un nuevo `*C.zend_string`. Las funciones helper manejan toda la complejidad de gestión de memoria y conversión por nosotros. ```go package ejemplo // #include import "C" import ( "unsafe" "strings" "github.com/dunglas/frankenphp" ) //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` Este enfoque es mucho más limpio y seguro que la gestión manual de memoria. Las funciones helper de FrankenPHP manejan la conversión entre el formato `zend_string` de PHP y las cadenas Go automáticamente. El parámetro `false` en `PHPString()` indica que queremos crear una nueva cadena no persistente (liberada al final de la solicitud). > [!TIP] > > En este ejemplo, no realizamos ningún manejo de errores, pero siempre debes verificar que los punteros no sean `nil` y que los datos sean válidos antes de usarlos en tus funciones Go. ### Integrando la Extensión en FrankenPHP Nuestra extensión ahora está lista para ser compilada e integrada en FrankenPHP. Para hacerlo, consulta la documentación de [compilación de FrankenPHP](compile.md) para aprender cómo compilar FrankenPHP. Agrega el módulo usando la bandera `--with`, apuntando a la ruta de tu módulo: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/mi-cuenta/mi-módulo ``` ¡Eso es todo! Tu extensión ahora está integrada en FrankenPHP y puede ser usada en tu código PHP. ### Probando tu Extensión Después de integrar tu extensión en FrankenPHP, puedes crear un archivo `index.php` con ejemplos para las funciones que has implementado: ```php [!WARNING] > Esta función está destinada **únicamente a entornos de desarrollo**. > No active `hot_reload` en producción, ya que vigilar el sistema de archivos implica una sobrecarga de rendimiento y expone endpoints internos. ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` Por omisión, FrankenPHP vigilará todos los archivos en el directorio de trabajo actual que coincidan con este patrón glob: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` Es posible establecer explícitamente los archivos a vigilar usando la sintaxis glob: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Use la forma larga para especificar el tema de Mercure a utilizar, así como qué directorios o archivos vigilar, proporcionando rutas a la opción `hot_reload`: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## Integración Lado-Cliente Mientras el servidor detecta los cambios, el navegador necesita suscribirse a estos eventos para actualizar la página. FrankenPHP expone la URL del Mercure Hub a utilizar para suscribirse a los cambios de archivos a través de la variable de entorno `$_SERVER['FRANKENPHP_HOT_RELOAD']`. Una biblioteca JavaScript de conveniencia, [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload), también está disponible para manejar la lógica lado-cliente. Para usarla, agregue lo siguiente a su diseño principal: ```php FrankenPHP Hot Reload ``` La biblioteca se suscribirá automáticamente al hub de Mercure, obtendrá la URL actual en segundo plano cuando se detecte un cambio en un archivo y transformará el DOM. Está disponible como un paquete [npm](https://www.npmjs.com/package/frankenphp-hot-reload) y en [GitHub](https://github.com/dunglas/frankenphp-hot-reload). Alternativamente, puede implementar su propia lógica lado-cliente suscribiéndose directamente al hub de Mercure usando la clase nativa de JavaScript `EventSource`. ### Modo Worker Si está ejecutando su aplicación en [Modo Worker](https://frankenphp.dev/docs/worker/), el script de su aplicación permanece en memoria. Esto significa que los cambios en su código PHP no se reflejarán inmediatamente, incluso si el navegador se recarga. Para la mejor experiencia de desarrollador, debe combinar `hot_reload` con [la subdirectiva `watch` en la directiva `worker`](config.md#watching-for-file-changes). - `hot_reload`: actualiza el **navegador** cuando los archivos cambian - `worker.watch`: reinicia el worker cuando los archivos cambian ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ### Funcionamiento 1. **Vigilancia**: FrankenPHP monitorea el sistema de archivos en busca de modificaciones usando [la biblioteca `e-dant/watcher`](https://github.com/e-dant/watcher) internamente (contribuimos con el binding de Go). 2. **Reinicio (Modo Worker)**: si `watch` está habilitado en la configuración del worker, el worker de PHP se reinicia para cargar el nuevo código. 3. **Envío**: se envía una carga útil JSON que contiene la lista de archivos modificados al [hub de Mercure](https://mercure.rocks) integrado. 4. **Recepción**: El navegador, escuchando a través de la biblioteca JavaScript, recibe el evento de Mercure. 5. **Actualización**: - Si se detecta **Idiomorph**, obtiene el contenido actualizado y transforma el HTML actual para que coincida con el nuevo estado, aplicando los cambios al instante sin perder el estado. - De lo contrario, se llama a `window.location.reload()` para recargar la página. ================================================ FILE: docs/es/known-issues.md ================================================ # Problemas Conocidos ## Extensiones PHP no Soportadas Las siguientes extensiones se sabe que no son compatibles con FrankenPHP: | Nombre | Razón | Alternativas | | ----------------------------------------------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/es/imap.installation.php) | No es thread-safe | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | No es thread-safe | - | ## Extensiones PHP con Errores Las siguientes extensiones tienen errores conocidos y comportamientos inesperados cuando se usan con FrankenPHP: | Nombre | Problema | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [ext-openssl](https://www.php.net/manual/es/book.openssl.php) | Cuando se usa musl libc, la extensión OpenSSL puede fallar bajo cargas pesadas. El problema no ocurre cuando se usa la más popular GNU libc. Este error está [siendo rastreado por PHP](https://github.com/php/php-src/issues/13648). | ## get_browser La función [get_browser()](https://www.php.net/manual/es/function.get-browser.php) parece funcionar mal después de un tiempo. Una solución es almacenar en caché (por ejemplo, con [APCu](https://www.php.net/manual/es/book.apcu.php)) los resultados por User Agent, ya que son estáticos. ## Binario Autónomo e Imágenes Docker Basadas en Alpine Los binarios completamente estáticos y las imágenes Docker basadas en Alpine (`dunglas/frankenphp:*-alpine`) usan [musl libc](https://musl.libc.org/) en lugar de [glibc](https://www.etalabs.net/compare_libcs.html), para mantener un tamaño de binario más pequeño. Esto puede llevar a algunos problemas de compatibilidad. En particular, la bandera glob `GLOB_BRACE` [no está disponible](https://www.php.net/manual/es/function.glob.php). Se recomienda usar la variante GNU del binario estático y las imágenes Docker basadas en Debian si encuentras problemas. ## Usar `https://127.0.0.1` con Docker Por defecto, FrankenPHP genera un certificado TLS para `localhost`. Es la opción más fácil y recomendada para el desarrollo local. Si realmente deseas usar `127.0.0.1` como host en su lugar, es posible configurarlo para generar un certificado para él estableciendo el nombre del servidor en `127.0.0.1`. Desafortunadamente, esto no es suficiente al usar Docker debido a [su sistema de red](https://docs.docker.com/network/). Obtendrás un error TLS similar a `curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`. Si estás usando Linux, una solución es usar [el controlador de red host](https://docs.docker.com/network/network-tutorial-host/): ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` El controlador de red host no está soportado en Mac y Windows. En estas plataformas, tendrás que adivinar la dirección IP del contenedor e incluirla en los nombres del servidor. Ejecuta `docker network inspect bridge` y busca la clave `Containers` para identificar la última dirección IP actualmente asignada bajo la clave `IPv4Address`, y incrementa en uno. Si no hay contenedores en ejecución, la primera dirección IP asignada suele ser `172.17.0.2`. Luego, incluye esto en la variable de entorno `SERVER_NAME`: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > Asegúrate de reemplazar `172.17.0.3` con la IP que se asignará a tu contenedor. Ahora deberías poder acceder a `https://127.0.0.1` desde la máquina host. Si no es así, inicia FrankenPHP en modo depuración para intentar identificar el problema: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Scripts de Composer que Referencian `@php` Los [scripts de Composer](https://getcomposer.org/doc/articles/scripts.md) pueden querer ejecutar un binario PHP para algunas tareas, por ejemplo, en [un proyecto Laravel](laravel.md) para ejecutar `@php artisan package:discover --ansi`. Esto [actualmente falla](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) por dos razones: - Composer no sabe cómo llamar al binario de FrankenPHP; - Composer puede agregar configuraciones de PHP usando la bandera `-d` en el comando, que FrankenPHP aún no soporta. Como solución alternativa, podemos crear un script de shell en `/usr/local/bin/php` que elimine los parámetros no soportados y luego llame a FrankenPHP: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Luego, establece la variable de entorno `PHP_BINARY` a la ruta de nuestro script `php` y ejecuta Composer: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## Solución de Problemas de TLS/SSL con Binarios Estáticos Al usar los binarios estáticos, puedes encontrar los siguientes errores relacionados con TLS, por ejemplo, al enviar correos electrónicos usando STARTTLS: ```text No se puede conectar con STARTTLS: stream_socket_enable_crypto(): La operación SSL falló con el código 5. Mensajes de error de OpenSSL: error:80000002:librería del sistema::No existe el archivo o el directorio error:80000002:librería del sistema::No existe el archivo o el directorio error:80000002:librería del sistema::No existe el archivo o el directorio error:0A000086:rutinas de SSL::falló la verificación del certificado ``` Dado que el binario estático no incluye certificados TLS, necesitas indicar a OpenSSL la ubicación de tu instalación local de certificados CA. Inspecciona la salida de [`openssl_get_cert_locations()`](https://www.php.net/manual/es/function.openssl-get-cert-locations.php), para encontrar dónde deben instalarse los certificados CA y guárdalos en esa ubicación. > [!CAUTION] > > Los contextos web y CLI pueden tener configuraciones diferentes. > Asegúrate de ejecutar `openssl_get_cert_locations()` en el contexto adecuado. [Los certificados CA extraídos de Mozilla pueden descargarse del sitio de cURL](https://curl.se/docs/caextract.html). Alternativamente, muchas distribuciones, incluyendo Debian, Ubuntu y Alpine, proporcionan paquetes llamados `ca-certificates` que contienen estos certificados. También es posible usar `SSL_CERT_FILE` y `SSL_CERT_DIR` para indicar a OpenSSL dónde buscar los certificados CA: ```console # Establecer variables de entorno de certificados TLS export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/es/laravel.md ================================================ # Laravel ## Docker Servir una aplicación web [Laravel](https://laravel.com) con FrankenPHP es tan fácil como montar el proyecto en el directorio `/app` de la imagen Docker oficial. Ejecuta este comando desde el directorio principal de tu aplicación Laravel: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` ¡Y listo! ## Instalación Local Alternativamente, puedes ejecutar tus proyectos Laravel con FrankenPHP desde tu máquina local: 1. [Descarga el binario correspondiente a tu sistema](../#binario-autónomo) 2. Agrega la siguiente configuración a un archivo llamado `Caddyfile` en el directorio raíz de tu proyecto Laravel: ```caddyfile { frankenphp } # El nombre de dominio de tu servidor localhost { # Establece el directorio web raíz en public/ root public/ # Habilita la compresión (opcional) encode zstd br gzip # Ejecuta archivos PHP desde el directorio public/ y sirve los assets php_server { try_files {path} index.php } } ``` 3. Inicia FrankenPHP desde el directorio raíz de tu proyecto Laravel: `frankenphp run` ## Laravel Octane Octane se puede instalar a través del gestor de paquetes Composer: ```console composer require laravel/octane ``` Después de instalar Octane, puedes ejecutar el comando Artisan `octane:install`, que instalará el archivo de configuración de Octane en tu aplicación: ```console php artisan octane:install --server=frankenphp ``` El servidor Octane se puede iniciar mediante el comando Artisan `octane:frankenphp`. ```console php artisan octane:frankenphp ``` El comando `octane:frankenphp` puede tomar las siguientes opciones: - `--host`: La dirección IP a la que el servidor debe enlazarse (por defecto: `127.0.0.1`) - `--port`: El puerto en el que el servidor debe estar disponible (por defecto: `8000`) - `--admin-port`: El puerto en el que el servidor de administración debe estar disponible (por defecto: `2019`) - `--workers`: El número de workers que deben estar disponibles para manejar solicitudes (por defecto: `auto`) - `--max-requests`: El número de solicitudes a procesar antes de recargar el servidor (por defecto: `500`) - `--caddyfile`: La ruta al archivo `Caddyfile` de FrankenPHP (por defecto: [Caddyfile de plantilla en Laravel Octane](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: Habilita HTTPS, HTTP/2 y HTTP/3, y genera y renueva certificados automáticamente - `--http-redirect`: Habilita la redirección de HTTP a HTTPS (solo se habilita si se pasa --https) - `--watch`: Recarga automáticamente el servidor cuando se modifica la aplicación - `--poll`: Usa la sondea del sistema de archivos mientras se observa para vigilar archivos a través de una red - `--log-level`: Registra mensajes en o por encima del nivel de registro especificado, usando el registrador nativo de Caddy > [!TIP] > Para obtener registros JSON estructurados (útil al usar soluciones de análisis de registros), pasa explícitamente la opción `--log-level`. Consulta también [cómo usar Mercure con Octane](#soporte-para-mercure). Aprende más sobre [Laravel Octane en su documentación oficial](https://laravel.com/docs/octane). ## Aplicaciones Laravel como Binarios Autónomos Usando [la característica de incrustación de aplicaciones de FrankenPHP](embed.md), es posible distribuir aplicaciones Laravel como binarios autónomos. Sigue estos pasos para empaquetar tu aplicación Laravel como un binario autónomo para Linux: 1. Crea un archivo llamado `static-build.Dockerfile` en el repositorio de tu aplicación: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Si tienes intención de ejecutar el binario en sistemas musl-libc, usa static-builder-musl en su lugar # Copia tu aplicación WORKDIR /go/src/app/dist/app COPY . . # Elimina las pruebas y otros archivos innecesarios para ahorrar espacio # Alternativamente, agrega estos archivos a un archivo .dockerignore RUN rm -Rf tests/ # Copia el archivo .env RUN cp .env.example .env # Cambia APP_ENV y APP_DEBUG para que estén listos para producción RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Realiza otros cambios en tu archivo .env si es necesario # Instala las dependencias RUN composer install --ignore-platform-reqs --no-dev -a # Compila el binario estático WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Algunos archivos `.dockerignore` > ignorarán el directorio `vendor/` y los archivos `.env`. Asegúrate de ajustar o eliminar el archivo `.dockerignore` antes de la compilación. 2. Compila: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. Extrae el binario: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Rellena las cachés: ```console frankenphp php-cli artisan optimize ``` 5. Ejecuta las migraciones de la base de datos (si las hay): ```console frankenphp php-cli artisan migrate ``` 6. Genera la clave secreta de la aplicación: ```console frankenphp php-cli artisan key:generate ``` 7. Inicia el servidor: ```console frankenphp php-server ``` ¡Tu aplicación ya está lista! Aprende más sobre las opciones disponibles y cómo compilar binarios para otros sistemas operativos en la documentación de [incrustación de aplicaciones](embed.md). ### Cambiar la Ruta de Almacenamiento Por defecto, Laravel almacena los archivos subidos, cachés, registros, etc. en el directorio `storage/` de la aplicación. Esto no es adecuado para aplicaciones incrustadas, ya que cada nueva versión se extraerá en un directorio temporal diferente. Establece la variable de entorno `LARAVEL_STORAGE_PATH` (por ejemplo, en tu archivo `.env`) o llama al método `Illuminate\Foundation\Application::useStoragePath()` para usar un directorio fuera del directorio temporal. ### Soporte para Mercure [Mercure](https://mercure.rocks) es una excelente manera de agregar capacidades en tiempo real a tus aplicaciones Laravel. FrankenPHP incluye [soporte para Mercure integrado](mercure.md). Si no estás usando [Octane](#laravel-octane), consulta [la entrada de documentación de Mercure](mercure.md). Si estás usando Octane, puedes habilitar el soporte para Mercure agregando las siguientes líneas a tu archivo `config/octane.php`: ```php // ... return [ // ... 'mercure' => [ 'anonymous' => true, 'publisher_jwt' => '!CambiaEstaClaveSecretaJWTDelHubMercure!', 'subscriber_jwt' => '!CambiaEstaClaveSecretaJWTDelHubMercure!', ], ]; ``` Puedes usar [todas las directivas soportadas por Mercure](https://mercure.rocks/docs/hub/config#directives) en este array. Para publicar y suscribirte a actualizaciones, recomendamos usar la biblioteca [Laravel Mercure Broadcaster](https://github.com/mvanduijker/laravel-mercure-broadcaster). Alternativamente, consulta [la documentación de Mercure](mercure.md) para hacerlo en PHP y JavaScript puros. ### Ejecutar Octane con Binarios Autónomos ¡Incluso es posible empaquetar aplicaciones Laravel Octane como binarios autónomos! Para hacerlo, [instala Octane correctamente](#laravel-octane) y sigue los pasos descritos en [la sección anterior](#aplicaciones-laravel-como-binarios-autónomos). Luego, para iniciar FrankenPHP en modo worker a través de Octane, ejecuta: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > Para que el comando funcione, el binario autónomo **debe** llamarse `frankenphp` > porque Octane necesita un programa llamado `frankenphp` disponible en la ruta. ================================================ FILE: docs/es/logging.md ================================================ # Registro de actividad FrankenPHP se integra perfectamente con [el sistema de registro de Caddy](https://caddyserver.com/docs/logging). Puede registrar mensajes usando funciones estándar de PHP o aprovechar la función dedicada `frankenphp_log()` para capacidades avanzadas de registro estructurado. ## `frankenphp_log()` La función `frankenphp_log()` le permite emitir registros estructurados directamente desde su aplicación PHP, facilitando la ingesta en plataformas como Datadog, Grafana Loki o Elastic, así como el soporte para OpenTelemetry. Internamente, `frankenphp_log()` envuelve [el paquete `log/slog` de Go](https://pkg.go.dev/log/slog) para proporcionar funciones avanzadas de registro. Estos registros incluyen el nivel de gravedad y datos de contexto opcionales. ```php function frankenphp_log(string $message, int $level = FRANKENPHP_LOG_LEVEL_INFO, array $context = []): void ``` ### Parámetros - **`message`**: El string del mensaje de registro. - **`level`**: El nivel de gravedad del registro. Puede ser cualquier entero arbitrario. Se proporcionan constantes de conveniencia para niveles comunes: `FRANKENPHP_LOG_LEVEL_DEBUG` (`-4`), `FRANKENPHP_LOG_LEVEL_INFO` (`0`), `FRANKENPHP_LOG_LEVEL_WARN` (`4`) y `FRANKENPHP_LOG_LEVEL_ERROR` (`8`)). Por omisión es `FRANKENPHP_LOG_LEVEL_INFO`. - **`context`**: Un array asociativo de datos adicionales para incluir en la entrada del registro. ### Ejemplo ```php memory_get_usage(), 'uso_pico' => memory_get_peak_usage(), ], ); ``` Al ver los registros (por ejemplo, mediante `docker compose logs`), la salida aparecerá como JSON estructurado: ```json {"level":"info","ts":1704067200,"logger":"frankenphp","msg":"¡Hola desde FrankenPHP!"} {"level":"warn","ts":1704067200,"logger":"frankenphp","msg":"Uso de memoria alto","uso_actual":10485760,"uso_pico":12582912} ``` ## `error_log()` FrankenPHP también permite el registro mediante la función estándar `error_log()`. Si el parámetro `$message_type` es `4` (SAPI), estos mensajes se redirigen al registrador de Caddy. Por omisión, los mensajes enviados a través de `error_log()` se tratan como texto no estructurado. Son útiles para la compatibilidad con aplicaciones o bibliotecas existentes que dependen de la biblioteca estándar de PHP. ### Uso ```php error_log("Fallo en la conexión a la base de datos", 4); ``` Esto aparecerá en los registros de Caddy, a menudo con un prefijo que indica que se originó desde PHP. > [!TIP] > Para una mejor observabilidad en entornos de producción, prefiera `frankenphp_log()` > ya que permite filtrar registros por nivel (Depuración, Error, etc.) > y consultar campos específicos en su infraestructura de registro. ================================================ FILE: docs/es/mercure.md ================================================ # Tiempo Real ¡FrankenPHP incluye un hub [Mercure](https://mercure.rocks) integrado! Mercure te permite enviar eventos en tiempo real a todos los dispositivos conectados: recibirán un evento JavaScript al instante. ¡Es una alternativa conveniente a WebSockets que es simple de usar y es soportada nativamente por todos los navegadores web modernos! ![Mercure](../mercure-hub.png) ## Habilitando Mercure El soporte para Mercure está deshabilitado por defecto. Aquí tienes un ejemplo mínimo de un `Caddyfile` que habilita tanto FrankenPHP como el hub Mercure: ```caddyfile # El nombre de host al que responder localhost mercure { # La clave secreta usada para firmar los tokens JWT para los publicadores publisher_jwt !CambiaEstaClaveSecretaJWTDelHubMercure! # Cuando se establece publisher_jwt, ¡también debes establecer subscriber_jwt! subscriber_jwt !CambiaEstaClaveSecretaJWTDelHubMercure! # Permite suscriptores anónimos (sin JWT) anonymous } root public/ php_server ``` > [!TIP] > > El [`Caddyfile` de ejemplo](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) > proporcionado por [las imágenes Docker](docker.md) ya incluye una configuración comentada de Mercure > con variables de entorno convenientes para configurarlo. > > Descomenta la sección Mercure en `/etc/frankenphp/Caddyfile` para habilitarla. ## Suscribiéndose a Actualizaciones Por defecto, el hub Mercure está disponible en la ruta `/.well-known/mercure` de tu servidor FrankenPHP. Para suscribirte a actualizaciones, usa la clase nativa [`EventSource`](https://developer.mozilla.org/es/docs/Web/API/EventSource) de JavaScript: ```html Ejemplo Mercure ``` ## Publicando Actualizaciones ### Usando `mercure_publish()` FrankenPHP proporciona una función conveniente `mercure_publish()` para publicar actualizaciones en el hub Mercure integrado: ```php 'valor'])); // Escribir en los registros de FrankenPHP error_log("actualización $updateID publicada", 4); ``` La firma completa de la función es: ```php /** * @param string|string[] $topics */ function mercure_publish(string|array $topics, string $data = '', bool $private = false, ?string $id = null, ?string $type = null, ?int $retry = null): string {} ``` ### Usando `file_get_contents()` Para enviar una actualización a los suscriptores conectados, envía una solicitud POST autenticada al hub Mercure con los parámetros `topic` y `data`: ```php [ 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\nAuthorization: Bearer " . JWT, 'content' => http_build_query([ 'topic' => 'mi-tema', 'data' => json_encode(['clave' => 'valor']), ]), ]])); // Escribir en los registros de FrankenPHP error_log("actualización $updateID publicada", 4); ``` La clave pasada como parámetro de la opción `mercure.publisher_jwt` en el `Caddyfile` debe usarse para firmar el token JWT usado en el encabezado `Authorization`. El JWT debe incluir un reclamo `mercure` con un permiso `publish` para los temas a los que deseas publicar. Consulta [la documentación de Mercure](https://mercure.rocks/spec#publishers) sobre autorización. Para generar tus propios tokens, puedes usar [este enlace de jwt.io](https://www.jwt.io/#token=eyJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.PXwpfIGng6KObfZlcOXvcnWCJOWTFLtswGI5DZuWSK4), pero para aplicaciones en producción, se recomienda usar tokens de corta duración generados dinámicamente usando una biblioteca [JWT](https://www.jwt.io/libraries?programming_language=php) confiable. ### Usando Symfony Mercure Alternativamente, puedes usar el [Componente Symfony Mercure](https://symfony.com/components/Mercure), una biblioteca PHP independiente. Esta biblioteca maneja la generación de JWT, la publicación de actualizaciones así como la autorización basada en cookies para los suscriptores. Primero, instala la biblioteca usando Composer: ```console composer require symfony/mercure lcobucci/jwt ``` Luego, puedes usarla de la siguiente manera: ```php publish(new \Symfony\Component\Mercure\Update('mi-tema', json_encode(['clave' => 'valor']))); // Escribir en los registros de FrankenPHP error_log("actualización $updateID publicada", 4); ``` Mercure también es soportado nativamente por: - [Laravel](laravel.md#soporte-para-mercure) - [Symfony](https://symfony.com/doc/current/mercure.html) - [API Platform](https://api-platform.com/docs/core/mercure/) ================================================ FILE: docs/es/metrics.md ================================================ # Métricas Cuando las [métricas de Caddy](https://caddyserver.com/docs/metrics) están habilitadas, FrankenPHP expone las siguientes métricas: - `frankenphp_total_threads`: El número total de hilos PHP. - `frankenphp_busy_threads`: El número de hilos PHP procesando actualmente una solicitud (los workers en ejecución siempre consumen un hilo). - `frankenphp_queue_depth`: El número de solicitudes regulares en cola - `frankenphp_total_workers{worker="[nombre_worker]"}`: El número total de workers. - `frankenphp_busy_workers{worker="[nombre_worker]"}`: El número de workers procesando actualmente una solicitud. - `frankenphp_worker_request_time{worker="[nombre_worker]"}`: El tiempo dedicado al procesamiento de solicitudes por todos los workers. - `frankenphp_worker_request_count{worker="[nombre_worker]"}`: El número de solicitudes procesadas por todos los workers. - `frankenphp_ready_workers{worker="[nombre_worker]"}`: El número de workers que han llamado a `frankenphp_handle_request` al menos una vez. - `frankenphp_worker_crashes{worker="[nombre_worker]"}`: El número de veces que un worker ha terminado inesperadamente. - `frankenphp_worker_restarts{worker="[nombre_worker]"}`: El número de veces que un worker ha sido reiniciado deliberadamente. - `frankenphp_worker_queue_depth{worker="[nombre_worker]"}`: El número de solicitudes en cola. Para las métricas de los workers, el marcador de posición `[nombre_worker]` es reemplazado por el nombre del worker en el Caddyfile; de lo contrario, se usará la ruta absoluta del archivo del worker. ================================================ FILE: docs/es/performance.md ================================================ # Rendimiento Por defecto, FrankenPHP intenta ofrecer un buen compromiso entre rendimiento y facilidad de uso. Sin embargo, es posible mejorar sustancialmente el rendimiento usando una configuración adecuada. ## Número de Hilos y Workers Por defecto, FrankenPHP inicia 2 veces más hilos y workers (en modo worker) que el número de CPUs disponibles. Los valores apropiados dependen en gran medida de cómo está escrita tu aplicación, qué hace y tu hardware. Recomendamos encarecidamente cambiar estos valores. Para una mejor estabilidad del sistema, se recomienda que `num_threads` x `memory_limit` < `memoria_disponible`. Para encontrar los valores correctos, es mejor ejecutar pruebas de carga que simulen tráfico real. [k6](https://k6.io) y [Gatling](https://gatling.io) son buenas herramientas para esto. Para configurar el número de hilos, usa la opción `num_threads` de las directivas `php_server` y `php`. Para cambiar el número de workers, usa la opción `num` de la sección `worker` de la directiva `frankenphp`. ### `max_threads` Aunque siempre es mejor saber exactamente cómo será tu tráfico, las aplicaciones reales tienden a ser más impredecibles. La configuración `max_threads` [configuración](config.md#caddyfile-config) permite a FrankenPHP generar automáticamente hilos adicionales en tiempo de ejecución hasta el límite especificado. `max_threads` puede ayudarte a determinar cuántos hilos necesitas para manejar tu tráfico y puede hacer que el servidor sea más resiliente a picos de latencia. Si se establece en `auto`, el límite se estimará en función del `memory_limit` en tu `php.ini`. Si no puede hacerlo, `auto` se establecerá por defecto en 2x `num_threads`. Ten en cuenta que `auto` puede subestimar fuertemente el número de hilos necesarios. `max_threads` es similar a [pm.max_children](https://www.php.net/manual/es/install.fpm.configuration.php#pm.max-children) de PHP FPM. La principal diferencia es que FrankenPHP usa hilos en lugar de procesos y los delega automáticamente entre diferentes scripts de worker y el 'modo clásico' según sea necesario. ## Modo Worker Habilitar [el modo worker](worker.md) mejora drásticamente el rendimiento, pero tu aplicación debe adaptarse para ser compatible con este modo: debes crear un script de worker y asegurarte de que la aplicación no tenga fugas de memoria. ## No Usar musl La variante Alpine Linux de las imágenes Docker oficiales y los binarios predeterminados que proporcionamos usan [la libc musl](https://musl.libc.org). Se sabe que PHP es [más lento](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) cuando usa esta biblioteca C alternativa en lugar de la biblioteca GNU tradicional, especialmente cuando se compila en modo ZTS (thread-safe), que es requerido para FrankenPHP. La diferencia puede ser significativa en un entorno con muchos hilos. Además, [algunos errores solo ocurren cuando se usa musl](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). En entornos de producción, recomendamos usar FrankenPHP vinculado a glibc, compilado con un nivel de optimización adecuado. Esto se puede lograr usando las imágenes Docker de Debian, usando los paquetes de nuestros mantenedores [.deb](https://debs.henderkes.com) o [.rpm](https://rpms.henderkes.com), o [compilando FrankenPHP desde las fuentes](compile.md). ## Configuración del Runtime de Go FrankenPHP está escrito en Go. En general, el runtime de Go no requiere ninguna configuración especial, pero en ciertas circunstancias, una configuración específica mejora el rendimiento. Probablemente quieras establecer la variable de entorno `GODEBUG` en `cgocheck=0` (el valor predeterminado en las imágenes Docker de FrankenPHP). Si ejecutas FrankenPHP en contenedores (Docker, Kubernetes, LXC...) y limitas la memoria disponible para los contenedores, establece la variable de entorno `GOMEMLIMIT` en la cantidad de memoria disponible. Para más detalles, [la página de documentación de Go dedicada a este tema](https://pkg.go.dev/runtime#hdr-Environment_Variables) es una lectura obligada para aprovechar al máximo el runtime. ## `file_server` Por defecto, la directiva `php_server` configura automáticamente un servidor de archivos para servir archivos estáticos (assets) almacenados en el directorio raíz. Esta característica es conveniente, pero tiene un costo. Para deshabilitarla, usa la siguiente configuración: ```caddyfile php_server { file_server off } ``` ## `try_files` Además de los archivos estáticos y los archivos PHP, `php_server` también intentará servir los archivos de índice de tu aplicación y los índices de directorio (`/ruta/` -> `/ruta/index.php`). Si no necesitas índices de directorio, puedes deshabilitarlos definiendo explícitamente `try_files` de esta manera: ```caddyfile php_server { try_files {path} index.php root /ruta/a/tu/app # agregar explícitamente la raíz aquí permite un mejor almacenamiento en caché } ``` Esto puede reducir significativamente el número de operaciones de archivo innecesarias. Un enfoque alternativo con 0 operaciones innecesarias de sistema de archivos sería usar en su lugar la directiva `php` y separar los archivos de PHP por ruta. Este enfoque funciona bien si toda tu aplicación es servida por un solo archivo de entrada. Un ejemplo de [configuración](config.md#caddyfile-config) que sirve archivos estáticos detrás de una carpeta `/assets` podría verse así: ```caddyfile route { @assets { path /assets/* } # todo lo que está detrás de /assets es manejado por el servidor de archivos file_server @assets { root /ruta/a/tu/app } # todo lo que no está en /assets es manejado por tu archivo index o worker PHP rewrite index.php php { root /ruta/a/tu/app # agregar explícitamente la raíz aquí permite un mejor almacenamiento en caché } } ``` ## Marcadores de Posición (Placeholders) Puedes usar [marcadores de posición](https://caddyserver.com/docs/conventions#placeholders) en las directivas `root` y `env`. Sin embargo, esto evita el almacenamiento en caché de estos valores y conlleva un costo significativo de rendimiento. Si es posible, evita los marcadores de posición en estas directivas. ## `resolve_root_symlink` Por defecto, si la raíz del documento es un enlace simbólico, se resuelve automáticamente por FrankenPHP (esto es necesario para que PHP funcione correctamente). Si la raíz del documento no es un enlace simbólico, puedes deshabilitar esta característica. ```caddyfile php_server { resolve_root_symlink false } ``` Esto mejorará el rendimiento si la directiva `root` contiene [marcadores de posición](https://caddyserver.com/docs/conventions#placeholders). La ganancia será negligible en otros casos. ## Registros (Logs) El registro es obviamente muy útil, pero, por definición, requiere operaciones de E/S y asignaciones de memoria, lo que reduce considerablemente el rendimiento. Asegúrate de [establecer el nivel de registro](https://caddyserver.com/docs/caddyfile/options#log) correctamente, y registra solo lo necesario. ## Rendimiento de PHP FrankenPHP usa el intérprete oficial de PHP. Todas las optimizaciones de rendimiento habituales relacionadas con PHP se aplican con FrankenPHP. En particular: - verifica que [OPcache](https://www.php.net/manual/es/book.opcache.php) esté instalado, habilitado y correctamente configurado - habilita [optimizaciones del autoload de Composer](https://getcomposer.org/doc/articles/autoloader-optimization.md) - asegúrate de que la caché `realpath` sea lo suficientemente grande para las necesidades de tu aplicación - usa [preloading](https://www.php.net/manual/es/opcache.preloading.php) Para más detalles, lee [la entrada de documentación dedicada de Symfony](https://symfony.com/doc/current/performance.html) (la mayoría de los consejos son útiles incluso si no usas Symfony). ## Dividiendo el Pool de Hilos Es común que las aplicaciones interactúen con servicios externos lentos, como una API que tiende a ser poco confiable bajo alta carga o que consistentemente tarda 10+ segundos en responder. En tales casos, puede ser beneficioso dividir el pool de hilos para tener pools "lentos" dedicados. Esto evita que los endpoints lentos consuman todos los recursos/hilos del servidor y limita la concurrencia de solicitudes hacia el endpoint lento, similar a un pool de conexiones. ```caddyfile { frankenphp { max_threads 100 # máximo 100 hilos compartidos por todos los workers } } ejemplo.com { php_server { root /app/public # la raíz de tu aplicación worker index.php { match /endpoint-lento/* # todas las solicitudes con la ruta /endpoint-lento/* son manejadas por este pool de hilos num 10 # mínimo 10 hilos para solicitudes que coincidan con /endpoint-lento/* } worker index.php { match * # todas las demás solicitudes son manejadas por separado num 20 # mínimo 20 hilos para otras solicitudes, incluso si los endpoints lentos comienzan a colgarse } } } ``` En general, también es aconsejable manejar endpoints muy lentos de manera asíncrona, utilizando mecanismos relevantes como colas de mensajes. ================================================ FILE: docs/es/production.md ================================================ # Despliegue en Producción En este tutorial, aprenderemos cómo desplegar una aplicación PHP en un único servidor usando Docker Compose. Si estás usando Symfony, consulta la documentación "[Despliegue en producción](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)" del proyecto Symfony Docker (que usa FrankenPHP). Si estás usando API Platform (que también usa FrankenPHP), consulta [la documentación de despliegue del framework](https://api-platform.com/docs/deployment/). ## Preparando tu Aplicación Primero, crea un archivo `Dockerfile` en el directorio raíz de tu proyecto PHP: ```dockerfile FROM dunglas/frankenphp # Asegúrate de reemplazar "tu-dominio.ejemplo.com" por tu nombre de dominio ENV SERVER_NAME=tu-dominio.ejemplo.com # Si quieres deshabilitar HTTPS, usa este valor en su lugar: #ENV SERVER_NAME=:80 # Si tu proyecto no usa el directorio "public" como raíz web, puedes establecerlo aquí: # ENV SERVER_ROOT=web/ # Habilitar configuración de producción de PHP RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Copiar los archivos PHP de tu proyecto en el directorio público COPY . /app/public # Si usas Symfony o Laravel, necesitas copiar todo el proyecto en su lugar: #COPY . /app ``` Consulta "[Construyendo una Imagen Docker Personalizada](docker.md)" para más detalles y opciones, y para aprender cómo personalizar la configuración, instalar extensiones PHP y módulos de Caddy. Si tu proyecto usa Composer, asegúrate de incluirlo en la imagen Docker e instalar tus dependencias. Luego, agrega un archivo `compose.yaml`: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Volúmenes necesarios para los certificados y configuración de Caddy volumes: caddy_data: caddy_config: ``` > [!NOTE] > > Los ejemplos anteriores están destinados a uso en producción. > En desarrollo, es posible que desees usar un volumen, una configuración PHP diferente y un valor diferente para la variable de entorno `SERVER_NAME`. > > Consulta el proyecto [Symfony Docker](https://github.com/dunglas/symfony-docker) > (que usa FrankenPHP) para un ejemplo más avanzado usando imágenes multi-etapa, > Composer, extensiones PHP adicionales, etc. Finalmente, si usas Git, haz commit de estos archivos y haz push. ## Preparando un Servidor Para desplegar tu aplicación en producción, necesitas un servidor. En este tutorial, usaremos una máquina virtual proporcionada por DigitalOcean, pero cualquier servidor Linux puede funcionar. Si ya tienes un servidor Linux con Docker instalado, puedes saltar directamente a [la siguiente sección](#configurando-un-nombre-de-dominio). De lo contrario, usa [este enlace de afiliado](https://m.do.co/c/5d8aabe3ab80) para obtener $200 de crédito gratuito, crea una cuenta y luego haz clic en "Crear un Droplet". Luego, haz clic en la pestaña "Marketplace" bajo la sección "Elegir una imagen" y busca la aplicación llamada "Docker". Esto aprovisionará un servidor Ubuntu con las últimas versiones de Docker y Docker Compose ya instaladas. Para fines de prueba, los planes más económicos serán suficientes. Para un uso real en producción, probablemente querrás elegir un plan en la sección "uso general" que se adapte a tus necesidades. ![Desplegando FrankenPHP en DigitalOcean con Docker](digitalocean-droplet.png) Puedes mantener los valores predeterminados para otras configuraciones o ajustarlos según tus necesidades. No olvides agregar tu clave SSH o crear una contraseña y luego presionar el botón "Finalizar y crear". Luego, espera unos segundos mientras se aprovisiona tu Droplet. Cuando tu Droplet esté listo, usa SSH para conectarte: ```console ssh root@ ``` ## Configurando un Nombre de Dominio En la mayoría de los casos, querrás asociar un nombre de dominio a tu sitio. Si aún no tienes un nombre de dominio, deberás comprar uno a través de un registrador. Luego, crea un registro DNS de tipo `A` para tu nombre de dominio que apunte a la dirección IP de tu servidor: ```dns tu-dominio.ejemplo.com. IN A 207.154.233.113 ``` Ejemplo con el servicio de Dominios de DigitalOcean ("Redes" > "Dominios"): ![Configurando DNS en DigitalOcean](../digitalocean-dns.png) > [!NOTE] > > Let's Encrypt, el servicio utilizado por defecto por FrankenPHP para generar automáticamente un certificado TLS, no soporta el uso de direcciones IP puras. Usar un nombre de dominio es obligatorio para usar Let's Encrypt. ## Despliegue Copia tu proyecto en el servidor usando `git clone`, `scp` o cualquier otra herramienta que se ajuste a tus necesidades. Si usas GitHub, es posible que desees usar [una clave de despliegue](https://docs.github.com/es/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys). Las claves de despliegue también son [soportadas por GitLab](https://docs.gitlab.com/ee/user/project/deploy_keys/). Ejemplo con Git: ```console git clone git@github.com:/.git ``` Ve al directorio que contiene tu proyecto (``) e inicia la aplicación en modo producción: ```console docker compose up --wait ``` Tu servidor está en funcionamiento y se ha generado automáticamente un certificado HTTPS para ti. Ve a `https://tu-dominio.ejemplo.com` y ¡disfruta! > [!CAUTION] > > Docker puede tener una capa de caché, asegúrate de tener la compilación correcta para cada despliegue o vuelve a compilar tu proyecto con la opción `--no-cache` para evitar problemas de caché. ## Despliegue en Múltiples Nodos Si deseas desplegar tu aplicación en un clúster de máquinas, puedes usar [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), que es compatible con los archivos Compose proporcionados. Para desplegar en Kubernetes, consulta [el gráfico Helm proporcionado con API Platform](https://api-platform.com/docs/deployment/kubernetes/), que usa FrankenPHP. ================================================ FILE: docs/es/static.md ================================================ # Crear una Compilación Estática En lugar de usar una instalación local de la biblioteca PHP, es posible crear una compilación estática o mayormente estática de FrankenPHP gracias al excelente [proyecto static-php-cli](https://github.com/crazywhalecc/static-php-cli) (a pesar de su nombre, este proyecto soporta todas las SAPI, no solo CLI). Con este método, un único binario portátil contendrá el intérprete de PHP, el servidor web Caddy y FrankenPHP. Los ejecutables nativos completamente estáticos no requieren dependencias y pueden ejecutarse incluso en la imagen Docker [`scratch`](https://docs.docker.com/build/building/base-images/#create-a-minimal-base-image-using-scratch). Sin embargo, no pueden cargar extensiones PHP dinámicas (como Xdebug) y tienen algunas limitaciones porque usan la libc musl. Los binarios mayormente estáticos solo requieren `glibc` y pueden cargar extensiones dinámicas. Cuando sea posible, recomendamos usar compilaciones mayormente estáticas basadas en glibc. FrankenPHP también soporta [incrustar la aplicación PHP en el binario estático](embed.md). ## Linux Proporcionamos imágenes Docker para compilar binarios Linux estáticos: ### Compilación Completamente Estática Basada en musl Para un binario completamente estático que se ejecuta en cualquier distribución Linux sin dependencias pero que no soporta carga dinámica de extensiones: ```console docker buildx bake --load static-builder-musl docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-musl ``` Para un mejor rendimiento en escenarios altamente concurrentes, considera usar el asignador [mimalloc](https://github.com/microsoft/mimalloc). ```console docker buildx bake --load --set static-builder-musl.args.MIMALLOC=1 static-builder-musl ``` ### Compilación Mayormente Estática Basada en glibc (Con Soporte para Extensiones Dinámicas) Para un binario que soporta la carga dinámica de extensiones PHP mientras tiene las extensiones seleccionadas compiladas estáticamente: ```console docker buildx bake --load static-builder-gnu docker cp $(docker create --name static-builder-gnu dunglas/frankenphp:static-builder-gnu):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-gnu ``` Este binario soporta todas las versiones de glibc 2.17 y superiores, pero no se ejecuta en sistemas basados en musl (como Alpine Linux). El binario resultante (mayormente estático excepto por `glibc`) se llama `frankenphp` y está disponible en el directorio actual. Si deseas compilar el binario estático sin Docker, consulta las instrucciones para macOS, que también funcionan para Linux. ### Extensiones Personalizadas Por omisión, se compilan las extensiones PHP más populares. Para reducir el tamaño del binario y disminuir la superficie de ataque, puedes elegir la lista de extensiones a compilar usando el ARG de Docker `PHP_EXTENSIONS`. Por ejemplo, ejecuta el siguiente comando para compilar solo la extensión `opcache`: ```console docker buildx bake --load --set static-builder-musl.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder-musl # ... ``` Para agregar bibliotecas que habiliten funcionalidades adicionales a las extensiones que has habilitado, puedes pasar el ARG de Docker `PHP_EXTENSION_LIBS`: ```console docker buildx bake \ --load \ --set static-builder-musl.args.PHP_EXTENSIONS=gd \ --set static-builder-musl.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder-musl ``` ### Módulos Adicionales de Caddy Para agregar módulos adicionales de Caddy o pasar otros argumentos a [xcaddy](https://github.com/caddyserver/xcaddy), usa el ARG de Docker `XCADDY_ARGS`: ```console docker buildx bake \ --load \ --set static-builder-musl.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder-musl ``` En este ejemplo, agregamos el módulo de caché HTTP [Souin](https://souin.io) para Caddy, así como los módulos [cbrotli](https://github.com/dunglas/caddy-cbrotli), [Mercure](https://mercure.rocks) y [Vulcain](https://vulcain.rocks). > [!TIP] > > Los módulos cbrotli, Mercure y Vulcain están incluidos por omisión si `XCADDY_ARGS` está vacío o no está configurado. > Si personalizas el valor de `XCADDY_ARGS`, debes incluirlos explícitamente si deseas que estén incluidos. Consulta también cómo [personalizar la compilación](#personalizando-la-compilación). ### Token de GitHub Si alcanzas el límite de tasa de la API de GitHub, establece un Token de Acceso Personal de GitHub en una variable de entorno llamada `GITHUB_TOKEN`: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS Ejecuta el siguiente script para crear un binario estático para macOS (debes tener [Homebrew](https://brew.sh/) instalado): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Nota: este script también funciona en Linux (y probablemente en otros Unix) y es usado internamente por las imágenes Docker que proporcionamos. ## Personalizando la Compilación Las siguientes variables de entorno pueden pasarse a `docker build` y al script `build-static.sh` para personalizar la compilación estática: - `FRANKENPHP_VERSION`: la versión de FrankenPHP a usar - `PHP_VERSION`: la versión de PHP a usar - `PHP_EXTENSIONS`: las extensiones PHP a compilar ([lista de extensiones soportadas](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: bibliotecas adicionales a compilar que añaden funcionalidades a las extensiones - `XCADDY_ARGS`: argumentos a pasar a [xcaddy](https://github.com/caddyserver/xcaddy), por ejemplo para agregar módulos adicionales de Caddy - `EMBED`: ruta de la aplicación PHP a incrustar en el binario - `CLEAN`: cuando está establecido, libphp y todas sus dependencias se compilan desde cero (sin caché) - `NO_COMPRESS`: no comprimir el binario resultante usando UPX - `DEBUG_SYMBOLS`: cuando está establecido, los símbolos de depuración no se eliminarán y se añadirán al binario - `MIMALLOC`: (experimental, solo Linux) reemplaza mallocng de musl por [mimalloc](https://github.com/microsoft/mimalloc) para mejorar el rendimiento. Solo recomendamos usar esto para compilaciones orientadas a musl; para glibc, preferimos deshabilitar esta opción y usar [`LD_PRELOAD`](https://microsoft.github.io/mimalloc/overrides.html) cuando ejecutes tu binario. - `RELEASE`: (solo para mantenedores) cuando está establecido, el binario resultante se subirá a GitHub ## Extensiones Con los binarios basados en glibc o macOS, puedes cargar extensiones PHP dinámicamente. Sin embargo, estas extensiones deberán ser compiladas con soporte ZTS. Dado que la mayoría de los gestores de paquetes no ofrecen actualmente versiones ZTS de sus extensiones, tendrás que compilarlas tú mismo. Para esto, puedes compilar y ejecutar el contenedor Docker `static-builder-gnu`, acceder a él y compilar las extensiones con `./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config`. Pasos de ejemplo para [la extensión Xdebug](https://xdebug.org): ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` Esto creará `frankenphp` y `xdebug-zts.so` en el directorio actual. Si mueves `xdebug-zts.so` a tu directorio de extensiones, agrega `zend_extension=xdebug-zts.so` a tu php.ini y ejecuta FrankenPHP, cargará Xdebug. ================================================ FILE: docs/es/wordpress.md ================================================ # WordPress Ejecute [WordPress](https://wordpress.org/) con FrankenPHP para disfrutar de una pila moderna y de alto rendimiento con HTTPS automático, HTTP/3 y compresión Zstandard. ## Instalación Mínima 1. [Descargue WordPress](https://wordpress.org/download/) 2. Extraiga el archivo ZIP y abra una terminal en el directorio extraído 3. Ejecute: ```console frankenphp php-server ``` 4. Vaya a `http://localhost/wp-admin/` y siga las instrucciones de instalación 5. ¡Listo! Para una configuración lista para producción, prefiera usar `frankenphp run` con un `Caddyfile` como este: ```caddyfile example.com php_server encode zstd br gzip log ``` ## Hot Reload Para usar la función de [Hot reload](hot-reload.md) con WordPress, active [Mercure](mercure.md) y agregue la subdirectiva `hot_reload` a la directiva `php_server` en su `Caddyfile`: ```caddyfile localhost mercure { anonymous } php_server { hot_reload } ``` Luego, agregue el código necesario para cargar las bibliotecas JavaScript en el archivo `functions.php` de su tema de WordPress: ```php function hot_reload() { ?> [!TIP] > La siguiente sección es necesaria solo para versiones anteriores a Symfony 7.4, donde se introdujo soporte nativo para el modo worker de FrankenPHP. El modo worker de FrankenPHP es soportado por el [Componente Runtime de Symfony](https://symfony.com/doc/current/components/runtime.html). Para iniciar cualquier aplicación Symfony en un worker, instala el paquete FrankenPHP de [PHP Runtime](https://github.com/php-runtime/runtime): ```console composer require runtime/frankenphp-symfony ``` Inicia tu servidor de aplicación definiendo la variable de entorno `APP_RUNTIME` para usar el Runtime de FrankenPHP Symfony: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane Consulta [la documentación dedicada](laravel.md#laravel-octane). ## Aplicaciones Personalizadas El siguiente ejemplo muestra cómo crear tu propio script de worker sin depender de una biblioteca de terceros: ```php boot(); // Manejador fuera del bucle para mejor rendimiento (menos trabajo) $handler = static function () use ($myApp) { try { // Llamado cuando se recibe una petición, // las superglobales, php://input y similares se reinician echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` se llama solo cuando el script de worker termina, // lo cual puede no ser lo que esperas, así que captura y maneja excepciones aquí (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // Haz algo después de enviar la respuesta HTTP $myApp->terminate(); // Llama al recolector de basura para reducir las posibilidades de que se active en medio de la generación de una página gc_collect_cycles(); if (!$keepRunning) break; } // Limpieza $myApp->shutdown(); ``` Luego, inicia tu aplicación y usa la variable de entorno `FRANKENPHP_CONFIG` para configurar tu worker: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Por omisión, se inician 2 workers por CPU. También puedes configurar el número de workers a iniciar: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Reiniciar el Worker Después de un Número Determinado de Peticiones Como PHP no fue diseñado originalmente para procesos de larga duración, aún hay muchas bibliotecas y códigos heredados que generan fugas de memoria. Una solución para usar este tipo de código en modo worker es reiniciar el script de worker después de procesar un cierto número de peticiones: El fragmento de worker anterior permite configurar un número máximo de peticiones a manejar estableciendo una variable de entorno llamada `MAX_REQUESTS`. ### Reiniciar Workers Manualmente Aunque es posible reiniciar workers [al detectar cambios en archivos](config.md#watching-for-file-changes), también es posible reiniciar todos los workers de manera controlada a través de la [API de administración de Caddy](https://caddyserver.com/docs/api). Si el admin está habilitado en tu [Caddyfile](config.md#caddyfile-config), puedes activar el endpoint de reinicio con una simple petición POST como esta: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Fallos en Workers Si un script de worker falla con un código de salida distinto de cero, FrankenPHP lo reiniciará con una estrategia de retroceso exponencial. Si el script de worker permanece activo más tiempo que el último retroceso * 2, no penalizará al script de worker y lo reiniciará nuevamente. Sin embargo, si el script de worker continúa fallando con un código de salida distinto de cero en un corto período de tiempo (por ejemplo, tener un error tipográfico en un script), FrankenPHP fallará con el error: `too many consecutive failures`. El número de fallos consecutivos puede configurarse en tu [Caddyfile](config.md#caddyfile-config) con la opción `max_consecutive_failures`: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Comportamiento de las Superglobales Las [superglobales de PHP](https://www.php.net/manual/es/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) se comportan de la siguiente manera: - antes de la primera llamada a `frankenphp_handle_request()`, las superglobales contienen valores vinculados al script de worker en sí - durante y después de la llamada a `frankenphp_handle_request()`, las superglobales contienen valores generados a partir de la petición HTTP procesada; cada llamada a `frankenphp_handle_request()` cambia los valores de las superglobales Para acceder a las superglobales del script de worker dentro de la retrollamada, debes copiarlas e importar la copia en el ámbito de la retrollamada: ```php import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. Ensure worker is ready if worker == nil { return false } // 2. Dispatch to the background worker _, err := worker.SendMessage( context.Background(), // Standard Go context unsafe.Pointer(data), // Data to pass to the worker nil, // Optional http.ResponseWriter ) return err == nil } ``` ### HTTP Emulation :`SendRequest` Use `SendRequest` if your extension needs to invoke a PHP script that expects a standard web environment (populating `$_SERVER`, `$_GET`, etc.). ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. Prepare the request and recorder url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. Dispatch to the worker if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Return the captured response return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Worker Script The PHP worker script runs in a loop and can handle both raw messages and HTTP requests. ```php [!TIP] > If you want to understand how extensions can be written in Go from scratch, you can read the manual implementation section below demonstrating how to write a PHP extension in Go without using the generator. Keep in mind that this tool is **not a full-fledged extension generator**. It is meant to help you write simple extensions in Go, but it does not provide the most advanced features of PHP extensions. If you need to write a more **complex and optimized** extension, you may need to write some C code or use CGO directly. ### Prerequisites As covered in the manual implementation section below as well, you need to [get the PHP sources](https://www.php.net/downloads.php) and create a new Go module. #### Create a New Module and Get PHP Sources The first step to writing a PHP extension in Go is to create a new Go module. You can use the following command for this: ```console go mod init example.com/example ``` The second step is to [get the PHP sources](https://www.php.net/downloads.php) for the next steps. Once you have them, decompress them into the directory of your choice, not inside your Go module: ```console tar xf php-* ``` ### Writing the Extension Everything is now setup to write your native function in Go. Create a new file named `stringext.go`. Our first function will take a string as an argument, the number of times to repeat it, a boolean to indicate whether to reverse the string, and return the resulting string. This should look like this: ```go package example // #include import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` There are two important things to note here: - A directive comment `//export_php:function` defines the function signature in PHP. This is how the generator knows how to generate the PHP function with the right parameters and return type; - The function must return an `unsafe.Pointer`. FrankenPHP provides an API to help you with type juggling between C and Go. While the first point speaks for itself, the second may be harder to apprehend. Let's take a deeper dive to type juggling in the next section. ### Type Juggling While some variable types have the same memory representation between C/PHP and Go, some types require more logic to be directly used. This is maybe the hardest part when it comes to writing extensions because it requires understanding internals of the Zend Engine and how variables are stored internally in PHP. This table summarizes what you need to know: | PHP type | Go type | Direct conversion | C to Go helper | Go to C helper | Class Methods Support | | ------------------ | ----------------------------- | ----------------- | --------------------------------- | ---------------------------------- | --------------------- | | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | `frankenphp.GoString()` | `frankenphp.PHPString()` | ✅ | | `array` | `frankenphp.AssociativeArray` | ❌ | `frankenphp.GoAssociativeArray()` | `frankenphp.PHPAssociativeArray()` | ✅ | | `array` | `map[string]any` | ❌ | `frankenphp.GoMap()` | `frankenphp.PHPMap()` | ✅ | | `array` | `[]any` | ❌ | `frankenphp.GoPackedArray()` | `frankenphp.PHPPackedArray()` | ✅ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `callable` | `*C.zval` | ❌ | - | frankenphp.CallPHPCallable() | ❌ | | `object` | `struct` | ❌ | _Not yet implemented_ | _Not yet implemented_ | ❌ | > [!NOTE] > > This table is not exhaustive yet and will be completed as the FrankenPHP types API gets more complete. > > For class methods specifically, primitive types and arrays are currently supported. Objects cannot be used as method parameters or return types yet. If you refer to the code snippet of the previous section, you can see that helpers are used to convert the first parameter and the return value. The second and third parameter of our `repeat_this()` function don't need to be converted as memory representation of the underlying types are the same for both C and Go. #### Working with Arrays FrankenPHP provides native support for PHP arrays through `frankenphp.AssociativeArray` or direct conversion to a map or slice. `AssociativeArray` represents a [hash map](https://en.wikipedia.org/wiki/Hash_table) composed of a `Map: map[string]any`field and an optional `Order: []string` field (unlike PHP "associative arrays", Go maps aren't ordered). If order or association are not needed, it's also possible to directly convert to a slice `[]any` or unordered map `map[string]any`. **Creating and manipulating arrays in Go:** ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:function process_data_ordered(array $input): array func process_data_ordered_map(arr *C.zend_array) unsafe.Pointer { // Convert PHP associative array to Go while keeping the order associativeArray, err := frankenphp.GoAssociativeArray[any](unsafe.Pointer(arr)) if err != nil { // handle error } // loop over the entries in order for _, key := range associativeArray.Order { value, _ = associativeArray.Map[key] // do something with key and value } // return an ordered array // if 'Order' is not empty, only the key-value pairs in 'Order' will be respected return frankenphp.PHPAssociativeArray[string](frankenphp.AssociativeArray[string]{ Map: map[string]string{ "key1": "value1", "key2": "value2", }, Order: []string{"key1", "key2"}, }) } // export_php:function process_data_unordered(array $input): array func process_data_unordered_map(arr *C.zend_array) unsafe.Pointer { // Convert PHP associative array to a Go map without keeping the order // ignoring the order will be more performant goMap, err := frankenphp.GoMap[any](unsafe.Pointer(arr)) if err != nil { // handle error } // loop over the entries in no specific order for key, value := range goMap { // do something with key and value } // return an unordered array return frankenphp.PHPMap(map[string]string { "key1": "value1", "key2": "value2", }) } // export_php:function process_data_packed(array $input): array func process_data_packed(arr *C.zend_array) unsafe.Pointer { // Convert PHP packed array to Go goSlice, err := frankenphp.GoPackedArray(unsafe.Pointer(arr)) if err != nil { // handle error } // loop over the slice in order for index, value := range goSlice { // do something with index and value } // return a packed array return frankenphp.PHPPackedArray([]string{"value1", "value2", "value3"}) } ``` **Key features of array conversion:** - **Ordered key-value pairs** - Option to keep the order of the associative array - **Optimized for multiple cases** - Option to ditch the order for better performance or convert straight to a slice - **Automatic list detection** - When converting to PHP, automatically detects if array should be a packed list or hashmap - **Nested Arrays** - Arrays can be nested and will convert all support types automatically (`int64`,`float64`,`string`,`bool`,`nil`,`AssociativeArray`,`map[string]any`,`[]any`) - **Objects are not supported** - Currently, only scalar types and arrays can be used as values. Providing an object will result in a `null` value in the PHP array. ##### Available methods: Packed and Associative - `frankenphp.PHPAssociativeArray(arr frankenphp.AssociativeArray) unsafe.Pointer` - Convert to an ordered PHP array with key-value pairs - `frankenphp.PHPMap(arr map[string]any) unsafe.Pointer` - Convert a map to an unordered PHP array with key-value pairs - `frankenphp.PHPPackedArray(slice []any) unsafe.Pointer` - Convert a slice to a PHP packed array with indexed values only - `frankenphp.GoAssociativeArray(arr unsafe.Pointer, ordered bool) frankenphp.AssociativeArray` - Convert a PHP array to an ordered Go `AssociativeArray` (map with order) - `frankenphp.GoMap(arr unsafe.Pointer) map[string]any` - Convert a PHP array to an unordered Go map - `frankenphp.GoPackedArray(arr unsafe.Pointer) []any` - Convert a PHP array to a Go slice - `frankenphp.IsPacked(zval *C.zend_array) bool` - Check if a PHP array is packed (indexed only) or associative (key-value pairs) ### Working with Callables FrankenPHP provides a way to work with PHP callables using the `frankenphp.CallPHPCallable` helper. This allows you to call PHP functions or methods from Go code. To showcase this, let's create our own `array_map()` function that takes a callable and an array, applies the callable to each element of the array, and returns a new array with the results: ```go // export_php:function my_array_map(array $data, callable $callback): array func my_array_map(arr *C.zend_array, callback *C.zval) unsafe.Pointer { goSlice, err := frankenphp.GoPackedArray[any](unsafe.Pointer(arr)) if err != nil { panic(err) } result := make([]any, len(goSlice)) for index, value := range goSlice { result[index] = frankenphp.CallPHPCallable(unsafe.Pointer(callback), []interface{}{value}) } return frankenphp.PHPPackedArray(result) } ``` Notice how we use `frankenphp.CallPHPCallable()` to call the PHP callable passed as a parameter. This function takes a pointer to the callable and an array of arguments, and it returns the result of the callable execution. You can use the callable syntax you're used to: ```php name` won't work) - **Method-only interface** - All interactions must go through methods you define - **Better encapsulation** - Internal data structure is completely controlled by Go code - **Type safety** - No risk of PHP code corrupting internal state with wrong types - **Cleaner API** - Forces to design a proper public interface This approach provides better encapsulation and prevents PHP code from accidentally corrupting the internal state of your Go objects. All interactions with the object must go through the methods you explicitly define. #### Adding Methods to Classes Since properties are not directly accessible, you **must define methods** to interact with your opaque classes. Use the `//export_php:method` directive to define behavior: ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### Nullable Parameters The generator supports nullable parameters using the `?` prefix in PHP signatures. When a parameter is nullable, it becomes a pointer in your Go function, allowing you to check if the value was `null` in PHP: ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // Check if name was provided (not null) if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // Check if age was provided (not null) if age != nil { us.Age = int(*age) } // Check if active was provided (not null) if active != nil { us.Active = *active } } ``` **Key points about nullable parameters:** - **Nullable primitive types** (`?int`, `?float`, `?bool`) become pointers (`*int64`, `*float64`, `*bool`) in Go - **Nullable strings** (`?string`) remain as `*C.zend_string` but can be `nil` - **Check for `nil`** before dereferencing pointer values - **PHP `null` becomes Go `nil`** - when PHP passes `null`, your Go function receives a `nil` pointer > [!WARNING] > > Currently, class methods have the following limitations. **Objects are not supported** as parameter types or return types. **Arrays are fully supported** for both parameters and return types. Supported types: `string`, `int`, `float`, `bool`, `array`, and `void` (for return type). **Nullable parameter types are fully supported** for all scalar types (`?string`, `?int`, `?float`, `?bool`). After generating the extension, you will be allowed to use the class and its methods in PHP. Note that you **cannot access properties directly**: ```php setAge(25); echo $user->getName(); // Output: (empty, default value) echo $user->getAge(); // Output: 25 $user->setNamePrefix("Employee"); // ✅ This also works - nullable parameters $user->updateInfo("John", 30, true); // All parameters provided $user->updateInfo("Jane", null, false); // Age is null $user->updateInfo(null, 25, null); // Name and active are null // ❌ This will NOT work - direct property access // echo $user->name; // Error: Cannot access private property // $user->age = 30; // Error: Cannot access private property ``` This design ensures that your Go code has complete control over how the object's state is accessed and modified, providing better encapsulation and type safety. ### Declaring Constants The generator supports exporting Go constants to PHP using two directives: `//export_php:const` for global constants and `//export_php:classconst` for class constants. This allows you to share configuration values, status codes, and other constants between Go and PHP code. #### Global Constants Use the `//export_php:const` directive to create global PHP constants: ```go package example //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const ( STATUS_OK = iota STATUS_ERROR ) ``` > [!NOTE] > PHP constants will take the name of the Go constant, thus using upper case letters is recommended. #### Class Constants Use the `//export_php:classconst ClassName` directive to create constants that belong to a specific PHP class: ```go package example //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const ( STATE_PENDING = iota STATE_PROCESSING STATE_COMPLETED ) ``` > [!NOTE] > Just like global constants, the class constants will take the name of the Go constant. Class constants are accessible using the class name scope in PHP: ```php import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:const const STR_REVERSE = iota //export_php:const const STR_NORMAL = iota //export_php:classconst StringProcessor const MODE_LOWERCASE = 1 //export_php:classconst StringProcessor const MODE_UPPERCASE = 2 //export_php:function repeat_this(string $str, int $count, int $mode): string func repeat_this(s *C.zend_string, count int64, mode int) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if mode == STR_REVERSE { // reverse the string } if mode == STR_NORMAL { // no-op, just to showcase the constant } return frankenphp.PHPString(result, false) } //export_php:class StringProcessor type StringProcessorStruct struct { // internal fields } //export_php:method StringProcessor::process(string $input, int $mode): string func (sp *StringProcessorStruct) Process(input *C.zend_string, mode int64) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(input)) switch mode { case MODE_LOWERCASE: str = strings.ToLower(str) case MODE_UPPERCASE: str = strings.ToUpper(str) } return frankenphp.PHPString(str, false) } ``` ### Using Namespaces The generator supports organizing your PHP extension's functions, classes, and constants under a namespace using the `//export_php:namespace` directive. This helps avoid naming conflicts and provides better organization for your extension's API. #### Declaring a Namespace Use the `//export_php:namespace` directive at the top of your Go file to place all exported symbols under a specific namespace: ```go //export_php:namespace My\Extension package example import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function hello(): string func hello() string { return "Hello from My\\Extension namespace!" } //export_php:class User type UserStruct struct { // internal fields } //export_php:method User::getName(): string func (u *UserStruct) GetName() unsafe.Pointer { return frankenphp.PHPString("John Doe", false) } //export_php:const const STATUS_ACTIVE = 1 ``` #### Using Namespaced Extension in PHP When a namespace is declared, all functions, classes, and constants are placed under that namespace in PHP: ```php getName(); // "John Doe" echo My\Extension\STATUS_ACTIVE; // 1 ``` #### Important Notes - Only **one** namespace directive is allowed per file. If multiple namespace directives are found, the generator will return an error. - The namespace applies to **all** exported symbols in the file: functions, classes, methods, and constants. - Namespace names follow PHP namespace conventions using backslashes (`\`) as separators. - If no namespace is declared, symbols are exported to the global namespace as usual. ### Generating the Extension This is where the magic happens, and your extension can now be generated. You can run the generator with the following command: ```console GEN_STUB_SCRIPT=php-src/build/gen_stub.php frankenphp extension-init my_extension.go ``` > [!NOTE] > Don't forget to set the `GEN_STUB_SCRIPT` environment variable to the path of the `gen_stub.php` file in the PHP sources you downloaded earlier. This is the same `gen_stub.php` script mentioned in the manual implementation section. If everything went well, your project directory should contain the following files for your extension: - **`my_extension.go`** - Your original source file (remains unchanged) - **`my_extension_generated.go`** - Generated file with CGO wrappers that call your functions - **`my_extension.stub.php`** - PHP stub file for IDE autocompletion - **`my_extension_arginfo.h`** - PHP argument information - **`my_extension.h`** - C header file - **`my_extension.c`** - C implementation file - **`README.md`** - Documentation > [!IMPORTANT] > **Your source file (`my_extension.go`) is never modified.** The generator creates a separate `_generated.go` file containing CGO wrappers that call your original functions. This means you can safely version control your source file without worrying about generated code polluting it. ### Integrating the Generated Extension into FrankenPHP Our extension is now ready to be compiled and integrated into FrankenPHP. To do this, refer to the FrankenPHP [compilation documentation](compile.md) to learn how to compile FrankenPHP. Add the module using the `--with` flag, pointing to the path of your module: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module/build ``` Note that you point to the `/build` subdirectory that was created during the generation step. However, this is not mandatory: you can also copy the generated files to your module directory and point to it directly. ### Testing Your Generated Extension You can create a PHP file to test the functions and classes you've created. For example, create an `index.php` file with the following content: ```php process('Hello World', StringProcessor::MODE_LOWERCASE); // "hello world" echo $processor->process('Hello World', StringProcessor::MODE_UPPERCASE); // "HELLO WORLD" ``` Once you've integrated your extension into FrankenPHP as demonstrated in the previous section, you can run this test file using `./frankenphp php-server`, and you should see your extension working. ## Manual Implementation If you want to understand how extensions work or need full control over your extension, you can write them manually. This approach gives you complete control but requires more boilerplate code. ### Basic Function We'll see how to write a simple PHP extension in Go that defines a new native function. This function will be called from PHP and will trigger a goroutine that logs a message in Caddy's logs. This function doesn't take any parameters and returns nothing. #### Define the Go Function In your module, you need to define a new native function that will be called from PHP. To do this, create a file with the name you want, for example, `extension.go`, and add the following code: ```go package example // #include "extension.h" import "C" import ( "log/slog" "unsafe" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { slog.Info("Hello from a goroutine!") }() } ``` The `frankenphp.RegisterExtension()` function simplifies the extension registration process by handling the internal PHP registration logic. The `go_print_something` function uses the `//export` directive to indicate that it will be accessible in the C code we will write, thanks to CGO. In this example, our new function will trigger a goroutine that logs a message in Caddy's logs. #### Define the PHP Function To allow PHP to call our function, we need to define a corresponding PHP function. For this, we will create a stub file, for example, `extension.stub.php`, which will contain the following code: ```php extern zend_module_entry ext_module_entry; #endif ``` Next, create a file named `extension.c` that will perform the following steps: - Include PHP headers; - Declare our new native PHP function `go_print()`; - Declare the extension metadata. Let's start by including the required headers: ```c #include #include "extension.h" #include "extension_arginfo.h" // Contains symbols exported by Go #include "_cgo_export.h" ``` We then define our PHP function as a native language function: ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` In this case, our function takes no parameters and returns nothing. It simply calls the Go function we defined earlier, exported using the `//export` directive. Finally, we define the extension's metadata in a `zend_module_entry` structure, such as its name, version, and properties. This information is necessary for PHP to recognize and load our extension. Note that `ext_functions` is an array of pointers to the PHP functions we defined, and it was automatically generated by the `gen_stub.php` script in the `extension_arginfo.h` file. The extension registration is automatically handled by FrankenPHP's `RegisterExtension()` function that we call in our Go code. ### Advanced Usage Now that we know how to create a basic PHP extension in Go, let's complexify our example. We will now create a PHP function that takes a string as a parameter and returns its uppercase version. #### Define the PHP Function Stub To define the new PHP function, we will modify our `extension.stub.php` file to include the new function signature: ```php [!TIP] > Don't neglect the documentation of your functions! You are likely to share your extension stubs with other developers to document how to use your extension and which features are available. By regenerating the stub file with the `gen_stub.php` script, the `extension_arginfo.h` file should look like this: ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` We can see that the `go_upper` function is defined with a parameter of type `string` and a return type of `string`. #### Type Juggling Between Go and PHP/C Your Go function cannot directly accept a PHP string as a parameter. You need to convert it to a Go string. Fortunately, FrankenPHP provides helper functions to handle the conversion between PHP strings and Go strings, similar to what we saw in the generator approach. The header file remains simple: ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` We can now write the bridge between Go and C in our `extension.c` file. We will pass the PHP string directly to our Go function: ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` You can learn more about the `ZEND_PARSE_PARAMETERS_START` and parameters parsing in the dedicated page of [the PHP Internals Book](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters). Here, we tell PHP that our function takes one mandatory parameter of type `string` as a `zend_string`. We then pass this string directly to our Go function and return the result using `RETVAL_STR`. There's only one thing left to do: implement the `go_upper` function in Go. #### Implement the Go Function Our Go function will take a `*C.zend_string` as a parameter, convert it to a Go string using FrankenPHP's helper function, process it, and return the result as a new `*C.zend_string`. The helper functions handle all the memory management and conversion complexity for us. ```go package example // #include import "C" import ( "unsafe" "strings" "github.com/dunglas/frankenphp" ) //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` This approach is much cleaner and safer than manual memory management. FrankenPHP's helper functions handle the conversion between PHP's `zend_string` format and Go strings automatically. The `false` parameter in `PHPString()` indicates that we want to create a new non-persistent string (freed at the end of the request). > [!TIP] > > In this example, we don't perform any error handling, but you should always check that pointers are not `nil` and that the data is valid before using it in your Go functions. ### Integrating the Extension into FrankenPHP Our extension is now ready to be compiled and integrated into FrankenPHP. To do this, refer to the FrankenPHP [compilation documentation](compile.md) to learn how to compile FrankenPHP. Add the module using the `--with` flag, pointing to the path of your module: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module ``` That's it! Your extension is now integrated into FrankenPHP and can be used in your PHP code. ### Testing Your Extension After integrating your extension into FrankenPHP, you can create an `index.php` file with examples for the functions you've implemented: ```php [!NOTE] > > Si vous utilisez Docker, vous devrez soit lier le port 80 du conteneur, soit exécuter depuis l'intérieur du conteneur. ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## Serveur de test minimal Construire le serveur de test minimal : ```console cd internal/testserver/ go build cd ../../ ``` Lancer le test serveur : ```console cd testdata/ ../internal/testserver/testserver ``` Le serveur est configuré pour écouter à l'adresse `127.0.0.1:8080`: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Construire localement les images Docker Afficher le plan de compilation : ```console docker buildx bake -f docker-bake.hcl --print ``` Construire localement les images FrankenPHP pour amd64 : ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` Construire localement les images FrankenPHP pour arm64 : ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` Construire à partir de zéro les images FrankenPHP pour arm64 & amd64 et les pousser sur Docker Hub : ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## Déboguer les erreurs de segmentation avec les builds statiques 1. Téléchargez la version de débogage du binaire FrankenPHP depuis GitHub ou créez votre propre build statique incluant des symboles de débogage : ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. Remplacez votre version actuelle de `frankenphp` par l'exécutable de débogage de FrankenPHP. 3. Démarrez FrankenPHP comme d'habitude (alternativement, vous pouvez directement démarrer FrankenPHP avec GDB : `gdb --args frankenphp run`). 4. Attachez-vous au processus avec GDB : ```console gdb -p `pidof frankenphp` ``` 5. Si nécessaire, tapez `continue` dans le shell GDB 6. Faites planter FrankenPHP. 7. Tapez `bt` dans le shell GDB 8. Copiez la sortie ## Déboguer les erreurs de segmentation dans GitHub Actions 1. Ouvrir `.github/workflows/tests.yml` 2. Activer les symboles de débogage de la bibliothèque PHP ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. Activer `tmate` pour se connecter au conteneur ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. Se connecter au conteneur 5. Ouvrir `frankenphp.go` 6. Activer `cgosymbolizer` ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Télécharger le module : `go get` 8. Dans le conteneur, vous pouvez utiliser GDB et similaires : ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. Quand le bug est corrigé, annulez tous les changements. ## Ressources Diverses pour le Développement - [Intégration de PHP dans uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [Intégration de PHP dans NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [Intégration de PHP dans Go (go-php)](https://github.com/deuill/go-php) - [Intégration de PHP dans Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [Intégration de PHP dans C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Extending and Embedding PHP par Sara Golemon](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [Qu'est-ce que TSRMLS_CC, au juste ?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [Intégration de PHP sur Mac](https://gist.github.com/jonnywang/61427ffc0e8dde74fff40f479d147db4) - [Bindings SDL](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Ressources Liées à Docker - [Définition du fichier Bake](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Commande utile ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## Traduire la documentation Pour traduire la documentation et le site dans une nouvelle langue, procédez comme suit : 1. Créez un nouveau répertoire nommé avec le code ISO à 2 caractères de la langue dans le répertoire `docs/` de ce dépôt 2. Copiez tous les fichiers `.md` à la racine du répertoire `docs/` dans le nouveau répertoire (utilisez toujours la version anglaise comme source de traduction, car elle est toujours à jour). 3. Copiez les fichiers `README.md` et `CONTRIBUTING.md` du répertoire racine vers le nouveau répertoire. 4. Traduisez le contenu des fichiers, mais ne changez pas les noms de fichiers, ne traduisez pas non plus les chaînes commençant par `> [!` (c'est un balisage spécial pour GitHub). 5. Créez une Pull Request avec les traductions 6. Dans le [référentiel du site](https://github.com/dunglas/frankenphp-website/tree/main), copiez et traduisez les fichiers de traduction dans les répertoires `content/`, `data/` et `i18n/`. 7. Traduire les valeurs dans le fichier YAML créé. 8. Ouvrir une Pull Request sur le dépôt du site. ================================================ FILE: docs/fr/README.md ================================================ # FrankenPHP : le serveur d'applications PHP moderne, écrit en Go

FrankenPHP

FrankenPHP est un serveur d'applications moderne pour PHP construit à partir du serveur web [Caddy](https://caddyserver.com/). FrankenPHP donne des super-pouvoirs à vos applications PHP grâce à ses fonctionnalités à la pointe : [_Early Hints_](early-hints.md), [mode worker](worker.md), [fonctionnalités en temps réel](mercure.md), HTTPS automatique, prise en charge de HTTP/2 et HTTP/3... FrankenPHP fonctionne avec n'importe quelle application PHP et rend vos projets Laravel et Symfony plus rapides que jamais grâce à leurs intégrations officielles avec le mode worker. FrankenPHP peut également être utilisé comme une bibliothèque Go autonome qui permet d'intégrer PHP dans n'importe quelle application en utilisant `net/http`. Découvrez plus de détails sur ce serveur d’application dans le replay de cette conférence donnée au Forum PHP 2022 : Diapositives ## Pour Commencer Sur Windows, utilisez [WSL](https://learn.microsoft.com/windows/wsl/) pour exécuter FrankenPHP. ### Script d'installation Vous pouvez copier cette ligne dans votre terminal pour installer automatiquement une version adaptée à votre plateforme : ```console curl https://frankenphp.dev/install.sh | sh ``` ### Binaire autonome Nous fournissons des binaires statiques de FrankenPHP pour le développement, pour Linux et macOS, contenant [PHP 8.4](https://www.php.net/releases/8.4/fr.php) et la plupart des extensions PHP populaires. [Télécharger FrankenPHP](https://github.com/php/frankenphp/releases) **Installation d'extensions :** Les extensions les plus courantes sont incluses. Il n'est pas possible d'en installer davantage. ### Paquets rpm Nos mainteneurs proposent des paquets rpm pour tous les systèmes utilisant `dnf`. Pour installer, exécutez : ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 8.2-8.5 disponibles sudo dnf install frankenphp ``` **Installation d'extensions :** `sudo dnf install php-zts-` Pour les extensions non disponibles par défaut, utilisez [PIE](https://github.com/php/pie) : ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Paquets deb Nos mainteneurs proposent des paquets deb pour tous les systèmes utilisant `apt`. Pour installer, exécutez : ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **Installation d'extensions :** `sudo apt install php-zts-` Pour les extensions non disponibles par défaut, utilisez [PIE](https://github.com/php/pie) : ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker Des [images Docker](https://frankenphp.dev/docs/fr/docker/) sont également disponibles : ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Rendez-vous sur `https://localhost`, c'est parti ! > [!TIP] > > Ne tentez pas d'utiliser `https://127.0.0.1`. Utilisez `https://localhost` et acceptez le certificat auto-signé. > Utilisez [la variable d'environnement `SERVER_NAME`](config.md#variables-denvironnement) pour changer le domaine à utiliser. ### Homebrew FrankenPHP est également disponible sous forme de paquet [Homebrew](https://brew.sh) pour macOS et Linux. Pour l'installer : ```console brew install dunglas/frankenphp/frankenphp ``` **Installation d'extensions :** Utilisez [PIE](https://github.com/php/pie). ### Utilisation Pour servir le contenu du répertoire courant, exécutez : ```console frankenphp php-server ``` Vous pouvez également exécuter des scripts en ligne de commande avec : ```console frankenphp php-cli /path/to/your/script.php ``` Pour les paquets deb et rpm, vous pouvez aussi démarrer le service systemd : ```console sudo systemctl start frankenphp ``` ## Documentation - [Le mode classique](classic.md) - [Le mode worker](worker.md) - [Le support des Early Hints (code de statut HTTP 103)](early-hints.md) - [Temps réel](mercure.md) - [Servir efficacement les fichiers statiques volumineux](x-sendfile.md) - [Configuration](config.md) - [Écrire des extensions PHP en Go](extensions.md) - [Images Docker](docker.md) - [Déploiement en production](production.md) - [Optimisation des performances](performance.md) - [Créer des applications PHP **standalone**, auto-exécutables](embed.md) - [Créer un build statique](static.md) - [Compiler depuis les sources](compile.md) - [Surveillance de FrankenPHP](metrics.md) - [Intégration Laravel](laravel.md) - [Problèmes connus](known-issues.md) - [Application de démo (Symfony) et benchmarks](https://github.com/dunglas/frankenphp-demo) - [Documentation de la bibliothèque Go](https://pkg.go.dev/github.com/dunglas/frankenphp) - [Contribuer et débugger](CONTRIBUTING.md) ## Exemples et squelettes - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/distribution/) - [Laravel](laravel.md) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/fr/classic.md ================================================ # Utilisation du mode classique Sans aucune configuration additionnelle, FrankenPHP fonctionne en mode classique. Dans ce mode, FrankenPHP fonctionne comme un serveur PHP traditionnel, en servant directement les fichiers PHP. Cela en fait un remplaçant parfait à PHP-FPM ou Apache avec mod_php. Comme Caddy, FrankenPHP accepte un nombre illimité de connexions et utilise un [nombre fixe de threads](config.md#configuration-du-caddyfile) pour les servir. Le nombre de connexions acceptées et en attente n'est limité que par les ressources système disponibles. Le pool de threads PHP fonctionne avec un nombre fixe de threads initialisés au démarrage, comparable au mode statique de PHP-FPM. Il est également possible de laisser les threads [s'adapter automatiquement à l'exécution](performance.md#max_threads), comme dans le mode dynamique de PHP-FPM. Les connexions en file d'attente attendront indéfiniment jusqu'à ce qu'un thread PHP soit disponible pour les servir. Pour éviter cela, vous pouvez utiliser la [configuration](config.md#configuration-du-caddyfile) `max_wait_time` dans la configuration globale de FrankenPHP pour limiter la durée pendant laquelle une requête peut attendre un thread PHP libre avant d'être rejetée. En outre, vous pouvez définir un [délai d'écriture dans Caddy](https://caddyserver.com/docs/caddyfile/options#timeouts) raisonnable. Chaque instance de Caddy n'utilisera qu'un seul pool de threads FrankenPHP, qui sera partagé par tous les blocs `php_server`. ================================================ FILE: docs/fr/compile.md ================================================ # Compiler depuis les sources Ce document explique comment créer un build FrankenPHP qui chargera PHP en tant que bibliothèque dynamique. C'est la méthode recommandée. Alternativement, il est aussi possible de [créer des builds statiques](static.md). ## Installer PHP FrankenPHP est compatible avec PHP 8.2 et versions ultérieures. ### Avec Homebrew (Linux et Mac) La manière la plus simple d'installer une version de libphp compatible avec FrankenPHP est d'utiliser les paquets ZTS fournis par [Homebrew PHP](https://github.com/shivammathur/homebrew-php). Tout d'abord, si ce n'est déjà fait, installez [Homebrew](https://brew.sh). Ensuite, installez la variante ZTS de PHP, Brotli (facultatif, pour la prise en charge de la compression) et watcher (facultatif, pour la détection des modifications de fichiers) : ```console brew install shivammathur/php/php-zts brotli watcher brew link --overwrite --force shivammathur/php/php-zts ``` ### En compilant PHP Vous pouvez également compiler PHP à partir des sources avec les options requises par FrankenPHP en suivant ces étapes. Tout d'abord, [téléchargez les sources de PHP](https://www.php.net/downloads.php) et extrayez-les : ```console tar xf php-* cd php-*/ ``` Ensuite, configurez PHP pour votre système d'exploitation. Les options de configuration suivantes sont nécessaires pour la compilation, mais vous pouvez également inclure d'autres options selon vos besoins, par exemple pour ajouter des extensions et fonctionnalités supplémentaires. ### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` ### Mac Utilisez le gestionnaire de paquets [Homebrew](https://brew.sh/) pour installer les dépendances obligatoires et optionnelles : ```console brew install libiconv bison brotli re2c pkg-config watcher echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` Puis exécutez le script de configuration : ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --disable-opcache-jit \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` ### Compilez PHP Finalement, compilez et installez PHP : ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Installez les dépendances optionnelles Certaines fonctionnalités de FrankenPHP nécessitent des dépendances optionnelles qui doivent être installées. Ces fonctionnalités peuvent également être désactivées en passant des tags de compilation au compilateur Go. | Fonctionnalité | Dépendance | Tag de compilation pour la désactiver | | ------------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------- | | Compression Brotli | [Brotli](https://github.com/google/brotli) | nobrotli | | Redémarrage des workers en cas de changement de fichier | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | ## Compiler l'application Go ### Utiliser xcaddy La méthode recommandée consiste à utiliser [xcaddy](https://github.com/caddyserver/xcaddy) pour compiler FrankenPHP. `xcaddy` permet également d'ajouter facilement des [modules Caddy personnalisés](https://caddyserver.com/docs/modules/) et des extensions FrankenPHP : ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/caddy-cbrotli \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Ajoutez les modules Caddy supplémentaires et les extensions FrankenPHP ici ``` > [!TIP] > > Si vous utilisez musl libc (la bibliothèque par défaut sur Alpine Linux) et Symfony, > vous pourriez avoir besoin d'augmenter la taille par défaut de la pile. > Sinon, vous pourriez rencontrer des erreurs telles que `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression` > > Pour ce faire, modifiez la variable d'environnement `XCADDY_GO_BUILD_FLAGS` en quelque chose comme > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (modifiez la valeur de la taille de la pile selon les besoins de votre application). ### Sans xcaddy Il est également possible de compiler FrankenPHP sans `xcaddy` en utilisant directement la commande `go` : ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/fr/config.md ================================================ # Configuration FrankenPHP, Caddy ainsi que les modules [Mercure](mercure.md) et [Vulcain](https://vulcain.rocks) peuvent être configurés à l'aide [des formats pris en charge par Caddy](https://caddyserver.com/docs/getting-started#your-first-config). Le format le plus courant est le `Caddyfile`, un format texte simple et facilement lisible par les humains. Par défaut, FrankenPHP recherchera un `Caddyfile` dans le répertoire courant. Vous pouvez spécifier un chemin personnalisé avec l'option `-c` ou `--config`. Un `Caddyfile` minimal pour servir une application PHP est présenté ci-dessous : ```caddyfile # Le nom d'hôte auquel répondre localhost # Optionnellement, le répertoire à partir duquel servir les fichiers, sinon le répertoire courant sera utilisé par défaut #root public/ php_server ``` Un `Caddyfile` plus avancé, activant davantage de fonctionnalités et fournissant des variables d'environnement pratiques, est disponible [dans le dépôt FrankenPHP](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) et avec les images Docker. PHP lui-même peut être configuré [en utilisant un fichier `php.ini`](https://www.php.net/manual/fr/configuration.file.php). Selon votre méthode d'installation, FrankenPHP et l'interpréteur PHP chercheront les fichiers de configuration aux emplacements décrits ci-dessous. ## Docker FrankenPHP : - `/etc/frankenphp/Caddyfile` : le fichier de configuration principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile` : fichiers de configuration additionnels qui sont chargés automatiquement PHP : - `php.ini` : `/usr/local/etc/php/php.ini` (aucun `php.ini` n'est fourni par défaut) - Fichiers de configuration supplémentaires : `/usr/local/etc/php/conf.d/*.ini` - Extensions PHP : `/usr/local/lib/php/extensions/no-debug-zts-/` - Vous devriez copier un modèle officiel fourni par le projet PHP : ```dockerfile FROM dunglas/frankenphp # Production : RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Ou développement : RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## Packages RPM et Debian FrankenPHP : - `/etc/frankenphp/Caddyfile` : le fichier de configuration principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile` : fichiers de configuration additionnels qui sont chargés automatiquement PHP : - `php.ini` : `/etc/php-zts/php.ini` (un fichier `php.ini` avec des préréglages de production est fourni par défaut) - fichiers de configuration supplémentaires : `/etc/php-zts/conf.d/*.ini` ## Binaire statique FrankenPHP : - Dans le répertoire de travail actuel : `Caddyfile` PHP : - `php.ini` : Le répertoire dans lequel `frankenphp run` ou `frankenphp php-server` est exécuté, puis `/etc/frankenphp/php.ini` - fichiers de configuration supplémentaires : `/etc/frankenphp/php.d/*.ini` - Extensions PHP : ne peuvent pas être chargées, intégrez-les au binaire lui-même - copiez l'un des fichiers `php.ini-production` ou `php.ini-development` fournis [dans les sources de PHP](https://github.com/php/php-src/). ## Configuration du Caddyfile Les [directives HTTP](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` ou `php` peuvent être utilisées dans les blocs de site pour servir votre application PHP. Exemple minimal : ```caddyfile localhost { # Activer la compression (optionnel) encode zstd br gzip # Exécuter les fichiers PHP dans le répertoire courant et servir les assets php_server } ``` Vous pouvez également configurer explicitement FrankenPHP en utilisant l'[option globale](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp` : ```caddyfile { frankenphp { num_threads # Définit le nombre de threads PHP à démarrer. Par défaut : 2x le nombre de CPUs disponibles. max_threads # Limite le nombre de threads PHP supplémentaires qui peuvent être démarrés au moment de l'exécution. Valeur par défaut : num_threads. Peut être mis à 'auto'. max_wait_time # Définit le temps maximum pendant lequel une requête peut attendre un thread PHP libre avant d'être interrompue. Valeur par défaut : désactivé. max_idle_time # Définit le temps maximum pendant lequel un thread auto-dimensionné peut être inactif avant d'être désactivé. Par défaut : 5s. php_ini # Définit une directive php.ini. Peut être utilisé plusieurs fois pour définir plusieurs directives. worker { file # Définit le chemin vers le script worker. num # Définit le nombre de threads PHP à démarrer, par défaut 2x le nombre de CPUs disponibles. env # Définit une variable d'environnement supplémentaire avec la valeur donnée. Peut être spécifié plusieurs fois pour régler plusieurs variables d'environnement. watch # Définit le chemin d'accès à surveiller pour les modifications de fichiers. Peut être spécifié plusieurs fois pour plusieurs chemins. name # Définit le nom du worker, utilisé dans les journaux et les métriques. Par défaut : chemin absolu du fichier du worker max_consecutive_failures # Définit le nombre maximum d'échecs consécutifs avant que le worker ne soit considéré comme défaillant, -1 signifie que le worker redémarre toujours. Par défaut : 6. } } } # ... ``` Vous pouvez également utiliser la forme courte de l'option `worker` en une seule ligne : ```caddyfile { frankenphp { worker } } # ... ``` Vous pouvez aussi définir plusieurs workers si vous servez plusieurs applications sur le même serveur : ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # permet une meilleure mise en cache worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` L'utilisation de la directive `php_server` est généralement ce dont vous avez besoin, mais si vous avez besoin d'un contrôle total, vous pouvez utiliser la sous-directive `php`. La directive `php` transmet toutes les entrées à PHP, au lieu de vérifier d'abord si c'est un fichier PHP ou pas. En savoir plus à ce sujet dans la [documentation liée aux performances](performance.md#try_files). Utiliser la directive `php_server` est équivalent à cette configuration : ```caddyfile route { # Ajoute un slash final pour les requêtes de répertoire @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # Si le fichier demandé n'existe pas, essayer les fichiers index @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` Les directives `php_server` et `php` disposent des options suivantes : ```caddyfile php_server [] { root # Définit le dossier racine du site. Par défaut : la directive `root`. split_path # Définit les sous-chaînes pour diviser l'URI en deux parties. La première sous-chaîne correspondante sera utilisée pour séparer le "path info" du chemin. La première partie est suffixée avec la sous-chaîne correspondante et sera considérée comme le nom réel de la ressource (script CGI). La seconde partie sera définie comme PATH_INFO pour utilisation par le script. Par défaut : `.php` resolve_root_symlink false # Désactive la résolution du répertoire `root` vers sa valeur réelle en évaluant un lien symbolique, s'il existe (activé par défaut). env # Définit une variable d'environnement supplémentaire avec la valeur donnée. Peut être spécifié plusieurs fois pour plusieurs variables d'environnement. file_server off # Désactive la directive file_server intégrée. worker { # Crée un worker spécifique à ce serveur. Peut être spécifié plusieurs fois pour plusieurs workers. file # Définit le chemin vers le script worker, peut être relatif à la racine du php_server num # Définit le nombre de threads PHP à démarrer, par défaut 2x le nombre de CPUs disponibles name # Définit le nom du worker, utilisé dans les journaux et les métriques. Par défaut : chemin absolu du fichier du worker. Commence toujours par m# lorsqu'il est défini dans un bloc php_server. watch # Définit le chemin d'accès à surveiller pour les modifications de fichiers. Peut être spécifié plusieurs fois pour plusieurs chemins. env # Définit une variable d'environnement supplémentaire avec la valeur donnée. Peut être spécifié plusieurs fois pour plusieurs variables d'environnement. Les variables d'environnement pour ce worker sont également héritées du parent php_server, mais peuvent être écrasées ici. match # fait correspondre le worker à un modèle de chemin. Écrase try_files et ne peut être utilisé que dans la directive php_server. } worker # Peut également utiliser la forme courte comme dans le bloc frankenphp global. } ``` ### Surveillance des modifications de fichier Vu que les workers ne démarrent votre application qu'une seule fois et la gardent en mémoire, toute modification apportée à vos fichiers PHP ne sera pas répercutée immédiatement. Les workers peuvent être redémarrés en cas de changement de fichier via la directive `watch`. Ceci est utile pour les environnements de développement. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` Cette fonctionnalité est souvent utilisée en combinaison avec [le rechargement à chaud](hot-reload.md). Si le répertoire `watch` n'est pas précisé, il se rabattra sur `./**/*.{env,php,twig,yaml,yml}`, qui surveille tous les fichiers `.env`, `.php`, `.twig`, `.yaml` et `.yml` dans le répertoire et les sous-répertoires où le processus FrankenPHP a été lancé. Vous pouvez également spécifier un ou plusieurs répertoires via un [motif de nom de fichier shell](https://pkg.go.dev/path/filepath#Match) : ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # surveille tous les fichiers dans tous les sous-répertoires de /path/to/app watch /path/to/app/*.php # surveille les fichiers se terminant par .php dans /path/to/app watch /path/to/app/**/*.php # surveille les fichiers PHP dans /path/to/app et les sous-répertoires watch /path/to/app/**/*.{php,twig} # surveille les fichiers PHP et Twig dans /path/to/app et les sous-répertoires } } } ``` - Le motif `**` signifie une surveillance récursive. - Les répertoires peuvent également être relatifs (depuis l'endroit où le processus FrankenPHP est démarré). - Si vous avez défini plusieurs workers, ils seront tous redémarrés lorsqu'un fichier est modifié. - Méfiez-vous des fichiers créés au moment de l'exécution (comme les logs) car ils peuvent provoquer des redémarrages intempestifs du worker. La surveillance des fichiers est basée sur [e-dant/watcher](https://github.com/e-dant/watcher). ## Faire correspondre le Worker à un chemin Dans les applications PHP traditionnelles, les scripts sont toujours placés dans le répertoire public. C'est également vrai pour les scripts worker, qui sont traités comme n'importe quel autre script PHP. Si vous souhaitez plutôt placer le script worker en dehors du répertoire public, vous pouvez le faire via la directive `match`. La directive `match` est une alternative optimisée à `try_files` disponible uniquement à l'intérieur de `php_server` et `php`. L'exemple suivant servira toujours un fichier dans le répertoire public s'il est présent et transmettra sinon la requête au worker correspondant au modèle de chemin. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # le fichier peut être en dehors du chemin public match /api/* # toutes les requêtes commençant par /api/ seront traitées par ce worker } } } } ``` ## Variables d'environnement Les variables d'environnement suivantes peuvent être utilisées pour insérer des directives Caddy dans le `Caddyfile` sans le modifier : - `SERVER_NAME` : change [les adresses sur lesquelles écouter](https://caddyserver.com/docs/caddyfile/concepts#addresses), les noms d'hôte fournis seront également utilisés pour le certificat TLS généré - `SERVER_ROOT` : change le répertoire racine du site, par défaut `public/` - `CADDY_GLOBAL_OPTIONS` : injecte [des options globales](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG` : insère la configuration sous la directive `frankenphp` Comme pour les SAPI FPM et CLI, les variables d'environnement sont exposées par défaut dans la superglobale `$_SERVER`. La valeur `S` de [la directive `variables_order` de PHP](https://www.php.net/manual/fr/ini.core.php#ini.variables-order) est toujours équivalente à `ES`, que `E` soit défini ailleurs dans cette directive ou non. ## Configuration PHP Pour charger [des fichiers de configuration PHP supplémentaires](https://www.php.net/manual/fr/configuration.file.php#configuration.file.scan), la variable d'environnement `PHP_INI_SCAN_DIR` peut être utilisée. Lorsqu'elle est définie, PHP chargera tous les fichiers avec l'extension `.ini` présents dans les répertoires donnés. Vous pouvez également modifier la configuration de PHP en utilisant la directive `php_ini` dans le fichier `Caddyfile` : ```caddyfile { frankenphp { php_ini memory_limit 256M # or php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### Désactiver HTTPS Par défaut, FrankenPHP activera automatiquement HTTPS pour tous les noms d'hôte, y compris `localhost`. Si vous souhaitez désactiver HTTPS (par exemple dans un environnement de développement), vous pouvez définir la variable d'environnement `SERVER_NAME` à `http://` ou `:80` : Alternativement, vous pouvez utiliser toutes les autres méthodes décrites dans la [documentation Caddy](https://caddyserver.com/docs/automatic-https#activation). Si vous souhaitez utiliser HTTPS avec l'adresse IP `127.0.0.1` au lieu du nom d'hôte `localhost`, veuillez lire la section [problèmes connus](known-issues.md#using-https127001-with-docker). ### Full Duplex (HTTP/1) Lors de l'utilisation de HTTP/1.x, il peut être souhaitable d'activer le mode full-duplex pour permettre l'écriture d'une réponse avant que le corps entier n'ait été lu. (par exemple : [Mercure](mercure.md), WebSocket, Server-Sent Events, etc.) Il s'agit d'une configuration facultative qui doit être ajoutée aux options globales dans le `Caddyfile` : ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > L'activation de cette option peut entraîner un blocage (deadlock) des anciens clients HTTP/1.x qui ne supportent pas le full-duplex. > Cela peut aussi être configuré en utilisant la variable d'environnement `CADDY_GLOBAL_OPTIONS` : ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` Vous trouverez plus d'informations sur ce paramètre dans la [documentation Caddy](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex). ## Activer le mode Debug Lors de l'utilisation de l'image Docker, définissez la variable d'environnement `CADDY_GLOBAL_OPTIONS` sur `debug` pour activer le mode debug : ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Autocomplétion Shell FrankenPHP fournit un support d'autocomplétion intégré pour Bash, Zsh, Fish et PowerShell. Cela permet l'autocomplétion de toutes les commandes (y compris les commandes personnalisées comme `php-server`, `php-cli` et `extension-init`) ainsi que leurs options. ### Bash Pour charger l'autocomplétion dans votre session shell actuelle : ```console source <(frankenphp completion bash) ``` Pour charger l'autocomplétion à chaque nouvelle session, exécutez : **Linux :** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS :** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh Si l'autocomplétion shell n'est pas déjà activée dans votre environnement, vous devrez l'activer. Vous pouvez exécuter la commande suivante une fois : ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` Pour charger l'autocomplétion à chaque session, exécutez une fois : ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` Vous devrez démarrer un nouveau shell pour que cette configuration prenne effet. ### Fish Pour charger l'autocomplétion dans votre session shell actuelle : ```console frankenphp completion fish | source ``` Pour charger l'autocomplétion à chaque nouvelle session, exécutez une fois : ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell Pour charger l'autocomplétion dans votre session shell actuelle : ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` Pour charger l'autocomplétion à chaque nouvelle session, exécutez une fois : ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` Vous devrez démarrer un nouveau shell pour que cette configuration prenne effet. Vous devrez ensuite démarrer un nouveau shell pour que cette configuration prenne effet. ================================================ FILE: docs/fr/docker.md ================================================ # Création d'une image Docker personnalisée Les images Docker de [FrankenPHP](https://hub.docker.com/r/dunglas/frankenphp) sont basées sur les [images PHP officielles](https://hub.docker.com/_/php/). Des variantes Debian et Alpine Linux sont fournies pour les architectures populaires. Les variantes Debian sont recommandées. Des variantes pour PHP 8.2, 8.3, 8.4 et 8.5 sont disponibles. [Parcourir les tags](https://hub.docker.com/r/dunglas/frankenphp/tags). Les tags suivent le pattern suivant : `dunglas/frankenphp:-php-` - `` et `` sont respectivement les numéros de version de FrankenPHP et PHP, allant de majeur (e.g. `1`), mineur (e.g. `1.2`) à des versions correctives (e.g. `1.2.3`). - `` est soit `trixie` (pour Debian Trixie), `bookworm` (pour Debian Bookworm), ou `alpine` (pour la dernière version stable d'Alpine). [Parcourir les tags](https://hub.docker.com/r/dunglas/frankenphp/tags). ## Comment utiliser les images Créez un `Dockerfile` dans votre projet : ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Ensuite, exécutez ces commandes pour construire et exécuter l'image Docker : ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## Comment ajuster la configuration Pour une meilleure expérience initiale, un [`Caddyfile` par défaut](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) contenant des variables d'environnement communément utilisées est fourni dans l'image. ## Comment installer plus d'extensions PHP Le script [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) est fourni dans l'image de base. L'ajout d'extensions PHP supplémentaires se fait de cette manière : ```dockerfile FROM dunglas/frankenphp # ajoutez des extensions supplémentaires ici : RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Comment installer plus de modules Caddy FrankenPHP est construit sur Caddy, et tous les [modules Caddy](https://caddyserver.com/docs/modules/) peuvent être utilisés avec FrankenPHP. La manière la plus simple d'installer des modules Caddy personnalisés est d'utiliser [xcaddy](https://github.com/caddyserver/xcaddy) : ```dockerfile FROM dunglas/frankenphp:builder AS builder # Copier xcaddy dans l'image du constructeur COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # CGO doit être activé pour construire FrankenPHP RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure et Vulcain sont inclus dans la construction officielle, mais n'hésitez pas à les retirer --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Ajoutez des modules Caddy supplémentaires ici FROM dunglas/frankenphp AS runner # Remplacer le binaire officiel par celui contenant vos modules personnalisés COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` L'image `builder` fournie par FrankenPHP contient une version compilée de `libphp`. [Les images builder](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) sont fournies pour toutes les versions de FrankenPHP et PHP, à la fois pour Debian et Alpine. > [!TIP] > > Si vous utilisez Alpine Linux et Symfony, > vous devrez peut-être [augmenter la taille de pile par défaut](compile.md#utiliser-xcaddy). ## Activer le mode Worker par défaut Définissez la variable d'environnement `FRANKENPHP_CONFIG` pour démarrer FrankenPHP avec un script worker : ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Utiliser un volume en développement Pour développer facilement avec FrankenPHP, montez le répertoire de l'hôte contenant le code source de l'application comme un volume dans le conteneur Docker : ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > L'option --tty permet d'avoir des logs lisibles par un humain au lieu de logs JSON. Avec Docker Compose : ```yaml # compose.yaml services: php: image: dunglas/frankenphp # décommentez la ligne suivante si vous souhaitez utiliser un Dockerfile personnalisé #build: . # décommentez la ligne suivante si vous souhaitez exécuter ceci dans un environnement de production # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # commentez la ligne suivante en production, elle permet d'avoir de beaux logs lisibles en dev tty: true # Volumes nécessaires pour les certificats et la configuration de Caddy volumes: caddy_data: caddy_config: ``` ## Exécution en tant qu'utilisateur non-root FrankenPHP peut s'exécuter en tant qu'utilisateur non-root dans Docker. Voici un exemple de `Dockerfile` le permettant : ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Utilisez "adduser -D ${USER}" pour les distributions basées sur Alpine useradd ${USER}; \ # Ajouter la capacité supplémentaire de se lier aux ports 80 et 443 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # Donner l'accès en écriture à /config/caddy et /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Exécution sans capacité Même lorsqu'il s'exécute en tant qu'utilisateur non-root, FrankenPHP a besoin de la capacité `CAP_NET_BIND_SERVICE` pour lier le serveur web sur les ports privilégiés (80 et 443). Si vous exposez FrankenPHP sur un port non privilégié (1024 et au-delà), il est possible d'exécuter le serveur web en tant qu'utilisateur non-root, et sans avoir besoin d'aucune capacité : ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Utiliser "adduser -D ${USER}" pour les distros basées sur Alpine useradd ${USER}; \ # Supprimer la capacité par défaut setcap -r /usr/local/bin/frankenphp; \ # Donner un accès en écriture à /config/caddy et /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Ensuite, définissez la variable d'environnement `SERVER_NAME` pour utiliser un port non privilégié. Exemple : `:8000` ## Mises à jour Les images Docker sont construites : - lorsqu'une nouvelle version est taguée - tous les jours à 4h UTC, si de nouvelles versions des images officielles PHP sont disponibles ## Renforcer la sécurité des images Pour réduire davantage la surface d'attaque et la taille de vos images Docker FrankenPHP, il est également possible de les construire sur une image [Google distroless](https://github.com/GoogleContainerTools/distroless) ou [Docker hardened](https://www.docker.com/products/hardened-images). > [!WARNING] > Ces images de base minimales n'incluent pas de shell ou de gestionnaire de paquets, ce qui rend le débogage plus difficile. Elles sont donc recommandées uniquement pour la production si la sécurité est une priorité. Lors de l'ajout d'extensions PHP supplémentaires, vous aurez besoin d'une étape de build intermédiaire : ```dockerfile FROM dunglas/frankenphp AS builder # Ajoutez ici des extensions PHP supplémentaires RUN install-php-extensions pdo_mysql pdo_pgsql #... # Copiez les bibliothèques partagées de frankenphp et toutes les extensions installées vers un emplacement temporaire # Vous pouvez également effectuer cette étape manuellement en analysant la sortie ldd du binaire frankenphp et de chaque fichier .so d'extension RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Image de base Debian distroless, assurez-vous que c'est la même version de Debian que l'image de base FROM gcr.io/distroless/base-debian13 # Alternative d'image Docker renforcée # FROM dhi.io/debian:13 # Emplacement de votre application et du Caddyfile à copier dans le conteneur ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Copiez votre application dans /app # Pour un renforcement supplémentaire, assurez-vous que seuls les chemins accessibles en écriture sont détenus par l'utilisateur non-root COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # Copiez frankenphp et les bibliothèques nécessaires COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # Copiez les fichiers de configuration php.ini COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Répertoires de données Caddy — doivent être accessibles en écriture pour l'utilisateur non-root, même sur un système de fichiers racine en lecture seule ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # Point d'entrée pour exécuter frankenphp avec le Caddyfile fourni ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Versions de développement Les versions de développement sont disponibles dans le dépôt Docker [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev). Un nouveau build est déclenché chaque fois qu'un commit est poussé sur la branche principale du dépôt GitHub. Les tags `latest*` pointent vers la tête de la branche `main`. Les tags sous la forme `sha-` sont également disponibles. ================================================ FILE: docs/fr/early-hints.md ================================================ # Early Hints FrankenPHP prend nativement en charge le code de statut [103 Early Hints](https://developer.chrome.com/blog/early-hints/). L'utilisation des Early Hints peut améliorer le temps de chargement de vos pages web de 30 %. ```php ; rel=preload; as=style'); headers_send(103); // vos algorithmes lents et requêtes SQL 🤪 echo <<<'HTML' Hello FrankenPHP HTML; ``` Les Early Hints sont pris en charge à la fois par les modes "standard" et [worker](worker.md). ================================================ FILE: docs/fr/embed.md ================================================ # Applications PHP en tant que binaires autonomes FrankenPHP a la capacité d'incorporer le code source et les assets des applications PHP dans un binaire statique et autonome. Grâce à cette fonctionnalité, les applications PHP peuvent être distribuées en tant que binaires autonomes qui incluent l'application elle-même, l'interpréteur PHP et Caddy, un serveur web de qualité production. Pour en savoir plus sur cette fonctionnalité, consultez [la présentation faite par Kévin à la SymfonyCon 2023](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/). Pour embarquer des applications Laravel, [lisez ce point spécifique de la documentation](laravel.md#les-applications-laravel-en-tant-que-binaires-autonomes). ## Préparer votre application Avant de créer le binaire autonome, assurez-vous que votre application est prête à être intégrée. Vous devrez probablement : - Installer les dépendances de production de l'application - Dumper l'autoloader - Activer le mode production de votre application (si disponible) - Supprimer les fichiers inutiles tels que `.git` ou les tests pour réduire la taille de votre binaire final Par exemple, pour une application Symfony, lancez les commandes suivantes : ```console # Exporter le projet pour se débarrasser de .git/, etc. mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # Définir les variables d'environnement appropriées echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Supprimer les tests et autres fichiers inutiles pour économiser de l'espace # Alternativement, ajoutez ces fichiers avec l'attribut export-ignore dans votre fichier .gitattributes rm -Rf tests/ # Installer les dépendances composer install --ignore-platform-reqs --no-dev -a # Optimiser le .env composer dump-env prod ``` ### Personnaliser la configuration Pour personnaliser [la configuration](config.md), vous pouvez mettre un fichier `Caddyfile` ainsi qu'un fichier `php.ini` dans le répertoire principal de l'application à intégrer (`$TMPDIR/my-prepared-app` dans l'exemple précédent). ## Créer un binaire Linux La manière la plus simple de créer un binaire Linux est d'utiliser le builder basé sur Docker que nous fournissons. 1. Créez un fichier nommé `static-build.Dockerfile` dans le répertoire de votre application préparée : ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Si vous envisagez d'exécuter le binaire sur des systèmes musl-libc, utilisez plutôt static-builder-musl # Copy your app WORKDIR /go/src/app/dist/app COPY . . WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Certains fichiers `.dockerignore` (par exemple celui fourni par défaut par [Symfony Docker](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > empêchent la copie du dossier `vendor/` et des fichiers `.env`. Assurez-vous d'ajuster ou de supprimer le fichier `.dockerignore` avant le build. 2. Construisez: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. Extrayez le binaire : ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` Le binaire généré sera nommé `my-app` dans le répertoire courant. ## Créer un binaire pour d'autres systèmes d'exploitation Si vous ne souhaitez pas utiliser Docker, ou souhaitez construire un binaire macOS, utilisez le script shell que nous fournissons : ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` Le binaire obtenu est le fichier nommé `frankenphp--` dans le répertoire `dist/`. ## Utiliser le binaire C'est tout ! Le fichier `my-app` (ou `dist/frankenphp--` sur d'autres systèmes d'exploitation) contient votre application autonome ! Pour démarrer l'application web, exécutez : ```console ./my-app php-server ``` Si votre application contient un [script worker](worker.md), démarrez le worker avec quelque chose comme : ```console ./my-app php-server --worker public/index.php ``` Pour activer HTTPS (un certificat Let's Encrypt est automatiquement créé), HTTP/2 et HTTP/3, spécifiez le nom de domaine à utiliser : ```console ./my-app php-server --domain localhost ``` Vous pouvez également exécuter les scripts CLI PHP incorporés dans votre binaire : ```console ./my-app php-cli bin/console ``` ## Extensions PHP Par défaut, le script construira les extensions requises par le fichier `composer.json` de votre projet, s'il y en a. Si le fichier `composer.json` n'existe pas, les extensions par défaut sont construites, comme documenté dans [Créer un binaire statique](static.md). Pour personnaliser les extensions, utilisez la variable d'environnement `PHP_EXTENSIONS`. ```console EMBED=/path/to/your/app \ PHP_EXTENSIONS=ctype,iconv,pdo_sqlite \ ./build-static.sh ``` ## Personnaliser la compilation [Consultez la documentation sur la compilation statique](static.md) pour voir comment personnaliser le binaire (extensions, version PHP...). ## Distribuer le binaire Sous Linux, le binaire est compressé par défaut à l'aide de [UPX](https://upx.github.io). Sous Mac, pour réduire la taille du fichier avant de l'envoyer, vous pouvez le compresser. Nous recommandons `xz`. ================================================ FILE: docs/fr/extension-workers.md ================================================ # Workers d'extension Les Workers d'extension permettent à votre [extension FrankenPHP](https://frankenphp.dev/docs/extensions/) de gérer un pool dédié de threads PHP pour exécuter des tâches en arrière-plan, gérer des événements asynchrones ou implémenter des protocoles personnalisés. Cela se révèle utile pour les systèmes de files d'attente, les event listeners, les planificateurs, etc. ## Enregistrement du Worker ### Enregistrement statique Si vous n'avez pas besoin de rendre le worker configurable par l'utilisateur (chemin de script fixe, nombre de threads fixe), vous pouvez simplement enregistrer le worker dans la fonction `init()`. ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // Handle global pour communiquer avec le pool de workers var worker frankenphp.Workers func init() { // Enregistre le worker lorsque le module est chargé. worker = caddy.RegisterWorkers( "my-internal-worker", // Nom unique "worker.php", // Chemin du script (relatif à l'exécution ou absolu) 2, // Nombre de threads fixe // Hooks de cycle de vie optionnels frankenphp.WithWorkerOnServerStartup(func() { // Logique de configuration globale... }), ) } ``` ### Dans un module Caddy (configurable par l'utilisateur) Si vous prévoyez de partager votre extension (comme une file d'attente générique ou un écouteur d'événements), vous devriez l'envelopper dans un module Caddy. Cela permet aux utilisateurs de configurer le chemin du script et le nombre de threads via leur `Caddyfile`. Cela nécessite d'implémenter l'interface `caddy.Provisioner` et de parser le Caddyfile ([voir un exemple](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)). ### Dans une application Go pure (intégration) Si vous [intégrez FrankenPHP dans une application Go standard sans Caddy](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), vous pouvez enregistrer des workers d'extension en utilisant `frankenphp.WithExtensionWorkers` lors de l'initialisation des options. ## Interaction avec les Workers Une fois le pool de workers actif, vous pouvez lui envoyer des tâches. Cela peut être fait à l'intérieur de [fonctions natives exportées vers PHP](https://frankenphp.dev/docs/extensions/#writing-the-extension), ou à partir de toute logique Go telle qu'un planificateur cron, un écouteur d'événements (MQTT, Kafka), ou toute autre goroutine. ### Mode sans tête : `SendMessage` Utilisez `SendMessage` pour passer des données brutes directement à votre script worker. C'est idéal pour les files d'attente ou les commandes simples. #### Exemple : Une extension de file d'attente asynchrone ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. S'assurer que le worker est prêt if worker == nil { return false } // 2. Envoyer au worker en arrière-plan _, err := worker.SendMessage( context.Background(), // Contexte Go standard unsafe.Pointer(data), // Données à passer au worker nil, // http.ResponseWriter optionnel ) return err == nil } ``` ### Émulation HTTP : `SendRequest` Utilisez `SendRequest` si votre extension doit invoquer un script PHP qui s'attend à un environnement web standard (remplir `$_SERVER`, `$_GET`, etc.). ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. Préparer la requête et l'enregistreur url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. Envoyer au worker if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Retourner la réponse capturée return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Script Worker Le script worker PHP s'exécute dans une boucle et peut gérer à la fois les messages bruts et les requêtes HTTP. ```php [!TIP] > Si vous voulez comprendre comment les extensions peuvent être écrites en Go à partir de zéro, vous pouvez lire la section d'implémentation manuelle ci-dessous démontrant comment écrire une extension PHP en Go sans utiliser le générateur. Gardez à l'esprit que cet outil n'est **pas un générateur d'extensions complet**. Il est destiné à vous aider à écrire des extensions simples en Go, mais il ne fournit pas les fonctionnalités les plus avancées des extensions PHP. Si vous devez écrire une extension plus **complexe et optimisée**, vous devrez peut-être écrire du code C ou utiliser CGO directement. ### Prérequis Comme aussi couvert dans la section d'implémentation manuelle ci-dessous, vous devez [obtenir les sources PHP](https://www.php.net/downloads.php) et créer un nouveau module Go. #### Créer un Nouveau Module et Obtenir les Sources PHP La première étape pour écrire une extension PHP en Go est de créer un nouveau module Go. Vous pouvez utiliser la commande suivante pour cela : ```console go mod init github.com/my-account/my-module ``` La seconde étape est [l'obtention des sources PHP](https://www.php.net/downloads.php) pour les étapes suivantes. Une fois que vous les avez, décompressez-les dans le répertoire de votre choix, mais pas à l'intérieur de votre module Go : ```console tar xf php-* ``` ### Écrire l'Extension Tout est maintenant configuré pour écrire votre fonction native en Go. Créez un nouveau fichier nommé `stringext.go`. Notre première fonction prendra une chaîne comme argument, le nombre de fois à la répéter, un booléen pour indiquer s'il faut inverser la chaîne, et retournera la chaîne résultante. Cela devrait ressembler à ceci : ```go package example // #include import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` Il y a deux choses importantes à noter ici : - Une directive `//export_php:function` définit la signature de la fonction en PHP. C'est ainsi que le générateur sait comment générer la fonction PHP avec les bons paramètres et le bon type de retour ; - La fonction doit retourner un `unsafe.Pointer`. FrankenPHP fournit une API pour vous aider avec le jonglage de types entre C et Go. Alors que le premier point parle de lui-même, le second peut être plus difficile à appréhender. Plongeons plus profondément dans le jonglage de types dans la section suivante. ### Jonglage de Types Bien que certains types de variables aient la même représentation mémoire entre C/PHP et Go, certains types nécessitent plus de logique pour être directement utilisés. C'est peut-être la partie la plus difficile quand il s'agit d'écrire des extensions car cela nécessite de comprendre les fonctionnements internes du moteur Zend et comment les variables sont stockées dans le moteur de PHP. Ce tableau résume ce que vous devez savoir : | Type PHP | Type Go | Conversion directe | Assistant C vers Go | Assistant Go vers C | Support des Méthodes de Classe | | ------------------ | ----------------------------- | ------------------ | --------------------------------- | ---------------------------------- | ------------------------------ | | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | frankenphp.GoString() | frankenphp.PHPString() | ✅ | | `array` | `frankenphp.AssociativeArray` | ❌ | `frankenphp.GoAssociativeArray()` | `frankenphp.PHPAssociativeArray()` | ✅ | | `array` | `map[string]any` | ❌ | `frankenphp.GoMap()` | `frankenphp.PHPMap()` | ✅ | | `array` | `[]any` | ❌ | `frankenphp.GoPackedArray()` | `frankenphp.PHPPackedArray()` | ✅ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `object` | `struct` | ❌ | _Pas encore implémenté_ | _Pas encore implémenté_ | ❌ | > [!NOTE] > Ce tableau n'est pas encore exhaustif et sera complété au fur et à mesure que l'API de types FrankenPHP deviendra plus complète. > > Pour les méthodes de classe spécifiquement, les types primitifs et les tableaux sont supportés. Les objets ne peuvent pas encore être utilisés comme paramètres de méthode ou types de retour. Si vous vous référez à l'extrait de code de la section précédente, vous pouvez voir que des assistants sont utilisés pour convertir le premier paramètre et la valeur de retour. Les deuxième et troisième paramètres de notre fonction `repeat_this()` n'ont pas besoin d'être convertis car la représentation mémoire des types sous-jacents est la même pour C et Go. #### Travailler avec les Tableaux FrankenPHP fournit un support natif pour les tableaux PHP à travers `frankenphp.AssociativeArray` ou une conversion directe vers une map ou un slice. `AssociativeArray` représente une [hash map](https://fr.wikipedia.org/wiki/Table_de_hachage) composée d'un champ `Map: map[string]any` et d'un champ optionnel `Order: []string` (contrairement aux "tableaux associatifs" PHP, les maps Go ne sont pas ordonnées). Si l'ordre ou l'association ne sont pas nécessaires, il est également possible de convertir directement vers un slice `[]any` ou une map non ordonnée `map[string]any`. **Créer et manipuler des tableaux en Go :** ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:function process_data_ordered(array $input): array func process_data_ordered_map(arr *C.zval) unsafe.Pointer { // Convertir le tableau associatif PHP vers Go en conservant l'ordre associativeArray, err := frankenphp.GoAssociativeArray[any](unsafe.Pointer(arr)) if err != nil { // gérer l'erreur } // parcourir les entrées dans l'ordre for _, key := range associativeArray.Order { value, _ = associativeArray.Map[key] // faire quelque chose avec key et value } // retourner un tableau ordonné // si 'Order' n'est pas vide, seules les paires clé-valeur dans 'Order' seront respectées return frankenphp.PHPAssociativeArray[string](frankenphp.AssociativeArray[string]{ Map: map[string]string{ "key1": "value1", "key2": "value2", }, Order: []string{"key1", "key2"}, }) } // export_php:function process_data_unordered(array $input): array func process_data_unordered_map(arr *C.zval) unsafe.Pointer { // Convertir le tableau associatif PHP vers une map Go sans conserver l'ordre // ignorer l'ordre sera plus performant goMap, err := frankenphp.GoMap[any](unsafe.Pointer(arr)) if err != nil { // gérer l'erreur } // parcourir les entrées sans ordre spécifique for key, value := range goMap { // faire quelque chose avec key et value } // retourner un tableau non ordonné return frankenphp.PHPMap(map[string]string { "key1": "value1", "key2": "value2", }) } // export_php:function process_data_packed(array $input): array func process_data_packed(arr *C.zval) unsafe.Pointer { // Convertir le tableau packed PHP vers Go goSlice, err := frankenphp.GoPackedArray(unsafe.Pointer(arr)) if err != nil { // gérer l'erreur } // parcourir le slice dans l'ordre for index, value := range goSlice { // faire quelque chose avec index et value } // retourner un tableau packed return frankenphp.PHPPackedArray([]string{"value1", "value2", "value3"}) } ``` **Fonctionnalités clés de la conversion de tableaux :** - **Paires clé-valeur ordonnées** - Option pour conserver l'ordre du tableau associatif - **Optimisé pour plusieurs cas** - Option de ne pas conserver l'ordre pour de meilleures performances ou conversion directe vers un slice - **Détection automatique de liste** - Lors de la conversion vers PHP, détecte automatiquement si le tableau doit être une liste packed ou un hashmap - **Tableaux imbriqués** - Les tableaux peuvent être imbriqués et convertiront automatiquement tous les types supportés (`int64`, `float64`, `string`, `bool`, `nil`, `AssociativeArray`, `map[string]any`, `[]any`) - **Les objets ne sont pas supportés** - Actuellement, seuls les types scalaires et les tableaux peuvent être utilisés comme valeurs. Fournir un objet résultera en une valeur `null` dans le tableau PHP. ##### Méthodes disponibles : Packed et Associatif - `frankenphp.PHPAssociativeArray(arr frankenphp.AssociativeArray) unsafe.Pointer` - Convertir vers un tableau PHP ordonné avec des paires clé-valeur - `frankenphp.PHPMap(arr map[string]any) unsafe.Pointer` - Convertir une map vers un tableau PHP non ordonné avec des paires clé-valeur - `frankenphp.PHPPackedArray(slice []any) unsafe.Pointer` - Convertir un slice vers un tableau PHP packed avec uniquement des valeurs indexées - `frankenphp.GoAssociativeArray(arr unsafe.Pointer, ordered bool) frankenphp.AssociativeArray` - Convertir un tableau PHP vers un `AssociativeArray` Go ordonné (map avec ordre) - `frankenphp.GoMap(arr unsafe.Pointer) map[string]any` - Convertir un tableau PHP vers une map Go non ordonnée - `frankenphp.GoPackedArray(arr unsafe.Pointer) []any` - Convertir un tableau PHP vers un slice Go - `frankenphp.IsPacked(zval *C.zend_array) bool` - Vérifie si le tableau PHP est une liste ou un tableau associatif ### Travailler avec des Callables FrankenPHP propose un moyen de travailler avec les _callables_ PHP grâce au helper `frankenphp.CallPHPCallable()`. Cela permet d'appeler des fonctions ou des méthodes PHP depuis du code Go. Pour illustrer cela, créons notre propre fonction `array_map()` qui prend un _callable_ et un tableau, applique le _callable_ à chaque élément du tableau, et retourne un nouveau tableau avec les résultats : ```go // export_php:function my_array_map(array $data, callable $callback): array func my_array_map(arr *C.zend_array, callback *C.zval) unsafe.Pointer { goSlice, err := frankenphp.GoPackedArray[any](unsafe.Pointer(arr)) if err != nil { panic(err) } result := make([]any, len(goSlice)) for index, value := range goSlice { result[index] = frankenphp.CallPHPCallable(unsafe.Pointer(callback), []interface{}{value}) } return frankenphp.PHPPackedArray(result) } ``` Remarquez comment nous utilisons `frankenphp.CallPHPCallable()` pour appeler le _callable_ PHP passé en paramètre. Cette fonction prend un pointeur vers le _callable_ et un tableau d'arguments, et elle retourne le résultat de l'exécution du _callable_. Vous pouvez utiliser la syntaxe habituelle des _callables_ : ```php name` ne fonctionnera pas) - **Interface uniquement par méthodes** - Toutes les interactions doivent passer par les méthodes que vous définissez - **Meilleure encapsulation** - La structure de données interne est complètement contrôlée par le code Go - **Sécurité de type** - Aucun risque que le code PHP corrompe l'état interne avec de mauvais types - **API plus propre** - Force à concevoir une interface publique appropriée Cette approche fournit une meilleure encapsulation et empêche le code PHP de corrompre accidentellement l'état interne de vos objets Go. Toutes les interactions avec l'objet doivent passer par les méthodes que vous définissez explicitement. #### Ajouter des Méthodes aux Classes Puisque les propriétés ne sont pas directement accessibles, vous **devez définir des méthodes** pour interagir avec vos classes opaques. Utilisez la directive `//export_php:method` pour définir cela : ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### Paramètres Nullables Le générateur prend en charge les paramètres nullables en utilisant le préfixe `?` dans les signatures PHP. Quand un paramètre est nullable, il devient un pointeur dans votre fonction Go, vous permettant de vérifier si la valeur était `null` en PHP : ```go package example // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // Vérifier si name a été fourni (pas null) if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // Vérifier si age a été fourni (pas null) if age != nil { us.Age = int(*age) } // Vérifier si active a été fourni (pas null) if active != nil { us.Active = *active } } ``` **Points clés sur les paramètres nullables :** - **Types primitifs nullables** (`?int`, `?float`, `?bool`) deviennent des pointeurs (`*int64`, `*float64`, `*bool`) en Go - **Chaînes nullables** (`?string`) restent comme `*C.zend_string` mais peuvent être `nil` - **Vérifiez `nil`** avant de déréférencer les valeurs de pointeur - **PHP `null` devient Go `nil`** - quand PHP passe `null`, votre fonction Go reçoit un pointeur `nil` > [!WARNING] > Actuellement, les méthodes de classe ont les limitations suivantes. **Les objets ne sont pas supportés** comme types de paramètres ou types de retour. **Les tableaux sont entièrement supportés** pour les paramètres et types de retour. Types supportés : `string`, `int`, `float`, `bool`, `array`, et `void` (pour le type de retour). **Les types de paramètres nullables sont entièrement supportés** pour tous les types scalaires (`?string`, `?int`, `?float`, `?bool`). Après avoir généré l'extension, vous serez autorisé à utiliser la classe et ses méthodes en PHP. Notez que vous **ne pouvez pas accéder aux propriétés directement** : ```php setAge(25); echo $user->getName(); // Output : (vide, valeur par défaut) echo $user->getAge(); // Output : 25 $user->setNamePrefix("Employee"); // ✅ Fonctionne aussi - paramètres nullables $user->updateInfo("John", 30, true); // Tous les paramètres fournis $user->updateInfo("Jane", null, false); // L'âge est null $user->updateInfo(null, 25, null); // Le nom et actif sont null // ❌ Ne fonctionnera PAS - accès direct aux propriétés // echo $user->name; // Erreur : Impossible d'accéder à la propriété privée // $user->age = 30; // Erreur : Impossible d'accéder à la propriété privée ``` Cette conception garantit que votre code Go a un contrôle complet sur la façon dont l'état de l'objet est accédé et modifié, fournissant une meilleure encapsulation et sécurité de type. ### Déclarer des Constantes Le générateur prend en charge l'exportation de constantes Go vers PHP en utilisant deux directives : `//export_php:const` pour les constantes globales et `//export_php:classconst` pour les constantes de classe. Cela vous permet de partager des valeurs de configuration, des codes de statut et d'autres constantes entre le code Go et PHP. #### Constantes Globales Utilisez la directive `//export_php:const` pour créer des constantes PHP globales : ```go package example //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const ( STATUS_OK = iota STATUS_ERROR ) ``` > [!NOTE] > Les constantes PHP prennent le nom de la constante Go, d'où l'utilisation de majuscules pour les noms des constants en Go. #### Constantes de Classe Utilisez la directive `//export_php:classconst ClassName` pour créer des constantes qui appartiennent à une classe PHP spécifique : ```go package example //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const ( STATE_PENDING = iota STATE_PROCESSING STATE_COMPLETED ) ``` > [!NOTE] > Comme les constantes globales, les constantes de classe prennent le nom de la constante Go. Les constantes de classe sont accessibles en utilisant la portée du nom de classe en PHP : ```php import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:const const STR_REVERSE = iota //export_php:const const STR_NORMAL = iota //export_php:classconst StringProcessor const MODE_LOWERCASE = 1 //export_php:classconst StringProcessor const MODE_UPPERCASE = 2 //export_php:function repeat_this(string $str, int $count, int $mode): string func repeat_this(s *C.zend_string, count int64, mode int) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if mode == STR_REVERSE { // inverser la chaîne } if mode == STR_NORMAL { // no-op, juste pour montrer la constante } return frankenphp.PHPString(result, false) } //export_php:class StringProcessor type StringProcessorStruct struct { // champs internes } //export_php:method StringProcessor::process(string $input, int $mode): string func (sp *StringProcessorStruct) Process(input *C.zend_string, mode int64) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(input)) switch mode { case MODE_LOWERCASE: str = strings.ToLower(str) case MODE_UPPERCASE: str = strings.ToUpper(str) } return frankenphp.PHPString(str, false) } ``` ### Utilisation des Espaces de Noms Le générateur prend en charge l'organisation des fonctions, classes et constantes de votre extension PHP sous un espace de noms (namespace) en utilisant la directive `//export_php:namespace`. Cela aide à éviter les conflits de noms et fournit une meilleure organisation pour l'API de votre extension. #### Déclarer un Espace de Noms Utilisez la directive `//export_php:namespace` en haut de votre fichier Go pour placer tous les symboles exportés sous un espace de noms spécifique : ```go //export_php:namespace My\Extension package example import ( "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function hello(): string func hello() string { return "Bonjour depuis l'espace de noms My\\Extension !" } //export_php:class User type UserStruct struct { // champs internes } //export_php:method User::getName(): string func (u *UserStruct) GetName() unsafe.Pointer { return frankenphp.PHPString("Jean Dupont", false) } //export_php:const const STATUS_ACTIVE = 1 ``` #### Utilisation de l'Extension avec Espace de Noms en PHP Quand un espace de noms est déclaré, toutes les fonctions, classes et constantes sont placées sous cet espace de noms en PHP : ```php getName(); // "Jean Dupont" echo My\Extension\STATUS_ACTIVE; // 1 ``` #### Notes Importantes - Seule **une** directive d'espace de noms est autorisée par fichier. Si plusieurs directives d'espace de noms sont trouvées, le générateur retournera une erreur. - L'espace de noms s'applique à **tous** les symboles exportés dans le fichier : fonctions, classes, méthodes et constantes. - Les noms d'espaces de noms suivent les conventions des espaces de noms PHP en utilisant les barres obliques inverses (`\`) comme séparateurs. - Si aucun espace de noms n'est déclaré, les symboles sont exportés vers l'espace de noms global comme d'habitude. ### Générer l'Extension C'est là que la magie opère, et votre extension peut maintenant être générée. Vous pouvez exécuter le générateur avec la commande suivante : ```console GEN_STUB_SCRIPT=php-src/build/gen_stub.php frankenphp extension-init my_extension.go ``` > [!NOTE] > N'oubliez pas de définir la variable d'environnement `GEN_STUB_SCRIPT` sur le chemin du fichier `gen_stub.php` dans les sources PHP que vous avez téléchargées plus tôt. C'est le même script `gen_stub.php` mentionné dans la section d'implémentation manuelle. Si tout s'est bien passé, un nouveau répertoire nommé `build` devrait avoir été créé. Ce répertoire contient les fichiers générés pour votre extension, incluant le fichier `my_extension.go` avec les stubs de fonction PHP générés. ### Intégrer l'Extension Générée dans FrankenPHP Notre extension est maintenant prête à être compilée et intégrée dans FrankenPHP. Pour ce faire, référez-vous à la [documentation de compilation](compile.md) de FrankenPHP pour apprendre comment compiler FrankenPHP. Ajoutez le module en utilisant le flag `--with`, pointant vers le chemin de votre module : ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module/build ``` Notez que vous pointez vers le sous-répertoire `/build` qui a été créé pendant l'étape de génération. Cependant, ce n'est pas obligatoire : vous pouvez aussi copier les fichiers générés dans le répertoire de votre module et pointer directement vers lui. ### Tester Votre Extension Générée Vous pouvez créer un fichier PHP pour tester les fonctions et classes que vous avez créées. Par exemple, créez un fichier `index.php` avec le contenu suivant : ```php process('Hello World', StringProcessor::MODE_LOWERCASE); // "hello world" echo $processor->process('Hello World', StringProcessor::MODE_UPPERCASE); // "HELLO WORLD" ``` Une fois que vous avez intégré votre extension dans FrankenPHP comme indiqué dans la section précédente, vous pouvez exécuter ce fichier de test en utilisant `./frankenphp php-server`, et vous devriez voir votre extension fonctionner. ## Implémentation Manuelle Si vous voulez comprendre comment les extensions fonctionnent ou avez besoin d'un contrôle total sur votre extension, vous pouvez les écrire manuellement. Cette approche vous donne un contrôle complet mais nécessite plus de code intermédiaire. ### Fonction de Base Nous allons voir comment écrire une extension PHP simple en Go qui définit une nouvelle fonction native. Cette fonction sera appelée depuis PHP et déclenchera une goroutine qui enregistrera un message dans les logs de Caddy. Cette fonction ne prend aucun paramètre et ne retourne rien. #### Définir la Fonction Go Dans votre module, vous devez définir une nouvelle fonction native qui sera appelée depuis PHP. Pour ce faire, créez un fichier avec le nom que vous voulez, par exemple, `extension.go`, et ajoutez le code suivant : ```go package example // #include "extension.h" import "C" import ( "log/slog" "unsafe" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { slog.Info("Hello from a goroutine!") }() } ``` La fonction `frankenphp.RegisterExtension()` simplifie le processus d'enregistrement d'extension en gérant la logique interne de PHP. La fonction `go_print_something` utilise la directive `//export` pour indiquer qu'elle sera accessible dans le code C que nous écrirons, grâce à CGO. Dans cet exemple, notre nouvelle fonction déclenchera une goroutine qui enregistrera un message dans les logs de Caddy. #### Définir la Fonction PHP Pour permettre à PHP d'appeler notre fonction, nous devons définir une fonction PHP correspondante. Pour cela, nous créerons un fichier stub, par exemple, `extension.stub.php`, qui contiendra le code suivant : ```php extern zend_module_entry ext_module_entry; #endif ``` Ensuite, créez un fichier nommé `extension.c` qui effectuera les étapes suivantes : - Inclure les en-têtes PHP ; - Déclarer notre nouvelle fonction PHP native `go_print()` ; - Déclarer les métadonnées de l'extension. Commençons par inclure les en-têtes requis : ```c #include #include "extension.h" #include "extension_arginfo.h" // Contient les symboles exportés par Go #include "_cgo_export.h" ``` Nous définissons ensuite notre fonction PHP comme une fonction de langage natif : ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` Dans ce cas, notre fonction ne prend aucun paramètre et ne retourne rien. Elle appelle simplement la fonction Go que nous avons définie plus tôt, exportée en utilisant la directive `//export`. Enfin, nous définissons les métadonnées de l'extension dans une structure `zend_module_entry`, telles que son nom, sa version et ses propriétés. Cette information est nécessaire pour que PHP reconnaisse et charge notre extension. Notez que `ext_functions` est un tableau de pointeurs vers les fonctions PHP que nous avons définies, et il a été automatiquement généré par le script `gen_stub.php` dans le fichier `extension_arginfo.h`. L'enregistrement de l'extension est automatiquement géré par la fonction `RegisterExtension()` de FrankenPHP que nous appelons dans notre code Go. ### Usage Avancé Maintenant que nous savons comment créer une extension PHP de base en Go, complexifions notre exemple. Nous allons maintenant créer une fonction PHP qui prend une chaîne comme paramètre et retourne sa version en majuscules. #### Définir le Stub de Fonction PHP Pour définir la nouvelle fonction PHP, nous modifierons notre fichier `extension.stub.php` pour inclure la nouvelle signature de fonction : ```php [!TIP] > Ne négligez pas la documentation de vos fonctions ! Vous êtes susceptible de partager vos stubs d'extension avec d'autres développeurs pour documenter comment utiliser votre extension et quelles fonctionnalités sont disponibles. En régénérant le fichier stub avec le script `gen_stub.php`, le fichier `extension_arginfo.h` devrait ressembler à ceci : ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` Nous pouvons voir que la fonction `go_upper` est définie avec un paramètre de type `string` et un type de retour `string`. #### Jonglerie de Types entre Go et PHP/C Votre fonction Go ne peut pas accepter directement une chaîne PHP comme paramètre. Vous devez la convertir en chaîne Go. Heureusement, FrankenPHP fournit des fonctions d'aide pour gérer la conversion entre les chaînes PHP et les chaînes Go, similaire à ce que nous avons vu dans l'approche du générateur. Le fichier d'en-tête reste simple : ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` Nous pouvons maintenant écrire le pont entre Go et C dans notre fichier `extension.c`. Nous passerons la chaîne PHP directement à notre fonction Go : ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` Vous pouvez en apprendre plus sur `ZEND_PARSE_PARAMETERS_START` et l'analyse des paramètres dans la page dédiée du [PHP Internals Book](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters). Ici, nous disons à PHP que notre fonction prend un paramètre obligatoire de type `string` comme `zend_string`. Nous passons ensuite cette chaîne directement à notre fonction Go et retournons le résultat en utilisant `RETVAL_STR`. Il ne reste qu'une chose à faire : implémenter la fonction `go_upper` en Go. #### Implémenter la Fonction Go Notre fonction Go prendra un `*C.zend_string` comme paramètre, le convertira en chaîne Go en utilisant la fonction d'aide de FrankenPHP, le traitera, et retournera le résultat comme un nouveau `*C.zend_string`. Les fonctions d'aide gèrent toute la complexité de gestion de mémoire et de conversion pour nous. ```go package example // #include import "C" import ( "unsafe" "strings" "github.com/dunglas/frankenphp" ) //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` Cette approche est beaucoup plus propre et sûre que la gestion manuelle de la mémoire. Les fonctions d'aide de FrankenPHP gèrent la conversion entre le format `zend_string` de PHP et les chaînes Go automatiquement. Le paramètre `false` dans `PHPString()` indique que nous voulons créer une nouvelle chaîne non persistante (libérée à la fin de la requête). > [!TIP] > Dans cet exemple, nous n'effectuons aucune gestion d'erreur, mais vous devriez toujours vérifier que les pointeurs ne sont pas `nil` et que les données sont valides avant de les utiliser dans vos fonctions Go. ### Intégrer l'Extension dans FrankenPHP Notre extension est maintenant prête à être compilée et intégrée dans FrankenPHP. Pour ce faire, référez-vous à la [documentation de compilation](compile.md) de FrankenPHP pour apprendre comment compiler FrankenPHP. Ajoutez le module en utilisant le flag `--with`, pointant vers le chemin de votre module : ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module ``` C'est tout ! Votre extension est maintenant intégrée dans FrankenPHP et peut être utilisée dans votre code PHP. ### Tester Votre Extension Après avoir intégré votre extension dans FrankenPHP, vous pouvez créer un fichier `index.php` avec des exemples pour les fonctions que vous avez implémentées : ```php [!WARNING] > Cette fonctionnalité est destinée **uniquement aux environnements de développement**. > N'activez pas `hot_reload` en production, car cette fonctionnalité n'est pas sécurisée (expose des détails internes sensibles) et ralentit l'application. ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` Par défaut, FrankenPHP surveillera tous les fichiers du répertoire de travail actuel correspondant au motif glob suivant : `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` Il est possible de définir explicitement les fichiers à surveiller en utilisant un motif glob : ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Utilisez la forme longue de `hot_reload` pour spécifier le *topic* Mercure à utiliser ainsi que les répertoires ou fichiers à surveiller : ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## Intégration côté client Le serveur détecte les modifications et publie les modifications automatiquement. Le navigateur doit s'abonner à ces événements pour mettre à jour la page. FrankenPHP expose l'URL du Hub Mercure à utiliser pour s'abonner aux modifications de fichiers via la variable d'environnement `$_SERVER['FRANKENPHP_HOT_RELOAD']`. La bibliothèque JavaScript [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload) gére la logique côté client. Pour l'utiliser, ajoutez le code suivant à votre gabarit (*layout*) principal : ```php FrankenPHP Hot Reload ``` La bibliothèque s'abonnera automatiquement au hub Mercure, récupérera l'URL actuelle en arrière-plan lorsqu'une modification de fichier est détectée et transformera le DOM. Elle est disponible en tant que package [npm](https://www.npmjs.com/package/frankenphp-hot-reload) et sur [GitHub](https://github.com/dunglas/frankenphp-hot-reload). Alternativement, vous pouvez implémenter votre propre logique côté client en vous abonnant directement au hub Mercure en utilisant la classe JavaScript native `EventSource`. ### Conserver les nœuds DOM existants Dans de rares cas, comme lors de l'utilisation d'outils de développement tels que [la *web debug toolbar* de Symfony](https://github.com/symfony/symfony/pull/62970), vous pouvez souhaiter conserver des nœuds DOM spécifiques. Pour ce faire, ajoutez l'attribut `data-frankenphp-hot-reload-preserve` à l'élément HTML concerné : ```html
``` ## Mode Worker Si vous exécutez votre application en [mode Worker](worker.md), le script de votre application reste en mémoire. Cela signifie que les modifications de votre code PHP ne seront pas reflétées immédiatement, même si le navigateur recharge la page. Pour une meilleure expérience de développement, combinez `hot_reload` avec [la sous-directive `watch` dans la directive `worker`](config.md#surveillance-des-modifications-de-fichier). - `hot_reload` : rafraîchit le **navigateur** lorsque les fichiers changent - `worker.watch` : redémarre le worker lorsque les fichiers changent ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## Comment ça fonctionne 1. **Surveillance** : FrankenPHP surveille le système de fichiers pour les modifications en utilisant [la bibliothèque `e-dant/watcher`](https://github.com/e-dant/watcher) en interne (nous avons contribué à son binding Go). 2. **Redémarrage (mode Worker)** : si `watch` est activé dans la configuration du worker, le worker PHP est redémarré pour charger le nouveau code. 3. **Envoi** : un payload JSON contenant la liste des fichiers modifiés est envoyé au [hub Mercure](https://mercure.rocks) intégré. 4. **Réception** : le navigateur, à l'écoute via la bibliothèque JavaScript, reçoit l'événement Mercure. 5. **Mise à jour** : - Si **Idiomorph** est détecté, il récupère le contenu mis à jour et transforme le HTML actuel pour correspondre au nouvel état, appliquant les modifications instantanément sans perdre l'état. - Sinon, `window.location.reload()` est appelé pour rafraîchir la page. ================================================ FILE: docs/fr/known-issues.md ================================================ # Problèmes Connus ## Extensions PHP non prises en charge Les extensions suivantes sont connues pour ne pas être compatibles avec FrankenPHP : | Nom | Raison | Alternatives | | ----------------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/en/imap.installation.php) | Non thread-safe | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | Non thread-safe | - | ## Extensions PHP boguées Les extensions suivantes ont des bugs connus ou des comportements inattendus lorsqu'elles sont utilisées avec FrankenPHP : | Nom | Problème | | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [ext-openssl](https://www.php.net/manual/fr/book.openssl.php) | Lors de l'utilisation d'une version statique de FrankenPHP (construite avec la libc musl), l'extension OpenSSL peut planter sous de fortes charges. Une solution consiste à utiliser une version liée dynamiquement (comme celle utilisée dans les images Docker). Ce bogue est [suivi par PHP](https://github.com/php/php-src/issues/13648). | ## get_browser La fonction [get_browser()](https://www.php.net/manual/fr/function.get-browser.php) semble avoir de mauvaises performances après un certain temps. Une solution est de mettre en cache (par exemple, avec [APCu](https://www.php.net/manual/en/book.apcu.php)) les résultats par agent utilisateur, car ils sont statiques. ## Binaire autonome et images Docker basées sur Alpine Le binaire autonome et les images Docker basées sur Alpine (`dunglas/frankenphp:*-alpine`) utilisent [musl libc](https://musl.libc.org/) au lieu de [glibc et ses amis](https://www.etalabs.net/compare_libcs.html), pour garder une taille de binaire plus petite. Cela peut entraîner des problèmes de compatibilité. En particulier, le drapeau glob `GLOB_BRACE` n'est [pas disponible](https://www.php.net/manual/fr/function.glob.php). ## Utilisation de `https://127.0.0.1` avec Docker Par défaut, FrankenPHP génère un certificat TLS pour `localhost`. C'est l'option la plus simple et recommandée pour le développement local. Si vous voulez vraiment utiliser `127.0.0.1` comme hôte, il est possible de configurer FrankenPHP pour générer un certificat pour cela en définissant le nom du serveur à `127.0.0.1`. Malheureusement, cela ne suffit pas lors de l'utilisation de Docker à cause de [son système de gestion des réseaux](https://docs.docker.com/network/). Vous obtiendrez une erreur TLS similaire à `curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`. Si vous utilisez Linux, une solution est d'utiliser [le pilote de réseau "hôte"](https://docs.docker.com/network/network-tutorial-host/) : ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` Le pilote de réseau "hôte" n'est pas pris en charge sur Mac et Windows. Sur ces plateformes, vous devrez deviner l'adresse IP du conteneur et l'inclure dans les noms de serveur. Exécutez la commande `docker network inspect bridge` et inpectez la clef `Containers` pour identifier la dernière adresse IP attribuée sous la clef `IPv4Address`, puis incrémentez-la d'un. Si aucun conteneur n'est en cours d'exécution, la première adresse IP attribuée est généralement `172.17.0.2`. Ensuite, incluez ceci dans la variable d'environnement `SERVER_NAME` : ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > Assurez-vous de remplacer `172.17.0.3` par l'IP qui sera attribuée à votre conteneur. Vous devriez maintenant pouvoir accéder à `https://127.0.0.1` depuis la machine hôte. Si ce n'est pas le cas, lancez FrankenPHP en mode debug pour essayer de comprendre le problème : ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Scripts Composer Faisant Références à `@php` Les [scripts Composer](https://getcomposer.org/doc/articles/scripts.md) peuvent vouloir exécuter un binaire PHP pour certaines tâches, par exemple dans [un projet Laravel](laravel.md) pour exécuter `@php artisan package:discover --ansi`. Cela [echoue actuellement](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) pour deux raisons : - Composer ne sait pas comment appeler le binaire FrankenPHP ; - Composer peut ajouter des paramètres PHP en utilisant le paramètre `-d` dans la commande, ce que FrankenPHP ne supporte pas encore. Comme solution de contournement, nous pouvons créer un script shell dans `/usr/local/bin/php` qui supprime les paramètres non supportés et appelle ensuite FrankenPHP : ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Ensuite, mettez la variable d'environnement `PHP_BINARY` au chemin de notre script `php` et lancez Composer : ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## Résolution des problèmes TLS/SSL avec les binaires statiques Lorsque vous utilisez les binaires statiques, vous pouvez rencontrer les erreurs suivantes liées à TLS, par exemple lors de l'envoi de courriels utilisant STARTTLS : ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` Comme le binaire statique ne contient pas de certificats TLS, vous devez indiquer à OpenSSL l'installation de vos certificats CA locaux. Inspectez la sortie de [`openssl_get_cert_locations()`](https://www.php.net/manual/en/function.openssl-get-cert-locations.php), pour trouver l'endroit où les certificats CA doivent être installés et stockez-les à cet endroit. > [!WARNING] > > Les contextes Web et CLI peuvent avoir des paramètres différents. > Assurez-vous d'exécuter `openssl_get_cert_locations()` dans le bon contexte. [Les certificats CA extraits de Mozilla peuvent être téléchargés sur le site de cURL](https://curl.se/docs/caextract.html). Alternativement, de nombreuses distributions, y compris Debian, Ubuntu, et Alpine fournissent des paquets nommés `ca-certificates` qui contiennent ces certificats. Il est également possible d'utiliser `SSL_CERT_FILE` et `SSL_CERT_DIR` pour indiquer à OpenSSL où chercher les certificats CA : ```console # Définir les variables d'environnement des certificats TLS export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/fr/laravel.md ================================================ # Laravel ## Docker Déployer une application web [Laravel](https://laravel.com) avec FrankenPHP est très facile. Il suffit de monter le projet dans le répertoire `/app` de l'image Docker officielle. Exécutez cette commande depuis le répertoire principal de votre application Laravel : ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` Et profitez ! ## Installation Locale Vous pouvez également exécuter vos projets Laravel avec FrankenPHP depuis votre machine locale : 1. [Téléchargez le binaire correspondant à votre système](README.md#binaire-autonome) 2. Ajoutez la configuration suivante dans un fichier nommé `Caddyfile` placé dans le répertoire racine de votre projet Laravel : ```caddyfile { frankenphp } # Le nom de domaine de votre serveur localhost { # Définir le répertoire racine sur le dossier public/ root public/ # Autoriser la compression (optionnel) encode zstd br gzip # Exécuter les scripts PHP du dossier public/ et servir les assets php_server { try_files {path} index.php } } ``` 3. Démarrez FrankenPHP depuis le répertoire racine de votre projet Laravel : `frankenphp run` ## Laravel Octane Octane peut être installé via le gestionnaire de paquets Composer : ```console composer require laravel/octane ``` Après avoir installé Octane, vous pouvez exécuter la commande Artisan `octane:install`, qui installera le fichier de configuration d'Octane dans votre application : ```console php artisan octane:install --server=frankenphp ``` Le serveur Octane peut être démarré via la commande Artisan `octane:frankenphp`. ```console php artisan octane:frankenphp ``` La commande `octane:frankenphp` peut prendre les options suivantes : - `--host` : L'adresse IP à laquelle le serveur doit se lier (par défaut : `127.0.0.1`) - `--port` : Le port sur lequel le serveur doit être disponible (par défaut : `8000`) - `--admin-port` : Le port sur lequel le serveur administratif doit être disponible (par défaut : `2019`) - `--workers` : Le nombre de workers qui doivent être disponibles pour traiter les requêtes (par défaut : `auto`) - `--max-requests` : Le nombre de requêtes à traiter avant de recharger le serveur (par défaut : `500`) - `--caddyfile` : Le chemin vers le fichier `Caddyfile` de FrankenPHP - `--https` : Activer HTTPS, HTTP/2, et HTTP/3, et générer automatiquement et renouveler les certificats - `--http-redirect` : Activer la redirection HTTP vers HTTPS (uniquement activé si --https est passé) - `--watch` : Recharger automatiquement le serveur lorsque l'application est modifiée - `--poll` : Utiliser le sondage du système de fichiers pendant la surveillance pour surveiller les fichiers sur un réseau - `--log-level` : Enregistrer les messages au niveau de journalisation spécifié ou au-dessus, en utilisant le logger natif de Caddy > [!TIP] > Pour obtenir des logs structurés en JSON logs (utile quand vous utilisez des solutions d'analyse de logs), passez explicitement l'option `--log-level`. En savoir plus sur Laravel Octane [dans sa documentation officielle](https://laravel.com/docs/octane). ## Les Applications Laravel En Tant Que Binaires Autonomes En utilisant la [fonctionnalité d'intégration d'applications de FrankenPHP](embed.md), il est possible de distribuer les applications Laravel sous forme de binaires autonomes. Suivez ces étapes pour empaqueter votre application Laravel en tant que binaire autonome pour Linux : 1. Créez un fichier nommé `static-build.Dockerfile` dans le dépôt de votre application : ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Si vous avez l'intention d'exécuter le binaire sur des systèmes musl-libc, utilisez plutôt static-builder-musl # Copiez votre application WORKDIR /go/src/app/dist/app COPY . . # Supprimez les tests et autres fichiers inutiles pour gagner de la place # Alternativement, ajoutez ces fichiers à un fichier .dockerignore RUN rm -Rf tests/ # Copiez le fichier .env RUN cp .env.example .env # Modifier APP_ENV et APP_DEBUG pour qu'ils soient prêts pour la production RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Apportez d'autres modifications à votre fichier .env si nécessaire # Installez les dépendances RUN composer install --ignore-platform-reqs --no-dev -a # Construire le binaire statique WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Certains fichiers `.dockerignore` ignoreront le répertoire `vendor/` > et les fichiers `.env`. Assurez-vous d'ajuster ou de supprimer le fichier `.dockerignore` avant la construction. 2. Build: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. Extraire le binaire ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Remplir les caches : ```console frankenphp php-cli artisan optimize ``` 5. Exécutez les migrations de base de données (s'il y en a) : ```console frankenphp php-cli artisan migrate ``` 6. Générer la clé secrète de l'application : ```console frankenphp php-cli artisan key:generate ``` 7. Démarrez le serveur: ```console frankenphp php-server ``` Votre application est maintenant prête ! Pour en savoir plus sur les options disponibles et sur la construction de binaires pour d'autres systèmes d'exploitation, consultez la documentation [Applications PHP en tant que binaires autonomes](embed.md). ### Changer le chemin de stockage Par défaut, Laravel stocke les fichiers téléchargés, les caches, les logs, etc. dans le répertoire `storage/` de l'application. Ceci n'est pas adapté aux applications embarquées, car chaque nouvelle version sera extraite dans un répertoire temporaire différent. Définissez la variable d'environnement `LARAVEL_STORAGE_PATH` (par exemple, dans votre fichier `.env`) ou appelez la méthode `Illuminate\Foundation\Application::useStoragePath()` pour utiliser un répertoire en dehors du répertoire temporaire. ### Exécuter Octane avec des binaires autonomes Il est même possible d'empaqueter les applications Laravel Octane en tant que binaires autonomes ! Pour ce faire, [installez Octane correctement](#laravel-octane) et suivez les étapes décrites dans [la section précédente](#les-applications-laravel-en-tant-que-binaires-autonomes). Ensuite, pour démarrer FrankenPHP en mode worker via Octane, exécutez : ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > Pour que la commande fonctionne, le binaire autonome **doit** être nommé `frankenphp` > car Octane a besoin d'un programme nommé `frankenphp` disponible dans le chemin ================================================ FILE: docs/fr/mercure.md ================================================ # Temps Réel FrankenPHP est livré avec un hub [Mercure](https://mercure.rocks) intégré. Mercure permet de pousser des événements en temps réel vers tous les appareils connectés : ils recevront un événement JavaScript instantanément. Aucune bibliothèque JS ou SDK requis ! ![Mercure](../mercure-hub.png) Pour activer le hub Mercure, mettez à jour le `Caddyfile` comme décrit [sur le site de Mercure](https://mercure.rocks/docs/hub/config). Pour pousser des mises à jour Mercure depuis votre code, nous recommandons le [Composant Mercure de Symfony](https://symfony.com/components/Mercure) (vous n'avez pas besoin du framework full stack Symfony pour l'utiliser). ================================================ FILE: docs/fr/metrics.md ================================================ # Métriques Lorsque les [métriques Caddy](https://caddyserver.com/docs/metrics) sont activées, FrankenPHP expose les métriques suivantes : - `frankenphp_total_threads` : Le nombre total de threads PHP. - `frankenphp_busy_threads` : Le nombre de threads PHP en cours de traitement d'une requête (les workers en cours d'exécution consomment toujours un thread). - `frankenphp_queue_depth` : Le nombre de requêtes régulières en file d'attente - `frankenphp_total_workers{worker=« [nom_du_worker] »}` : Le nombre total de workers. - `frankenphp_busy_workers{worker=« [nom_du_worker] »}` : Le nombre de workers qui traitent actuellement une requête. - `frankenphp_worker_request_time{worker=« [nom_du_worker] »}` : Le temps passé à traiter les requêtes par tous les workers. - `frankenphp_worker_request_count{worker=« [nom_du_worker] »}` : Le nombre de requêtes traitées par tous les workers. - `frankenphp_ready_workers{worker=« [nom_du_worker] »}` : Le nombre de workers qui ont appelé `frankenphp_handle_request` au moins une fois. - `frankenphp_worker_crashes{worker=« [nom_du_worker] »}` : Le nombre de fois où un worker s'est arrêté de manière inattendue. - `frankenphp_worker_restarts{worker=« [nom_du_worker] »}` : Le nombre de fois où un worker a été délibérément redémarré. - `frankenphp_worker_queue_depth{worker=« [nom_du_worker] »}` : Le nombre de requêtes en file d'attente. Pour les métriques de worker, le placeholder `[nom_du_worker]` est remplacé par le nom du worker dans le Caddyfile, sinon le chemin absolu du fichier du worker sera utilisé. ================================================ FILE: docs/fr/performance.md ================================================ # Performance Par défaut, FrankenPHP essaie d'offrir un bon compromis entre performance et facilité d'utilisation. Cependant, il est possible d'améliorer considérablement les performances en utilisant une configuration appropriée. ## Nombre de threads et de workers Par défaut, FrankenPHP démarre deux fois plus de threads et de workers (en mode worker) que le nombre de cœurs de CPU disponibles. Les valeurs appropriées dépendent fortement de la manière dont votre application est écrite, de ce qu'elle fait et de votre matériel. Nous recommandons vivement de modifier ces valeurs. Pour une stabilité optimale du système, il est recommandé d'avoir `num_threads` x `memory_limit` < `available_memory`. Pour trouver les bonnes valeurs, il est préférable d'effectuer des tests de charge simulant le trafic réel. [k6](https://k6.io) et [Gatling](https://gatling.io) sont de bons outils pour cela. Pour configurer le nombre de threads, utilisez l'option `num_threads` des directives `php_server` et `php`. Pour changer le nombre de workers, utilisez l'option `num` de la section `worker` de la directive `frankenphp`. ### `max_threads` Bien qu'il soit toujours préférable de savoir exactement à quoi ressemblera votre trafic, les applications réelles ont tendance à être plus imprévisibles. La [configuration](config.md#configuration-du-caddyfile) `max_threads` permet à FrankenPHP de créer automatiquement des threads supplémentaires au moment de l'exécution, jusqu'à la limite spécifiée. `max_threads` peut vous aider à déterminer le nombre de threads dont vous avez besoin pour gérer votre trafic et peut rendre le serveur plus résistant aux pics de latence. Si elle est fixée à `auto`, la limite sera estimée en fonction de la valeur de `memory_limit` dans votre `php.ini`. Si ce n'est pas possible, `auto` prendra par défaut 2x `num_threads`. Gardez à l'esprit que `auto` peut fortement sous-estimer le nombre de threads nécessaires. `max_threads` est similaire à [pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children) de PHP FPM. La principale différence est que FrankenPHP utilise des threads au lieu de processus et les délègue automatiquement à différents scripts worker et au 'mode classique' selon les besoins. ## Mode worker Activer [le mode worker](worker.md) améliore considérablement les performances, mais votre application doit être adaptée pour être compatible avec ce mode : vous devez créer un script worker et vous assurer que l'application n'a pas de fuite de mémoire. ## Ne pas utiliser musl La variante Alpine Linux des images Docker officielles et les binaires par défaut que nous fournissons utilisent [la bibliothèque musl](https://musl.libc.org). PHP est connu pour être [plus lent](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) lorsqu'il utilise cette bibliothèque C alternative au lieu de la bibliothèque GNU traditionnelle, surtout lorsqu'il est compilé en mode ZTS (_thread-safe_), ce qui est nécessaire pour FrankenPHP. La différence peut être significative dans un environnement fortement multithreadé. En outre, [certains bogues ne se produisent que lors de l'utilisation de musl](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). Dans les environnements de production, nous recommandons d'utiliser FrankenPHP lié à glibc, compilé avec un niveau d'optimisation approprié. Cela peut être réalisé en utilisant les images Docker Debian, en utilisant [les paquets .deb, .rpm ou .apk proposés par l'un de nos mainteneurs](https://pkgs.henderkes.com), ou en [compilant FrankenPHP à partir des sources](compile.md). Pour des conteneurs plus légers ou plus sécurisés, vous pourriez envisager [une image Debian renforcée](docker.md#hardening-images) plutôt qu'Alpine. ## Configuration du runtime Go FrankenPHP est écrit en Go. En général, le runtime Go ne nécessite pas de configuration particulière, mais dans certaines circonstances, une configuration spécifique améliore les performances. Vous voudrez probablement mettre la variable d'environnement `GODEBUG` à `cgocheck=0` (la valeur par défaut dans les images Docker de FrankenPHP). Si vous exécutez FrankenPHP dans des conteneurs (Docker, Kubernetes, LXC...) et que vous limitez la mémoire disponible pour les conteneurs, mettez la variable d'environnement `GOMEMLIMIT` à la quantité de mémoire disponible. Pour plus de détails, [la page de documentation Go dédiée à ce sujet](https://pkg.go.dev/runtime#hdr-Environment_Variables) est à lire absolument pour tirer le meilleur parti du runtime. ## `file_server` Par défaut, la directive `php_server` met automatiquement en place un serveur de fichiers pour servir les fichiers statiques (assets) stockés dans le répertoire racine. Cette fonctionnalité est pratique, mais a un coût. Pour la désactiver, utilisez la configuration suivante : ```caddyfile php_server { file_server off } ``` ## `try_files` En plus des fichiers statiques et des fichiers PHP, `php_server` essaiera aussi de servir les fichiers d'index et d'index de répertoire de votre application (`/path/` -> `/path/index.php`). Si vous n'avez pas besoin des index de répertoires, vous pouvez les désactiver en définissant explicitement `try_files` comme ceci : ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # l'ajout explicite de la racine ici permet une meilleure mise en cache } ``` Cela permet de réduire considérablement le nombre d'opérations inutiles sur les fichiers. Un équivalent worker de la configuration précédente serait : ```caddyfile route { php_server { # utilisez "php" au lieu de "php_server" si vous n'avez pas du tout besoin du serveur de fichiers root /root/to/your/app worker /path/to/worker.php { match * # envoie toutes les requêtes directement au worker } } } ``` Une approche alternative avec 0 opérations inutiles sur le système de fichiers serait d'utiliser la directive `php` et de diviser les fichiers de PHP par chemin. Cette approche fonctionne bien si votre application entière est servie par un seul fichier d'entrée. Un exemple de [configuration](config.md#configuration-du-caddyfile) qui sert des fichiers statiques derrière un dossier `/assets` pourrait ressembler à ceci : ```caddyfile route { @assets { path /assets/* } # tout ce qui se trouve derrière /assets est géré par le serveur de fichiers file_server @assets { root /root/to/your/app } # tout ce qui n'est pas dans /assets est géré par votre fichier PHP d'index ou worker rewrite index.php php { root /root/to/your/app # l'ajout explicite de la racine ici permet une meilleure mise en cache } } ``` ## _Placeholders_ Vous pouvez utiliser des [_placeholders_](https://caddyserver.com/docs/conventions#placeholders) dans les directives `root` et `env`. Cependant, cela empêche la mise en cache de ces valeurs et a un coût important en termes de performances. Si possible, évitez les _placeholders_ dans ces directives. ## `resolve_root_symlink` Par défaut, si le _document root_ est un lien symbolique, il est automatiquement résolu par FrankenPHP (c'est nécessaire pour le bon fonctionnement de PHP). Si la racine du document n'est pas un lien symbolique, vous pouvez désactiver cette fonctionnalité. ```caddyfile php_server { resolve_root_symlink false } ``` Cela améliorera les performances si la directive `root` contient des [_placeholders_](https://caddyserver.com/docs/conventions#placeholders). Le gain sera négligeable dans les autres cas. ## Journaux La journalisation est évidemment très utile, mais, par définition, elle nécessite des opérations d'_I/O_ et des allocations de mémoire, ce qui réduit considérablement les performances. Assurez-vous de [définir le niveau de journalisation](https://caddyserver.com/docs/caddyfile/options#log) correctement, et de ne journaliser que ce qui est nécessaire. ## Performances de PHP FrankenPHP utilise l'interpréteur PHP officiel. Toutes les optimisations de performances habituelles liées à PHP s'appliquent à FrankenPHP. En particulier : - vérifiez que [OPcache](https://www.php.net/manual/en/book.opcache.php) est installé, activé et correctement configuré - activez [les optimisations de l'autoloader de Composer](https://getcomposer.org/doc/articles/autoloader-optimization.md) - assurez-vous que le cache `realpath` est suffisamment grand pour les besoins de votre application - utilisez le [pré-chargement](https://www.php.net/manual/en/opcache.preloading.php) Pour plus de détails, lisez [l'entrée de la documentation dédiée de Symfony](https://symfony.com/doc/current/performance.html) (la plupart des conseils sont utiles même si vous n'utilisez pas Symfony). ## Division du pool de threads Il est courant que les applications interagissent avec des services externes lents, comme une API qui a tendance à être peu fiable sous forte charge ou qui met constamment plus de 10 secondes à répondre. Dans de tels cas, il peut être bénéfique de diviser le pool de threads pour avoir des pools "lents" dédiés. Cela empêche les points d'accès lents de consommer toutes les ressources/threads du serveur et limite la concurrence des requêtes se dirigeant vers le point d'accès lent, à l'instar d'un pool de connexions. ```caddyfile example.com { php_server { root /app/public # la racine de votre application worker index.php { match /slow-endpoint/* # toutes les requêtes avec le chemin /slow-endpoint/* sont gérées par ce pool de threads num 1 # minimum 1 thread pour les requêtes correspondant à /slow-endpoint/* max_threads 20 # autorise jusqu'à 20 threads pour les requêtes correspondant à /slow-endpoint/*, si nécessaire } worker index.php { match * # toutes les autres requêtes sont gérées séparément num 1 # minimum 1 thread pour les autres requêtes, même si les points d'accès lents commencent à bloquer max_threads 20 # autorise jusqu'à 20 threads pour les autres requêtes, si nécessaire } } } ``` De manière générale, il est également conseillé de gérer les points d'accès très lents de manière asynchrone, en utilisant des mécanismes pertinents tels que les files d'attente de messages. ================================================ FILE: docs/fr/production.md ================================================ # Déploiement en Production Dans ce tutoriel, nous apprendrons comment déployer une application PHP sur un serveur unique en utilisant Docker Compose. Si vous utilisez Symfony, lisez plutôt la page de documentation "[Déployer en production](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)" du projet Symfony Docker (qui utilise FrankenPHP). Si vous utilisez API Platform (qui utilise également FrankenPHP), référez-vous à [la documentation de déploiement du framework](https://api-platform.com/docs/deployment/). ## Préparer votre application Tout d'abord, créez un `Dockerfile` dans le répertoire racine de votre projet PHP : ```dockerfile FROM dunglas/frankenphp # Assurez-vous de remplacer "your-domain-name.example.com" par votre nom de domaine ENV SERVER_NAME=your-domain-name.example.com # Si vous souhaitez désactiver HTTPS, utilisez cette valeur à la place : #ENV SERVER_NAME=:80 # Si votre projet n'utilise pas le répertoire "public" comme racine web, vous pouvez le définir ici : # ENV SERVER_ROOT=web/ # Activer les paramètres de production de PHP RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Copiez les fichiers PHP de votre projet dans le répertoire public COPY . /app/public # Si vous utilisez Symfony ou Laravel, vous devez copier l'intégralité du projet à la place : #COPY . /app ``` Consultez "[Construire une image Docker personnalisée](docker.md)" pour plus de détails et d'options, et pour apprendre à personnaliser la configuration, installer des extensions PHP et des modules Caddy. Si votre projet utilise Composer, assurez-vous de l'inclure dans l'image Docker et d'installer vos dépendances. Ensuite, ajoutez un fichier `compose.yaml` : ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Volumes nécessaires pour les certificats et la configuration de Caddy volumes: caddy_data: caddy_config: ``` > [!NOTE] > > Les exemples précédents sont destinés à une utilisation en production. > En développement, vous pourriez vouloir utiliser un volume, une configuration PHP différente et une valeur différente pour la variable d'environnement `SERVER_NAME`. > > Jetez un œil au projet [Symfony Docker](https://github.com/dunglas/symfony-docker) > (qui utilise FrankenPHP) pour un exemple plus avancé utilisant des images multi-étapes, > Composer, des extensions PHP supplémentaires, etc. Pour finir, si vous utilisez Git, commitez ces fichiers et poussez-les. ## Préparer un serveur Pour déployer votre application en production, vous avez besoin d'un serveur. Dans ce tutoriel, nous utiliserons une machine virtuelle fournie par DigitalOcean, mais n'importe quel serveur Linux peut fonctionner. Si vous avez déjà un serveur Linux avec Docker installé, vous pouvez passer directement à [la section suivante](#configurer-un-nom-de-domaine). Sinon, utilisez [ce lien affilié](https://m.do.co/c/5d8aabe3ab80) pour obtenir 200$ de crédit gratuit, créez un compte, puis cliquez sur "Créer un Droplet". Ensuite, cliquez sur l'onglet "Marketplace" sous la section "Choisir une image" et recherchez l'application nommée "Docker". Cela provisionnera un serveur Ubuntu avec les dernières versions de Docker et Docker Compose déjà installées ! Pour des fins de test, les plans les moins chers seront suffisants. Pour une utilisation en production réelle, vous voudrez probablement choisir un plan dans la section "General Usage" pour répondre à vos besoins. ![Déployer FrankenPHP sur DigitalOcean avec Docker](../digitalocean-droplet.png) Vous pouvez conserver les paramètres par défaut pour les autres paramètres, ou les ajuster selon vos besoins. N'oubliez pas d'ajouter votre clé SSH ou de créer un mot de passe puis appuyez sur le bouton "Finalize and create". Ensuite, attendez quelques secondes pendant que votre Droplet est en cours de provisionnement. Lorsque votre Droplet est prêt, utilisez SSH pour vous connecter : ```console ssh root@ ``` ## Configurer un nom de domaine Dans la plupart des cas, vous souhaiterez associer un nom de domaine à votre site. Si vous ne possédez pas encore de nom de domaine, vous devrez en acheter un via un registraire. Ensuite, créez un enregistrement DNS de type `A` pour votre nom de domaine pointant vers l'adresse IP de votre serveur : ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` Exemple avec le service DigitalOcean Domains ("Networking" > "Domains") : ![Configurer les DNS sur DigitalOcean](../digitalocean-dns.png) > [!NOTE] > > Let's Encrypt, le service utilisé par défaut par FrankenPHP pour générer automatiquement un certificat TLS, ne prend pas en charge l'utilisation d'adresses IP nues. L'utilisation d'un nom de domaine est obligatoire pour utiliser Let's Encrypt. ## Déploiement Copiez votre projet sur le serveur en utilisant `git clone`, `scp`, ou tout autre outil qui pourrait répondre à votre besoin. Si vous utilisez GitHub, vous voudrez peut-être utiliser [une clef de déploiement](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys). Les clés de déploiement sont également [prises en charge par GitLab](https://docs.gitlab.com/ee/user/project/deploy_keys/). Exemple avec Git : ```console git clone git@github.com:/.git ``` Accédez au répertoire contenant votre projet (``), et démarrez l'application en mode production : ```console docker compose up -d --wait ``` Votre serveur est opérationnel, et un certificat HTTPS a été automatiquement généré pour vous. Rendez-vous sur `https://your-domain-name.example.com` ! > [!CAUTION] > > Docker peut avoir une couche de cache, assurez-vous d'avoir la bonne version de build pour chaque déploiement ou reconstruisez votre projet avec l'option `--no-cache` pour éviter les problèmes de cache. ## Déploiement sur Plusieurs Nœuds Si vous souhaitez déployer votre application sur un cluster de machines, vous pouvez utiliser [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), qui est compatible avec les fichiers Compose fournis. Pour un déploiement sur Kubernetes, jetez un œil au [Helm chart fourni avec API Platform](https://api-platform.com/docs/deployment/kubernetes/), qui utilise FrankenPHP. ================================================ FILE: docs/fr/static.md ================================================ # Créer un binaire statique Au lieu d'utiliser une installation locale de la bibliothèque PHP, il est possible de créer un build statique de FrankenPHP grâce à l'excellent projet [static-php-cli](https://github.com/crazywhalecc/static-php-cli) (malgré son nom, ce projet prend en charge tous les SAPIs, pas seulement CLI). Avec cette méthode, un binaire portable unique contiendra l'interpréteur PHP, le serveur web Caddy et FrankenPHP ! Les exécutables natifs entièrement statiques ne nécessitent aucune dépendance et peuvent même être exécutés sur une [image Docker `scratch`](https://docs.docker.com/build/building/base-images/#create-a-minimal-base-image-using-scratch). Cependant, ils ne peuvent pas charger les extensions dynamiques de PHP (comme Xdebug) et ont quelques limitations parce qu'ils utilisent la librairie musl. La plupart des binaires statiques ne nécessitent que la `glibc` et peuvent charger des extensions dynamiques. Lorsque c'est possible, nous recommandons d'utiliser des binaires statiques basés sur la glibc. FrankenPHP permet également [d'embarquer l'application PHP dans le binaire statique](embed.md). ## Linux Nous fournissons des images Docker pour créer des binaires statiques pour Linux : ### Build entièrement statique, basé sur musl Pour un binaire entièrement statique qui fonctionne sur n'importe quelle distribution Linux sans dépendances, mais qui ne prend pas en charge le chargement dynamique des extensions : ```console docker buildx bake --load static-builder-musl docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-musl ``` Pour améliorer les performances dans les scénarios fortement concurrents, envisagez d'utiliser l'allocateur [mimalloc](https://github.com/microsoft/mimalloc). ```console docker buildx bake --load --set static-builder-musl.args.MIMALLOC=1 static-builder-musl ``` ### Construction principalement statique (avec prise en charge des extensions dynamiques), basé sur la glibc Pour un binaire qui supporte le chargement dynamique des extensions PHP tout en ayant les extensions sélectionnées compilées statiquement : ```console docker buildx bake --load static-builder-gnu docker cp $(docker create --name static-builder-gnu dunglas/frankenphp:static-builder-gnu):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-gnu ``` Ce binaire supporte toutes les versions 2.17 et supérieures de la glibc mais ne fonctionne pas sur les systèmes basés sur musl (comme Alpine Linux). Le binaire résultant, principalement statique (à l'exception de `glibc`), est nommé `frankenphp` et est disponible dans le répertoire courant. Si vous voulez construire le binaire statique sans Docker, jetez un coup d'œil aux instructions pour macOS, qui fonctionnent aussi pour Linux. ### Extensions personnalisées Par défaut, la plupart des extensions PHP populaires sont compilées. Pour réduire la taille du binaire et diminuer la surface d'attaque, vous pouvez choisir la liste des extensions à construire en utilisant l'argument Docker `PHP_EXTENSIONS`. Par exemple, exécutez la commande suivante pour ne construire que l'extension `opcache` : ```console docker buildx bake --load --set static-builder-musl.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder-musl # ... ``` Pour ajouter des bibliothèques permettant des fonctionnalités supplémentaires aux extensions que vous avez activées, vous pouvez utiliser l'argument Docker `PHP_EXTENSION_LIBS` : ```console docker buildx bake \ --load \ --set static-builder-musl.args.PHP_EXTENSIONS=gd \ --set static-builder-musl.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder-musl ``` ### Modules supplémentaires de Caddy Pour ajouter des modules Caddy supplémentaires ou passer d'autres arguments à [xcaddy](https://github.com/caddyserver/xcaddy), utilisez l'argument Docker `XCADDY_ARGS` : ```console docker buildx bake \ --load \ --set static-builder-musl.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder-musl ``` Dans cet exemple, nous ajoutons le module de cache HTTP [Souin](https://souin.io) pour Caddy ainsi que les modules [cbrotli](https://github.com/dunglas/caddy-cbrotli), [Mercure](https://mercure.rocks) et [Vulcain](https://vulcain.rocks). > [!TIP] > > Les modules cbrotli, Mercure et Vulcain sont inclus par défaut si `XCADDY_ARGS` est vide ou n'est pas défini. > Si vous personnalisez la valeur de `XCADDY_ARGS`, vous devez les inclure explicitement si vous voulez qu'ils soient inclus. Voir aussi comment [personnaliser la construction](#personnalisation-de-la-construction) ### Jeton GitHub Si vous atteignez la limite de taux d'appels de l'API GitHub, définissez un jeton d'accès personnel GitHub dans une variable d'environnement nommée `GITHUB_TOKEN` : ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS Exécutez le script suivant pour créer un binaire statique pour macOS (vous devez avoir [Homebrew](https://brew.sh/) d'installé) : ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Note : ce script fonctionne également sur Linux (et probablement sur d'autres Unix) et est utilisé en interne par le builder statique basé sur Docker que nous fournissons. ## Personnalisation de la construction Les variables d'environnement suivantes peuvent être transmises à `docker build` et au script `build-static.sh` pour personnaliser la construction statique : - `FRANKENPHP_VERSION` : la version de FrankenPHP à utiliser - `PHP_VERSION` : la version de PHP à utiliser - `PHP_EXTENSIONS` : les extensions PHP à construire ([liste des extensions prises en charge](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS` : bibliothèques supplémentaires à construire qui ajoutent des fonctionnalités aux extensions - `XCADDY_ARGS` : arguments à passer à [xcaddy](https://github.com/caddyserver/xcaddy), par exemple pour ajouter des modules Caddy supplémentaires - `EMBED` : chemin de l'application PHP à intégrer dans le binaire - `CLEAN` : lorsque défini, `libphp` et toutes ses dépendances sont construites à partir de zéro (pas de cache) - `DEBUG_SYMBOLS` : lorsque défini, les symboles de débogage ne seront pas supprimés et seront ajoutés dans le binaire - `NO_COMPRESS`: ne pas compresser le binaire avec UPX - `MIMALLOC`: (expérimental, Linux seulement) remplace l'allocateur mallocng de musl par [mimalloc](https://github.com/microsoft/mimalloc) pour des performances améliorées - `RELEASE` : (uniquement pour les mainteneurs) lorsque défini, le binaire résultant sera uploadé sur GitHub ## Extensions Avec la glibc ou les binaires basés sur macOS, vous pouvez charger des extensions PHP dynamiquement. Cependant, ces extensions devront être compilées avec le support ZTS. Comme la plupart des gestionnaires de paquets ne proposent pas de versions ZTS de leurs extensions, vous devrez les compiler vous-même. Pour cela, vous pouvez construire et exécuter le conteneur Docker `static-builder-gnu`, vous y connecter à distance et compiler les extensions avec `./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config`. Exemple d'étapes pour [l'extension Xdebug](https://xdebug.org) : ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` Cela aura créé `frankenphp` et `xdebug-zts.so` dans le répertoire courant. Si vous déplacez `xdebug-zts.so` dans votre répertoire d'extension, ajoutez `zend_extension=xdebug-zts.so` à votre php.ini et lancez FrankenPHP, il chargera Xdebug. ================================================ FILE: docs/fr/worker.md ================================================ # Utilisation des workers FrankenPHP Démarrez votre application une fois et gardez-la en mémoire. FrankenPHP traitera les requêtes entrantes en quelques millisecondes. ## Démarrage des scripts workers ### Docker Définissez la valeur de la variable d'environnement `FRANKENPHP_CONFIG` à `worker /path/to/your/worker/script.php` : ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Binaire autonome Utilisez l'option `--worker` de la commande `php-server` pour servir le contenu du répertoire courant en utilisant un worker : ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` Si votre application PHP est [intégrée dans le binaire](embed.md), vous pouvez ajouter un `Caddyfile` personnalisé dans le répertoire racine de l'application. Il sera utilisé automatiquement. Il est également possible de [redémarrer le worker en cas de changement de fichier](config.md#watching-for-file-changes) avec l'option `--watch`. La commande suivante déclenchera un redémarrage si un fichier se terminant par `.php` dans le répertoire `/path/to/your/app/` ou ses sous-répertoires est modifié : ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` Cette fonctionnalité se combine très bien avec le [rechargement à chaud](hot-reload.md). ## Runtime Symfony > [!TIP] > La section suivante est nécessaire uniquement avant Symfony 7.4, où le support natif du mode worker de FrankenPHP a été introduit. Le mode worker de FrankenPHP est pris en charge par le [Composant Runtime de Symfony](https://symfony.com/doc/current/components/runtime.html). Pour démarrer une application Symfony dans un worker, installez le package FrankenPHP de [PHP Runtime](https://github.com/php-runtime/runtime) : ```console composer require runtime/frankenphp-symfony ``` Démarrez votre serveur d'application en définissant la variable d'environnement `APP_RUNTIME` pour utiliser le Runtime Symfony de FrankenPHP : ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane Voir [la documentation dédiée](laravel.md#laravel-octane). ## Applications Personnalisées L'exemple suivant montre comment créer votre propre script worker sans dépendre d'une bibliothèque tierce : ```php boot(); // Déclarer le handler en dehors de la boucle pour de meilleures performances (moins de travail effectué) $handler = static function () use ($myApp) { try { // Appelé lorsqu'une requête est reçue, // les superglobales, php://input, etc., sont réinitialisés echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` est appelé uniquement lorsque le script worker se termine, // ce qui peut ne pas être ce que vous attendez, alors interceptez et gérez les exceptions ici (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // Faire quelque chose après l'envoi de la réponse HTTP $myApp->terminate(); // Exécuter le ramasse-miettes pour réduire les chances qu'il soit déclenché au milieu de la génération d'une page gc_collect_cycles(); if (!$keepRunning) break; } // Nettoyage $myApp->shutdown(); ``` Ensuite, démarrez votre application et utilisez la variable d'environnement `FRANKENPHP_CONFIG` pour configurer votre worker : ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Par défaut, 2 workers par CPU sont démarrés. Vous pouvez également configurer le nombre de workers à démarrer : ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Redémarrer le worker après un certain nombre de requêtes Comme PHP n'a pas été initialement conçu pour des processus de longue durée, de nombreuses bibliothèques et codes anciens présentent encore des fuites de mémoire. Une solution pour utiliser ce type de code en mode worker est de redémarrer le script worker après avoir traité un certain nombre de requêtes : Le code du worker précédent permet de configurer un nombre maximal de requêtes à traiter en définissant une variable d'environnement nommée `MAX_REQUESTS`. ### Redémarrer les workers manuellement Bien qu'il soit possible de redémarrer les workers [en cas de changement de fichier](config.md#watching-for-file-changes), il est également possible de redémarrer tous les workers de manière élégante via l'[API Admin de Caddy](https://caddyserver.com/docs/api). Si l'administration est activée dans votre [Caddyfile](config.md#caddyfile-config), vous pouvez envoyer un ping à l'endpoint de redémarrage avec une simple requête POST comme celle-ci : ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Échecs des workers Si un script de worker se plante avec un code de sortie non nul, FrankenPHP le redémarre avec une stratégie de backoff exponentielle. Si le script worker reste en place plus longtemps que le dernier backoff \* 2, FrankenPHP ne pénalisera pas le script et le redémarrera à nouveau. Toutefois, si le script de worker continue d'échouer avec un code de sortie non nul dans un court laps de temps (par exemple, une faute de frappe dans un script), FrankenPHP plantera avec l'erreur : `too many consecutive failures` (trop d'échecs consécutifs). Le nombre d'échecs consécutifs peut être configuré dans votre [Caddyfile](config.md#caddyfile-config) avec l'option `max_consecutive_failures` : ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Comportement des superglobales [Les superglobales PHP](https://www.php.net/manual/fr/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) se comportent comme suit : - avant le premier appel à `frankenphp_handle_request()`, les superglobales contiennent des valeurs liées au script worker lui-même - pendant et après l'appel à `frankenphp_handle_request()`, les superglobales contiennent des valeurs générées à partir de la requête HTTP traitée, chaque appel à `frankenphp_handle_request()` change les valeurs des superglobales Pour accéder aux superglobales du script worker à l'intérieur de la fonction de rappel, vous devez les copier et importer la copie dans le scope de la fonction : ```php [!WARNING] > > This feature is intended for **development environments only**. > Do not enable `hot_reload` in production, as this feature is not secure (exposes sensitive internal details) and slows down the application. > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` By default, FrankenPHP will watch all files in the current working directory matching this glob pattern: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` It's possible to set the files to watch using the glob syntax explicitly: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Use the long form of `hot_reload` to specify the Mercure topic to use, as well as which directories or files to watch: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## Client-Side Integration While the server detects changes, the browser needs to subscribe to these events to update the page. FrankenPHP exposes the Mercure Hub URL to use for subscribing to file changes via the `$_SERVER['FRANKENPHP_HOT_RELOAD']` environment variable. A convenience JavaScript library, [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload), is also available to handle the client-side logic. To use it, add the following to your main layout: ```php FrankenPHP Hot Reload ``` The library will automatically subscribe to the Mercure hub, fetch the current URL in the background when a file change is detected, and morph the DOM. It is available as an [npm](https://www.npmjs.com/package/frankenphp-hot-reload) package and on [GitHub](https://github.com/dunglas/frankenphp-hot-reload). Alternatively, you can implement your own client-side logic by subscribing directly to the Mercure hub using the `EventSource` native JavaScript class. ### Preserving Existing DOM Nodes In rare cases, such as when using development tools [like the Symfony web debug toolbar](https://github.com/symfony/symfony/pull/62970), you may want to preserve specific DOM nodes. To do so, add the `data-frankenphp-hot-reload-preserve` attribute to the relevant HTML element: ```html
``` ## Worker Mode If you are running your application in [Worker Mode](https://frankenphp.dev/docs/worker/), your application script remains in memory. This means changes to your PHP code will not be reflected immediately, even if the browser reloads. For the best developer experience, you should combine `hot_reload` with [the `watch` sub-directive in the `worker` directive](config.md#watching-for-file-changes). - `hot_reload`: refreshes the **browser** when files change - `worker.watch`: restarts the worker when files change ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## How It Works 1. **Watch**: FrankenPHP monitors the filesystem for modifications using [the `e-dant/watcher` library](https://github.com/e-dant/watcher) under the hood (we contributed the Go binding). 2. **Restart (Worker Mode)**: if `watch` is enabled in the worker config, the PHP worker is restarted to load the new code. 3. **Push**: a JSON payload containing the list of changed files is sent to the built-in [Mercure hub](https://mercure.rocks). 4. **Receive**: The browser, listening via the JavaScript library, receives the Mercure event. 5. **Update**: - If **Idiomorph** is detected, it fetches the updated content and morphs the current HTML to match the new state, applying changes instantly without losing state. - Otherwise, `window.location.reload()` is called to refresh the page. ================================================ FILE: docs/ja/CONTRIBUTING.md ================================================ # コントリビューション ## PHPのコンパイル ### Dockerを使用する場合(Linux) 開発用Dockerイメージをビルドします: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` このイメージには通常の開発ツール(Go、GDB、Valgrind、Neovimなど)が含まれており、PHP設定ファイルは以下の場所に配置されます。 - php.ini: `/etc/frankenphp/php.ini` 開発用のプリセットが適用されたphp.iniファイルがデフォルトで提供されます。 - 追加の設定ファイル: `/etc/frankenphp/php.d/*.ini` - PHP拡張モジュール: `/usr/lib/frankenphp/modules/` お使いのDockerのバージョンが23.0未満の場合、dockerignore[パターンの問題](https://github.com/moby/moby/pull/42676)によりビルドに失敗する可能性があります。以下のように`.dockerignore`にディレクトリを追加してください。 ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### Dockerを使用しない場合(LinuxおよびmacOS) [ソースからのコンパイル手順](https://frankenphp.dev/docs/compile/)に従い、`--debug`設定フラグを渡してください。 ## テストスイートの実行 ```console go test -race -v ./... ``` ## Caddyモジュール FrankenPHPのCaddyモジュール付きでCaddyをビルドします: ```console cd caddy/frankenphp/ go build -tags nobadger,nomysql,nopgx cd ../../ ``` FrankenPHPのCaddyモジュール付きでCaddyを実行します: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` サーバーは`127.0.0.1:80`で待ち受けています: > [!NOTE] > Dockerを使用している場合は、コンテナのポート80をバインドするか、コンテナ内で実行する必要があります。 ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## 最小構成のテストサーバー 最小構成のテストサーバーをビルドします: ```console cd internal/testserver/ go build cd ../../ ``` テストサーバーを実行します: ```console cd testdata/ ../internal/testserver/testserver ``` サーバーは`127.0.0.1:8080`で待ち受けています: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Dockerイメージをローカルでビルドする bakeプランを出力します: ```console docker buildx bake -f docker-bake.hcl --print ``` amd64用のFrankenPHPイメージをローカルでビルドします: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` arm64用のFrankenPHPイメージをローカルでビルドします: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` arm64とamd64用のFrankenPHPイメージをスクラッチからビルドしてDocker Hubにプッシュします: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## 静的ビルドでのセグメンテーション違反のデバッグ 1. GitHubからFrankenPHPバイナリのデバッグ版をダウンロードするか、デバッグシンボルを含む独自の静的ビルドを作成します: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. 現在使用している`frankenphp`を、デバッグ版のFrankenPHP実行ファイルに置き換えます 3. 通常通りFrankenPHPを起動します(あるいは、GDBで直接FrankenPHPを開始することもできます:`gdb --args frankenphp run`) 4. GDBでプロセスにアタッチします: ```console gdb -p `pidof frankenphp` ``` 5. 必要に応じて、GDBシェルで`continue`と入力します 6. FrankenPHPをクラッシュさせます 7. GDBシェルで`bt`と入力します 8. 出力結果をコピーします ## GitHub Actionsでのセグメンテーション違反のデバッグ 1. `.github/workflows/tests.yml`を開きます 2. PHPデバッグシンボルを有効にします ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. `tmate`を有効にしてコンテナに接続できるようにします ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. コンテナに接続します 5. `frankenphp.go`を開きます 6. `cgosymbolizer`を有効にします ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. モジュールを取得します:`go get` 8. コンテナ内で、GDBなどを使用できます: ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. バグが修正されたら、これらの変更をすべて元に戻します ## その他の開発リソース - [uWSGIでのPHP埋め込み](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [NGINX UnitでのPHP埋め込み](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [Go言語でのPHP埋め込み (go-php)](https://github.com/deuill/go-php) - [Go言語でのPHP埋め込み (GoEmPHP)](https://github.com/mikespook/goemphp) - [C++でのPHP埋め込み](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Sara Golemon 著『Extending and Embedding PHP』](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [TSRMLS_CCとは何か?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [SDL バインディング](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Docker関連リソース - [Bakeファイル定義](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## 便利なコマンド ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## ドキュメントの翻訳 新しい言語でドキュメントとサイトを翻訳するには、 以下の手順で行ってください。 1. このリポジトリの`docs/`ディレクトリに、言語の2文字ISOコードを名前にした新しいディレクトリを作成します 2. `docs/`ディレクトリのルートにある全ての`.md`ファイルを新しいディレクトリにコピーします(翻訳のソースとして常に英語版を使用してください。英語版が最新版だからです) 3. ルートディレクトリから`README.md`と`CONTRIBUTING.md`ファイルを新しいディレクトリにコピーします 4. ファイルの内容を翻訳しますが、ファイル名は変更せず、`> [!`で始まる文字列も翻訳しないでください(これはGitHub用の特別なマークアップです) 5. 翻訳でプルリクエストを作成します 6. [サイトリポジトリ](https://github.com/dunglas/frankenphp-website/tree/main)で、`content/`、`data/`、`i18n/`ディレクトリの翻訳ファイルをコピーして翻訳します 7. 作成されたYAMLファイルの値を翻訳します 8. サイトリポジトリでプルリクエストを開きます ================================================ FILE: docs/ja/README.md ================================================ # FrankenPHP: PHPのためのモダンなアプリケーションサーバー

FrankenPHP

FrankenPHPは、[Caddy](https://caddyserver.com/) Webサーバーをベースに構築された、PHPのためのモダンなアプリケーションサーバーです。 FrankenPHPは、[_Early Hints_](https://frankenphp.dev/docs/early-hints/)、[ワーカーモード](https://frankenphp.dev/docs/worker/)、[リアルタイム機能](https://frankenphp.dev/docs/mercure/)、自動HTTPS、HTTP/2、HTTP/3などの驚異的な機能により、あなたのPHPアプリに強力な力を与えます。 FrankenPHPはあらゆるPHPアプリと連携し、ワーカーモードの公式統合によってLaravelやSymfonyプロジェクトをこれまで以上に高速化します。 また、FrankenPHPはスタンドアロンのGoライブラリとしても利用可能で、`net/http`を使って任意のアプリにPHPを埋め込むことができます。 [**詳しくは** _frankenphp.dev_](https://frankenphp.dev)と、このスライド資料もご参照ください: Slides ## はじめに Windowsをお使いの場合は、[WSL](https://learn.microsoft.com/windows/wsl/)を使用してFrankenPHPを実行してください。 ### インストールスクリプト 以下のコマンドをターミナルに貼り付けると、環境に合ったバージョンが自動的にインストールされます: ```console curl https://frankenphp.dev/install.sh | sh ``` ### スタンドアロンバイナリ LinuxとmacOS向けに、開発用途の静的FrankenPHPバイナリを提供しています。 [PHP 8.4](https://www.php.net/releases/8.4/en.php)と主要なPHP拡張が含まれます。 [FrankenPHPをダウンロード](https://github.com/php/frankenphp/releases) **拡張のインストール:** よく使われる拡張は同梱されています。追加の拡張をインストールすることはできません。 ### rpm パッケージ メンテナーが `dnf` を使用するすべてのシステム向けに rpm パッケージを提供しています。インストール方法: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 8.2-8.5 利用可能 sudo dnf install frankenphp ``` **拡張のインストール:** `sudo dnf install php-zts-` デフォルトで提供されていない拡張については [PIE](https://github.com/php/pie) を使用してください: ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### deb パッケージ メンテナーが `apt` を使用するすべてのシステム向けに deb パッケージを提供しています。インストール方法: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **拡張のインストール:** `sudo apt install php-zts-` デフォルトで提供されていない拡張については [PIE](https://github.com/php/pie) を使用してください: ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker また、[Dockerイメージ](https://frankenphp.dev/docs/docker/)も利用可能です: ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ブラウザで`https://localhost`にアクセスして、FrankenPHPをお楽しみください! > [!TIP] > > `https://127.0.0.1`ではなく、`https://localhost`を使用して、自己署名証明書を受け入れてください。 > 使用するドメインを変更したい場合は、[`SERVER_NAME` 環境変数](docs/config.md#environment-variables)を設定してください。 ### Homebrew FrankenPHPはmacOSおよびLinux向けに[Homebrew](https://brew.sh)パッケージとしても利用可能です。 インストール方法: ```console brew install dunglas/frankenphp/frankenphp ``` **拡張のインストール:** [PIE](https://github.com/php/pie) を使用してください。 ### 使い方 現在のディレクトリのコンテンツを配信するには、以下を実行してください: ```console frankenphp php-server ``` コマンドラインスクリプトも実行できます: ```console frankenphp php-cli /path/to/your/script.php ``` deb / rpm パッケージの場合は、systemd サービスを起動することもできます: ```console sudo systemctl start frankenphp ``` ## ドキュメント - [クラシックモード](https://frankenphp.dev/docs/classic/) - [ワーカーモード](https://frankenphp.dev/docs/worker/) - [Early Hintsサポート(103 HTTPステータスコード)](https://frankenphp.dev/docs/early-hints/) - [リアルタイム](https://frankenphp.dev/docs/mercure/) - [大きな静的ファイルの効率的な提供](https://frankenphp.dev/docs/x-sendfile/) - [設定](https://frankenphp.dev/docs/config/) - [Dockerイメージ](https://frankenphp.dev/docs/docker/) - [本番環境でのデプロイ](https://frankenphp.dev/docs/production/) - [パフォーマンス最適化](https://frankenphp.dev/docs/performance/) - [**スタンドアロン**、自己実行可能なPHPアプリの作成](https://frankenphp.dev/docs/embed/) - [静的バイナリの作成](https://frankenphp.dev/docs/static/) - [ソースからのコンパイル](https://frankenphp.dev/docs/compile/) - [FrankenPHPの監視](https://frankenphp.dev/docs/metrics/) - [Laravel統合](https://frankenphp.dev/docs/laravel/) - [既知の問題](https://frankenphp.dev/docs/known-issues/) - [デモアプリ(Symfony)とベンチマーク](https://github.com/dunglas/frankenphp-demo) - [Goライブラリドキュメント](https://pkg.go.dev/github.com/dunglas/frankenphp) - [コントリビューションとデバッグ](https://frankenphp.dev/docs/contributing/) ## 例とスケルトン - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/symfony) - [Laravel](https://frankenphp.dev/docs/laravel/) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/ja/classic.md ================================================ # クラシックモードの使用 追加の設定を行わなくても、FrankenPHPはクラシックモードで動作します。このモードでは、FrankenPHPは従来のPHPサーバーのように機能し、PHPファイルを直接提供します。これにより、PHP-FPMやmod_phpを使ったApacheの置き換えとしてシームレスに利用できます。 Caddyと同様に、FrankenPHPは無制限の接続を受け付け、[固定数のスレッド](config.md#caddyfile-config)でそれらを処理します。受け入れられキューに入れられる接続の数は、利用可能なシステムリソースによってのみ制限されます。 PHPスレッドプールは、起動時に初期化された固定数のスレッドで動作し、これはPHP-FPMの静的モードに相当します。また、PHP-FPMの動的モードと同様に、[実行時にスレッドを自動的にスケール](performance.md#max_threads)させることも可能です。 キューに入った接続は、PHPスレッドが空くまで無期限に待機します。これを避けるために、FrankenPHP のグローバル設定内の `max_wait_time` [設定](config.md#caddyfile-config)を使って、リクエストが空きスレッドを待てる最大時間を制限し、それを超えるとリクエストが拒否されるようにできます。 加えて、[Caddy側で適切な書き込みタイムアウト](https://caddyserver.com/docs/caddyfile/options#timeouts)を設定することも可能です。 各Caddyインスタンスは、1つのFrankenPHPスレッドプールのみを起動し、すべての`php_server`ブロック間でこのプールを共有します。 ================================================ FILE: docs/ja/compile.md ================================================ # ソースからのコンパイル このドキュメントでは、PHPを動的ライブラリとしてロードするFrankenPHPバイナリの作成方法を説明します。 これが推奨される方法です。 または、[完全静的およびほぼ静的なビルド](static.md)も作成できます。 ## PHPのインストール FrankenPHPはPHP 8.2以上と互換性があります。 ### Homebrewを使用する場合(LinuxとMac) FrankenPHPと互換性のあるlibphpのバージョンをインストールする最も簡単な方法は、[Homebrew PHP](https://github.com/shivammathur/homebrew-php)が提供するZTSパッケージを使用することです。 まず、まだインストールしていない場合は[Homebrew](https://brew.sh)をインストールしてください。 次に、PHPのZTSバリアント、Brotli(オプション、圧縮サポート用)、watcher(オプション、ファイル変更検出用)をインストールします: ```console brew install shivammathur/php/php-zts brotli watcher brew link --overwrite --force shivammathur/php/php-zts ``` ### PHPをコンパイルする場合 別の方法として、FrankenPHPに必要なオプションを指定してPHPをソースからコンパイルすることもできます。 まず、[PHPのソース](https://www.php.net/downloads.php)を取得して展開します: ```console tar xf php-* cd php-*/ ``` 次に、プラットフォームに応じて必要なオプションを指定して`configure`スクリプトを実行します。 以下の`./configure`フラグは必須ですが、例えば拡張機能モジュールや追加機能をコンパイルするために他のフラグを追加することもできます。 #### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` #### Mac [Homebrew](https://brew.sh/)パッケージマネージャーを使用して、必須およびオプションの依存関係をインストールします: ```console brew install libiconv bison brotli re2c pkg-config watcher echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` その後、以下のようにconfigureスクリプトを実行します: ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` #### PHPのコンパイル 最後に、PHPをコンパイルしてインストールします: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## オプション依存関係のインストール FrankenPHPの一部の機能は、システムにインストールされているオプションの依存パッケージに依存しています。 または、Goコンパイラにビルドタグを渡すことで、これらの機能を無効にできます。 | 機能 | 依存関係 | 無効にするためのビルドタグ | | ------------------------------ | --------------------------------------------------------------------- | -------------------------- | | Brotli圧縮 | [Brotli](https://github.com/google/brotli) | nobrotli | | ファイル変更時のワーカー再起動 | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | ## Goアプリのコンパイル いよいよ最終的なバイナリをビルドできるようになりました。 ### xcaddyを使う場合 推奨される方法は、[xcaddy](https://github.com/caddyserver/xcaddy)を使用してFrankenPHPをコンパイルする方法です。 `xcaddy`を使うと、[Caddyのカスタムモジュール](https://caddyserver.com/docs/modules/)やFrankenPHP拡張を簡単に追加できます: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # 追加のCaddyモジュールとFrankenPHP拡張をここに追加 ``` > [!TIP] > > musl libc(Alpine Linuxのデフォルト)とSymfonyを使用している場合、 > デフォルトのスタックサイズを増やす必要がある場合があります。 > そうしないと、`PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression`のようなエラーが発生する可能性があります。 > > これを行うには、`XCADDY_GO_BUILD_FLAGS`環境変数を > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'`のようなものに変更してください > (アプリの要件に応じてスタックサイズの値を変更してください)。 ### xcaddyを使用しない場合 代替として、`xcaddy`を使わずに`go`コマンドを直接使ってFrankenPHPをコンパイルすることも可能です: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/ja/config.md ================================================ # 設定 FrankenPHP、Caddy、そして[Mercure](mercure.md)や[Vulcain](https://vulcain.rocks)モジュールは、[Caddyでサポートされる形式](https://caddyserver.com/docs/getting-started#your-first-config)を使用して設定できます。 最も一般的な形式は`Caddyfile`で、シンプルで人間が読めるテキスト形式です。 デフォルトでは、FrankenPHPは現在のディレクトリにある`Caddyfile`を探します。 `-c`または`--config`オプションでカスタムパスを指定できます。 PHPアプリケーションを配信するための最小限の`Caddyfile`を以下に示します: ```caddyfile # レスポンスするホスト名 localhost # オプションで、ファイルを配信するディレクトリ。指定しない場合は現在のディレクトリがデフォルト #root public/ php_server ``` より多くの機能を有効にし、便利な環境変数を提供するより高度な`Caddyfile`は、[FrankenPHPリポジトリ](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile)およびDockerイメージに同梱されています。 PHP自体は、[`php.ini` ファイルを使用](https://www.php.net/manual/en/configuration.file.php)して設定できます。 インストール方法に応じて、FrankenPHPとPHPインタープリターは以下の場所に記載された設定ファイルを探します。 ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: メインの設定ファイル - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: 自動的にロードされる追加の設定ファイル PHP: - `php.ini`: `/usr/local/etc/php/php.ini`(デフォルトでは`php.ini`は含まれていません) - 追加の設定ファイル: `/usr/local/etc/php/conf.d/*.ini` - PHP拡張モジュール: `/usr/local/lib/php/extensions/no-debug-zts-/` - PHPプロジェクトが提供する公式テンプレートをコピーすることを推奨します: ```dockerfile FROM dunglas/frankenphp # Production: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Or development: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## RPMおよびDebianパッケージ FrankenPHP: - `/etc/frankenphp/Caddyfile`: メインの設定ファイル - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: 自動的にロードされる追加の設定ファイル PHP: - `php.ini`: `/etc/php-zts/php.ini`(本番環境向けのプリセットの`php.ini`ファイルがデフォルトで提供されます) - 追加の設定ファイル: `/etc/php-zts/conf.d/*.ini` ## 静的バイナリ FrankenPHP: - 現在の作業ディレクトリ: `Caddyfile` PHP: - `php.ini`: `frankenphp run`または`frankenphp php-server`を実行したディレクトリ内、なければ`/etc/frankenphp/php.ini`を参照 - 追加の設定ファイル: `/etc/frankenphp/php.d/*.ini` - PHP拡張モジュール: ロードできません、バイナリ自体にバンドルする必要があります - [PHPソース](https://github.com/php/php-src/)で提供される`php.ini-production`または`php.ini-development`のいずれかをコピーしてください。 ## Caddyfileの設定 `php_server`または`php`の[HTTPディレクティブ](https://caddyserver.com/docs/caddyfile/concepts#directives)は、サイトブロック内で使用してPHPアプリを配信できます。 最小構成の例: ```caddyfile localhost { # 圧縮を有効化(オプション) encode zstd br gzip # 現在のディレクトリ内のPHPファイルを実行し、アセットを配信 php_server } ``` FrankenPHPは、`frankenphp`の[グローバルオプション](https://caddyserver.com/docs/caddyfile/concepts#global-options)を使用して明示的に設定することもできます: ```caddyfile { frankenphp { num_threads # 開始するPHPスレッド数を設定します。デフォルト: 利用可能なCPU数の2倍。 max_threads # 実行時に追加で開始できるPHPスレッドの最大数を制限します。デフォルト: num_threads。 'auto'を設定可能。 max_wait_time # リクエストがタイムアウトする前にPHPのスレッドが空くのを待つ最大時間を設定します。デフォルト: 無効。 max_idle_time # 自動スケーリングされたスレッドが非アクティブ化されるまでにアイドル状態である最大時間を設定します。デフォルト: 5秒。 php_ini # php.iniのディレクティブを設定します。複数のディレクティブを設定するために何度でも使用できます。 worker { file # ワーカースクリプトのパスを設定します。 num # 開始するPHPスレッド数を設定します。デフォルト: 利用可能なCPU数の2倍。 env # 追加の環境変数を指定された値に設定する。複数の環境変数に対して複数回指定することができます。 watch # ファイル変更を監視するパスを設定します。複数のパスに対して複数回指定できます。 name # ワーカーの名前を設定します。ログとメトリクスで使用されます。デフォルト: ワーカーファイルの絶対パス max_consecutive_failures # workerが不健全とみなされるまでの、連続失敗の最大回数を設定します。 -1 はワーカーを常に再起動することを意味します。デフォルトは 6 です。 } } } # ... ``` 代わりに、`worker`オプションのワンライナー形式を使用することもできます: ```caddyfile { frankenphp { worker } } # ... ``` 同じサーバーで複数のアプリを提供する場合は、複数のワーカーを定義することもできます: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # キャッシュ効率を高める worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` 通常は`php_server`ディレクティブを使えば十分ですが、 より細かい制御が必要な場合は、より低レベルの`php`ディレクティブを使用できます。 `php`ディレクティブは、対象がPHPファイルかどうかを確認せず、すべての入力をPHPに渡します。 詳しくは[パフォーマンスページ](performance.md#try_files)をお読みください。 `php_server`ディレクティブの使用は、以下の設定と同等です: ```caddyfile route { # ディレクトリへのリクエストに末尾スラッシュを追加 @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # 要求されたファイルが存在しない場合は、indexファイルを試行 @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` `php_server`と`php`ディレクティブには以下のオプションがあります: ```caddyfile php_server [] { root # サイトのルートフォルダを設定します。デフォルト: `root`ディレクティブ。 split_path # URIを2つの部分に分割するための部分文字列を設定します。最初にマッチする部分文字列がURIから「パス情報」を分割するために使用されます。最初の部分はマッチする部分文字列で接尾辞が付けられ、実際のリソース(CGIスクリプト)名とみなされます。2番目の部分はスクリプトが使用する PATH_INFO に設定されます。デフォルト: `.php` resolve_root_symlink false # シンボリックリンクが存在する場合`root`ディレクトリをシンボリックリンクの評価によって実際の値に解決することを無効にする(デフォルトで有効)。 env # 追加の環境変数を指定された値に設定する。複数の環境変数を指定する場合は、複数回指定することができます。 file_server off # 組み込みのfile_serverディレクティブを無効にします。 worker { # このサーバー固有のワーカーを作成します。複数のワーカーに対して複数回指定できます。 file # ワーカースクリプトへのパスを設定します。php_serverのルートからの相対パスとなります。 num # 起動するPHPスレッド数を設定します。デフォルトは利用可能なCPU数の2倍です。 name # ログとメトリクスで使用されるワーカーの名前を設定します。デフォルト: ワーカーファイルの絶対パス。php_server ブロックで定義されている場合は、常にm#で始まります。 watch # ファイルの変更を監視するパスを設定する。複数のパスに対して複数回指定することができる。 env # 追加の環境変数を指定された値に設定する。複数の環境変数を指定する場合は、複数回指定することができます。このワーカーの環境変数もphp_serverの親から継承されますが、 ここで上書きすることもできます。 match # ワーカーをパスパターンにマッチさせます。try_filesを上書きし、php_serverディレクティブでのみ使用できます。 } worker # グローバルfrankenphpブロックのような短縮形式も使用できます。 } ``` ### ファイルの変更監視 ワーカーはアプリケーションを一度だけ起動してメモリに保持するため、 PHPファイルに変更を加えても即座には反映されません。 代わりに、`watch`ディレクティブを使用してファイル変更時にワーカーを再起動させることができます。 これは開発環境において有用です。 ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` この機能は、[ホットリロード](hot-reload.md)と組み合わせてよく使用されます。 `watch`ディレクトリが指定されていない場合、`./**/*.{env,php,twig,yaml,yml}`にフォールバックします。 これは、FrankenPHPプロセスが開始されたディレクトリおよびそのサブディレクトリ内のすべての`.env`、`.php`、`.twig`、`.yaml`、`.yml`ファイルすべてを監視します。 代わりに、[シェルのファイル名パターン](https://pkg.go.dev/path/filepath#Match)を使用して 1つ以上のディレクトリを指定することもできます: ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # /path/to/app以下すべてのサブディレクトリのファイルを監視 watch /path/to/app/*.php # /path/to/app内の.phpで終わるファイルを監視 watch /path/to/app/**/*.php # /path/to/appおよびサブディレクトリのPHPファイルを監視 watch /path/to/app/**/*.{php,twig} # /path/to/appおよびサブディレクトリ内のPHPとTwigファイルを監視 } } } ``` - `**` パターンは再帰的な監視を意味します - ディレクトリは相対パス(FrankenPHPプロセスの開始ディレクトリから)にもできます - 複数のワーカーが定義されている場合、いずれかのファイルが変更されるとすべてのワーカーが再起動されます - 実行時に生成されるファイル(ログなど)を監視対象に含めると、意図しないワーカーの再起動を引き起こす可能性があるため注意が必要です ファイルウォッチャーは[e-dant/watcher](https://github.com/e-dant/watcher)に基づいています。 ## パスにワーカーをマッチさせる 従来のPHPアプリケーションでは、スクリプトは常にpublicディレクトリに配置されます。 これはワーカースクリプトにも当てはまり、他のPHPスクリプトと同様に扱われます。 ワーカースクリプトをpublicディレクトリの外に配置したい場合は、`match`ディレクティブを使用して実現できます。 `match`ディレクティブは、`try_files`の最適化された代替手段であり、`php_server`および`php`の中でのみ使用できます。 次の例では、public ディレクトリ内にファイルが存在すればそれを配信し、 存在しなければ、パスパターンに一致するワーカーにリクエストを転送します。 ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # ファイルはpublicパス外でも可 match /api/* # /api/で始まるすべてのリクエストはこのワーカーで処理される } } } } ``` ## 環境変数 以下の環境変数を使用することで、`Caddyfile`を直接変更せずにCaddyディレクティブを注入できます: - `SERVER_NAME`: [待ち受けアドレス](https://caddyserver.com/docs/caddyfile/concepts#addresses)を変更し、指定したホスト名はTLS証明書の生成にも使用されます - `SERVER_ROOT`: サイトのルートディレクトリを変更します。デフォルトは`public/` - `CADDY_GLOBAL_OPTIONS`: [グローバルオプション](https://caddyserver.com/docs/caddyfile/options)を注入します - `FRANKENPHP_CONFIG`: `frankenphp`ディレクティブの下に設定を注入します FPM や CLI SAPI と同様に、環境変数はデフォルトで`$_SERVER`スーパーグローバルで公開されます。 [`variables_order` PHPディレクティブ](https://www.php.net/manual/en/ini.core.php#ini.variables-order)の`S`値は、このディレクティブ内での`E`の位置にかかわらず常に`ES`と同等です。 ## PHP設定 [追加のPHP設定ファイル](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan)を読み込むには、 `PHP_INI_SCAN_DIR`環境変数を使用できます。 設定されると、PHPは指定されたディレクトリに存在する`.ini`拡張子を持つすべてのファイルを読み込みます。 また、`Caddyfile`の`php_ini`ディレクティブを使用してPHP設定を変更することもできます: ```caddyfile { frankenphp { php_ini memory_limit 256M # or php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### HTTPSの無効化 デフォルトでは、FrankenPHPは`localhost`を含むすべてのホスト名に対してHTTPSを自動的に有効にします。 HTTPSを無効にしたい場合(例えば開発環境で)、`SERVER_NAME`環境変数を`http://`または`:80`に設定できます: または、[Caddyのドキュメント](https://caddyserver.com/docs/automatic-https#activation)に記載されている他のすべての方法を使用することもできます。 `localhost`ホスト名の代わりに`127.0.0.1` IPアドレスでHTTPSを使用したい場合は、[既知の問題](known-issues.md#using-https127001-with-docker)セクションを読んでください。 ### フルデュプレックス(HTTP/1) HTTP/1.xを使用する場合、全体のボディが読み取られる前にレスポンスを書き込めるようにするため、 フルデュプレックスモードを有効にすることが望ましい場合があります(例:[Mercure](mercure.md)、WebSocket、Server-Sent Eventsなど)。 これは明示的に有効化する必要がある設定で、`Caddyfile`のグローバルオプションに追加する必要があります: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > このオプションを有効にすると、フルデュプレックスをサポートしない古いHTTP/1.xクライアントでデッドロックが発生する可能性があります。 > これは`CADDY_GLOBAL_OPTIONS`環境設定を使用しても設定できます: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` この設定の詳細については、[Caddyドキュメント](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex)をご覧ください。 ## デバッグモードの有効化 Dockerイメージを使用する場合、`CADDY_GLOBAL_OPTIONS`環境変数に`debug`を設定するとデバッグモードが有効になります: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Shell Completion FrankenPHPはBash、Zsh、Fish、およびPowerShell用のシェル補完機能を内蔵しています。これにより、すべてのコマンド(`php-server`、`php-cli`、`extension-init`などのカスタムコマンドを含む)とそのフラグのオートコンプリートが可能になります。 ### Bash 現在のシェルセッションで補完を読み込むには: ```console source <(frankenphp completion bash) ``` 新しいセッションごとに補完を読み込むには、以下を実行してください: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh シェル補完がまだ環境で有効になっていない場合は、有効にする必要があります。以下のコマンドを一度実行してください: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` 各セッションで補完を読み込むには、一度実行してください: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` この設定を有効にするには、新しいシェルを起動する必要があります。 ### Fish 現在のシェルセッションで補完を読み込むには: ```console frankenphp completion fish | source ``` 新しいセッションごとに補完を読み込むには、一度実行してください: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell 現在のシェルセッションで補完を読み込むには: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` 新しいセッションごとに補完を読み込むには、一度実行してください: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` この設定を有効にするには、新しいシェルを起動する必要があります。 この設定を有効にするには、新しいシェルを起動する必要があります。 ================================================ FILE: docs/ja/docker.md ================================================ # カスタムDockerイメージのビルド [FrankenPHPのDockerイメージ](https://hub.docker.com/r/dunglas/frankenphp)は、[公式PHPイメージ](https://hub.docker.com/_/php/)をベースにしています。主要なアーキテクチャに対してDebianとAlpine Linuxのバリアントを提供しており、Debianバリアントの使用を推奨しています。 PHP 8.2、8.3、8.4、8.5向けのバリアントが提供されています。 タグは次のパターンに従います:`dunglas/frankenphp:-php-` - ``および``は、それぞれFrankenPHPおよびPHPのバージョン番号で、メジャー(例:`1`)、マイナー(例:`1.2`)からパッチバージョン(例:`1.2.3`)まであります。 - ``は`trixie`(Debian Trixie用)、`bookworm`(Debian Bookworm用)、または`alpine`(Alpine最新安定版用)のいずれかです。 [タグを閲覧](https://hub.docker.com/r/dunglas/frankenphp/tags)。 ## イメージの使用方法 プロジェクトに`Dockerfile`を作成します: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` 次に、以下のコマンドを実行してDockerイメージをビルドし、実行します: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## 設定を調整する方法 利便性のため、役立つ環境変数を含む[デフォルトの`Caddyfile`](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile)がイメージに含まれています。 ## PHP拡張モジュールの追加インストール方法 ベースイメージには[`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer)スクリプトが含まれており、 追加のPHP拡張モジュールを簡単にインストールできます: ```dockerfile FROM dunglas/frankenphp # ここに追加の拡張モジュールを追加: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Caddyモジュールの追加インストール方法 FrankenPHPはCaddyをベースに構築されているため、すべての[Caddyモジュール](https://caddyserver.com/docs/modules/)をFrankenPHPでも使用できます。 カスタムCaddyモジュールをインストールする最も簡単な方法は、[xcaddy](https://github.com/caddyserver/xcaddy)を使用することです: ```dockerfile FROM dunglas/frankenphp:builder AS builder # builderイメージにxcaddyをコピー COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # FrankenPHPをビルドするにはCGOを有効にする必要があります RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # MercureとVulcainは公式ビルドに含まれていますが、お気軽に削除してください --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # ここに追加のCaddyモジュールを指定してください FROM dunglas/frankenphp AS runner # 公式バイナリをカスタムモジュールを含むものに置き換え COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` FrankenPHPが提供する`builder`イメージには、コンパイル済みの`libphp`が含まれています。 [ビルダーイメージ](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder)は、FrankenPHPおよびPHPのすべてのバージョンに対して、DebianとAlpineの両方が提供されています。 > [!TIP] > > Alpine LinuxとSymfonyを使用している場合は、 > [デフォルトのスタックサイズを増やす](compile.md#using-xcaddy) 必要がある場合があります。 ## デフォルトでワーカーモードを有効にする FrankenPHPをワーカースクリプトで起動するには、`FRANKENPHP_CONFIG`環境変数を設定します: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## 開発時にボリュームを使う FrankenPHPでの開発を簡単に行うには、ホスト側のアプリケーションのソースコードを含むディレクトリを、Dockerコンテナ内にボリュームとしてマウントします: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > `--tty`オプションを使うと、JSONではなく人間が読みやすいログが表示されます。 Docker Composeを使用する場合: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # カスタムDockerfileを使用したい場合は以下の行のコメントを外してください #build: . # 本番環境で使用する場合は以下の行のコメントを外してください # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # 開発環境で人間が読みやすいログを出力するため、本番ではこの行をコメントアウトしてください tty: true # Caddyの証明書や設定に必要なボリューム volumes: caddy_data: caddy_config: ``` ## 非rootユーザーとして実行する FrankenPHPはDockerで非rootユーザーとして実行できます。 これを行うサンプル`Dockerfile`は以下の通りです: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Alpine系ディストリビューションでは "adduser -D ${USER}" を使用 useradd ${USER}; \ # ポート 80 や 443 にバインドするための追加ケーパビリティを追加 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # /config/caddy および /data/caddy への書き込み権限を付与 chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### ケーパビリティなしでの実行 FrankenPHPをroot以外のユーザーで実行する場合でも、特権ポート(80と443)でWebサーバーを バインドするために`CAP_NET_BIND_SERVICE`ケーパビリティが必要です。 FrankenPHPを非特権ポート(1024以上)で公開する場合は、 ウェブサーバーを非rootユーザーとして実行し、ケーパビリティを必要とせずに実行することが可能です: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Alpine 系ディストリビューションでは "adduser -D ${USER}" を使用 useradd ${USER}; \ # デフォルトのケーパビリティを削除 setcap -r /usr/local/bin/frankenphp; \ # /config/caddy と /data/caddy への書き込み権限を付与 chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` その後、`SERVER_NAME`環境変数を設定して非特権ポートを使用します。 例: `:8000` ## アップデート Dockerイメージは以下のタイミングでビルドされます: - 新しいリリースがタグ付けされたとき - 公式PHPイメージに新しいバージョンがある場合、毎日UTC午前4時に自動ビルド ## イメージの強化 FrankenPHP Dockerイメージの攻撃対象領域とサイズをさらに削減するために、[Google distroless](https://github.com/GoogleContainerTools/distroless)または[Docker hardened](https://www.docker.com/products/hardened-images)イメージをベースにビルドすることも可能です。 > [!WARNING] > これらの最小限のベースイメージにはシェルやパッケージマネージャーが含まれていないため、デバッグがより困難になります。そのため、セキュリティが最優先される本番環境でのみ推奨されます。 追加のPHP拡張機能を追加する場合は、中間ビルドステージが必要になります: ```dockerfile FROM dunglas/frankenphp AS builder # ここに追加のPHP拡張機能を追加 RUN install-php-extensions pdo_mysql pdo_pgsql #... # frankenphpとインストールされているすべての拡張機能の共有ライブラリを一時的な場所にコピー # この手順は、frankenphpバイナリおよび各拡張機能の.soファイルのldd出力を分析することで手動で行うこともできます RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Distroless Debianベースイメージ。ベースイメージと同じDebianバージョンであることを確認してください FROM gcr.io/distroless/base-debian13 # Docker hardened イメージの代替 # FROM dhi.io/debian:13 # コンテナにコピーするアプリケーションとCaddyfileの場所 ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # アプリケーションを/appにコピー # さらに強化するために、書き込み可能なパスのみが非rootユーザーに所有されていることを確認してください COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # frankenphpと必要なライブラリをコピー COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # php.ini設定ファイルをコピー COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Caddyデータディレクトリ — 読み取り専用のルートファイルシステム上でも、非rootユーザーが書き込み可能である必要があります ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # 指定されたCaddyfileでfrankenphpを実行するエントリポイント ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## 開発版 開発版は[`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev)Dockerリポジトリで利用できます。 GitHubリポジトリの`main`ブランチにコミットがpushされるたびに新しいビルドが実行されます。 `latest*`タグは`main`ブランチのヘッドを指しており、`sha-` 形式のタグも利用可能です。 ================================================ FILE: docs/ja/early-hints.md ================================================ # Early Hints FrankenPHPは[103 Early Hints ステータスコード](https://developer.chrome.com/blog/early-hints/)をネイティブサポートしています。 Early Hintsを使用することで、ウェブページの読み込み時間を30%改善できます。 ```php ; rel=preload; as=style'); headers_send(103); // 遅いアルゴリズムとSQLクエリ 🤪 echo <<<'HTML' Hello FrankenPHP HTML; ``` Early Hintsは通常モードと[ワーカー](worker.md)モードの両方でサポートされています。 ================================================ FILE: docs/ja/embed.md ================================================ # PHPアプリのスタンドアロンバイナリ化 FrankenPHPには、PHPアプリケーションのソースコードやアセットを静的な自己完結型バイナリに埋め込む機能があります。 この機能により、PHPアプリケーション自体に加えて、PHPインタープリターや本番環境対応のWebサーバーCaddyも含んだスタンドアロンバイナリとして配布できます。 この機能について詳しくは、[SymfonyCon 2023でKévinが行ったプレゼンテーション](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/)をご覧ください。 Laravelアプリケーションの埋め込みについては、[こちらの専用ドキュメント](laravel.md#laravel-apps-as-standalone-binaries)をお読みください。 ## アプリの準備 自己完結型バイナリを作成する前に、アプリが埋め込みに対応できる状態にあることを確認してください。 例えば、以下のような作業が必要です: - 本番環境用の依存パッケージをインストールする - オートローダーをダンプする - アプリケーションの本番モードを有効にする(ある場合) - 最終バイナリのサイズを減らすために`.git`やテストなどの不要なファイルを除外する 例えば、Symfonyアプリの場合、以下のコマンドを使用できます: ```console # .git/ などを除去するためにプロジェクトをエクスポート mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # 適切な環境変数を設定 echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # テストやその他不要ファイルを削除して容量削減 # あるいは、 .gitattributes の export-ignore 属性にこれらを追加してもよい rm -Rf tests/ # 依存パッケージをインストール composer install --ignore-platform-reqs --no-dev -a # .env を最適化 composer dump-env prod ``` ### 設定のカスタマイズ [設定](config.md) をカスタマイズするには、埋め込まれるアプリのメインディレクトリ (前の例では`$TMPDIR/my-prepared-app`)に`Caddyfile`と`php.ini`ファイルを配置できます。 ## Linux用バイナリの作成 Linux用バイナリを作成する最も簡単な方法は、提供されているDockerベースのビルダーを使用することです。 1. アプリのリポジトリに`static-build.Dockerfile`というファイルを作成します: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # バイナリをmusl-libcシステムで実行する場合は、static-builder-musl を使用してください # アプリをコピー WORKDIR /go/src/app/dist/app COPY . . # 静的バイナリをビルド WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > 一部の`.dockerignore`ファイル(例:デフォルトの[Symfony Docker `.dockerignore`](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > は`vendor/`ディレクトリと`.env`ファイルを無視します。ビルド前に`.dockerignore`ファイルを調整または削除してください。 2. ビルドします: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. バイナリを抽出します: ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` 生成されるバイナリは、現在のディレクトリの`my-app`というファイル名になります。 ## 他のOS用のバイナリの作成 Dockerを使用したくない場合や、macOSバイナリを作成したい場合は、提供されているシェルスクリプトを使用してください: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` 生成されるバイナリは、`dist/`ディレクトリの`frankenphp--`という名前のファイルです。 ## バイナリの使い方 これで完了です!`my-app`ファイル(または他のOSでは`dist/frankenphp--`)には、自己完結型アプリが含まれています! Webアプリを起動するには、以下を実行します: ```console ./my-app php-server ``` アプリに[ワーカースクリプト](worker.md)が含まれている場合は、以下のようにワーカーを開始します: ```console ./my-app php-server --worker public/index.php ``` HTTPS(Let's Encrypt証明書は自動作成)、HTTP/2、HTTP/3を有効にするには、使用するドメイン名を指定してください: ```console ./my-app php-server --domain localhost ``` バイナリに埋め込まれたPHP CLIスクリプトも実行できます: ```console ./my-app php-cli bin/console ``` ## PHP拡張モジュール デフォルトでは、スクリプトはプロジェクトの`composer.json`ファイルで必要な拡張モジュールをビルドします(存在する場合)。 `composer.json`ファイルが存在しない場合、[静的ビルドのドキュメント](static.md)に記載されているデフォルトの拡張モジュールがビルドされます。 拡張モジュールをカスタマイズしたい場合は、`PHP_EXTENSIONS`環境変数を使用してください。 ## ビルドのカスタマイズ バイナリをカスタマイズする方法(拡張モジュール、PHPバージョンなど)については、[静的ビルドのドキュメント](static.md)をお読みください。 ## バイナリの配布 Linuxでは、作成されたバイナリは[UPX](https://upx.github.io)を使用して圧縮されます。 Macでは、送信前にファイルサイズを減らすために圧縮できます。 `xz`の使用をお勧めします。 ================================================ FILE: docs/ja/extension-workers.md ================================================ # 拡張ワーカー 拡張ワーカーは、[FrankenPHP拡張機能](https://frankenphp.dev/docs/extensions/)がバックグラウンドタスクの実行、非同期イベントの処理、またはカスタムプロトコルの実装のために、PHPスレッドの専用プールを管理できるようにします。キューシステム、イベントリスナー、スケジューラーなどに役立ちます。 ## ワーカーの登録 ### 静的登録 ワーカーをユーザーが構成可能にする必要がない場合(固定スクリプトパス、固定スレッド数)、`init()` 関数でワーカーを登録するだけです。 ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // ワーカープールと通信するためのグローバルハンドル var worker frankenphp.Workers func init() { // モジュールがロードされたときにワーカーを登録します。 worker = caddy.RegisterWorkers( "my-internal-worker", // ユニークな名前 "worker.php", // スクリプトパス(実行場所からの相対パス、または絶対パス) 2, // 固定スレッド数 // オプションのライフサイクルフック frankenphp.WithWorkerOnServerStartup(func() { // グローバルなセットアップロジック... }), ) } ``` ### Caddyモジュール内 (ユーザーが構成可能) 拡張機能を共有する予定がある場合(一般的なキューやイベントリスナーなど)、Caddyモジュールにラップする必要があります。これにより、ユーザーは `Caddyfile` を介してスクリプトパスとスレッド数を構成できます([例を見る](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go))。 ### 純粋なGoアプリケーション内 (組み込み) [Caddyなしで標準GoアプリケーションにFrankenPHPを組み込む](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP)場合、初期化オプションで `frankenphp.WithExtensionWorkers` を使用して拡張ワーカーを登録できます。 ## ワーカーとの対話 ワーカープールがアクティブになったら、タスクをディスパッチできます。これは、[PHPにエクスポートされたネイティブ関数](https://frankenphp.dev/docs/extensions/#writing-the-extension)内、またはGoのロジック(cronスケジューラー、イベントリスナー(MQTT、Kafka)、その他のゴルーチンなど)から実行できます。 ### ヘッドレスモード: `SendMessage` `SendMessage` を使用して、生データをワーカーのスクリプトに直接渡します。これはキューや単純なコマンドに最適です。 #### 例: 非同期キュー拡張機能 ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. ワーカーが準備できていることを確認する if worker == nil { return false } // 2. バックグラウンドワーカーにディスパッチする _, err := worker.SendMessage( context.Background(), // 標準のGoコンテキスト unsafe.Pointer(data), // ワーカーに渡すデータ nil, // オプションのhttp.ResponseWriter ) return err == nil } ``` ### HTTPエミュレーション: `SendRequest` 拡張機能が標準のウェブ環境(`$_SERVER`、`$_GET` など)を期待するPHPスクリプトを呼び出す必要がある場合は、`SendRequest` を使用します。 ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. リクエストとレコーダーを準備する url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. ワーカーにディスパッチする if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. キャプチャされたレスポンスを返す return frankenphp.PHPString(rr.Body.String(), false) } ``` ## ワーカーのスクリプト PHPワーカーのスクリプトはループで実行され、生メッセージとHTTPリクエストの両方を処理できます。 ```php [!TIP] > 拡張モジュールをGoで一から書く方法を理解したい場合は、ジェネレーターを使用せずにGoでPHP拡張モジュールを書く方法を紹介する後述の手動実装セクションを参照してください。 注意すべきことは、このツールは**完全な拡張モジュールジェネレーター**ではないことです。GoでシンプルなPHP拡張モジュールを書くのには十分役立ちますが、高度なPHP拡張モジュールの機能には対応していません。より**複雑で最適化された**拡張モジュールを書く必要がある場合は、Cコードを書いたり、CGOを直接使用したりする必要があるかもしれません。 ### 前提条件 以下の手動実装セクションでも説明しているように、[PHPのソースを取得](https://www.php.net/downloads.php)し、新しいGoモジュールを作成する必要があります。 #### 新しいモジュールの作成とPHPソースの取得 GoでPHP拡張モジュールを書く最初のステップは、新しいGoモジュールの作成です。以下のコマンドを使用できます: ```console go mod init github.com/my-account/my-module ``` 2番目のステップは、次のステップのために[PHPのソースを取得](https://www.php.net/downloads.php)することです。取得したら、Goモジュールのディレクトリ内ではなく、任意のディレクトリに展開します: ```console tar xf php-* ``` ### 拡張モジュールの記述 これでGoでネイティブ関数を書く準備が整いました。`stringext.go`という名前の新しいファイルを作成します。最初の関数は文字列を引数として取り、それを指定された回数だけ繰り返し、文字列を逆転するかどうかを示すブール値を受け取り、結果の文字列を返します。これは以下のようになります: ```go import ( "C" "github.com/dunglas/frankenphp" "strings" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` ここで重要なポイントが2つあります: - ディレクティブコメント`//export_php:function`はPHPでの関数シグネチャを定義します。これにより、ジェネレーターは適切なパラメータと戻り値の型でPHP関数を生成する方法を知ることができます。 - 関数は`unsafe.Pointer`を返さなければなりません。FrankenPHPはCとGo間の型変換を支援するAPIを提供しています。 前者は理解しやすいですが、後者は少し複雑かもしれません。次のセクションで型変換について詳しく説明します。 ### 型変換 C/PHPとGoの間でメモリ表現が同じ変数型もありますが、直接使用するにはより多くのロジックが必要な型もあります。これは拡張モジュールを書く際の最も挑戦的な部分かもしれません。Zendエンジンの内部仕組みや、変数がPHP内でどのように格納されているかを理解する必要があるためです。以下の表は、知っておくべき重要な情報をまとめています: | PHP型 | Go型 | 直接変換 | CからGoヘルパー | GoからCヘルパー | クラスメソッドサポート | | ------------------ | ---------------- | -------- | --------------------- | ---------------------- | ---------------------- | | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | frankenphp.GoString() | frankenphp.PHPString() | ✅ | | `array` | `slice`/`map` | ❌ | _未実装_ | _未実装_ | ❌ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `object` | `struct` | ❌ | _未実装_ | _未実装_ | ❌ | > [!NOTE] > この表はまだ完全ではなく、FrankenPHPの型APIがより完全になるにつれて完成されます。 > > クラスメソッドについては、現在プリミティブ型のみがサポートされています。配列とオブジェクトはまだメソッドパラメータや戻り値の型として使用できません。 前のセクションのコードスニペットを参照すると、最初のパラメータと戻り値の変換にヘルパーが使用されていることがわかります。 `repeat_this()`関数の2番目と3番目の引数は、基礎となる型のメモリ表現がCとGoで同じであるため、変換する必要がありません。 ### ネイティブPHPクラスの宣言 ジェネレーターは、PHPオブジェクトを作成するために使用できる**不透明クラス(opaque classes)**をGo構造体として宣言することをサポートしています。`//export_php:class`ディレクティブコメントを使用してPHPクラスを定義できます。例: ```go //export_php:class User type UserStruct struct { Name string Age int } ``` #### 不透明クラスとは何ですか? **不透明クラス(opaque classes)**は、内部構造(プロパティ)がPHPコードから隠されているクラスです。これは以下を意味します: - **プロパティへの直接アクセス不可** :PHPから直接プロパティを読み書きできません(`$user->name`は機能しません) - **メソッド経由のみで操作** - すべてのやりとりはGoで定義したメソッドを通じて行う必要があります - **より良いカプセル化** - 内部データ構造は完全にGoコードによって制御されます - **型安全性** - PHP側から誤った型で内部状態が破壊されるリスクがありません - **よりクリーンなAPI** - 適切な公開インターフェースを設計することを強制します このアプローチは優れたカプセル化を実現し、PHPコードがGoオブジェクトの内部状態を意図せずに破壊してしまうことを防ぎます。オブジェクトとのすべてのやりとりは、明示的に定義したメソッドを通じて行う必要があります。 #### クラスにメソッドを追加する プロパティは直接アクセスできないため、不透明クラスとやりとりするには **メソッドを定義する必要があります** 。`//export_php:method`ディレクティブを使用して動作を定義します: ```go //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### Nullableパラメータ ジェネレーターは、PHPシグネチャにおける`?`プレフィックスを使用ったnullableパラメータをサポートしています。パラメータがnullableの場合、Go関数内ではポインタとして扱われ、PHP側で値が`null`だったかどうかを確認できます: ```go //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // nameが渡された(nullではない)かチェック if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // ageが渡された(nullではない)かチェック if age != nil { us.Age = int(*age) } // activeが渡された(nullではない)かチェック if active != nil { us.Active = *active } } ``` **Nullableパラメータの重要なポイント:** - **プリミティブ型のnullable** (`?int`, `?float`, `?bool`) はGoではそれぞれポインタ (`*int64`, `*float64`, `*bool`) になります - **nullable文字列** (`?string`) は `*C.zend_string` のままですが、`nil` になることがあります - ポインタ値を逆参照する前に **`nil`をチェック** してください - **PHPの`null`はGoの`nil`になります** - PHPが`null`を渡すと、Go関数は`nil`ポインタを受け取ります > [!WARNING] > 現在、クラスメソッドには次の制限があります。**配列とオブジェクトはパラメータ型や戻り値の型としてサポートされていません**。サポートされるのは`string`、`int`、`float`、`bool`、`void`(戻り値の型)といったスカラー型のみです。**nullableなスカラー型はすべてサポートされています** (`?string`、`?int`、`?float`、`?bool`)。 拡張を生成した後、PHP側でクラスとそのメソッドを使用できるようになります。ただし**プロパティに直接アクセスできない**ことに注意してください: ```php setAge(25); echo $user->getName(); // 出力: (empty、デフォルト値) echo $user->getAge(); // 出力: 25 $user->setNamePrefix("Employee"); // ✅ これも動作します - nullableパラメータ $user->updateInfo("John", 30, true); // すべて指定 $user->updateInfo("Jane", null, false); // Ageがnull $user->updateInfo(null, 25, null); // Nameとactiveがnull // ❌ これは動作しません - プロパティへの直接アクセス // echo $user->name; // エラー: privateプロパティにアクセスできません // $user->age = 30; // エラー: privateプロパティにアクセスできません ``` この設計により、Goコードがオブジェクトの状態へのアクセスと変更方法を完全に制御でき、より良いカプセル化と型安全性を提供します。 ### 定数の宣言 ジェネレーターは、2つのディレクティブを使用してGo定数をPHPにエクスポートすることをサポートしています:グローバル定数用の`//export_php:const`とクラス定数用の`//export_php:classconst`です。これにより、GoとPHPコード間で設定値、ステータスコード、その他の定数を共有できます。 #### グローバル定数 `//export_php:const`ディレクティブを使用してグローバルなPHP定数を作成できます: ```go //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const STATUS_OK = iota //export_php:const const STATUS_ERROR = iota ``` #### クラス定数 `//export_php:classconst ClassName`ディレクティブを使用して、特定のPHPクラスに属する定数を作成できます: ```go //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const STATE_PENDING = iota //export_php:classconst Order const STATE_PROCESSING = iota //export_php:classconst Order const STATE_COMPLETED = iota ``` クラス定数は、PHPでクラス名スコープを使用してアクセスできます: ```php [!NOTE] > `GEN_STUB_SCRIPT`環境変数に、先ほどダウンロードしたPHPソースの`gen_stub.php`ファイルのパスを設定するのを忘れないでください。これは手動実装セクションで言及されているのと同じ`gen_stub.php`スクリプトです。 すべてがうまくいけば、`build`という名前の新しいディレクトリが作成されているはずです。このディレクトリには、生成されたPHP関数スタブを含む`my_extension.go`ファイルなど、拡張用の生成されたファイルが含まれています。 ### 生成された拡張モジュールをFrankenPHPへ統合する 拡張モジュールがコンパイルされ、FrankenPHPに統合される準備が整いました。これを行うには、FrankenPHPのコンパイル方法を学ぶために、FrankenPHPの[コンパイルドキュメント](compile.md)を参照してください。`--with`フラグを使用してモジュールを追加し、モジュールのパスを指定します: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module/build ``` このとき、生成ステップで作成された`/build`サブディレクトリを指していることに注意してください。ただし、これは必須ではなく、生成されたファイルをモジュールのディレクトリにコピーして、直接それを指定することも可能です。 ### 生成された拡張モジュールのテスト 作成した関数とクラスをテストするPHPファイルを作成しましょう。例えば、以下の内容で`index.php`ファイルを作成します: ```php process('Hello World', StringProcessor::MODE_LOWERCASE); // "hello world" echo $processor->process('Hello World', StringProcessor::MODE_UPPERCASE); // "HELLO WORLD" ``` 前のセクションで示したように拡張モジュールをFrankenPHPに統合し、`./frankenphp php-server`を使用してこのテストファイルを実行することで、拡張モジュールが動作しているのを確認できるはずです。 ## 手動実装 拡張モジュールの仕組みを理解したい、または拡張モジュールを完全に制御したい場合は、手動で書くこともできます。このアプローチは完全な制御を実現できますが、より多くのボイラープレートコードが必要になります。 ### 基本的な関数 ここでは、新しいネイティブ関数を定義するシンプルなPHP拡張モジュールをGoで手動実装する方法を紹介します。この関数はPHPから呼び出され、その関数がgoroutineを使ってCaddyのログにメッセージ出力するという処理を行います。この関数は引数を取らず、戻り値もありません。 #### Go関数の定義 モジュール内で、PHPから呼び出される新しいネイティブ関数を定義する必要があります。これを行うには、例えば`extension.go`のように任意の名前でファイルを作成し、以下のコードを追加します: ```go package ext_go //#include "extension.h" import "C" import ( "unsafe" "github.com/caddyserver/caddy/v2" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { caddy.Log().Info("Hello from a goroutine!") }() } ``` `frankenphp.RegisterExtension()`関数は、内部のPHP登録ロジックを処理することで拡張登録プロセスを簡素化します。`go_print_something`関数は`//export`ディレクティブを使用して、CGOのおかげで、これから書くCコードでアクセスできるようになることを示しています。 この例では、新しい関数がCaddyのログにメッセージ出力するgoroutineをトリガーします。 #### PHP関数の定義 PHPがGo関数を呼び出せるようにするには、対応するPHP関数を定義する必要があります。このために、例えば`extension.stub.php`のようにスタブファイルを作成し、以下のコードを記述します: ```php extern zend_module_entry ext_module_entry; #endif ``` 次に、以下のステップを実行する`extension.c`という名前のファイルを作成します: - PHPヘッダーをインクルードする - 新しいネイティブPHP関数`go_print()`を宣言する - 拡張モジュールのメタデータを宣言する まずは必要なヘッダーのインクルードから始めましょう: ```c #include #include "extension.h" #include "extension_arginfo.h" // Goによってエクスポートされたシンボルを含みます #include "_cgo_export.h" ``` 次に、PHP関数をネイティブ言語関数として定義します: ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` この場合、関数はパラメータを取らず、何も返しません。単に`//export`ディレクティブを使用してエクスポートした、先ほど定義したGo関数を呼び出します。 最後に、名前、バージョン、プロパティなど、拡張のメタデータを`zend_module_entry`構造体で定義します。この情報はPHPが私たちの拡張モジュールを認識してロードするために必要です。`ext_functions`は定義したPHP関数へのポインタの配列であり、`gen_stub.php`スクリプトによって自動生成された`extension_arginfo.h`ファイル内に定義されています。 拡張モジュールの登録は、Goコード内で呼び出しているFrankenPHPの`RegisterExtension()`関数によって自動的に処理されます。 ### 高度な使用方法 基本的なPHP拡張をGoで作成する方法が分かったところで、少し例を複雑にしてみましょう。今度は文字列を引数として受け取り、その大文字版を返すPHP関数を作成します。 #### PHP関数スタブの定義 新しいPHP関数を定義するために、`extension.stub.php`ファイルを修正し、次の関数シグネチャを含めます: ```php [!TIP] > 関数のドキュメントを軽視しないでください!拡張スタブを他の開発者と共有する際、拡張機能の使い方や提供している機能を伝えるための重要な手段になります。 `gen_stub.php`スクリプトでスタブファイルを再生成すると、`extension_arginfo.h`ファイルは以下のようになるはずです: ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` この出力から、`go_upper`関数が`string`型の引数を1つ受け取り、`string`型の戻り値を返すことが定義されていのがわかります。 #### GoとPHP/C間の型変換(Type Juggling) Go関数はPHPの文字列を引数として直接受け取ることはできません。そのためPHPの文字列をGoの文字列へ変換する必要があります。幸いなことに、FrankenPHPは、ジェネレーターアプローチで見たものと同様に、PHP文字列とGo文字列間の変換を処理するヘルパー関数を提供しています。 ヘッダーファイルはシンプルなままです: ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` 次に、`extension.c`ファイルにGoとC間のブリッジを書きます。ここではPHPの文字列を直接Go関数に渡します: ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` `ZEND_PARSE_PARAMETERS_START`や引数のパースについては、[PHP Internals Book](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters)の該当ページで詳しく学ぶことができます。この例では、関数が`zend_string`として`string`型の必須引数を1つ取ることをPHPに伝えています。その後、この文字列を直接Go関数に渡し、`RETVAL_STR`を使用して結果を返します。 残るはただ一つ、Go側で`go_upper`関数を実装するだけです。 #### Go関数の実装 Go側の関数では`*C.zend_string`を引数として受け取り、FrankenPHPのヘルパー関数を使用してGoの文字列に変換し、処理を行ったうえで、結果を新たな`*C.zend_string`として返します。メモリ管理と変換の複雑さは、ヘルパー関数がすべて対応してくれます。 ```go import "strings" //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` このアプローチは、手動メモリ管理よりもはるかにクリーンで安全です。FrankenPHPのヘルパー関数は、PHPの`zend_string`形式とGoの文字列間の変換を自動的に処理してくれます。`PHPString()`に`false`引数を指定していることで、新しい非永続文字列(リクエストの終了時に解放される)を作成したいことを示しています。 > [!TIP] > この例ではエラーハンドリングを省略していますが、Go関数内でポインタが`nil`ではないこと、渡されたデータが有効であることを常に確認するべきです。 ### 拡張モジュールのFrankenPHPへの統合 拡張モジュールがコンパイルされ、FrankenPHPに統合される準備が整いました。手順についてはFrankenPHPのコンパイル方法を学ぶために、FrankenPHPの[コンパイルドキュメント](compile.md)を参照してください。`--with`フラグを使用してモジュールを追加し、モジュールのパスを指定します: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/my-account/my-module ``` これで完了です!拡張モジュールがFrankenPHPに統合され、PHPコードで利用できるようになりました。 ### 拡張モジュールのテスト 拡張モジュールをFrankenPHPに統合したら、実装した関数を試すための`index.php`ファイルを作成します: ```php [!WARNING] > > この機能は**開発環境のみ**を対象としています。 > `hot_reload`を本番環境で有効にしないでください。この機能は安全ではなく(機密性の高い内部詳細を公開します)、アプリケーションの速度を低下させます。 > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` デフォルトでは、FrankenPHPは現在の作業ディレクトリ内の以下のグロブパターンに一致するすべてのファイルを監視します: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` グロブ構文を使用して、監視するファイルを明示的に設定することも可能です。 ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` 使用するMercureトピック、および監視するディレクトリまたはファイルを指定するには、`hot_reload`のロングフォームを使用します。 ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## クライアントサイドの統合 サーバーは変更を検出しますが、ブラウザはこれらのイベントを購読してページを更新する必要があります。 FrankenPHPは、ファイル変更を購読するために使用するMercure HubのURLを、`$_SERVER['FRANKENPHP_HOT_RELOAD']`環境変数を通じて公開します。 クライアントサイドのロジックを処理するための便利なJavaScriptライブラリ、[frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload)も利用可能です。 これを使用するには、メインレイアウトに以下を追加します。 ```php FrankenPHP Hot Reload ``` このライブラリは自動的にMercureハブを購読し、ファイル変更が検出されるとバックグラウンドで現在のURLをフェッチし、DOMをモーフィングします。 [npm](https://www.npmjs.com/package/frankenphp-hot-reload)パッケージとして、また[GitHub](https://github.com/dunglas/frankenphp-hot-reload)で利用できます。 または、`EventSource`ネイティブJavaScriptクラスを使用してMercureハブに直接購読することで、独自のクライアントサイドロジックを実装することもできます。 ### 既存のDOMノードを保持する まれに、[Symfonyのウェブデバッグツールバーなどの開発ツール](https://github.com/symfony/symfony/pull/62970)を使用している場合など、特定のDOMノードを保持したいことがあります。 そのためには、関連するHTML要素に`data-frankenphp-hot-reload-preserve`属性を追加します。 ```html
``` ## ワーカーモード アプリケーションを[ワーカーモード](https://frankenphp.dev/docs/worker/)で実行している場合、アプリケーションスクリプトはメモリに常駐します。 これは、ブラウザがリロードされても、PHPコードの変更がすぐに反映されないことを意味します。 最高の開発者エクスペリエンスのためには、`hot_reload`を[ワーカーディレクティブ内の`watch`サブディレクティブ](config.md#watching-for-file-changes)と組み合わせるべきです。 - `hot_reload`: ファイルが変更されたときに**ブラウザ**をリフレッシュします - `worker.watch`: ファイルが変更されたときにワーカーを再起動します ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## 仕組み 1. **監視**: FrankenPHPは、内部で[`e-dant/watcher`ライブラリ](https://github.com/e-dant/watcher)を使用してファイルシステムの変更を監視します(私たちはGoバインディングに貢献しました)。 2. **再起動 (ワーカーモード)**: ワーカー設定で`watch`が有効になっている場合、新しいコードをロードするためにPHPワーカーが再起動されます。 3. **プッシュ**: 変更されたファイルのリストを含むJSONペイロードが、組み込みの[Mercureハブ](https://mercure.rocks)に送信されます。 4. **受信**: JavaScriptライブラリを介してリッスンしているブラウザがMercureイベントを受信します。 5. **更新**: - **Idiomorph**が検出された場合、更新されたコンテンツをフェッチし、現在のHTMLを新しい状態に合わせてモーフィングし、状態を失うことなく即座に変更を適用します。 - それ以外の場合、`window.location.reload()`が呼び出されてページがリフレッシュされます。 ================================================ FILE: docs/ja/known-issues.md ================================================ # 既知の問題 ## 未対応のPHP拡張モジュール 以下の拡張モジュールはFrankenPHPと互換性がないことが確認されています: | 名前 | 理由 | 代替手段 | | ----------------------------------------------------------------------------------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/en/imap.installation.php) | スレッドセーフでない | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | スレッドセーフでない | - | ## バグのあるPHP拡張モジュール 以下の拡張モジュールはFrankenPHPとの組み合わせで既知のバグや予期しない動作が確認されています: | 名前 | 問題 | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [ext-openssl](https://www.php.net/manual/en/book.openssl.php) | FrankenPHPの静的ビルド(musl libcでビルド)を使用した場合、高負荷時にOpenSSL拡張がクラッシュすることがあります。回避策として動的リンクのビルド(Dockerイメージで使用されているもの)を使用してください。このバグは[PHP側で追跡中](https://github.com/php/php-src/issues/13648)です。 | ## get_browser [get_browser()](https://www.php.net/manual/en/function.get-browser.php)関数は継続使用するとパフォーマンスが悪化することが確認されています。回避策として、User Agentごとの結果をキャッシュ(例:[APCu](https://www.php.net/manual/en/book.apcu.php)を利用)してください。User Agentごとの結果は静的なためです。 ## スタンドアロンバイナリおよびAlpineベースのDockerイメージ スタンドアロンバイナリおよびAlpineベースのDockerイメージ(`dunglas/frankenphp:*-alpine`)は、バイナリサイズを小さく保つために[glibc and friends](https://www.etalabs.net/compare_libcs.html)ではなく[musl libc](https://musl.libc.org/)を使用しています。これによりいくつかの互換性問題が発生する可能性があります。特に、globフラグ`GLOB_BRACE`は [サポートされていません](https://www.php.net/manual/en/function.glob.php) 。 ## Dockerで`https://127.0.0.1`を使用する デフォルトでは、FrankenPHPは`localhost`用のTLS証明書を生成します。 これはローカル開発における最も簡単かつ推奨される方法です。 どうしても`127.0.0.1`をホストとして使用したい場合は、サーバー名を`127.0.0.1`に設定してその証明書を生成させることが可能です。 ただし、[Dockerのネットワークシステム](https://docs.docker.com/network/)の仕組みにより、Dockerを使用する場合はこれだけでは不十分です。 この場合、`curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`のようなTLSエラーが発生します。 Linuxを使用している場合、[ホストネットワークドライバー](https://docs.docker.com/network/network-tutorial-host/)を使用することで、この問題を解決できます: ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` ホストネットワークドライバーはMacとWindowsではサポートされていません。これらのプラットフォームでは、コンテナのIPアドレスを推測してサーバー名に含める必要があります。 `docker network inspect bridge`を実行し、`Containers`キーを確認して`IPv4Address`にある現在割り当てられている最後のIPアドレスを特定し、それに1を加えます。コンテナがまだ実行されていない場合、最初に割り当てられるIPアドレスは通常`172.17.0.2`です。 そして、これを`SERVER_NAME`環境変数に含めます: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > `172.17.0.3`の部分は、実際にコンテナに割り当てられるIPに置き換えてください。 これでホストマシンから`https://127.0.0.1`へアクセスできるはずです。 うまくいかない場合は、FrankenPHPをデバッグモードで起動して問題を特定してみてください: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## `@php` を参照するComposerスクリプト [Composerスクリプト](https://getcomposer.org/doc/articles/scripts.md)では、いくつかのタスクでPHPバイナリを実行したい場合があります。例えば、[Laravelプロジェクト](laravel.md)で`@php artisan package:discover --ansi`を実行する場合です。しかし現在これは以下の2つの理由で[失敗します](https://github.com/dunglas/frankenphp/issues/483#issuecomment-1899890915): - ComposerはFrankenPHPバイナリを呼び出す方法を知りません - Composerはコマンドで`-d`フラグを使用してPHP設定を追加する場合があり、FrankenPHPはまだサポートしていません 回避策として、未サポートのパラメータを削除してFrankenPHPを呼び出すシェルスクリプトを`/usr/local/bin/php`に作成できます: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` 次に、環境変数`PHP_BINARY`にこの`php`スクリプトのパスを設定してComposerを実行します: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## 静的バイナリでのTLS/SSL問題のトラブルシューティング 静的バイナリを使用する場合、例えばSTARTTLSを使用してメールを送信する際に以下のTLS関連エラーが発生する可能性があります: ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` 静的バイナリにはTLS証明書がバンドルされていないため、OpenSSLにローカルのCA証明書の位置を明示する必要があります。 [`openssl_get_cert_locations()`](https://www.php.net/manual/en/function.openssl-get-cert-locations.php)の出力を調べて、 CA証明書をどこにインストールすべきか確認し、その場所に保存してください。 > [!WARNING] > > WebとCLIコンテキストでは設定が異なる場合があります。 > 適切なコンテキストで`openssl_get_cert_locations()`を実行してください。 [Mozillaから抽出されたCA証明書はcurlのサイトでダウンロードできます](https://curl.se/docs/caextract.html)。 または、Debian、Ubuntu、Alpineなどのディストリビューションでも、これらの証明書を含む`ca-certificates`というパッケージを提供しています。 `SSL_CERT_FILE`および`SSL_CERT_DIR`を使用してOpenSSLにCA証明書を探す場所をヒントとして与えることも可能です: ```console # TLS 証明書の環境変数を設定 export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/ja/laravel.md ================================================ # Laravel ## Docker FrankenPHPを使用して[Laravel](https://laravel.com)のWebアプリケーションを配信するのは簡単で、公式Dockerイメージの`/app`ディレクトリにプロジェクトをマウントするだけです。 Laravelアプリのメインディレクトリからこのコマンドを実行してください: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` お楽しみください! ## ローカルインストール または、ローカルマシンでFrankenPHPを使用してLaravelプロジェクトを実行することもできます: 1. [使用しているシステムに対応するバイナリをダウンロードします](../#standalone-binary) 2. Laravelプロジェクトのルートディレクトリに`Caddyfile`という名前のファイルを作成し、以下の設定を追加します: ```caddyfile { frankenphp } # サーバーのドメイン名 localhost { # webroot を public/ ディレクトリに設定 root public/ # 圧縮を有効にする(任意) encode zstd br gzip # public/ ディレクトリ内の PHP ファイルを実行し、アセットを提供 php_server { try_files {path} index.php } } ``` 3. LaravelプロジェクトのルートディレクトリからFrankenPHPを起動します: `frankenphp run` ## Laravel Octane OctaneはComposerパッケージマネージャーを使用してインストールできます: ```console composer require laravel/octane ``` Octaneをインストールした後、`octane:install` Artisanコマンドを実行すると、Octaneの設定ファイルがアプリケーションにインストールされます: ```console php artisan octane:install --server=frankenphp ``` Octaneサーバーは`octane:frankenphp` Artisanコマンドで開始できます。 ```console php artisan octane:frankenphp ``` `octane:frankenphp`コマンドは以下のオプションが利用可能です: - `--host`: サーバーがバインドするIPアドレス(デフォルト:`127.0.0.1`) - `--port`: サーバーが使用するポート(デフォルト: `8000`) - `--admin-port`: 管理サーバーが使用するポート(デフォルト: `2019`) - `--workers`: リクエスト処理に使うワーカー数(デフォルト: `auto`) - `--max-requests`: サーバーを再起動するまでに処理するリクエスト数(デフォルト: `500`) - `--caddyfile`: FrankenPHPの`Caddyfile`ファイルのパス(デフォルト: [Laravel OctaneのスタブCaddyfile](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: HTTPS、HTTP/2、HTTP/3を有効にし、証明書を自動的に生成・更新する - `--http-redirect`: HTTPからHTTPSへのリダイレクトを有効にする(--httpsオプション指定時のみ有効) - `--watch`: アプリケーションが変更されたときに自動的にサーバーをリロードする - `--poll`: ネットワーク越しのファイル監視のためにファイルシステムポーリングを使用する - `--log-level`: ネイティブCaddyロガーを使用して、指定されたログレベル以上でログメッセージを記録する > [!TIP] > 構造化されたJSONログ(ログ分析ソリューションを使用する際に便利)を取得するには、明示的に`--log-level`オプションを指定してください。 詳しくは[Laravel Octaneの公式ドキュメント](https://laravel.com/docs/octane)をご覧ください。 ## Laravelアプリのスタンドアロンバイナリ化 [FrankenPHPのアプリケーション埋め込み機能](embed.md)を使用して、Laravelアプリをスタンドアロンバイナリとして 配布することが可能です。 LaravelアプリをLinux用のスタンドアロンバイナリとしてパッケージ化するには、以下の手順に従ってください: 1. アプリのリポジトリに`static-build.Dockerfile`という名前のファイルを作成します: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # バイナリをmusl-libcシステムで実行する場合は、static-builder-musl を使用してください # アプリをコピー WORKDIR /go/src/app/dist/app COPY . . # スペースを節約するためにテストやその他の不要なファイルを削除 # 代わりに .dockerignore に記述して除外することも可能 RUN rm -Rf tests/ # .envファイルをコピー RUN cp .env.example .env # APP_ENV と APP_DEBUG を本番用に変更 RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # 必要に応じて .env ファイルにさらに変更を加える # 依存関係をインストール RUN composer install --ignore-platform-reqs --no-dev -a # 静的バイナリをビルド WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > 一部の`.dockerignore`ファイルは > `vendor/`ディレクトリや`.env`ファイルを無視します。ビルド前に`.dockerignore`ファイルを調整または削除してください。 2. ビルドします: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. バイナリを取り出します: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. キャッシュを構築します: ```console frankenphp php-cli artisan optimize ``` 5. データベースマイグレーションを実行します(ある場合): ```console frankenphp php-cli artisan migrate ``` 6. アプリの秘密鍵を生成します: ```console frankenphp php-cli artisan key:generate ``` 7. サーバーを起動します: ```console frankenphp php-server ``` これで、アプリの準備は完了です! 利用可能なオプションや他のOSでバイナリをビルドする方法については、[アプリケーション埋め込み](embed.md)ドキュメントをご覧ください。 ### ストレージパスの変更 Laravelはアップロードされたファイルやキャッシュ、ログなどをデフォルトでアプリケーションの`storage/`ディレクトリに保存します。 しかし、これは埋め込みアプリケーションには適していません。なぜなら、アプリの新しいバージョンごとに異なる一時ディレクトリに展開されるためです。 この問題を回避するには、`LARAVEL_STORAGE_PATH`環境変数を設定(例:`.env`ファイル内)するか、 `Illuminate\Foundation\Application::useStoragePath()`メソッドを呼び出して、一時ディレクトリの外にある任意のディレクトリを使用してください。 ### スタンドアロンバイナリでOctaneを実行する Laravel Octaneアプリもスタンドアロンバイナリとしてパッケージ化することが可能です! そのためには、[Octaneを正しくインストール](#laravel-octane)し、[前のセクション](#laravelアプリのスタンドアロンバイナリ化)で説明した手順に従ってください。 次に、Octaneを通じてワーカーモードでFrankenPHPを起動するには、以下を実行してください: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > コマンドを動作させるためには、スタンドアロンバイナリのファイル名が**必ず**`frankenphp`でなければなりません。 > Octaneは`frankenphp`という名前の実行ファイルがパス上に存在することを前提としています。 ================================================ FILE: docs/ja/mercure.md ================================================ # リアルタイム FrankenPHPには組み込みの[Mercure](https://mercure.rocks)ハブが付属しています! Mercureを使用すると、接続されているすべてのデバイスにリアルタイムイベントをプッシュでき、各デバイスは即座にJavaScriptイベントを受信します。 JSライブラリやSDKは必要ありません! ![Mercure](mercure-hub.png) Mercureハブを有効にするには、[Mercureのサイト](https://mercure.rocks/docs/hub/config)で説明されているように`Caddyfile`を更新してください。 Mercureハブのパスは`/.well-known/mercure`です。 FrankenPHPをDocker内で実行している場合、完全な送信URLは`http://php/.well-known/mercure`のようになります。ここでの`php`はFrankenPHPを実行するコンテナの名前です。 コードからMercureの更新をプッシュするには、[Symfony Mercure Component](https://symfony.com/components/Mercure)をお勧めします。なお、Symfonyのフルスタックフレームワークは必要ありません。 ================================================ FILE: docs/ja/metrics.md ================================================ # メトリクス [Caddyのメトリクス](https://caddyserver.com/docs/metrics)が有効になっていると、FrankenPHPは以下のメトリクスを公開します: - `frankenphp_total_threads`: PHPスレッドの総数 - `frankenphp_busy_threads`: 現在リクエストを処理中のPHPスレッド数。なお、実行中のワーカーは常にスレッドを消費します - `frankenphp_queue_depth`: 通常のキューに入っているリクエストの数 - `frankenphp_total_workers{worker="[worker_name]"}`: ワーカーの総数 - `frankenphp_busy_workers{worker="[worker_name]"}`: 現在リクエストを処理中のワーカーの数 - `frankenphp_worker_request_time{worker="[worker_name]"}`: すべてのワーカーがリクエスト処理に費やした時間 - `frankenphp_worker_request_count{worker="[worker_name]"}`: すべてのワーカーが処理したリクエスト数 - `frankenphp_ready_workers{worker="[worker_name]"}`: 少なくとも一度は `frankenphp_handle_request` を呼び出したワーカーの数 - `frankenphp_worker_crashes{worker="[worker_name]"}`: ワーカーが予期せず終了した回数 - `frankenphp_worker_restarts{worker="[worker_name]"}`: ワーカーが意図的に再起動された回数 - `frankenphp_worker_queue_depth{worker="[worker_name]"}`: キューに入っているリクエストの数 ワーカーメトリクスの`[worker_name]`プレースホルダーは、Caddyfileに指定されたワーカー名に置き換えられます。ワーカー名が指定されていない場合は、ワーカーファイルの絶対パスが使用されます。 ================================================ FILE: docs/ja/performance.md ================================================ # パフォーマンス デフォルトでは、FrankenPHPはパフォーマンスと使いやすさのバランスが取れた構成を提供するよう設計されています。 ただし、適切な設定により、パフォーマンスを大幅に向上させることが可能です。 ## スレッド数とワーカー数 デフォルトでは、FrankenPHPは利用可能なCPU数の2倍のスレッドとワーカー(ワーカーモードで)を開始します。 適切な値は、アプリケーションの書き方、機能、ハードウェアに大きく依存します。 これらの値を調整することを強く推奨します。最適なシステムの安定性のためには、`num_threads` x `memory_limit` < `available_memory`とすることをお勧めします。 適切な値を見つけるには、実際のトラフィックをシミュレートした負荷テストを実行するのが最も効果的です。 そのためのツールとして、[k6](https://k6.io)や[Gatling](https://gatling.io)が有用です。 スレッド数を設定するには、`php_server`や`php`ディレクティブ内の`num_threads`オプションを使用してください。 ワーカー数を変更するには、`frankenphp`ディレクティブ内の`worker`セクションにある`num`オプションを使用してください。 ### `max_threads` 実際のトラフィックがどのようなものになるかを正確に把握できれば理想ですが、現実のアプリケーションでは 予測困難な挙動が多いものです。`max_threads`[設定](config.md#caddyfile-config) により、FrankenPHPは指定された制限まで実行時に追加スレッドを自動的に生成できます。 `max_threads`はトラフィックを処理するために必要なスレッド数を把握するのに役立ち、レイテンシのスパイクに対してサーバーをより回復力のあるものにできます。 `auto`に設定すると、制限は`php.ini`の`memory_limit`に基づいて推定されます。推定できない場合、 `auto`は代わりに`num_threads`の2倍がデフォルトになります。`auto`は必要なスレッド数を大幅に過小評価する可能性があることに留意してください。 `max_threads`はPHP FPMの[pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children)に似ています。主な違いは、FrankenPHPがプロセスではなくスレッドを使用し、 必要に応じて異なるワーカースクリプトと「クラシックモード」間で自動的に委譲することです。 ## ワーカーモード [ワーカーモード](worker.md)を有効にするとパフォーマンスが劇的に向上しますが、 アプリがこのモードと互換性があるように適応する必要があります: ワーカースクリプトを作成し、アプリがメモリリークしていないことを確認する必要があります。 ## muslを使用しない 公式Dockerイメージと私たちが提供するデフォルトバイナリのAlpine Linuxバリアントは、[musl libc](https://musl.libc.org)を使用しています。 PHPは、従来のGNUライブラリの代わりにこの代替Cライブラリを使用すると[遅くなる](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381)ことが知られており、 特にFrankenPHPに必要なZTSモード(スレッドセーフ)でコンパイルされた場合です。高度にスレッド化された環境では、差が大きくなる可能性があります。 また、[一部のバグはmuslを使用した場合にのみ発生します](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl)。 本番環境では、glibcにリンクされたFrankenPHPを使用することをお勧めします。 これは、Debian Dockerイメージを使用するか、[公式パッケージ (.deb, .rpm, .apk)](https://pkgs.henderkes.com) を使用するか、あるいは[FrankenPHPをソースからコンパイル](compile.md)することで実現できます。 より軽量で安全なコンテナのためには、Alpineよりも[強化されたDebianイメージ](docker.md#hardening-images)を検討することをお勧めします。 ## Go Runtime設定 FrankenPHPはGoで書かれています。 一般的に、Go runtimeは特別な設定を必要としませんが、特定の状況では、 特定の設定でパフォーマンスが向上する場合があります。 おそらく`GODEBUG`環境変数を`cgocheck=0`に設定したいでしょう(FrankenPHP Dockerイメージのデフォルト)。 FrankenPHPをコンテナ(Docker、Kubernetes、LXC...)で実行しており、コンテナで利用可能なメモリを制限している場合は、 `GOMEMLIMIT`環境変数に利用可能なメモリ量を設定してください。 詳細については、Go ランタイムを最大限に活用するために、[この主題に特化したGoドキュメントページ](https://pkg.go.dev/runtime#hdr-Environment_Variables)を読むことを強く推奨します。 ## `file_server` デフォルトでは、`php_server`ディレクティブは自動的にファイルサーバーを設定して ルートディレクトリに保存された静的ファイル(アセット)を配信します。 この機能は便利ですが、コストがかかります。 無効にするには、以下の設定を使用してください: ```caddyfile php_server { file_server off } ``` ## `try_files` `php_server`は、静的ファイルとPHPファイルに加えて、アプリケーションのインデックスファイル およびディレクトリインデックスファイル(`/path/` -> `/path/index.php`)も試行します。ディレクトリインデックスが不要な場合、 次のように`try_files`を明示的に定義して無効にできます: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # ここで root を明示的に追加すると、キャッシュの効率が向上します } ``` これにより、不要なファイルの操作の回数を大幅に削減できます。 上記の構成をワーカーモードに相当させると、次のようになります: ```caddyfile route { php_server { # file server が全く不要な場合は "php_server" の代わりに "php" を使用します root /root/to/your/app worker /path/to/worker.php { match * # すべてのリクエストを直接ワーカーに送信します } } } ``` ファイルシステムへの不要な操作を完全にゼロにする代替アプローチとして、`php`ディレクティブを使用し、 パスによってPHPファイルとそれ以外を分ける方法があります。アプリケーション全体が1つのエントリーファイルで提供される場合、この方法は有効です。 たとえば`/assets`フォルダの背後で静的ファイルを提供する[設定](config.md#caddyfile-config)は次のようになります: ```caddyfile route { @assets { path /assets/* } # /assets 以下のリクエストはファイルサーバーが処理する file_server @assets { root /root/to/your/app } # /assets 以外のすべてのリクエストは index または worker の PHP ファイルで処理する rewrite index.php php { root /root/to/your/app # ここで root を明示的に追加すると、キャッシュの効率が向上します } } ``` ## プレースホルダー `root`および`env`ディレクティブ内では、[プレースホルダー](https://caddyserver.com/docs/conventions#placeholders)を使用できます。 ただし、これによりこれらの値をキャッシュすることができなくなり、大幅なパフォーマンスコストが発生します。 可能であれば、これらのディレクティブではプレースホルダーの使用を避けてください。 ## `resolve_root_symlink` デフォルトでは、ドキュメントルートがシンボリックリンクである場合、FrankenPHP はそれを自動的に解決します(これは PHP が正しく動作するために必要です)。 ドキュメントルートがシンボリックリンクでない場合、この機能を無効にできます。 ```caddyfile php_server { resolve_root_symlink false } ``` この設定は、`root`ディレクティブに[プレースホルダー](https://caddyserver.com/docs/conventions#placeholders)が含まれている場合にパフォーマンスを向上させます。 それ以外の場合の効果はごくわずかです。 ## ログ ログ出力は当然ながら非常に有用ですが、その性質上、 I/O操作およびメモリ確保が必要となり、パフォーマンスを大幅に低下させます。 [ログレベルを正しく設定](https://caddyserver.com/docs/caddyfile/options#log)し、 必要なもののみをログに記録するようにしてください。 ## PHPパフォーマンス FrankenPHPは公式のPHPインタープリターを使用しています。 通常のPHPに関するパフォーマンス最適化はすべてFrankenPHPでも有効です。 特に以下の点を確認してください: - [OPcache](https://www.php.net/manual/en/book.opcache.php)がインストールされ、有効化され、適切に設定されていること - [Composer autoloader optimizations](https://getcomposer.org/doc/articles/autoloader-optimization.md)を有効にすること - `realpath`キャッシュがアプリケーションのニーズに合わせて十分な大きさであること - [preloading](https://www.php.net/manual/en/opcache.preloading.php)を使用すること 詳細については、[Symfonyの専用ドキュメントエントリ](https://symfony.com/doc/current/performance.html)をお読みください (Symfonyを使用していなくても、多くのヒントが役立ちます)。 ## スレッドプールの分割 アプリケーションが、高負荷時に不安定になったり、常に10秒以上応答にかかるAPIのような遅い外部サービスと連携することはよくあります。 このような場合、スレッドプールを分割して専用の「遅い」プールを持つことが有益です。 これにより、遅いエンドポイントがすべてのサーバーリソース/スレッドを消費するのを防ぎ、コネクションプールと同様に、遅いエンドポイントへのリクエストの同時実行数を制限できます。 ```caddyfile example.com { php_server { root /app/public # アプリケーションのルート worker index.php { match /slow-endpoint/* # パスが /slow-endpoint/* のすべてリクエストはこのスレッドプールによって処理されます num 1 # /slow-endpoint/* に一致するリクエストに対しては最低1スレッド max_threads 20 # 必要に応じて、/slow-endpoint/* に一致するリクエストに対して最大20スレッドまで許可します } worker index.php { match * # 他のすべてのリクエストは個別に処理されます num 1 # 遅いエンドポイントがハングし始めても、他のリクエストには最低1スレッド max_threads 20 # 必要に応じて、他のリクエストに対して最大20スレッドまで許可します } } } ``` 一般的に、メッセージキューなどの適切なメカニズムを使用して、非常に遅いエンドポイントを非同期的に処理することも推奨されます。 ================================================ FILE: docs/ja/production.md ================================================ # 本番環境でのデプロイ このチュートリアルでは、Docker Composeを使用して単一サーバーにPHPアプリケーションをデプロイする方法を学びます。 Symfonyを使用している場合は、Symfony Dockerプロジェクトの「[本番環境へのデプロイ](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)」ドキュメントを参照してください。 API Platformを使用している場合は、[フレームワークのデプロイドキュメント](https://api-platform.com/docs/deployment/)を参照してください。 ## アプリの準備 まず、PHPプロジェクトのルートディレクトリに`Dockerfile`を作成します: ```dockerfile FROM dunglas/frankenphp # "your-domain-name.example.com" を実際のドメイン名に置き換えてください ENV SERVER_NAME=your-domain-name.example.com # HTTPSを無効にしたい場合は、次の値を代わりに使用してください: #ENV SERVER_NAME=:80 # プロジェクトで "public" ディレクトリをWebルートとして使用していない場合、ここで設定できます: # ENV SERVER_ROOT=web/ # PHPの本番設定を有効化 RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # プロジェクトのPHPファイルをpublicディレクトリにコピー COPY . /app/public # Symfony や Laravel を使用している場合は、代わりにプロジェクト全体をコピーする必要があります: #COPY . /app ``` より詳細な情報やカスタマイズ方法、PHP拡張モジュールやCaddyモジュールのインストール方法については、 「[カスタムDockerイメージのビルド](docker.md)」を参照してください。 プロジェクトでComposerを使用している場合は、 DockerイメージにComposerを含め、依存関係をインストールしてください。 次に、 `compose.yaml` ファイルを追加します: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Caddyの証明書と設定に必要なボリューム volumes: caddy_data: caddy_config: ``` > [!NOTE] > > 上記の例は本番環境向けです。 > 開発環境では、ボリューム、異なるPHP設定、`SERVER_NAME`環境変数の異なる値を使用したい場合があります。 > > [Symfony Docker](https://github.com/dunglas/symfony-docker)プロジェクト(FrankenPHPを使用)では、 > マルチステージイメージ、Composer、追加のPHP拡張モジュールなどを活用した、 > より高度な例を見ることができます。 最後に、Gitを使用している場合は、これらのファイルをコミットしてプッシュします。 ## サーバーの準備 本番環境にアプリケーションをデプロイするには、サーバーが必要です。 このチュートリアルではDigitalOceanの仮想マシンを使用しますが、他のLinuxサーバーでも同様に動作します。 DockerがインストールされたLinuxサーバーが既にある場合は、[次のセクション](#ドメイン名の設定)に進んでください。 まだサーバーがない場合は、[このアフィリエイトリンク](https://m.do.co/c/5d8aabe3ab80)を使用して$200の無料クレジットを取得し、アカウントを作成してください。その後、「Create a Droplet」をクリックします。 次に、「Choose an image」セクションの下の「Marketplace」タブをクリックし、「Docker」という名前のアプリを検索します。 これにより、DockerとDocker Composeの最新バージョンが既にインストールされたUbuntuサーバーがプロビジョニングされます! テスト目的であれば、最安のプランで十分です。 実際の本番使用では、おそらくニーズに合わせて「general purpose」セクションのプランを選びたいでしょう。 ![FrankenPHPをDockerでDigitalOceanにデプロイ](digitalocean-droplet.png) 他の設定はデフォルトのままにするか、必要に応じて調整も可能です。 SSHキーを追加するかパスワードを作成することを忘れずに行い、「Finalize and create」ボタンをクリックしてください。 次に、Dropletがプロビジョニングされるまで数秒待ちます。 Dropletの準備ができたら、SSHを使用して接続します: ```console ssh root@ ``` ## ドメイン名の設定 ほとんどの場合、サイトにドメイン名を関連付けたいでしょう。 まだドメイン名を所有していない場合は、レジストラーを通じて購入する必要があります。 次に、サーバーのIPアドレスを指すドメイン名のタイプ`A`のDNSレコードを作成します: ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` DigitalOceanのドメインサービス(「Networking」 > 「Domains」)での例: ![DigitalOceanでのDNS設定](digitalocean-dns.png) > [!NOTE] > > FrankenPHPがデフォルトで使用しているTLS証明書の自動生成サービスLet's Encryptは、IPアドレスの直接使用をサポートしていません。Let's Encryptを使用するにはドメイン名の使用が必須です。 ## デプロイ `git clone`や`scp`など、目的に合ったツールを使用してプロジェクトをサーバーにコピーします。 GitHubを使用している場合は、[deploy key](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys)の使用を検討してください。 deploy keyは[GitLabでもサポートされています](https://docs.gitlab.com/ee/user/project/deploy_keys/)。 Gitでの例: ```console git clone git@github.com:/.git ``` プロジェクトディレクトリ(``)に移動し、本番モードでアプリを開始します: ```console docker compose up --wait ``` サーバーが起動し、HTTPS証明書が自動的に生成されます。 `https://your-domain-name.example.com`にアクセスしてお楽しみください! > [!CAUTION] > > Dockerはキャッシュレイヤーを持つ可能性があるため、各デプロイメントで正しいビルドを持っているか確認するか、キャッシュの問題を避けるために`--no-cache`オプションでプロジェクトを再ビルドしてください。 ## 複数ノードへのデプロイ 複数のマシンクラスターにアプリをデプロイしたい場合は、提供されるComposeファイルと互換性のある[Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/)を 使用できます。 Kubernetesでデプロイするには、FrankenPHPを使用する[API Platformで提供されるHelmチャート](https://api-platform.com/docs/deployment/kubernetes/)をご覧ください。 ================================================ FILE: docs/ja/static.md ================================================ # 静的ビルドの作成 PHPライブラリのローカルインストールを使用する代わりに、 [static-php-cli プロジェクト](https://github.com/crazywhalecc/static-php-cli)を利用して、FrankenPHPの静的またはほぼ静的なビルドを作成することが可能です(プロジェクト名に「CLI」とありますが、CLIだけでなく全てのSAPIをサポートしています)。 この方法を使えば、PHPインタープリター、Caddy Webサーバー、FrankenPHPをすべて含んだ単一でポータブルなバイナリを作成できます! 完全に静的なネイティブ実行ファイルは依存関係を全く必要とせず、[`scratch` Dockerイメージ](https://docs.docker.com/build/building/base-images/#create-a-minimal-base-image-using-scratch)上でも実行可能です。 ただし、動的PHP拡張モジュール(Xdebugなど)をロードできず、musl libcを使用しているため、いくつかの制限があります。 ほぼ静的なバイナリは`glibc`のみを必要とし、動的拡張モジュールをロードできます。 可能であれば、glibcベースのほぼ静的ビルドの使用をお勧めします。 また、FrankenPHPは[静的バイナリへのPHPアプリの埋め込み](embed.md)もサポートしています。 ## Linux 静的なLinuxバイナリをビルドするためのDockerイメージを提供しています: ### muslベースの完全静的ビルド 依存関係なしにあらゆるLinuxディストリビューションで動作する完全静的バイナリ(ただし拡張モジュールの動的ロードはサポートしない)を作成するには、以下を実行します: ```console docker buildx bake --load static-builder-musl docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-musl ``` 高い並行性が求められるシナリオでは、より良いパフォーマンスのため、[mimalloc](https://github.com/microsoft/mimalloc)アロケーターの使用を検討してください。 ```console docker buildx bake --load --set static-builder-musl.args.MIMALLOC=1 static-builder-musl ``` ### glibcベースのほぼ静的なビルド(動的拡張モジュールのサポートあり) 選択した拡張モジュールを静的にコンパイルしながら、さらにPHP拡張モジュールを動的にロードできるバイナリを作成するには、以下を実行します: ```console docker buildx bake --load static-builder-gnu docker cp $(docker create --name static-builder-gnu dunglas/frankenphp:static-builder-gnu):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-gnu ``` このバイナリは、glibcバージョン2.17以上をすべてサポートしますが、muslベースシステム(Alpine Linuxなど)では動作しません。 生成されたほぼ静的(`glibc`を除く)バイナリは`frankenphp`という名前で、カレントディレクトリに出力されます。 Dockerを使わずに静的バイナリをビルドしたい場合は、macOS向けの手順を参照してください。これらの手順はLinuxでも使用できます。 ### カスタム拡張モジュール デフォルトでは、よく使われるPHP拡張モジュールがコンパイルされます。 バイナリのサイズを削減したり、攻撃対象領域(アタックサーフェス)を減らすために、`PHP_EXTENSIONS`というDocker引数を使用してビルドする拡張モジュールを明示的に指定できます。 例えば、`opcache`と`pdo_sqlite`拡張モジュールのみをビルドするには、以下のように実行します: ```console docker buildx bake --load --set static-builder-musl.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder-musl # ... ``` 有効にした拡張に必要なライブラリを追加するには、`PHP_EXTENSION_LIBS`というDocker引数を渡すことができます: ```console docker buildx bake \ --load \ --set static-builder-musl.args.PHP_EXTENSIONS=gd \ --set static-builder-musl.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder-musl ``` ### 追加のCaddyモジュール Caddyの拡張モジュールを追加したい場合は、`XCADDY_ARGS`というDocker引数を使用して、[xcaddy](https://github.com/caddyserver/xcaddy)に渡す引数を以下のように指定できます: ```console docker buildx bake \ --load \ --set static-builder-musl.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder-musl ``` この例では、Caddy用の[Souin](https://souin.io)HTTPキャッシュモジュールと[cbrotli](https://github.com/dunglas/caddy-cbrotli)、[Mercure](https://mercure.rocks)、[Vulcain](https://vulcain.rocks)モジュールを追加しています。 > [!TIP] > > cbrotli、Mercure、Vulcainモジュールは、`XCADDY_ARGS`が空または設定されていない場合はデフォルトで含まれます。 > `XCADDY_ARGS`の値をカスタマイズする場合、デフォルトのモジュールは含まれなくなるため、必要なものは明示的に記述してください。 [ビルドのカスタマイズ](#ビルドのカスタマイズ)も参照してください ### GitHubトークン GitHub API レート制限に達した場合は、`GITHUB_TOKEN`という名前の環境変数にGitHub Personal Access Tokenを設定してください: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS macOS用の静的バイナリを作成するには以下のスクリプトを実行してください([Homebrew](https://brew.sh/)がインストールされている必要があります): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` なお、このスクリプトはLinux(おそらく他のUnix系OS)でも動作し、私たちが提供するDockerイメージ内部でも使用されています。 ## ビルドのカスタマイズ 以下の環境変数を`docker build`や`build-static.sh` スクリプトに渡すことで、静的ビルドをカスタマイズできます: - `FRANKENPHP_VERSION`: 使用するFrankenPHPのバージョン - `PHP_VERSION`: 使用するPHPのバージョン - `PHP_EXTENSIONS`: ビルドするPHP拡張([サポートされる拡張のリスト](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: 拡張モジュールに追加機能を持たせるためにビルドする追加ライブラリ - `XCADDY_ARGS`: 追加のCaddyモジュールを導入するなど[xcaddy](https://github.com/caddyserver/xcaddy)に渡す引数 - `EMBED`: バイナリに埋め込むPHPアプリケーションのパス - `CLEAN`: 指定するとlibphpおよびそのすべての依存関係がスクラッチからビルドされます(キャッシュなし) - `NO_COMPRESS`: UPXを使用して結果のバイナリを圧縮しない - `DEBUG_SYMBOLS`: 指定すると、デバッグシンボルが除去されず、バイナリに含まれます - `MIMALLOC`: (実験的、Linuxのみ)パフォーマンス向上のためにmuslのmallocngを[mimalloc](https://github.com/microsoft/mimalloc)に置き換えます。muslをターゲットとするビルドにのみこれを使用することをお勧めします。glibcの場合は、このオプションを無効にして、代わりにバイナリを実行する際に[`LD_PRELOAD`](https://microsoft.github.io/mimalloc/overrides.html)を使用することをお勧めします。 - `RELEASE`: (メンテナー用)指定すると、生成されたバイナリがGitHubにアップロードされます ## 拡張モジュール glibcまたはmacOSベースのバイナリでは、PHP拡張モジュールを動的にロードできます。ただし、これらの拡張はZTSサポートでコンパイルされている必要があります。 ほとんどのパッケージマネージャーは現在、拡張のZTSバージョンを提供していないため、自分でコンパイルする必要があります。 このために、`static-builder-gnu`Dockerコンテナをビルドして実行し、リモートでアクセスし、`./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config`で拡張をコンパイルできます。 [Xdebug拡張モジュール](https://xdebug.org)の場合: ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` これにより、現在のディレクトリに`frankenphp`と`xdebug-zts.so`が作成されます。 `xdebug-zts.so`を拡張ディレクトリに移動し、php.iniに`zend_extension=xdebug-zts.so`を追加してFrankenPHPを実行すると、Xdebugがロードされます。 ================================================ FILE: docs/ja/worker.md ================================================ # FrankenPHPワーカーの使用 アプリケーションを一度起動してメモリに保持します。 FrankenPHPは数ミリ秒で受信リクエストを処理します。 ## ワーカースクリプトの開始 ### Docker `FRANKENPHP_CONFIG`環境変数の値を`worker /path/to/your/worker/script.php`に設定します: ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### スタンドアロンバイナリ `php-server`コマンドの`--worker`オプションを使って、現在のディレクトリのコンテンツをワーカーを通じて提供できます: ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` PHPアプリが[バイナリに埋め込まれている](embed.md)場合は、アプリのルートディレクトリにカスタムの`Caddyfile`を追加することができます。 これが自動的に使用されます。 また、`--watch`オプションを使えば、[ファイルの変更に応じてワーカーを再起動](config.md#watching-for-file-changes)することも可能です。 以下のコマンドは、`/path/to/your/app/`ディレクトリおよびそのサブディレクトリ内の`.php`で終わるファイルが変更された場合に再起動をトリガーします: ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` この機能は、[ホットリロード](hot-reload.md)と組み合わせてよく使用されます。 ## Symfonyランタイム > [!TIP] > 以下のセクションは、FrankenPHPワーカーモードのネイティブサポートが導入されたSymfony 7.4より前のバージョンでのみ必要です。 FrankenPHPのワーカーモードは[Symfony Runtime Component](https://symfony.com/doc/current/components/runtime.html)によってサポートされています。 ワーカーでSymfonyアプリケーションを開始するには、FrankenPHP用の[PHP Runtime](https://github.com/php-runtime/runtime)パッケージをインストールします: ```console composer require runtime/frankenphp-symfony ``` アプリケーションサーバーを起動するには、FrankenPHP Symfony Runtimeを使用するように`APP_RUNTIME`環境変数を定義します: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane [専用ドキュメント](laravel.md#laravel-octane)を参照してください。 ## カスタムアプリ 以下の例は、サードパーティライブラリに依存せずに独自のワーカースクリプトを作成する方法を示しています: ```php boot(); // パフォーマンス向上のため、ループの外側にハンドラーを配置(処理を減らす) $handler = static function () use ($myApp) { try { // リクエストを受信すると呼び出され、 // スーパーグローバル、php://inputなどがリセットされます。 echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler`はワーカースクリプトが終了するときにのみ呼び出されるため、 // 予期しない動作になる可能性があります。そのため、ここで例外をキャッチして処理します。 (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // HTTPレスポンス送信後に何らかの処理を実行 $myApp->terminate(); // ページ生成中にガベージコレクタが起動する可能性を減らすため、ここでガベージコレクタを明示的に呼び出す gc_collect_cycles(); if (!$keepRunning) break; } // クリーンアップ $myApp->shutdown(); ``` 次に、アプリを開始し、`FRANKENPHP_CONFIG`環境変数を使用してワーカーを設定します: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` デフォルトでは、CPU当たり2つのワーカーが開始されます。 開始するワーカー数を設定することもできます: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### 一定数のリクエスト処理後にワーカーを再起動する PHPはもともと長時間実行されるプロセス向けに設計されていなかったため、メモリリークを引き起こすライブラリやレガシーコードがいまだに多く存在します。 こうしたコードをワーカーモードで利用するための回避策として、一定数のリクエストを処理した後にワーカースクリプトを再起動する方法があります: 前述のワーカー用スニペットでは、`MAX_REQUESTS`という名前の環境変数を設定することで、処理する最大リクエスト数を設定できます。 ### ワーカーの手動再起動 [ファイルの変更を監視](config.md#watching-for-file-changes)してワーカーを再起動することも可能ですが、 [Caddy admin API](https://caddyserver.com/docs/api)を使用してすべてのワーカーをグレースフルに(安全に)再起動することも可能です。adminが [Caddyfile](config.md#caddyfile-config)で有効になっている場合、次のような単純なPOSTリクエストで再起動エンドポイントにpingできます: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### ワーカーの失敗 ワーカースクリプトがゼロ以外の終了コードでクラッシュした場合、FrankenPHP は指数的バックオフ戦略を用いて再起動を行います。 ワーカースクリプトが最後のバックオフ時間 × 2 より長く稼働し続けた場合、 それ以降の再起動ではペナルティを科しません。 しかし、スクリプトにタイプミスがあるなど短時間で何度もゼロ以外の終了コードで失敗し続ける場合、 FrankenPHP は`too many consecutive failures`というエラーとともにクラッシュします。 連続失敗の回数上限は、[Caddyfile](config.md#caddyfile-config)の`max_consecutive_failures`オプションで設定できます: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## スーパーグローバルの動作 [PHPのスーパーグローバル](https://www.php.net/manual/en/language.variables.superglobals.php)(`$_SERVER`、`$_ENV`、`$_GET`など) は以下のように動作します: - `frankenphp_handle_request()`が最初に呼び出される前は、スーパーグローバルにはワーカースクリプト自体にバインドされた値が格納されています - `frankenphp_handle_request()`の呼び出し中および呼び出し後は、スーパーグローバルには処理されたHTTPリクエストから生成された値が格納され、`frankenphp_handle_request()`を呼び出すたびにスーパーグローバルの値が変更されます コールバック内でワーカースクリプトのスーパーグローバルにアクセスするには、それらをコピーしてコールバックのスコープにコピーをインポートする必要があります: ```php [!CAUTION] > > Be sure to replace `172.17.0.3` with the IP that will be assigned to your container. You should now be able to access `https://127.0.0.1` from the host machine. If that's not the case, start FrankenPHP in debug mode to try to figure out the problem: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Composer Scripts Referencing `@php` [Composer scripts](https://getcomposer.org/doc/articles/scripts.md) may want to execute a PHP binary for some tasks, e.g. in [a Laravel project](laravel.md) to run `@php artisan package:discover --ansi`. This [currently fails](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) for two reasons: - Composer does not know how to call the FrankenPHP binary; - Composer may add PHP settings using the `-d` flag in the command, which FrankenPHP does not yet support. As a workaround, we can create a shell script in `/usr/local/bin/php` which strips the unsupported parameters and then calls FrankenPHP: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Then set the environment variable `PHP_BINARY` to the path of our `php` script and run Composer: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## Troubleshooting TLS/SSL Issues with Static Binaries When using the static binaries, you may encounter the following TLS-related errors, for instance when sending emails using STARTTLS: ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` As the static binary doesn't bundle TLS certificates, you need to point OpenSSL to your local CA certificates installation. Inspect the output of [`openssl_get_cert_locations()`](https://www.php.net/manual/en/function.openssl-get-cert-locations.php), to find where CA certificates must be installed and store them at this location. > [!WARNING] > > Web and CLI contexts may have different settings. > Be sure to run `openssl_get_cert_locations()` in the proper context. [CA certificates extracted from Mozilla can be downloaded on the cURL site](https://curl.se/docs/caextract.html). Alternatively, many distributions, including Debian, Ubuntu, and Alpine provide packages named `ca-certificates` that contain these certificates. It's also possible to use the `SSL_CERT_FILE` and `SSL_CERT_DIR` to hint OpenSSL where to look for CA certificates: ```console # Set TLS certificates environment variables export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/laravel.md ================================================ # Laravel ## Docker Serving a [Laravel](https://laravel.com) web application with FrankenPHP is as easy as mounting the project in the `/app` directory of the official Docker image. Run this command from the main directory of your Laravel app: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` And enjoy! ## Local Installation Alternatively, you can run your Laravel projects with FrankenPHP from your local machine: 1. [Download the binary corresponding to your system](../#standalone-binary) 2. Add the following configuration to a file named `Caddyfile` in the root directory of your Laravel project: ```caddyfile { frankenphp } # The domain name of your server localhost { # Set the webroot to the public/ directory root public/ # Enable compression (optional) encode zstd br gzip # Execute PHP files from the public/ directory and serve assets php_server { try_files {path} index.php } } ``` 3. Start FrankenPHP from the root directory of your Laravel project: `frankenphp run` ## Laravel Octane Octane may be installed via the Composer package manager: ```console composer require laravel/octane ``` After installing Octane, you may execute the `octane:install` Artisan command, which will install Octane's configuration file into your application: ```console php artisan octane:install --server=frankenphp ``` The Octane server can be started via the `octane:frankenphp` Artisan command. ```console php artisan octane:frankenphp ``` The `octane:frankenphp` command can take the following options: - `--host`: The IP address the server should bind to (default: `127.0.0.1`) - `--port`: The port the server should be available on (default: `8000`) - `--admin-port`: The port the admin server should be available on (default: `2019`) - `--workers`: The number of workers that should be available to handle requests (default: `auto`) - `--max-requests`: The number of requests to process before reloading the server (default: `500`) - `--caddyfile`: The path to the FrankenPHP `Caddyfile` file (default: [stubbed `Caddyfile` in Laravel Octane](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: Enable HTTPS, HTTP/2, and HTTP/3, and automatically generate and renew certificates - `--http-redirect`: Enable HTTP to HTTPS redirection (only enabled if --https is passed) - `--watch`: Automatically reload the server when the application is modified - `--poll`: Use file system polling while watching in order to watch files over a network - `--log-level`: Log messages at or above the specified log level, using the native Caddy logger > [!TIP] > To get structured JSON logs (useful when using log analytics solutions), explicitly the pass `--log-level` option. See also [how to use Mercure with Octane](#mercure-support). Learn more about [Laravel Octane in its official documentation](https://laravel.com/docs/octane). ## Laravel Apps As Standalone Binaries Using [FrankenPHP's application embedding feature](embed.md), it's possible to distribute Laravel apps as standalone binaries. Follow these steps to package your Laravel app as a standalone binary for Linux: 1. Create a file named `static-build.Dockerfile` in the repository of your app: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # If you intend to run the binary on musl-libc systems, use static-builder-musl instead # Copy your app WORKDIR /go/src/app/dist/app COPY . . # Remove the tests and other unneeded files to save space # Alternatively, add these files to a .dockerignore file RUN rm -Rf tests/ # Copy .env file RUN cp .env.example .env # Change APP_ENV and APP_DEBUG to be production ready RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Make other changes to your .env file if needed # Install the dependencies RUN composer install --ignore-platform-reqs --no-dev -a # Build the static binary WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Some `.dockerignore` files > will ignore the `vendor/` directory and `.env` files. Be sure to adjust or remove the `.dockerignore` file before the build. 2. Build: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. Extract the binary: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Populate caches: ```console frankenphp php-cli artisan optimize ``` 5. Run database migrations (if any): ```console frankenphp php-cli artisan migrate ``` 6. Generate app's secret key: ```console frankenphp php-cli artisan key:generate ``` 7. Start the server: ```console frankenphp php-server ``` Your app is now ready! Learn more about the options available and how to build binaries for other OSes in the [applications embedding](embed.md) documentation. ### Changing The Storage Path By default, Laravel stores uploaded files, caches, logs, etc. in the application's `storage/` directory. This is not suitable for embedded applications, as each new version will be extracted into a different temporary directory. Set the `LARAVEL_STORAGE_PATH` environment variable (for example, in your `.env` file) or call the `Illuminate\Foundation\Application::useStoragePath()` method to use a directory outside the temporary directory. ### Mercure Support [Mercure](https://mercure.rocks) is a great way to add real-time capabilities to your Laravel apps. FrankenPHP includes [Mercure support out of the box](mercure.md). If you are not using [Octane](#laravel-octane), see [the Mercure documentation entry](mercure.md). If you are using Octane, you can use enable Mercure support by adding the following lines to your `config/octane.php` file: ```php // ... return [ // ... 'mercure' => [ 'anonymous' => true, 'publisher_jwt' => '!ChangeThisMercureHubJWTSecretKey!', 'subscriber_jwt' => '!ChangeThisMercureHubJWTSecretKey!', ], ]; ``` You can use [all directives supported by Mercure](https://mercure.rocks/docs/hub/config#directives) in this array. To publish and subscribe to updates, we recommend using the [Laravel Mercure Broadcaster](https://github.com/mvanduijker/laravel-mercure-broadcaster) library. Alternatively, see [the Mercure documentation](mercure.md) to do it in pure PHP and JavaScript. ### Running Octane With Standalone Binaries It's even possible to package Laravel Octane apps as standalone binaries! To do so, [install Octane properly](#laravel-octane) and follow the steps described in [the previous section](#laravel-apps-as-standalone-binaries). Then, to start FrankenPHP in worker mode through Octane, run: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > For the command to work, the standalone binary **must** be named `frankenphp` > because Octane needs a program named `frankenphp` available in the path. ================================================ FILE: docs/logging.md ================================================ # Logging FrankenPHP integrates seamlessly with [Caddy's logging system](https://caddyserver.com/docs/logging). You can log messages using standard PHP functions or leverage the dedicated `frankenphp_log()` function for advanced structured logging capabilities. ## `frankenphp_log()` The `frankenphp_log()` function allows you to emit structured logs directly from your PHP application, making ingestion into platforms like Datadog, Grafana Loki, or Elastic, as well as OpenTelemetry support, much easier. Under the hood, `frankenphp_log()` wraps [Go's `log/slog` package](https://pkg.go.dev/log/slog) to provide rich logging features. These logs include the severity level and optional context data. ```php function frankenphp_log(string $message, int $level = FRANKENPHP_LOG_LEVEL_INFO, array $context = []): void ``` ### Parameters - **`message`**: The log message string. - **`level`**: The severity level of the log. Can be any arbitrary integer. Convenience constants are provided for common levels: `FRANKENPHP_LOG_LEVEL_DEBUG` (`-4`), `FRANKENPHP_LOG_LEVEL_INFO` (`0`), `FRANKENPHP_LOG_LEVEL_WARN` (`4`) and `FRANKENPHP_LOG_LEVEL_ERROR` (`8`)). Default is `FRANKENPHP_LOG_LEVEL_INFO`. - **`context`**: An associative array of additional data to include in the log entry. ### Example ```php memory_get_usage(), 'peak_usage' => memory_get_peak_usage(), ], ); ``` When viewing the logs (e.g., via `docker compose logs`), the output will appear as structured JSON: ```json {"level":"info","ts":1704067200,"logger":"frankenphp","msg":"Hello from FrankenPHP!"} {"level":"warn","ts":1704067200,"logger":"frankenphp","msg":"Memory usage high","current_usage":10485760,"peak_usage":12582912} ``` ## `error_log()` FrankenPHP also allows logging using the standard `error_log()` function. If the `$message_type` parameter is `4` (SAPI), these messages are routed to the Caddy logger. By default, messages sent via `error_log()` are treated as unstructured text. They are useful for compatibility with existing applications or libraries that rely on the standard PHP library. ### Example with error_log() ```php error_log("Database connection failed", 4); ``` This will appear in the Caddy logs, often prefixed to indicate it originated from PHP. > [!TIP] > For better observability in production environments, prefer `frankenphp_log()` > as it allows you to filter logs by level (Debug, Error, etc.) > and query specific fields in your logging infrastructure. ================================================ FILE: docs/mercure.md ================================================ # Real-time FrankenPHP comes with a built-in [Mercure](https://mercure.rocks) hub! Mercure allows you to push real-time events to all the connected devices: they will receive a JavaScript event instantly. It's a convenient alternative to WebSockets that is simple to use and is natively supported by all modern web browsers! ![Mercure](mercure-hub.png) ## Enabling Mercure Mercure support is disabled by default. Here is a minimal example of a `Caddyfile` enabling both FrankenPHP and the Mercure hub: ```caddyfile # The hostname to respond to localhost mercure { # The secret key used to sign the JWT tokens for publishers publisher_jwt !ChangeThisMercureHubJWTSecretKey! # When publisher_jwt is set, you must set subscriber_jwt too! subscriber_jwt !ChangeThisMercureHubJWTSecretKey! # Allows anonymous subscribers (without JWT) anonymous } root public/ php_server ``` > [!TIP] > > The [sample `Caddyfile`](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) > provided by [the Docker images](docker.md) already includes a commented Mercure configuration > with convenient environment variables to configure it. > > Uncomment the Mercure section in `/etc/frankenphp/Caddyfile` to enable it. ## Subscribing to Updates By default, the Mercure hub is available on the `/.well-known/mercure` path of your FrankenPHP server. To subscribe to updates, use the native [`EventSource`](https://developer.mozilla.org/docs/Web/API/EventSource) JavaScript class: ```html Mercure Example ``` ## Publishing Updates ### Using `mercure_publish()` FrankenPHP provides a convenient `mercure_publish()` function to publish updates to the built-in Mercure hub: ```php 'value'])); // Write to FrankenPHP's logs error_log("update $updateID published", 4); ``` The full function signature is: ```php /** * @param string|string[] $topics */ function mercure_publish(string|array $topics, string $data = '', bool $private = false, ?string $id = null, ?string $type = null, ?int $retry = null): string {} ``` ### Using `file_get_contents()` To dispatch an update to connected subscribers, send an authenticated POST request to the Mercure hub with the `topic` and `data` parameters: ```php [ 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\nAuthorization: Bearer " . JWT, 'content' => http_build_query([ 'topic' => 'my-topic', 'data' => json_encode(['key' => 'value']), ]), ]])); // Write to FrankenPHP's logs error_log("update $updateID published", 4); ``` The key passed as parameter of the `mercure.publisher_jwt` option in the `Caddyfile` must used to sign the JWT token used in the `Authorization` header. The JWT must include a `mercure` claim with a `publish` permission for the topics you want to publish to. See [the Mercure documentation](https://mercure.rocks/spec#publishers) about authorization. To generate your own tokens, you can use [this jwt.io link](https://www.jwt.io/#token=eyJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.PXwpfIGng6KObfZlcOXvcnWCJOWTFLtswGI5DZuWSK4), but for production apps, it's recommended to use short-lived tokens generated aerodynamically using with a trusted [JWT library](https://www.jwt.io/libraries?programming_language=php). ### Using Symfony Mercure Alternatively, you can use the [Symfony Mercure Component](https://symfony.com/components/Mercure), a standalone PHP library. This library handled the JWT generation, update publishing as well as cookie-based authorization for subscribers. First, install the library using Composer: ```console composer require symfony/mercure lcobucci/jwt ``` Then, you can use it like this: ```php publish(new \Symfony\Component\Mercure\Update('my-topic', json_encode(['key' => 'value']))); // Write to FrankenPHP's logs error_log("update $updateID published", 4); ``` Mercure is also natively supported by: - [Laravel](laravel.md#mercure-support) - [Symfony](https://symfony.com/doc/current/mercure.html) - [API Platform](https://api-platform.com/docs/core/mercure/) ================================================ FILE: docs/metrics.md ================================================ # Metrics When [Caddy metrics](https://caddyserver.com/docs/metrics) are enabled, FrankenPHP exposes the following metrics: - `frankenphp_total_threads`: The total number of PHP threads. - `frankenphp_busy_threads`: The number of PHP threads currently processing a request (running workers always consume a thread). - `frankenphp_queue_depth`: The number of regular queued requests - `frankenphp_total_workers{worker="[worker_name]"}`: The total number of workers. - `frankenphp_busy_workers{worker="[worker_name]"}`: The number of workers currently processing a request. - `frankenphp_worker_request_time{worker="[worker_name]"}`: The time spent processing requests by all workers. - `frankenphp_worker_request_count{worker="[worker_name]"}`: The number of requests processed by all workers. - `frankenphp_ready_workers{worker="[worker_name]"}`: The number of workers that have called `frankenphp_handle_request` at least once. - `frankenphp_worker_crashes{worker="[worker_name]"}`: The number of times a worker has unexpectedly terminated. - `frankenphp_worker_restarts{worker="[worker_name]"}`: The number of times a worker has been deliberately restarted. - `frankenphp_worker_queue_depth{worker="[worker_name]"}`: The number of queued requests. For worker metrics, the `[worker_name]` placeholder is replaced by the worker name in the Caddyfile, otherwise absolute path of worker file will be used. ================================================ FILE: docs/performance.md ================================================ # Performance By default, FrankenPHP tries to offer a good compromise between performance and ease of use. However, it is possible to substantially improve performance using an appropriate configuration. ## Number of Threads and Workers By default, FrankenPHP starts 2 times more threads and workers (in worker mode) than the available number of CPU cores. The appropriate values depend heavily on how your application is written, what it does, and your hardware. We strongly recommend changing these values. For best system stability, it is recommended to have `num_threads` x `memory_limit` < `available_memory`. To find the right values, it's best to run load tests simulating real traffic. [k6](https://k6.io) and [Gatling](https://gatling.io) are good tools for this. To configure the number of threads, use the `num_threads` option of the `php_server` and `php` directives. To change the number of workers, use the `num` option of the `worker` section of the `frankenphp` directive. ### `max_threads` While it's always better to know exactly what your traffic will look like, real-life applications tend to be more unpredictable. The `max_threads` [configuration](config.md#caddyfile-config) allows FrankenPHP to automatically spawn additional threads at runtime up to the specified limit. `max_threads` can help you figure out how many threads you need to handle your traffic and can make the server more resilient to latency spikes. If set to `auto`, the limit will be estimated based on the `memory_limit` in your `php.ini`. If not able to do so, `auto` will instead default to 2x `num_threads`. Keep in mind that `auto` might strongly underestimate the number of threads needed. `max_threads` is similar to PHP FPM's [pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children). The main difference is that FrankenPHP uses threads instead of processes and automatically delegates them across different worker scripts and 'classic mode' as needed. ## Worker Mode Enabling [the worker mode](worker.md) dramatically improves performance, but your app must be adapted to be compatible with this mode: you need to create a worker script and to be sure that the app is not leaking memory. ## Don't Use musl The Alpine Linux variant of the official Docker images and the default binaries we provide are using [the musl libc](https://musl.libc.org). PHP is known to be [slower](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) when using this alternative C library instead of the traditional GNU library, especially when compiled in ZTS mode (thread-safe), which is required for FrankenPHP. The difference can be significant in a heavily threaded environment. Also, [some bugs only happen when using musl](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). In production environments, we recommend using FrankenPHP linked against glibc, compiled with an appropriate optimization level. This can be achieved by using the Debian Docker images, using [our maintainers .deb, .rpm, or .apk packages](https://pkgs.henderkes.com), or by [compiling FrankenPHP from sources](compile.md). For leaner or more secure containers, you may want to consider [a hardened Debian image](docker.md#hardening-images) rather than Alpine. ## Go Runtime Configuration FrankenPHP is written in Go. In general, the Go runtime doesn't require any special configuration, but in certain circumstances, specific configuration improves performance. You likely want to set the `GODEBUG` environment variable to `cgocheck=0` (the default in the FrankenPHP Docker images). If you run FrankenPHP in containers (Docker, Kubernetes, LXC...) and limit the memory available for the containers, set the `GOMEMLIMIT` environment variable to the available amount of memory. For more details, [the Go documentation page dedicated to this subject](https://pkg.go.dev/runtime#hdr-Environment_Variables) is a must-read to get the most out of the runtime. ## `file_server` By default, the `php_server` directive automatically sets up a file server to serve static files (assets) stored in the root directory. This feature is convenient, but comes with a cost. To disable it, use the following config: ```caddyfile php_server { file_server off } ``` ## `try_files` Besides static files and PHP files, `php_server` will also try to serve your application's index and directory index files (`/path/` -> `/path/index.php`). If you don't need directory indices, you can disable them by explicitly defining `try_files` like this: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # explicitly adding the root here allows for better caching } ``` This can significantly reduce the number of unnecessary file operations. A worker equivalent of the previous configuration would be: ```caddyfile route { php_server { # use "php" instead of "php_server" if you don't need the file server at all root /root/to/your/app worker /path/to/worker.php { match * # send all requests directly to the worker } } } ``` An alternate approach with 0 unnecessary file system operations would be to instead use the `php` directive and split files from PHP by path. This approach works well if your entire application is served by one entry file. An example [configuration](config.md#caddyfile-config) that serves static files behind an `/assets` folder could look like this: ```caddyfile route { @assets { path /assets/* } # everything behind /assets is handled by the file server file_server @assets { root /root/to/your/app } # everything that is not in /assets is handled by your index or worker PHP file rewrite index.php php { root /root/to/your/app # explicitly adding the root here allows for better caching } } ``` ## Placeholders You can use [placeholders](https://caddyserver.com/docs/conventions#placeholders) in the `root` and `env` directives. However, this prevents caching these values, and comes with a significant performance cost. If possible, avoid placeholders in these directives. ## `resolve_root_symlink` By default, if the document root is a symbolic link, it is automatically resolved by FrankenPHP (this is necessary for PHP to work properly). If the document root is not a symlink, you can disable this feature. ```caddyfile php_server { resolve_root_symlink false } ``` This will improve performance if the `root` directive contains [placeholders](https://caddyserver.com/docs/conventions#placeholders). The gain will be negligible in other cases. ## Logs Logging is obviously very useful, but, by definition, it requires I/O operations and memory allocations, which considerably reduces performance. Make sure you [set the logging level](https://caddyserver.com/docs/caddyfile/options#log) correctly, and only log what's necessary. ## PHP Performance FrankenPHP uses the official PHP interpreter. All usual PHP-related performance optimizations apply with FrankenPHP. In particular: - check that [OPcache](https://www.php.net/manual/en/book.opcache.php) is installed, enabled, and properly configured - enable [Composer autoloader optimizations](https://getcomposer.org/doc/articles/autoloader-optimization.md) - ensure that the `realpath` cache is big enough for the needs of your application - use [preloading](https://www.php.net/manual/en/opcache.preloading.php) For more details, read [the dedicated Symfony documentation entry](https://symfony.com/doc/current/performance.html) (most tips are useful even if you don't use Symfony). ## Splitting The Thread Pool It is common for applications to interact with slow external services, like an API that tends to be unreliable under high load or consistently takes 10+ seconds to respond. In such cases, it can be beneficial to split the thread pool to have dedicated "slow" pools. This prevents the slow endpoints from consuming all server resources/threads and limits the concurrency of requests going towards the slow endpoint, similar to a connection pool. ```caddyfile example.com { php_server { root /app/public # the root of your application worker index.php { match /slow-endpoint/* # all requests with path /slow-endpoint/* are handled by this thread pool num 1 # minimum 1 threads for requests matching /slow-endpoint/* max_threads 20 # allow up to 20 threads for requests matching /slow-endpoint/*, if needed } worker index.php { match * # all other requests are handled separately num 1 # minimum 1 threads for other requests, even if the slow endpoints start hanging max_threads 20 # allow up to 20 threads for other requests, if needed } } } ``` Generally it's also advisable to handle very slow endpoints asynchronously, by using relevant mechanisms such as message queues. ================================================ FILE: docs/production.md ================================================ # Deploying in Production In this tutorial, we will learn how to deploy a PHP application on a single server using Docker Compose. If you're using Symfony, prefer reading the "[Deploy in production](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)" documentation entry of the Symfony Docker project (which uses FrankenPHP). If you're using API Platform (which also uses FrankenPHP), refer to [the deployment documentation of the framework](https://api-platform.com/docs/deployment/). ## Preparing Your App First, create a `Dockerfile` in the root directory of your PHP project: ```dockerfile FROM dunglas/frankenphp # Be sure to replace "your-domain-name.example.com" by your domain name ENV SERVER_NAME=your-domain-name.example.com # If you want to disable HTTPS, use this value instead: #ENV SERVER_NAME=:80 # If your project is not using the "public" directory as the web root, you can set it here: # ENV SERVER_ROOT=web/ # Enable PHP production settings RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Copy the PHP files of your project in the public directory COPY . /app/public # If you use Symfony or Laravel, you need to copy the whole project instead: #COPY . /app ``` Refer to "[Building Custom Docker Image](docker.md)" for more details and options, and to learn how to customize the configuration, install PHP extensions and Caddy modules. If your project uses Composer, be sure to include it in the Docker image and to install your dependencies. Then, add a `compose.yaml` file: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Volumes needed for Caddy certificates and configuration volumes: caddy_data: caddy_config: ``` > [!NOTE] > > The previous examples are intended for production usage. > In development, you may want to use a volume, a different PHP configuration and a different value for the `SERVER_NAME` environment variable. > > Take a look to the [Symfony Docker](https://github.com/dunglas/symfony-docker) project > (which uses FrankenPHP) for a more advanced example using multi-stage images, > Composer, extra PHP extensions, etc. Finally, if you use Git, commit these files and push. ## Preparing a Server To deploy your application in production, you need a server. In this tutorial, we will use a virtual machine provided by DigitalOcean, but any Linux server can work. If you already have a Linux server with Docker installed, you can skip straight to [the next section](#configuring-a-domain-name). Otherwise, use [this affiliate link](https://m.do.co/c/5d8aabe3ab80) to get $200 of free credit, create an account, then click on "Create a Droplet". Then, click on the "Marketplace" tab under the "Choose an image" section and search for the app named "Docker". This will provision an Ubuntu server with the latest versions of Docker and Docker Compose already installed! For test purposes, the cheapest plans will be enough. For real production usage, you'll probably want to pick a plan in the "general purpose" section to fit your needs. ![Deploying FrankenPHP on DigitalOcean with Docker](digitalocean-droplet.png) You can keep the defaults for other settings, or tweak them according to your needs. Don't forget to add your SSH key or create a password then press the "Finalize and create" button. Then, wait a few seconds while your Droplet is provisioning. When your Droplet is ready, use SSH to connect: ```console ssh root@ ``` ## Configuring a Domain Name In most cases, you'll want to associate a domain name with your site. If you don't own a domain name yet, you'll have to buy one through a registrar. Then create a DNS record of type `A` for your domain name pointing to the IP address of your server: ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` Example with the DigitalOcean Domains service ("Networking" > "Domains"): ![Configuring DNS on DigitalOcean](digitalocean-dns.png) > [!NOTE] > > Let's Encrypt, the service used by default by FrankenPHP to automatically generate a TLS certificate doesn't support using bare IP addresses. Using a domain name is mandatory to use Let's Encrypt. ## Deploying Copy your project on the server using `git clone`, `scp`, or any other tool that may fit your need. If you use GitHub, you may want to use [a deploy key](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys). Deploy keys are also [supported by GitLab](https://docs.gitlab.com/ee/user/project/deploy_keys/). Example with Git: ```console git clone git@github.com:/.git ``` Go into the directory containing your project (``), and start the app in production mode: ```console docker compose up --wait ``` Your server is up and running, and an HTTPS certificate has been automatically generated for you. Go to `https://your-domain-name.example.com` and enjoy! > [!CAUTION] > > Docker can have a cache layer, make sure you have the right build for each deployment or rebuild your project with `--no-cache` option to avoid cache issue. ## Deploying on Multiple Nodes If you want to deploy your app on a cluster of machines, you can use [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), which is compatible with the provided Compose files. To deploy on Kubernetes, take a look at [the Helm chart provided with API Platform](https://api-platform.com/docs/deployment/kubernetes/), which uses FrankenPHP. ================================================ FILE: docs/pt-br/CONTRIBUTING.md ================================================ # Contribuindo ## Compilando o PHP ### Com Docker (Linux) Crie a imagem Docker de desenvolvimento: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` A imagem contém as ferramentas de desenvolvimento usuais (Go, GDB, Valgrind, Neovim...) e usa os seguintes locais de configuração do PHP: - php.ini: `/etc/frankenphp/php.ini`. Um arquivo `php.ini` com configurações de desenvolvimento é fornecido por padrão. - Arquivos de configuração adicionais: `/etc/frankenphp/php.d/*.ini`. - Extensões PHP: `/usr/lib/frankenphp/modules/`. Se a sua versão do Docker for anterior à 23.0, a compilação falhará devido ao [problema de padrão do `.dockerignore`](https://github.com/moby/moby/pull/42676). Adicione diretórios ao `.dockerignore`. ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### Sem Docker (Linux e macOS) [Siga as instruções para compilar a partir do código-fonte](compile.md) e passe a flag de configuração `--debug`. ## Executando a suite de testes ```console go test -race -v ./... ``` ## Módulo Caddy Construa o Caddy com o módulo Caddy FrankenPHP: ```console cd caddy/frankenphp/ go build -tags nobadger,nomysql,nopgx cd ../../ ``` Execute o Caddy com o módulo Caddy FrankenPHP: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` O servidor está escutando em `127.0.0.1:80`: > [!NOTE] > Se você estiver usando o Docker, terá que vincular a porta 80 do contêiner ou > executar de dentro do contêiner. ```console curl -vk http://127.0.0.1/phpinfo.php ``` ## Servidor de teste mínimo Construa o servidor de teste mínimo: ```console cd internal/testserver/ go build cd ../../ ``` Execute o servidor de teste: ```console cd testdata/ ../internal/testserver/testserver ``` O servidor está escutando em `127.0.0.1:8080`: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Construindo imagens Docker localmente Imprima o plano do bake: ```console docker buildx bake -f docker-bake.hcl --print ``` Construa imagens FrankenPHP para amd64 localmente: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` Construa imagens FrankenPHP para arm64 localmente: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` Construa imagens FrankenPHP do zero para arm64 e amd64 e envie para o Docker Hub: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## Depurando falhas de segmentação com compilações estáticas 1. Baixe a versão de depuração do binário do FrankenPHP do GitHub ou crie sua própria compilação estática personalizada, incluindo símbolos de depuração: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. Substitua sua versão atual do `frankenphp` pelo executável de depuração do FrankenPHP. 3. Inicie o FrankenPHP normalmente (alternativamente, você pode iniciar o FrankenPHP diretamente com o GDB: `gdb --args frankenphp run`). 4. Anexe ao processo com o GDB: ```console gdb -p `pidof frankenphp` ``` 5. Se necessário, digite `continue` no shell do GDB. 6. Faça o FrankenPHP travar. 7. Digite `bt` no shell do GDB. 8. Copie a saída. ## Depurando falhas de segmentação no GitHub Actions 1. Abra o arquivo `.github/workflows/tests.yml`. 2. Habilite os símbolos de depuração do PHP: ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. Habilite o `tmate` para se conectar ao contêiner: ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - uses: mxschmitt/action-tmate@v3 ``` 4. Conecte-se ao contêiner. 5. Abra o `frankenphp.go`. 6. Habilite o `cgosymbolizer`: ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Baixe o módulo: `go get`. 8. No contêiner, você pode usar o GDB e similares: ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. Quando a falha for corrigida, reverta todas essas alterações. ## Recursos diversos de desenvolvimento - [PHP embedding in uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [PHP embedding in NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [PHP embedding in Go (go-php)](https://github.com/deuill/go-php) - [PHP embedding in Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [PHP embedding in C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Extending and Embedding PHP, por Sara Golemon](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [What the heck is TSRMLS_CC, anyway?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [SDL bindings](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Recursos relacionados ao Docker - [Definição do arquivo Bake](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Comando útil ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## Traduzindo a documentação Para traduzir a documentação e o site para um novo idioma, siga estes passos: 1. Crie um novo diretório com o código ISO de 2 caracteres do idioma no diretório `docs/` deste repositório. 2. Copie todos os arquivos `.md` da raiz do diretório `docs/` para o novo diretório (sempre use a versão em inglês como fonte para tradução, pois está sempre atualizada). 3. Copie os arquivos `README.md` e `CONTRIBUTING.md` do diretório raiz para o novo diretório. 4. Traduza o conteúdo dos arquivos, mas não altere os nomes dos arquivos, nem traduza strings que comecem com `> [!` (é uma marcação especial para o GitHub). 5. Crie um pull request com as traduções. 6. No [repositório do site](https://github.com/dunglas/frankenphp-website/tree/main), copie e traduza os arquivos de tradução nos diretórios `content/`, `data/` e `i18n/`. 7. Traduza os valores no arquivo YAML criado. 8. Abra um pull request no repositório do site. ================================================ FILE: docs/pt-br/README.md ================================================ # FrankenPHP: um moderno servidor de aplicações para PHP

FrankenPHP

O FrankenPHP é um moderno servidor de aplicações para PHP, construído sobre o servidor web [Caddy](https://caddyserver.com/). O FrankenPHP dá superpoderes às suas aplicações PHP graças aos seus recursos impressionantes: [_Early Hints_](early-hints.md), [modo worker](worker.md), [recursos em tempo real](mercure.md), suporte automático a HTTPS, HTTP/2 e HTTP/3... O FrankenPHP funciona com qualquer aplicação PHP e torna seus projetos Laravel e Symfony mais rápidos do que nunca, graças às suas integrações oficiais com o modo worker. O FrankenPHP também pode ser usado como uma biblioteca Go independente para incorporar PHP em qualquer aplicação usando `net/http`. [**Saiba mais** em _frankenphp.dev_](https://frankenphp.dev/pt-br) e neste conjunto de slides: Slides ## Começando No Windows, use [WSL](https://learn.microsoft.com/pt-br/windows/wsl/) para executar o FrankenPHP. ### Script de instalação Você pode copiar esta linha no seu terminal para instalar automaticamente a versão apropriada para sua plataforma: ```console curl https://frankenphp.dev/install.sh | sh ``` ### Binário independente Fornecemos binários estáticos do FrankenPHP para desenvolvimento em Linux e macOS contendo o [PHP 8.4](https://www.php.net/releases/8.4/pt_BR.php) e as extensões PHP mais populares. [Baixe o FrankenPHP](https://github.com/php/frankenphp/releases) **Instalação de extensões:** As extensões mais comuns já estão incluídas. Não é possível instalar mais extensões. ### Pacotes rpm Nossos mantenedores oferecem pacotes rpm para todos os sistemas que usam `dnf`. Para instalar, execute: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 8.2-8.5 disponíveis sudo dnf install frankenphp ``` **Instalação de extensões:** `sudo dnf install php-zts-` Para extensões não disponíveis por padrão, use o [PIE](https://github.com/php/pie): ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Pacotes deb Nossos mantenedores oferecem pacotes deb para todos os sistemas que usam `apt`. Para instalar, execute: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **Instalação de extensões:** `sudo apt install php-zts-` Para extensões não disponíveis por padrão, use o [PIE](https://github.com/php/pie): ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` Para servir o conteúdo do diretório atual, execute: ```console frankenphp php-server ``` Você também pode executar scripts de linha de comando com: ```console frankenphp php-cli /caminho/para/seu/script.php ``` ### Docker Alternativamente, [imagens Docker](docker.md) estão disponíveis: ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Acesse `https://localhost` e divirta-se! > [!TIP] > > Não tente usar `https://127.0.0.1`. > Use `https://localhost` e aceite o certificado autoassinado. > Use a > [variável de ambiente `SERVER_NAME`](config.md#variaveis-de-ambiente) > para alterar o domínio a ser usado. ### Homebrew O FrankenPHP também está disponível como um pacote [Homebrew](https://brew.sh) para macOS e Linux. Para instalá-lo: ```console brew install dunglas/frankenphp/frankenphp ``` **Instalação de extensões:** Use o [PIE](https://github.com/php/pie). ### Uso Para servir o conteúdo do diretório atual, execute: ```console frankenphp php-server ``` Você também pode executar scripts de linha de comando com: ```console frankenphp php-cli /caminho/para/seu/script.php ``` Para os pacotes deb e rpm, você também pode iniciar o serviço systemd: ```console sudo systemctl start frankenphp ``` ## Documentação - [Modo clássico](classic.md) - [Modo worker](worker.md) - [Suporte a Early Hints (código de status HTTP 103)](early-hints.md) - [Tempo real](mercure.md) - [Servindo grandes arquivos estáticos com eficiência](x-sendfile.md) - [Configuração](config.md) - [Escrevendo extensões PHP em Go](extensions.md) - [Imagens Docker](docker.md) - [Implantação em produção](production.md) - [Otimização de desempenho](performance.md) - [Crie aplicações PHP **independentes** e autoexecutáveis](embed.md) - [Crie binários estáticos](static.md) - [Compile a partir do código-fonte](compile.md) - [Monitorando o FrankenPHP](metrics.md) - [Integração com Laravel](laravel.md) - [Problemas conhecidos](known-issues.md) - [Aplicação de demonstração (Symfony) e benchmarks](https://github.com/dunglas/frankenphp-demo) - [Documentação da biblioteca Go](https://pkg.go.dev/github.com/php/frankenphp) - [Contribuindo e depurando](CONTRIBUTING.md) ## Exemplos e esqueletos - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/symfony) - [Laravel](laravel.md) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/pt-br/classic.md ================================================ # Usando o modo clássico Sem nenhuma configuração adicional, o FrankenPHP opera no modo clássico. Neste modo, o FrankenPHP funciona como um servidor PHP tradicional, servindo diretamente arquivos PHP. Isso o torna um substituto perfeito para PHP-FPM ou Apache com mod_php. Semelhante ao Caddy, o FrankenPHP aceita um número ilimitado de conexões e usa um [número fixo de threads](config.md#configuracao-do-caddyfile) para servi-las. O número de conexões aceitas e enfileiradas é limitado apenas pelos recursos disponíveis no sistema. O pool de threads do PHP opera com um número fixo de threads inicializadas na inicialização, comparável ao modo estático do PHP-FPM. Também é possível permitir que as threads [escalem automaticamente em tempo de execução](performance.md#max_threads), semelhante ao modo dinâmico do PHP-FPM. As conexões enfileiradas aguardarão indefinidamente até que uma thread PHP esteja disponível para servi-las. Para evitar isso, você pode usar a [configuração](config.md#configuracao-do-caddyfile) `max_wait_time` na configuração global do FrankenPHP para limitar o tempo que uma requisição pode esperar por uma thread PHP livre antes de ser rejeitada. Além disso, você pode definir um [tempo limite de escrita razoável no Caddy](https://caddyserver.com/docs/caddyfile/options#timeouts). Cada instância do Caddy ativará apenas um pool de threads do FrankenPHP, que será compartilhado entre todos os blocos `php_server`. ================================================ FILE: docs/pt-br/compile.md ================================================ # Compilar a partir do código-fonte Este documento explica como criar um binário FrankenPHP que carregará o PHP como uma biblioteca dinâmica. Este é o método recomendado. Como alternativa, [compilações totalmente e principalmente estáticas](static.md) também podem ser criadas. ## Instalar o PHP O FrankenPHP é compatível com PHP 8.2 e versões superiores. ### Com o Homebrew (Linux e Mac) A maneira mais fácil de instalar uma versão da `libphp` compatível com o FrankenPHP é usar os pacotes ZTS fornecidos pelo [Homebrew PHP](https://github.com/shivammathur/homebrew-php). Primeiro, se ainda não o fez, instale o [Homebrew](https://brew.sh). Em seguida, instale a variante ZTS do PHP, o Brotli (opcional, para suporte à compressão) e o watcher (opcional, para detecção de alterações em arquivos): ```console brew install shivammathur/php/php-zts brotli watcher brew link --overwrite --force shivammathur/php/php-zts ``` ### Compilando o PHP Alternativamente, você pode compilar o PHP a partir do código-fonte com as opções necessárias para o FrankenPHP seguindo estes passos. Primeiro, [obtenha o código-fonte do PHP](https://www.php.net/downloads.php) e extraia-os: ```console tar xf php-* cd php-*/ ``` Em seguida, execute o script `configure` com as opções necessárias para sua plataforma. As seguintes flags `./configure` são obrigatórias, mas você pode adicionar outras, por exemplo, para compilar extensões ou recursos adicionais. #### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` #### Mac Use o gerenciador de pacotes [Homebrew](https://brew.sh/) para instalar as dependências necessárias e opcionais: ```console brew install libiconv bison brotli re2c pkg-config watcher echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` Em seguida, execute o script `configure`: ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` #### Compilar o PHP Finalmente, compile e instale o PHP: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Instalar dependências opcionais Alguns recursos do FrankenPHP dependem de dependências opcionais do sistema que devem ser instaladas. Alternativamente, esses recursos podem ser desabilitados passando as tags de compilação para o compilador Go. | Recurso | Dependência | Tag de compilação para desabilitá-lo | | ------------------------------------- | --------------------------------------------------------------------- | ------------------------------------ | | Compressão Brotli | [Brotli](https://github.com/google/brotli) | `nobrotli` | | Reiniciar workers ao alterar arquivos | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | `nowatcher` | ## Compilando a aplicação Go Agora você pode compilar o binário final. ### Usando o `xcaddy` A maneira recomendada é usar o [`xcaddy`](https://github.com/caddyserver/xcaddy) para compilar o FrankenPHP. O `xcaddy` também permite adicionar facilmente [módulos Caddy personalizados](https://caddyserver.com/docs/modules/) e extensões FrankenPHP: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/php/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Adicione módulos Caddy e extensões FrankenPHP extras aqui ``` > [!TIP] > > Se você estiver usando a `libc` `musl` (o padrão no Alpine Linux) e Symfony, > pode ser necessário aumentar o tamanho da pilha padrão. > Caso contrário, você poderá receber erros como `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression`. > > Para fazer isso, altere a variável de ambiente `XCADDY_GO_BUILD_FLAGS` para > algo como > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (altere o valor do tamanho da pilha de acordo com as necessidades da sua > aplicação). ### Sem o `xcaddy` Alternativamente, é possível compilar o FrankenPHP sem o `xcaddy` usando o comando `go` diretamente: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ================================================ FILE: docs/pt-br/config.md ================================================ # Configuração FrankenPHP, Caddy, bem como os módulos [Mercure](mercure.md) e [Vulcain](https://vulcain.rocks), podem ser configurados usando [os formatos suportados pelo Caddy](https://caddyserver.com/docs/getting-started#your-first-config). O formato mais comum é o `Caddyfile`, que é um formato de texto simples e legível por humanos. Por padrão, o FrankenPHP procurará por um `Caddyfile` no diretório atual. Você pode especificar um caminho personalizado com a opção `-c` ou `--config`. Um `Caddyfile` mínimo para servir uma aplicação PHP é mostrado abaixo: ```caddyfile # O nome do host para responder localhost # Opcionalmente, o diretório para servir arquivos, caso contrário, o padrão é o diretório atual #root public/ php_server ``` Um `Caddyfile` mais avançado, que habilita mais recursos e fornece variáveis de ambiente convenientes, é disponibilizado [no repositório FrankenPHP](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile), e com as imagens Docker. O próprio PHP pode ser configurado [usando um arquivo `php.ini`](https://www.php.net/manual/en/configuration.file.php). Dependendo do seu método de instalação, o FrankenPHP e o interpretador PHP procurarão por arquivos de configuração nos locais descritos abaixo. ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: o arquivo de configuração principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: arquivos de configuração adicionais que são carregados automaticamente PHP: - `php.ini`: `/usr/local/etc/php/php.ini` (nenhum `php.ini` é fornecido por padrão) - arquivos de configuração adicionais: `/usr/local/etc/php/conf.d/*.ini` - extensões PHP: `/usr/local/lib/php/extensions/no-debug-zts-/` - Você deve copiar um modelo oficial fornecido pelo projeto PHP: ```dockerfile FROM dunglas/frankenphp # Produção: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Ou desenvolvimento: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## Pacotes RPM e Debian FrankenPHP: - `/etc/frankenphp/Caddyfile`: o arquivo de configuração principal - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: arquivos de configuração adicionais que são carregados automaticamente PHP: - `php.ini`: `/etc/php-zts/php.ini` (um arquivo `php.ini` com predefinições de produção é fornecido por padrão) - arquivos de configuração adicionais: `/etc/php-zts/conf.d/*.ini` ## Binário estático FrankenPHP: - No diretório de trabalho atual: `Caddyfile` PHP: - `php.ini`: O diretório no qual `frankenphp run` ou `frankenphp php-server` é executado, e então `/etc/frankenphp/php.ini` - arquivos de configuração adicionais: `/etc/frankenphp/php.d/*.ini` - extensões PHP: não podem ser carregadas, inclua-as no próprio binário - copie um dos arquivos `php.ini-production` ou `php.ini-development` fornecidos [nas fontes do PHP](https://github.com/php/php-src/). ## Configuração do Caddyfile As [diretivas HTTP](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` ou `php` podem ser usadas dentro dos blocos de site para servir sua aplicação PHP. Exemplo mínimo: ```caddyfile localhost { # Habilita compressão (opcional) encode zstd br gzip # Executa arquivos PHP no diretório atual e serve assets php_server } ``` Você também pode configurar explicitamente o FrankenPHP usando a [opção global](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp`: ```caddyfile { frankenphp { num_threads # Define o número de threads PHP a serem iniciadas. Padrão: 2x o número de CPUs disponíveis. max_threads # Limita o número de threads PHP adicionais que podem ser iniciadas em tempo de execução. Padrão: num_threads. Pode ser definido como 'auto'. max_wait_time # Define o tempo máximo que uma requisição pode esperar por uma thread PHP livre antes de atingir o tempo limite. Padrão: desabilitado. max_idle_time # Define o tempo máximo que uma thread autoescalada pode ficar ociosa antes de ser desativada. Padrão: 5s. php_ini # Define uma diretiva php.ini. Pode ser usada várias vezes para definir múltiplas diretivas. worker { file # Define o caminho para o script do worker. num # Define o número de threads PHP a serem iniciadas, o padrão é 2x o número de CPUs disponíveis. env # Define uma variável de ambiente extra para o valor fornecido. Pode ser especificada mais de uma vez para múltiplas variáveis de ambiente. watch # Define o caminho para monitorar alterações em arquivos. Pode ser especificada mais de uma vez para múltiplos caminhos. name # Define o nome do worker, usado em logs e métricas. Padrão: caminho absoluto do arquivo do worker max_consecutive_failures # Define o número máximo de falhas consecutivas antes que o worker seja considerado não saudável. -1 significa que o worker sempre reiniciará. Padrão: 6. } } } # ... ``` Alternativamente, você pode usar a forma abreviada de uma linha da opção `worker`: ```caddyfile { frankenphp { worker } } # ... ``` Você também pode definir múltiplos workers se servir múltiplas aplicações no mesmo servidor: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # permite melhor cache worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` Usar a diretiva `php_server` é geralmente o que você precisa, mas se precisar de controle total, você pode usar a diretiva `php` de mais baixo nível. A diretiva `php` passa toda a entrada para o PHP, em vez de primeiro verificar se é um arquivo PHP ou não. Leia mais sobre isso na [página de desempenho](performance.md#try_files). Usar a diretiva `php_server` é equivalente a esta configuração: ```caddyfile route { # Adiciona barra final para requisições de diretório @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # Se o arquivo requisitado não existir, tenta os arquivos index @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` As diretivas `php_server` e `php` têm as seguintes opções: ```caddyfile php_server [] { root # Define a pasta raiz para o site. Padrão: diretiva `root`. split_path # Define as substrings para dividir o URI em duas partes. A primeira substring correspondente será usada para separar as "informações de caminho" do caminho. A primeira parte é sufixada com a substring correspondente e será assumida como o nome real do recurso (script CGI). A segunda parte será definida como PATH_INFO para o script usar. Padrão: `.php` resolve_root_symlink false # Desabilita a resolução do diretório `root` para seu valor real avaliando um link simbólico, se houver (habilitado por padrão). env # Define uma variável de ambiente extra para o valor fornecido. Pode ser especificada mais de uma vez para múltiplas variáveis de ambiente. file_server off # Desabilita a diretiva integrada file_server. worker { # Cria um worker específico para este servidor. Pode ser especificada mais de uma vez para múltiplos workers. file # Define o caminho para o script do worker, pode ser relativo à raiz do php_server num # Define o número de threads PHP a serem iniciadas, o padrão é 2x o número de CPUs disponíveis. name # Define o nome para o worker, usado em logs e métricas. Padrão: caminho absoluto do arquivo do worker. Sempre começa com m# quando definido em um bloco php_server. watch # Define o caminho para monitorar alterações em arquivos. Pode ser especificada mais de uma vez para múltiplos caminhos. env # Define uma variável de ambiente extra para o valor fornecido. Pode ser especificada mais de uma vez para múltiplas variáveis de ambiente. As variáveis de ambiente para este worker também são herdadas do pai do php_server, mas podem ser sobrescritas aqui. match # Corresponde o worker a um padrão de caminho. Sobrescreve try_files e só pode ser usada na diretiva php_server. } worker # Também pode usar a forma abreviada, como no bloco global frankenphp. } ``` ### Monitorando alterações em arquivos Como os workers inicializam sua aplicação apenas uma vez e a mantêm na memória, quaisquer alterações nos seus arquivos PHP não serão refletidas imediatamente. Os workers podem ser reiniciados em caso de alterações em arquivos por meio da diretiva `watch`. Isso é útil para ambientes de desenvolvimento. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` Esta funcionalidade é frequentemente usada em combinação com [recarregamento a quente (hot reload)](hot-reload.md). Se o diretório `watch` não for especificado, ele usará o valor padrão `./**/*.{env,php,twig,yaml,yml}`, que monitora todos os arquivos `.env`, `.php`, `.twig`, `.yaml` e `.yml` no diretório e subdiretórios onde o processo FrankenPHP foi iniciado. Você também pode especificar um ou mais diretórios por meio de um [padrão de nome de arquivo shell](https://pkg.go.dev/path/filepath#Match): ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # monitora todos os arquivos em todos os subdiretórios de /path/to/app watch /path/to/app/*.php # monitora arquivos terminados em .php em /path/to/app watch /path/to/app/**/*.php # monitora arquivos PHP em /path/to/app e subdiretórios watch /path/to/app/**/*.{php,twig} # monitora arquivos PHP e Twig em /path/to/app e subdiretórios } } } ``` - O padrão `**` significa monitoramento recursivo - Diretórios também podem ser relativos (ao local de início do processo FrankenPHP) - Se você tiver múltiplos workers definidos, todos eles serão reiniciados quando um arquivo for alterado - Tenha cuidado ao monitorar arquivos que são criados em tempo de execução (como logs), pois eles podem causar reinicializações indesejadas de workers. O monitor de arquivos é baseado em [e-dant/watcher](https://github.com/e-dant/watcher). ## Correspondendo o worker a um caminho Em aplicações PHP tradicionais, scripts são sempre colocados no diretório público. Isso também é verdade para worker scripts, que são tratados como qualquer outro script PHP. Se você quiser, em vez disso, colocar o worker script fora do diretório público, pode fazê-lo via a diretiva `match`. A diretiva `match` é uma alternativa otimizada para `try_files`, disponível apenas dentro de `php_server` e `php`. O exemplo a seguir sempre servirá um arquivo no diretório público, se presente, e, caso contrário, encaminhará a requisição para o worker que corresponde ao padrão de caminho. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # o arquivo pode estar fora do caminho público match /api/* # todas as requisições que começam com /api/ serão tratadas por este worker } } } } ``` ## Variáveis de ambiente As seguintes variáveis de ambiente podem ser usadas para injetar diretivas Caddy no `Caddyfile` sem modificá-lo: - `SERVER_NAME`: altera [os endereços nos quais escutar](https://caddyserver.com/docs/caddyfile/concepts#addresses), os nomes de host fornecidos também serão usados para o certificado TLS gerado - `SERVER_ROOT`: altera o diretório raiz do site, o padrão é `public/` - `CADDY_GLOBAL_OPTIONS`: injeta [opções globais](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG`: injeta a configuração sob a diretiva `frankenphp` Assim como para as SAPIs FPM e CLI, as variáveis de ambiente são expostas por padrão na superglobal `$_SERVER`. O valor `S` da [diretiva `variables_order` do PHP](https://www.php.net/manual/en/ini.core.php#ini.variables-order) é sempre equivalente a `ES` independentemente da colocação de `E` em outra parte desta diretiva. ## Configuração do PHP Para carregar [arquivos de configuração adicionais do PHP](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan), a variável de ambiente `PHP_INI_SCAN_DIR` pode ser usada. Quando definida, o PHP carregará todos os arquivos com a extensão `.ini` presentes nos diretórios fornecidos. Você também pode alterar a configuração do PHP usando a diretiva `php_ini` no `Caddyfile`: ```caddyfile { frankenphp { php_ini memory_limit 256M # ou php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### Desabilitando HTTPS Por padrão, o FrankenPHP habilitará automaticamente o HTTPS para todos os nomes de host, incluindo `localhost`. Se você quiser desabilitar o HTTPS (por exemplo, em um ambiente de desenvolvimento), você pode definir a variável de ambiente `SERVER_NAME` para `http://` ou `:80`: Alternativamente, você pode usar todos os outros métodos descritos na [documentação do Caddy](https://caddyserver.com/docs/automatic-https#activation). Se você quiser usar HTTPS com o endereço IP `127.0.0.1` em vez do nome de host `localhost`, por favor, leia a seção de [problemas conhecidos](known-issues.md#using-https127001-with-docker). ### Full Duplex (HTTP/1) Ao usar HTTP/1.x, pode ser desejável habilitar o modo full-duplex para permitir a gravação de uma resposta antes que o corpo inteiro tenha sido lido. (por exemplo: [Mercure](mercure.md), WebSocket, Server-Sent Events, etc.) Esta é uma configuração de adesão que precisa ser adicionada às opções globais no `Caddyfile`: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > Habilitar esta opção pode causar deadlock em clientes HTTP/1.x antigos que não suportam full-duplex. > Isso também pode ser configurado usando a configuração de ambiente `CADDY_GLOBAL_OPTIONS`: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` Você pode encontrar mais informações sobre esta configuração na [documentação do Caddy](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex). ## Habilitar o modo de depuração Ao usar a imagem Docker, defina a variável de ambiente `CADDY_GLOBAL_OPTIONS` como `debug` para habilitar o modo de depuração: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Autocompletar do Shell FrankenPHP oferece suporte integrado de autocompletar do shell para Bash, Zsh, Fish e PowerShell. Isso permite o preenchimento automático para todos os comandos (incluindo comandos personalizados como `php-server`, `php-cli` e `extension-init`) e suas flags. ### Bash Para carregar o autocompletar na sua sessão atual do shell: ```console source <(frankenphp completion bash) ``` Para carregar o autocompletar para cada nova sessão, execute: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh Se o autocompletar do shell ainda não estiver habilitado em seu ambiente, você precisará ativá-lo. Você pode executar o seguinte uma vez: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` Para carregar o autocompletar para cada sessão, execute uma vez: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` Você precisará iniciar um novo shell para que esta configuração tenha efeito. ### Fish Para carregar o autocompletar na sua sessão atual do shell: ```console frankenphp completion fish | source ``` Para carregar o autocompletar para cada nova sessão, execute uma vez: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell Para carregar o autocompletar na sua sessão atual do shell: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` Para carregar o autocompletar para cada nova sessão, execute uma vez: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` Você precisará iniciar um novo shell para que esta configuração tenha efeito. Você precisará iniciar um novo shell para que esta configuração tenha efeito. ================================================ FILE: docs/pt-br/docker.md ================================================ # Construindo Imagens Docker Personalizadas [As imagens Docker do FrankenPHP](https://hub.docker.com/r/dunglas/frankenphp) são baseadas em [imagens oficiais do PHP](https://hub.docker.com/_/php/). Variantes do Debian e do Alpine Linux são fornecidas para arquiteturas populares. Variantes do Debian são recomendadas. Variantes para PHP 8.2, 8.3, 8.4 e 8.5 são fornecidas. As tags seguem este padrão: `dunglas/frankenphp:-php-` - `` e `` são números de versão do FrankenPHP e do PHP, respectivamente, variando de maior (ex.: `1`), menor (ex.: `1.2`) a versões de patch (ex.: `1.2.3`). - `` é `trixie` (para Debian Trixie), `bookworm` (para Debian Bookworm) ou `alpine` (para a versão estável mais recente do Alpine). [Navegue pelas tags](https://hub.docker.com/r/dunglas/frankenphp/tags). ## Como usar as imagens Crie um `Dockerfile` no seu projeto: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Em seguida, execute estes comandos para construir e executar a imagem Docker: ```console docker build -t minha-app-php . docker run -it --rm --name minha-app-rodando minha-app-php ``` ## Como ajustar a configuração Para sua conveniência, [um `Caddyfile` padrão](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) contendo variáveis de ambiente úteis é fornecido na imagem. ## Como instalar mais extensões PHP O script [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) é fornecido na imagem base. Adicionar extensões PHP adicionais é simples: ```dockerfile FROM dunglas/frankenphp # adicione extensões adicionais aqui: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Como instalar mais módulos Caddy O FrankenPHP é construído sobre o Caddy, e todos os [módulos Caddy](https://caddyserver.com/docs/modules/) podem ser usados com o FrankenPHP. A maneira mais fácil de instalar módulos Caddy personalizados é usar o [xcaddy](https://github.com/caddyserver/xcaddy): ```dockerfile FROM dunglas/frankenphp:builder AS builder # Copia o xcaddy para a imagem do builder COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # O CGO precisa estar habilitado para compilar o FrankenPHP RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure e Vulcain estão incluídos na compilação oficial, mas sinta-se # à vontade para removê-los --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Adicione módulos Caddy extras aqui FROM dunglas/frankenphp AS runner # Substitui o binário oficial pelo que contém seus módulos personalizados COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` A imagem `builder` fornecida pelo FrankenPHP contém uma versão compilada da `libphp`. [Imagens de builder](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) são fornecidas para todas as versões do FrankenPHP e do PHP, tanto para Debian quanto para Alpine. > [!TIP] > > Se você estiver usando Alpine Linux e Symfony, pode ser necessário > [aumentar o tamanho padrão da pilha](compile.md#using-xcaddy). ## Habilitando o modo worker por padrão Defina a variável de ambiente `FRANKENPHP_CONFIG` para iniciar o FrankenPHP com um worker script: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Usando um volume em desenvolvimento Para desenvolver facilmente com o FrankenPHP, monte o diretório do seu host que contém o código-fonte da aplicação como um volume no contêiner Docker: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty minha-app-php ``` > [!TIP] > > A opção `--tty` permite ter logs legíveis por humanos em vez de logs JSON. Com o Docker Compose: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # descomente a linha a seguir se quiser usar um Dockerfile personalizado #build: . # descomente a linha a seguir se quiser executar isso em um ambiente de # produção # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # comente a linha a seguir em produção, isso permite ter logs legíveis em # desenvolvimento tty: true # Volumes necessários para certificados e configuração do Caddy volumes: caddy_data: caddy_config: ``` ## Executando como um usuário não root O FrankenPHP pode ser executado como um usuário não root no Docker. Aqui está um exemplo de `Dockerfile` fazendo isso: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" para distribuições baseadas em Alpine useradd ${USER}; \ # Adiciona capacidade adicional para vincular às portas 80 e 443 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # Concede acesso de escrita a /config/caddy e /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Executando sem capacidades Mesmo executando sem root, o FrankenPHP precisa do recurso `CAP_NET_BIND_SERVICE` para vincular o servidor web em portas privilegiadas (80 e 443). Se você expor o FrankenPHP em uma porta não privilegiada (1024 e acima), é possível executar o servidor web como um usuário não root e sem a necessidade de nenhuma capacidade: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Use "adduser -D ${USER}" para distribuições baseadas em Alpine useradd ${USER}; \ # Remove a capacidade padrão setcap -r /usr/local/bin/frankenphp; \ # Concede acesso de escrita a /config/caddy e /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Em seguida, defina a variável de ambiente `SERVER_NAME` para usar uma porta sem privilégios. Exemplo: `:8000` ## Atualizações As imagens Docker são construídas: - quando uma nova release é marcada (tagueada) - diariamente às 4h UTC, se novas versões das imagens oficiais do PHP estiverem disponíveis ## Endurecendo Imagens Para reduzir ainda mais a superfície de ataque e o tamanho das suas imagens Docker do FrankenPHP, também é possível construí-las sobre uma [imagem Google distroless](https://github.com/GoogleContainerTools/distroless) ou [Docker hardened](https://www.docker.com/products/hardened-images). > [!WARNING] > Essas imagens base mínimas não incluem um shell ou gerenciador de pacotes, o que torna a depuração mais difícil. > Elas são, portanto, recomendadas apenas para produção se a segurança for uma alta prioridade. Ao adicionar extensões PHP adicionais, você precisará de uma etapa de build intermediária: ```dockerfile FROM dunglas/frankenphp AS builder # Adicione extensões PHP adicionais aqui RUN install-php-extensions pdo_mysql pdo_pgsql #... # Copia as bibliotecas compartilhadas do frankenphp e todas as extensões instaladas para um local temporário # Você também pode fazer esta etapa manualmente analisando a saída ldd do binário frankenphp e de cada arquivo .so da extensão RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Imagem base debian distroless, certifique-se de que esta é a mesma versão debian da imagem base FROM gcr.io/distroless/base-debian13 # Alternativa de imagem Docker endurecida # FROM dhi.io/debian:13 # Localização do seu aplicativo e Caddyfile a serem copiados para o contêiner ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Copia seu aplicativo para /app # Para um endurecimento adicional, certifique-se de que apenas os caminhos graváveis são de propriedade do usuário não-root COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # Copia frankenphp e bibliotecas necessárias COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # Copia arquivos de configuração php.ini COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Diretórios de dados do Caddy — devem ser graváveis para o usuário não-root, mesmo em um sistema de arquivos raiz somente leitura ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # Ponto de entrada para executar o frankenphp com o Caddyfile fornecido ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Versões de Desenvolvimento As versões de desenvolvimento estão disponíveis no repositório Docker [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev). Uma nova construção é acionada sempre que um commit é enviado para o branch principal do repositório do GitHub. As tags `latest*` apontam para o HEAD do branch `main`. Tags no formato `sha-` também estão disponíveis. ================================================ FILE: docs/pt-br/early-hints.md ================================================ # Early Hints O FrankenPHP suporta nativamente o [código de status 103 Early Hints](https://developer.chrome.com/blog/early-hints/). Usar Early Hints pode melhorar o tempo de carregamento das suas páginas web em 30%. ```php ; rel=preload; as=style'); headers_send(103); // seus algoritmos e consultas SQL lentos 🤪 echo <<<'HTML' Olá FrankenPHP HTML; ``` As Early Hints são suportadas tanto pelo modo normal quanto pelo modo [worker](worker.md). ================================================ FILE: docs/pt-br/embed.md ================================================ # Aplicações PHP como binários independentes O FrankenPHP tem a capacidade de incorporar o código-fonte e os assets de aplicações PHP em um binário estático e independente. Graças a esse recurso, aplicações PHP podem ser distribuídas como binários independentes que incluem a própria aplicação, o interpretador PHP e o Caddy, um servidor web de nível de produção. Saiba mais sobre esse recurso [na apresentação feita por Kévin na SymfonyCon 2023](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/). Para incorporar aplicações Laravel, [leia esta entrada específica na documentação](laravel.md#aplicacoes-laravel-como-binarios-independentes). ## Preparando sua aplicação Antes de criar o binário independente, certifique-se de que sua aplicação esteja pronta para ser incorporada. Por exemplo, você provavelmente deseja: - Instalar as dependências de produção da aplicação; - Fazer o dump do carregador automático; - Habilitar o modo de produção da sua aplicação (se houver); - Remover arquivos desnecessários, como `.git` ou testes, para reduzir o tamanho do seu binário final. Por exemplo, para uma aplicação Symfony, você pode usar os seguintes comandos: ```console # Exporta o projeto para se livrar de .git/, etc. mkdir $TMPDIR/minha-aplicacao-preparada git archive HEAD | tar -x -C $TMPDIR/minha-aplicacao-preparada cd $TMPDIR/minha-aplicacao-preparada # Define as variáveis de ambiente adequadas echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Remove os testes e outros arquivos desnecessários para economizar espaço. # Como alternativa, adicione esses arquivos com o atributo export-ignore no seu # arquivo .gitattributes. rm -Rf tests/ # Instala as dependências composer install --ignore-platform-reqs --no-dev -a # Otimiza o arquivo .env composer dump-env prod ``` ### Personalizando a configuração Para personalizar [a configuração](config.md), você pode colocar um arquivo `Caddyfile` e um arquivo `php.ini` no diretório principal da aplicação a ser incorporada (`$TMPDIR/minha-aplicacao-preparada` no exemplo anterior). ## Criando um binário do Linux A maneira mais fácil de criar um binário do Linux é usar o builder baseado em Docker que fornecemos. 1. Crie um arquivo chamado `static-build.Dockerfile` no repositório da sua aplicação: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Se você pretende executar o binário em sistemas musl-libc, use o static-builder-musl # Copia sua aplicação WORKDIR /go/src/app/dist/app COPY . . # Compila o binário estático WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Alguns arquivos `.dockerignore` (por exemplo, o > [`.dockerignore` padrão do Docker do Symfony](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > ignorarão o diretório `vendor/` e os arquivos `.env`. > Certifique-se de ajustar ou remover o arquivo `.dockerignore` antes da > construção. 2. Construa: ```console docker build -t aplicacao-estatica -f static-build.Dockerfile . ``` 3. Extraia o binário: ```console docker cp $(docker create --name aplicacao-estatica-tmp aplicacao-estatica):/go/src/app/dist/frankenphp-linux-x86_64 minha-aplicacao ; docker rm aplicacao-estatica-tmp ``` O binário resultante é o arquivo `minha-aplicacao` no diretório atual. ## Criando um binário para outros sistemas operacionais Se você não quiser usar o Docker ou quiser compilar um binário para macOS, use o script de shell que fornecemos: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/caminho/para/sua/aplicacao ./build-static.sh ``` O binário resultante é o arquivo `frankenphp--` no diretório `dist/`. ## Usando o binário É isso! O arquivo `minha-aplicacao` (ou `dist/frankenphp--` em outros sistemas operacionais) contém sua aplicação independente! Para iniciar a aplicação web, execute: ```console ./minha-aplicacao php-server ``` Se a sua aplicação contiver um [worker script](worker.md), inicie o worker com algo como: ```console ./minha-aplicacao php-server --worker public/index.php ``` Para habilitar HTTPS (um certificado Let's Encrypt é criado automaticamente), HTTP/2 e HTTP/3, especifique o nome de domínio a ser usado: ```console ./minha-aplicacao php-server --domain localhost ``` Você também pode executar os scripts PHP CLI incorporados ao seu binário: ```console ./minha-aplicacao php-cli bin/console ``` ## Extensões PHP Por padrão, o script compilará as extensões requeridas pelo arquivo `composer.json` do seu projeto, se houver. Se o arquivo `composer.json` não existir, as extensões padrão serão compiladas, conforme documentado na [entrada de compilações estáticas](static.md). Para personalizar as extensões, use a variável de ambiente `PHP_EXTENSIONS`. ## Personalizando a compilação [Leia a documentação da compilação estática](static.md) para ver como personalizar o binário (extensões, versão do PHP...). ## Distribuindo o binário No Linux, o binário criado é compactado usando [UPX](https://upx.github.io). No Mac, para reduzir o tamanho do arquivo antes de enviá-lo, você pode compactá-lo. Recomendamos usar `xz`. ================================================ FILE: docs/pt-br/extension-workers.md ================================================ # Workers de Extensão Os Workers de Extensão permitem que sua [extensão FrankenPHP](https://frankenphp.dev/docs/extensions/) gerencie um pool dedicado de threads PHP para executar tarefas em segundo plano, lidar com eventos assíncronos ou implementar protocolos personalizados. Útil para sistemas de fila, listeners de eventos, agendadores, etc. ## Registrando o Worker ### Registro Estático Se você não precisa que o worker seja configurável pelo usuário (caminho de script fixo, número de threads fixo), você pode simplesmente registrar o worker na função `init()`. ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // Handle global para comunicar com o pool de workers var worker frankenphp.Workers func init() { // Registra o worker quando o módulo é carregado. worker = caddy.RegisterWorkers( "my-internal-worker", // Nome único "worker.php", // Caminho do script (relativo à execução ou absoluto) 2, // Contagem fixa de threads // Hooks de ciclo de vida opcionais frankenphp.WithWorkerOnServerStartup(func() { // Lógica de configuração global... }), ) } ``` ### Em um Módulo Caddy (Configurável pelo usuário) Se você planeja compartilhar sua extensão (como uma fila genérica ou um listener de eventos), você deve encapsulá-la em um módulo Caddy. Isso permite que os usuários configurem o caminho do script e a contagem de threads através do seu `Caddyfile`. Isso exige a implementação da interface `caddy.Provisioner` e a análise do Caddyfile ([veja um exemplo](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)). ### Em uma Aplicação Go Pura (Embedagem) Se você está [embedando o FrankenPHP em uma aplicação Go padrão sem caddy](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), você pode registrar workers de extensão usando `frankenphp.WithExtensionWorkers` ao inicializar as opções. ## Interagindo com Workers Assim que o pool de workers estiver ativo, você pode despachar tarefas para ele. Isso pode ser feito dentro de [funções nativas exportadas para PHP](https://frankenphp.dev/docs/extensions/#writing-the-extension), ou de qualquer lógica Go, como um agendador cron, um listener de eventos (MQTT, Kafka), ou qualquer outra goroutine. ### Modo Headless: `SendMessage` Use `SendMessage` para passar dados brutos diretamente para o seu script worker. Isso é ideal para filas ou comandos simples. #### Exemplo: Uma Extensão de Fila Assíncrona ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. Garante que o worker esteja pronto if worker == nil { return false } // 2. Despacha para o worker em segundo plano _, err := worker.SendMessage( context.Background(), // Contexto Go padrão unsafe.Pointer(data), // Dados a serem passados para o worker nil, // http.ResponseWriter opcional ) return err == nil } ``` ### Emulação HTTP: `SendRequest` Use `SendRequest` se sua extensão precisar invocar um script PHP que espera um ambiente web padrão (populando `$_SERVER`, `$_GET`, etc.). ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. Prepara a requisição e o gravador url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. Despacha para o worker if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Retorna a resposta capturada return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Script do Worker O script PHP do worker é executado em um loop e pode lidar tanto com mensagens brutas quanto com requisições HTTP. ```php [!TIP] > Se quiser entender como as extensões podem ser escritas em Go do zero, leia a > seção de implementação manual abaixo, que demonstra como escrever uma extensão > PHP em Go sem usar o gerador. Lembre-se de que esta ferramenta **não é um gerador de extensões completo**. Ela foi criada para ajudar você a escrever extensões simples em Go, mas não oferece os recursos mais avançados das extensões PHP. Se precisar escrever uma extensão mais **complexa e otimizada**, talvez seja necessário escrever algum código em C ou usar CGO diretamente. ### Pré-requisitos Conforme abordado na seção de implementação manual abaixo, você precisa [obter o código-fonte do PHP](https://www.php.net/downloads.php) e criar um novo módulo Go. #### Criando um novo módulo e obtendo o código-fonte do PHP O primeiro passo para escrever uma extensão PHP em Go é criar um novo módulo Go. Você pode usar o seguinte comando para isso: ```console go mod init github.com// ``` O segundo passo é [obter o código-fonte do PHP](https://www.php.net/downloads.php) para os próximos passos. Depois de obtê-los, descompacte-os no diretório de sua escolha, não dentro do seu módulo Go: ```console tar xf php-* ``` ### Escrevendo a extensão Agora tudo está configurado para escrever sua função nativa em Go. Crie um novo arquivo chamado `stringext.go`. Nossa primeira função receberá uma string como argumento, o número de vezes que ela será repetida, um booleano para indicar se a string deve ser invertida e retornará a string resultante. Deve ficar assim: ```go import ( "C" "github.com/dunglas/frankenphp" "strings" ) //export_php:function repeat_this(string $str, int $count, bool $reverse): string func repeat_this(s *C.zend_string, count int64, reverse bool) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) result := strings.Repeat(str, int(count)) if reverse { runes := []rune(result) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } result = string(runes) } return frankenphp.PHPString(result, false) } ``` Há duas coisas importantes a serem observadas aqui: - Um comentário de diretiva `//export_php:function` define a assinatura da função no PHP. É assim que o gerador sabe como gerar a função PHP com os parâmetros e o tipo de retorno corretos; - A função deve retornar um `unsafe.Pointer`. O FrankenPHP fornece uma API para ajudar você com o malabarismo de tipos entre C e Go. Embora o primeiro ponto fale por si, o segundo pode ser mais difícil de entender. Vamos nos aprofundar no malabarismo de tipos na próxima seção. ### Malabarismo de tipos Embora alguns tipos de variáveis tenham a mesma representação de memória entre C/PHP e Go, alguns tipos exigem mais lógica para serem usados diretamente. Esta talvez seja a parte mais difícil quando se trata de escrever extensões, pois requer a compreensão dos componentes internos da Zend Engine e de como as variáveis são armazenadas internamente no PHP. Esta tabela resume o que você precisa saber: | Tipo PHP | Tipo Go | Conversão direta | Auxiliar de C para Go | Auxiliar de Go para C | Suporte a métodos de classe | | ------------------ | ----------------------------- | ---------------- | --------------------------------- | ---------------------------------- | --------------------------- | | `int` | `int64` | ✅ | - | - | ✅ | | `?int` | `*int64` | ✅ | - | - | ✅ | | `float` | `float64` | ✅ | - | - | ✅ | | `?float` | `*float64` | ✅ | - | - | ✅ | | `bool` | `bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `?bool` | `*bool` | ✅ | - | - | ✅ | | `string`/`?string` | `*C.zend_string` | ❌ | `frankenphp.GoString()` | `frankenphp.PHPString()` | ✅ | | `array` | `frankenphp.AssociativeArray` | ❌ | `frankenphp.GoAssociativeArray()` | `frankenphp.PHPAssociativeArray()` | ✅ | | `array` | `map[string]any` | ❌ | `frankenphp.GoMap()` | `frankenphp.PHPMap()` | ✅ | | `array` | `[]any` | ❌ | `frankenphp.GoPackedArray()` | `frankenphp.PHPPackedArray()` | ✅ | | `mixed` | `any` | ❌ | `GoValue()` | `PHPValue()` | ❌ | | `object` | `struct` | ❌ | _Ainda não implementado_ | _Ainda não implementado_ | ❌ | > [!NOTE] > Esta tabela ainda não é exaustiva e será completada à medida que a API de > tipos do FrankenPHP se tornar mais completa. > > Tipos primitivos e arrays são suportados atualmente, especificamente para > métodos de classe. > Objetos ainda não podem ser usados como parâmetros de métodos ou tipos de > retorno. Se você consultar o trecho de código da seção anterior, poderá ver que os auxiliares são usados para converter o primeiro parâmetro e o valor de retorno. O segundo e o terceiro parâmetros da nossa função `repeat_this()` não precisam ser convertidos, pois a representação em memória dos tipos subjacentes é a mesma para C e Go. #### Trabalhando com arrays O FrankenPHP oferece suporte nativo para arrays PHP por meio de `frankenphp.AssociativeArray` ou conversão direta para um mapa ou slice. `AssociativeArray` representa um [hashmap](https://en.wikipedia.org/wiki/Hash_table) composto por um campo `Map: map[string]any` e um campo opcional `Order: []string` (ao contrário dos arrays associativos do PHP, os mapas em Go não são ordenados). Se a ordem ou a associação não forem necessárias, também é possível converter diretamente para um slice `[]any` ou um mapa não ordenado `map[string]any`. **Criando e manipulando arrays em Go:** ```go //export_php:function process_data_ordered(array $input): array func process_data_ordered_map(arr *C.zval) unsafe.Pointer { // Converte um array associativo PHP para Go, mantendo a ordem associativeArray := frankenphp.GoAssociativeArray(unsafe.Pointer(arr)) // percorre as entradas em ordem for _, key := range associativeArray.Order { value, _ = associativeArray.Map[key] // faz algo com a chave e o valor } // retorna um array ordenado // se 'Order' não estiver vazio, apenas os pares chave-valor em 'Order' // serão respeitados return frankenphp.PHPAssociativeArray(AssociativeArray{ Map: map[string]any{ "chave1": "valor1", "chave2": "valor2", }, Order: []string{"chave1", "chave2"}, }) } //export_php:function process_data_unordered(array $input): array func process_data_unordered_map(arr *C.zval) unsafe.Pointer { // Converte um array associativo PHP em um mapa Go sem manter a ordem // Ignorar a ordem terá melhor desempenho goMap := frankenphp.GoMap(unsafe.Pointer(arr)) // percorre as entradas sem nenhuma ordem específica for key, value := range goMap { // faz algo com a chave e o valor } // retorna um array não ordenado return frankenphp.PHPMap(map[string]any{ "chave1": "valor1", "chave2": "valor2", }) } //export_php:function process_data_packed(array $input): array func process_data_packed(arr *C.zval) unsafe.Pointer { // Converte um array compactado PHP para Go goSlice := frankenphp.GoPackedArray(unsafe.Pointer(arr), false) // percorre o slice em ordem for index, value := range goSlice { // faz algo com a chave e o valor } // retorna um array compactado return frankenphp.PHPackedArray([]any{"valor1", "valor2", "value3"}) } ``` **Principais recursos da conversão de arrays:** - **Pares chave-valor ordenados** - Opção para manter a ordem do array associativo; - **Otimizado para múltiplos casos** - Opção para ignorar a ordem para melhor desempenho ou converter diretamente para um slice; - **Detecção automática de listas** - Ao converter para PHP, detecta automaticamente se o array deve ser uma lista compactada ou um hashmap; - **Arrays aninhados** - Os arrays podem ser aninhados e converterão todos os tipos suportados automaticamente (`int64`, `float64`, `string`, `bool`, `nil`, `AssociativeArray`, `map[string]any`, `[]any`); - **Objetos não são suportados** - Atualmente, apenas tipos escalares e arrays podem ser usados como valores. Fornecer um objeto resultará em um valor `null` no array PHP. ##### Métodos disponíveis: empacotado e associativo - `frankenphp.PHPAssociativeArray(arr frankenphp.AssociativeArray) unsafe.Pointer` \- Converte para um array PHP ordenado com pares chave-valor; - `frankenphp.PHPMap(arr map[string]any) unsafe.Pointer` - Converte um mapa em um array PHP não ordenado com pares chave-valor; - `frankenphp.PHPPackedArray(slice []any) unsafe.Pointer` - Converte um slice em um array PHP compactado apenas com valores indexados; - `frankenphp.GoAssociativeArray(arr unsafe.Pointer, ordered bool) frankenphp.AssociativeArray` \- Converte um array PHP em um `AssociativeArray` Go ordenado (mapa com ordem); - `frankenphp.GoMap(arr unsafe.Pointer) map[string]any` - Converte um array PHP em um mapa Go não ordenado; - `frankenphp.GoPackedArray(arr unsafe.Pointer) []any` - Converte um array PHP em um slice Go. ### Declarando uma classe PHP nativa O gerador suporta a declaração de **classes opacas** como estruturas Go, que podem ser usadas para criar objetos PHP. Você pode usar o comentário de diretiva `//export_php:class` para definir uma classe PHP. Por exemplo: ```go //export_php:class User type UserStruct struct { Name string Age int } ``` #### O que são classes opacas? **Classes Opacas** são classes cuja estrutura interna (propriedades) é ocultada do código PHP. Isso significa: - **Sem acesso direto às propriedades**: Você não pode ler ou escrever propriedades diretamente do PHP (`$user->name` não funcionará); - **Interface somente para métodos** - Todas as interações devem passar pelos métodos que você definir; - **Melhor encapsulamento** - A estrutura interna de dados é completamente controlada pelo código Go; - **Segurança de tipos** - Sem risco do código PHP corromper o estado interno com tipos incorretos; - **API mais limpa** - Força o design de uma interface pública adequada. Essa abordagem fornece melhor encapsulamento e evita que o código PHP corrompa acidentalmente o estado interno dos seus objetos Go. Todas as interações com o objeto devem passar pelos métodos que você definir explicitamente. #### Adicionando métodos às classes Como as propriedades não são diretamente acessíveis, você **deve definir métodos** para interagir com suas classes opacas. Use a diretiva `//export_php:method` para definir o comportamento: ```go //export_php:class User type UserStruct struct { Name string Age int } //export_php:method User::getName(): string func (us *UserStruct) GetUserName() unsafe.Pointer { return frankenphp.PHPString(us.Name, false) } //export_php:method User::setAge(int $age): void func (us *UserStruct) SetUserAge(age int64) { us.Age = int(age) } //export_php:method User::getAge(): int func (us *UserStruct) GetUserAge() int64 { return int64(us.Age) } //export_php:method User::setNamePrefix(string $prefix = "User"): void func (us *UserStruct) SetNamePrefix(prefix *C.zend_string) { us.Name = frankenphp.GoString(unsafe.Pointer(prefix)) + ": " + us.Name } ``` #### Parâmetros anuláveis O gerador suporta parâmetros anuláveis usando o prefixo `?` em assinaturas PHP. Quando um parâmetro é anulável, ele se torna um ponteiro na sua função Go, permitindo que você verifique se o valor era `null` no PHP: ```go //export_php:method User::updateInfo(?string $name, ?int $age, ?bool $active): void func (us *UserStruct) UpdateInfo(name *C.zend_string, age *int64, active *bool) { // Verifica se o parâmetro name foi fornecido (não nulo) if name != nil { us.Name = frankenphp.GoString(unsafe.Pointer(name)) } // Verifica se o parâmetro age foi fornecido (não nulo) if age != nil { us.Age = int(*age) } // Verifique se o parâmetro active foi fornecido (não nulo) if active != nil { us.Active = *active } } ``` **Pontos-chave sobre parâmetros anuláveis:** - **Tipos primitivos anuláveis** (`?int`, `?float`, `?bool`) tornam-se ponteiros (`*int64`, `*float64`, `*bool`) em Go; - **Strings anuláveis** (`?string`) permanecem como `*C.zend_string`, mas podem ser `*nil`; - **Verifique `nil`** antes de dereferenciar valores de ponteiro; - **`null` do PHP torna-se `nil` do Go** - quando o PHP passa `null`, sua função em Go recebe um ponteiro `nil`. > [!WARNING] > Atualmente, os métodos de classe têm as seguintes limitações. > **Objetos não são suportados** como tipos de parâmetros ou tipos de retorno. > **Arrays são totalmente suportados** tanto para parâmetros quanto para tipos > de retorno. > Tipos suportados: `string`, `int`, `float`, `bool`, `array` e `void` (para > tipo de retorno). > **Tipos de parâmetros anuláveis são totalmente suportados** para todos os > tipos escalares (`?string`, `?int`, `?float`, `?bool`). Após gerar a extensão, você poderá usar a classe e seus métodos no PHP. Observe que você **não pode acessar propriedades diretamente**: ```php setAge(25); echo $user->getName(); // Saída: (vazio, valor padrão) echo $user->getAge(); // Saída: 25 $user->setNamePrefix("Funcionária"); // ✅ Isso também funciona - parâmetros anuláveis $user->updateInfo("João", 30, true); // Todos os parâmetros fornecidos $user->updateInfo("Joana", null, false); // Age é nulo $user->updateInfo(null, 25, null); // Name e active são nulos // ❌ Isso NÃO funcionará - acesso direto à propriedade // echo $user->name; // Error: Cannot access private property // $user->age = 30; // Error: Cannot access private property ``` Este design garante que seu código Go tenha controle total sobre como o estado do objeto é acessado e modificado, proporcionando melhor encapsulamento e segurança de tipos. ### Declarando constantes O gerador suporta a exportação de constantes Go para PHP usando duas diretivas: `//export_php:const` para constantes globais e `//export_php:classconst` para constantes de classe. Isso permite que você compartilhe valores de configuração, códigos de status e outras constantes entre código Go e PHP. #### Constantes globais Use a diretiva `//export_php:const` para criar constantes PHP globais: ```go //export_php:const const MAX_CONNECTIONS = 100 //export_php:const const API_VERSION = "1.2.3" //export_php:const const STATUS_OK = iota //export_php:const const STATUS_ERROR = iota ``` #### Constantes de classe Use a diretiva `//export_php:classconst ClassName` para criar constantes que pertencem a uma classe PHP específica: ```go //export_php:classconst User const STATUS_ACTIVE = 1 //export_php:classconst User const STATUS_INACTIVE = 0 //export_php:classconst User const ROLE_ADMIN = "admin" //export_php:classconst Order const STATE_PENDING = iota //export_php:classconst Order const STATE_PROCESSING = iota //export_php:classconst Order const STATE_COMPLETED = iota ``` Constantes de classe são acessíveis usando o escopo do nome da classe no PHP: ```php getName(); // "João Ninguém" echo My\Extension\STATUS_ACTIVE; // 1 ``` #### Notas importantes - Apenas **uma** diretiva de namespace é permitida por arquivo. Se várias diretivas de namespace forem encontradas, o gerador retornará um erro; - O namespace se aplica a **todos** os símbolos exportados no arquivo: funções, classes, métodos e constantes; - Os nomes de namespace seguem as convenções de namespace do PHP, usando barras invertidas (`\`) como separadores; - Se nenhum namespace for declarado, os símbolos serão exportados para o namespace global como de costume. ### Gerando a extensão É aqui que a mágica acontece e sua extensão agora pode ser gerada. Você pode executar o gerador com o seguinte comando: ```console GEN_STUB_SCRIPT=php-src/build/gen_stub.php frankenphp extension-init my_extension.go ``` > [!NOTE] > Não se esqueça de definir a variável de ambiente `GEN_STUB_SCRIPT` para o > caminho do arquivo `gen_stub.php` no código-fonte PHP que você baixou > anteriormente. > Este é o mesmo script `gen_stub.php` mencionado na seção de implementação > manual. Se tudo correu bem, um novo diretório chamado `build` deve ter sido criado. Este diretório contém os arquivos gerados para sua extensão, incluindo o arquivo `my_extension.go` com os stubs de funções PHP gerados. ### Integrando a extensão gerada ao FrankenPHP Nossa extensão agora está pronta para ser compilada e integrada ao FrankenPHP. Para fazer isso, consulte a [documentação de compilação](compile.md) do FrankenPHP para aprender como compilar o FrankenPHP. Adicione o módulo usando a flag `--with`, apontando para o caminho do seu módulo: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com///build ``` Observe que você aponta para o subdiretório `/build` que foi criado durante a etapa de geração. Entretanto, isso não é obrigatório: você também pode copiar os arquivos gerados para o diretório do seu módulo e apontar diretamente para ele. ### Testando sua extensão gerada Você pode criar um arquivo PHP para testar as funções e classes que criou. Por exemplo, crie um arquivo `index.php` com o seguinte conteúdo: ```php process('Olá mundo', StringProcessor::MODE_LOWERCASE); // "olá mundo" echo $processor->process('Olá mundo', StringProcessor::MODE_UPPERCASE); // "OLÁ MUNDO" ``` Depois de integrar sua extensão ao FrankenPHP, como demonstrado na seção anterior, você pode executar este arquivo de teste usando `./frankenphp php-server` e deverá ver sua extensão funcionando. ## Implementação manual Se você quiser entender como as extensões funcionam ou precisar de controle total sobre elas, pode escrevê-las manualmente. Essa abordagem oferece controle total, mas requer mais código boilerplate. ### Função básica Veremos como escrever uma extensão PHP simples em Go que define uma nova função nativa. Essa função será chamada do PHP e disparará uma goroutine que registra uma mensagem nos logs do Caddy. Essa função não recebe parâmetros e não retorna nada. #### Definindo a função Go No seu módulo, você precisa definir uma nova função nativa que será chamada do PHP. Para fazer isso, crie um arquivo com o nome desejado, por exemplo, `extension.go`, e adicione o seguinte código: ```go package ext_go //#include "extension.h" import "C" import ( "unsafe" "github.com/caddyserver/caddy/v2" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.ext_module_entry)) } //export go_print_something func go_print_something() { go func() { caddy.Log().Info("Olá de uma goroutine!") }() } ``` A função `frankenphp.RegisterExtension()` simplifica o processo de registro de extensões, manipulando a lógica interna de registro do PHP. A função `go_print_something` usa a diretiva `//export` para indicar que estará acessível no código C que escreveremos, graças ao CGO. Neste exemplo, nossa nova função disparará uma goroutine que registra uma mensagem nos logs do Caddy. #### Definindo a função PHP Para permitir que o PHP chame nossa função, precisamos definir uma função PHP correspondente. Para isso, criaremos um arquivo stub, por exemplo, `extension.stub.php`, que conterá o seguinte código: ```php extern zend_module_entry ext_module_entry; #endif ``` Em seguida, crie um arquivo chamado `extension.c` que executará as seguintes etapas: - Incluir cabeçalhos PHP; - Declarar nossa nova função nativa PHP `go_print()`; - Declarar os metadados da extensão. Vamos começar incluindo os cabeçalhos necessários: ```c #include #include "extension.h" #include "extension_arginfo.h" // Contém símbolos exportados pelo Go #include "_cgo_export.h" ``` Em seguida, definimos nossa função PHP como uma função nativa da linguagem: ```c PHP_FUNCTION(go_print) { ZEND_PARSE_PARAMETERS_NONE(); go_print_something(); } zend_module_entry ext_module_entry = { STANDARD_MODULE_HEADER, "ext_go", ext_functions, /* Funções */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.1", STANDARD_MODULE_PROPERTIES }; ``` Neste caso, nossa função não recebe parâmetros e não retorna nada. Ela simplesmente chama a função Go que definimos anteriormente, exportada usando a diretiva `//export`. Finalmente, definimos os metadados da extensão em uma estrutura `zend_module_entry`, como seu nome, versão e propriedades. Essas informações são necessárias para que o PHP reconheça e carregue nossa extensão. Observe que `ext_functions` é um array de ponteiros para as funções PHP que definimos e foi gerado automaticamente pelo script `gen_stub.php` no arquivo `extension_arginfo.h`. O registro da extensão é tratado automaticamente pela função `RegisterExtension()` do FrankenPHP, que chamamos em nosso código Go. ### Uso avançado Agora que sabemos como criar uma extensão PHP básica em Go, vamos tornar nosso exemplo mais complexo. Agora, criaremos uma função PHP que recebe uma string como parâmetro e retorna sua versão em letras maiúsculas. #### Definindo o stub da função PHP Para definir a nova função PHP, modificaremos nosso arquivo `extension.stub.php` para incluir a nova assinatura da função: ```php [!TIP] > Não negligencie a documentação das suas funções! > Você provavelmente compartilhará os stubs da sua extensão com outras > pessoas desenvolvedoras para documentar como usar a sua extensão e quais > recursos estão disponíveis. Ao gerar novamente o arquivo stub com o script `gen_stub.php`, o arquivo `extension_arginfo.h` deverá ficar assim: ```c ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_go_upper, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_FUNCTION(go_upper); static const zend_function_entry ext_functions[] = { ZEND_FE(go_upper, arginfo_go_upper) ZEND_FE_END }; ``` Podemos ver que a função `go_upper` é definida com um parâmetro do tipo `string` e um tipo de retorno `string`. #### Malabarismo de tipos entre Go e PHP/C Sua função Go não pode aceitar diretamente uma string PHP como parâmetro. Você precisa convertê-la para uma string Go. Felizmente, o FrankenPHP fornece funções auxiliares para lidar com a conversão entre strings PHP e strings Go, semelhante ao que vimos na abordagem do gerador. O arquivo de cabeçalho permanece simples: ```c #ifndef _EXTENSION_H #define _EXTENSION_H #include extern zend_module_entry ext_module_entry; #endif ``` Agora podemos escrever a ponte entre Go e C no nosso arquivo `extension.c`. Passaremos a string PHP diretamente para a nossa função Go: ```c PHP_FUNCTION(go_upper) { zend_string *str; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(str) ZEND_PARSE_PARAMETERS_END(); zend_string *result = go_upper(str); RETVAL_STR(result); } ``` Você pode aprender mais sobre `ZEND_PARSE_PARAMETERS_START` e análise de parâmetros na página dedicada do [PHP Internals Book](https://www.phpinternalsbook.com/php7/extensions_design/php_functions.html#parsing-parameters-zend-parse-parameters). Aqui, informamos ao PHP que nossa função recebe um parâmetro obrigatório do tipo `string` como uma `zend_string`. Em seguida, passamos essa string diretamente para nossa função Go e retornamos o resultado usando `RETVAL_STR`. Só resta uma coisa a fazer: implementar a função `go_upper` em Go. #### Implementando a função Go Nossa função Go receberá uma `*C.zend_string` como parâmetro, a converterá em uma string Go usando a função auxiliar do FrankenPHP, a processará e retornará o resultado como uma nova `*C.zend_string`. As funções auxiliares cuidam de todo o gerenciamento de memória e da complexidade da conversão para nós. ```go import "strings" //export go_upper func go_upper(s *C.zend_string) *C.zend_string { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return (*C.zend_string)(frankenphp.PHPString(upper, false)) } ``` Essa abordagem é muito mais limpa e segura do que o gerenciamento manual de memória. As funções auxiliares do FrankenPHP lidam automaticamente com a conversão entre o formato `zend_string` do PHP e strings em Go. O parâmetro `false` em `PHPString()` indica que queremos criar uma nova string não persistente (liberada ao final da requisição). > [!TIP] > Neste exemplo, não realizamos nenhum tratamento de erro, mas você deve sempre > verificar se os ponteiros não são `nil` e se os dados são válidos antes de > usá-los em suas funções em Go. ### Integrando a extensão ao FrankenPHP Nossa extensão agora está pronta para ser compilada e integrada ao FrankenPHP. Para isso, consulte a [documentação de compilação](compile.md) do FrankenPHP para aprender como compilar o FrankenPHP. Adicione o módulo usando a flag `--with`, apontando para o caminho do seu módulo: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com// ``` Pronto! Sua extensão agora está integrada ao FrankenPHP e pode ser usada no seu código PHP. ### Testando sua extensão Após integrar sua extensão ao FrankenPHP, você pode criar um arquivo `index.php` com exemplos para as funções que você implementou: ```php [!WARNING] > > Este recurso é destinado **apenas para ambientes de desenvolvimento**. > Não ative `hot_reload` em produção, pois este recurso não é seguro (expõe detalhes internos sensíveis) e desacelera a aplicação. > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` Por padrão, o FrankenPHP monitorará todos os arquivos no diretório de trabalho atual que correspondem a este padrão glob: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` É possível definir os arquivos a serem monitorados usando a sintaxe glob explicitamente: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Use a forma longa de `hot_reload` para especificar o tópico Mercure a ser usado, bem como quais diretórios ou arquivos monitorar: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## Integração no Lado do Cliente Enquanto o servidor detecta as alterações, o navegador precisa se inscrever nesses eventos para atualizar a página. O FrankenPHP expõe a URL do Hub Mercure a ser usada para se inscrever em alterações de arquivo através da variável de ambiente `$_SERVER['FRANKENPHP_HOT_RELOAD']`. Uma biblioteca JavaScript de conveniência, [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload), também está disponível para lidar com a lógica do lado do cliente. Para usá-la, adicione o seguinte ao seu layout principal: ```php FrankenPHP Hot Reload ``` A biblioteca se inscreverá automaticamente no hub Mercure, buscará a URL atual em segundo plano quando uma alteração de arquivo for detectada e transformará o DOM. Está disponível como um pacote [npm](https://www.npmjs.com/package/frankenphp-hot-reload) e no [GitHub](https://github.com/dunglas/frankenphp-hot-reload). Alternativamente, você pode implementar sua própria lógica do lado do cliente inscrevendo-se diretamente no hub Mercure usando a classe nativa `EventSource` do JavaScript. ### Preservando Nós DOM Existentes Em casos raros, como ao usar ferramentas de desenvolvimento [como a barra de depuração da web do Symfony](https://github.com/symfony/symfony/pull/62970), você pode querer preservar nós DOM específicos. Para fazer isso, adicione o atributo `data-frankenphp-hot-reload-preserve` ao elemento HTML relevante: ```html
``` ## Modo Worker Se você estiver executando sua aplicação em [Modo Worker](https://frankenphp.dev/docs/worker/), seu script de aplicação permanece na memória. Isso significa que as alterações no seu código PHP não serão refletidas imediatamente, mesmo que o navegador recarregue. Para a melhor experiência do desenvolvedor, você deve combinar `hot_reload` com [a subdiretiva `watch` na diretiva `worker`](config.md#observando-alteracoes-de-arquivos). - `hot_reload`: atualiza o **navegador** quando os arquivos são alterados - `worker.watch`: reinicia o worker quando os arquivos são alterados ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## Como Funciona 1. **Monitoramento**: O FrankenPHP monitora o sistema de arquivos em busca de modificações usando a biblioteca [`e-dant/watcher`](https://github.com/e-dant/watcher) por baixo dos panos (contribuímos com o binding Go). 2. **Reiniciar (Modo Worker)**: se `watch` estiver habilitado na configuração do worker, o worker PHP é reiniciado para carregar o novo código. 3. **Envio**: Um payload JSON contendo a lista de arquivos alterados é enviado para o [hub Mercure](https://mercure.rocks) embutido. 4. **Recebimento**: O navegador, ouvindo através da biblioteca JavaScript, recebe o evento Mercure. 5. **Atualização**: - Se o **Idiomorph** for detectado, ele busca o conteúdo atualizado e transforma o HTML atual para corresponder ao novo estado, aplicando as alterações instantaneamente sem perder o estado. - Caso contrário, `window.location.reload()` é chamado para recarregar a página. ================================================ FILE: docs/pt-br/known-issues.md ================================================ # Problemas conhecidos ## Extensões PHP não suportadas As seguintes extensões são conhecidas por não serem compatíveis com o FrankenPHP: | Nome | Motivo | Alternativas | | ----------------------------------------------------------------------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/pt_BR/imap.installation.php) | Não é thread-safe | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | Não é thread-safe | - | ## Extensões PHP com falhas As seguintes extensões apresentam falhas conhecidas e comportamentos inesperados quando usadas com o FrankenPHP: | Nome | Problema | | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [ext-openssl](https://www.php.net/manual/pt_BR/book.openssl.php) | Ao usar uma versão estática do FrankenPHP (compilada com a `libc` `musl`), a extensão OpenSSL pode quebrar sob cargas pesadas. Uma solução alternativa é usar uma versão vinculada dinamicamente (como a usada em imagens Docker). Esta falha está [sendo monitorada pelo PHP](https://github.com/php/php-src/issues/13648) | ## `get_browser` A função [`get_browser()`](https://www.php.net/manual/pt_BR/function.get-browser.php) parece apresentar mau desempenho após algum tempo. Uma solução alternativa é armazenar em cache (por exemplo, com [APCu](https://www.php.net/manual/pt_BR/book.apcu.php)) os resultados por Agente de Usuário, pois são estáticos. ## Imagens Docker binárias independentes e baseadas em Alpine As imagens Docker binárias independentes e baseadas em Alpine (`dunglas/frankenphp:*-alpine`) usam a [`libc` `musl`](https://musl.libc.org/) em vez de [`glibc` e similares](https://www.etalabs.net/compare_libcs.html) para manter um tamanho binário menor. Isso pode levar a alguns problemas de compatibilidade. Em particular, o sinalizador glob `GLOB_BRACE` [não está disponível](https://www.php.net/manual/pt_BR/function.glob.php) ## Usando `https://127.0.0.1` com o Docker Por padrão, o FrankenPHP gera um certificado TLS para `localhost`. É a opção mais fácil e recomendada para desenvolvimento local. Se você realmente deseja usar `127.0.0.1` como host, é possível configurá-lo para gerar um certificado definindo o nome do servidor como `127.0.0.1`. Infelizmente, isso não é suficiente ao usar o Docker devido ao [seu sistema de rede](https://docs.docker.com/network/). Você receberá um erro TLS semelhante a `curl: (35) LibreSSL/3.3.6: erro:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`. Se você estiver usando Linux, uma solução é usar [o driver de rede do host](https://docs.docker.com/network/network-tutorial-host/): ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` O driver de rede do host não é compatível com Mac e Windows. Nessas plataformas, você terá que descobrir o endereço IP do contêiner e incluí-lo nos nomes dos servidores. Execute o comando `docker network inspect bridge` e verifique a chave `Containers` para identificar o último endereço IP atribuído atualmente sob a chave `IPv4Address` e incremente-o em um. Se nenhum contêiner estiver em execução, o primeiro endereço IP atribuído geralmente é `172.17.0.2`. Em seguida, inclua isso na variável de ambiente `SERVER_NAME`: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > Certifique-se de substituir `172.17.0.3` pelo IP que será atribuído ao seu > contêiner. Agora você deve conseguir acessar `https://127.0.0.1` a partir da máquina host. Se este não for o caso, inicie o FrankenPHP em modo de depuração para tentar descobrir o problema: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Scripts do Composer que referenciam `@php` [Scripts do Composer](https://getcomposer.org/doc/articles/scripts.md) podem querer executar um binário PHP para algumas tarefas, por exemplo, em [um projeto Laravel](laravel.md) para executar `@php artisan package:discover --ansi`. Isso [atualmente falha](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) por dois motivos: - O Composer não sabe como chamar o binário do FrankenPHP; - O Composer pode adicionar configurações do PHP usando a flag `-d` no comando, que o FrankenPHP ainda não suporta. Como solução alternativa, podemos criar um script de shell em `/usr/local/bin/php` que remove os parâmetros não suportados e, em seguida, chama o FrankenPHP: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Em seguida, defina a variável de ambiente `PHP_BINARY` para o caminho do nosso script `php` e execute o Composer: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## Solução de problemas de TLS/SSL com binários estáticos Ao usar binários estáticos, você pode encontrar os seguintes erros relacionados a TLS, por exemplo, ao enviar emails usando STARTTLS: ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` Como o binário estático não empacota certificados TLS, você precisa apontar o OpenSSL para a instalação local de certificados de CA. Inspecione a saída de [`openssl_get_cert_locations()`](https://www.php.net/manual/pt_BR/function.openssl-get-cert-locations.php), para descobrir onde os certificados de CA devem ser instalados e armazene-os neste local. > [!WARNING] > > Contextos web e CLI podem ter configurações diferentes. > Certifique-se de executar `openssl_get_cert_locations()` no contexto > apropriado. [Certificados CA extraídos do Mozilla podem ser baixados no site do cURL](https://curl.se/docs/caextract.html). Como alternativa, muitas distribuições, incluindo Debian, Ubuntu e Alpine, fornecem pacotes chamados `ca-certificates` que contêm esses certificados. Também é possível usar `SSL_CERT_FILE` e `SSL_CERT_DIR` para indicar à OpenSSL onde procurar certificados CA: ```console # Define variáveis de ambiente para certificados TLS export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/pt-br/laravel.md ================================================ # Laravel ## Docker Servir uma aplicação web [Laravel](https://laravel.com) com FrankenPHP é tão fácil quanto montar o projeto no diretório `/app` da imagem Docker oficial. Execute este comando a partir do diretório principal da sua aplicação Laravel: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` E divirta-se! ## Instalação local Alternativamente, você pode executar seus projetos Laravel com FrankenPHP a partir da sua máquina local: 1. [Baixe o binário correspondente ao seu sistema](../#standalone-binary). 2. Adicione a seguinte configuração a um arquivo chamado `Caddyfile` no diretório raiz do seu projeto Laravel: ```caddyfile { frankenphp } # O nome de domínio do seu servidor localhost { # Define o diretório raiz como public/ root public/ # Habilita a compressão (opcional) encode zstd br gzip # Executa os arquivos PHP a partir do diretório public/ e serve os assets php_server { try_files {path} index.php } } ``` 3. Inicie o FrankenPHP a partir do diretório raiz do seu projeto Laravel: `frankenphp run`. ## Laravel Octane O Octane pode ser instalado através do gerenciador de pacotes Composer: ```console composer require laravel/octane ``` Após instalar o Octane, você pode executar o comando `octane:install` do Artisan, que instalará o arquivo de configuração do Octane em sua aplicação: ```console php artisan octane:install --server=frankenphp ``` O servidor Octane pode ser iniciado por meio do comando `octane:frankenphp` do Artisan. ```console php artisan octane:frankenphp ``` O comando `octane:frankenphp` pode receber as seguintes opções: - `--host`: O endereço IP ao qual o servidor deve se vincular (padrão: `127.0.0.1`); - `--port`: A porta na qual o servidor deve estar disponível (padrão: `8000`); - `--admin-port`: A porta na qual o servidor de administração deve estar disponível (padrão: `2019`); - `--workers`: O número de workers que devem estar disponíveis para processar requisições (padrão: `auto`); - `--max-requests`: O número de requisições a serem processadas antes de recarregar o servidor (padrão: `500`); - `--caddyfile`: O caminho para o arquivo `Caddyfile` do FrankenPHP (padrão: [stub do `Caddyfile` no Laravel Octane](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)); - `--https`: Habilita HTTPS, HTTP/2 e HTTP/3 e gera e renova certificados automaticamente; - `--http-redirect`: Habilita o redirecionamento de HTTP para HTTPS (somente - habilitado se `--https` for passada); - `--watch`: Recarrega o servidor automaticamente quando a aplicação é modificada; - `--poll`: Usa o polling do sistema de arquivos durante a verificação para monitorar arquivos em uma rede; - `--log-level`: Registra mensagens de log no nível de log especificado ou acima dele, usando o logger nativo do Caddy. > [!TIP] > Para obter logs JSON estruturados (útil ao usar soluções de análise de logs), > passe explicitamente a opção `--log-level`. Saiba mais sobre o [Laravel Octane em sua documentação oficial](https://laravel.com/docs/octane). ## Aplicações Laravel como binários independentes Usando o [recurso de incorporação de aplicações do FrankenPHP](embed.md), é possível distribuir aplicações Laravel como binários independentes. Siga estes passos para empacotar sua aplicação Laravel como um binário independente para Linux: 1. Crie um arquivo chamado `static-build.Dockerfile` no repositório da sua aplicação: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Se você pretende executar o binário em sistemas musl-libc, use o static-builder-musl # Copia sua aplicação WORKDIR /go/src/app/dist/app COPY . . # Remove os testes e outros arquivos desnecessários para economizar espaço # Como alternativa, adicione esses arquivos a um arquivo .dockerignore RUN rm -Rf tests/ # Copia o arquivo .env RUN cp .env.example .env # Altera APP_ENV e APP_DEBUG para que estejam prontas para produção RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Faça outras alterações no seu arquivo .env, se necessário # Instala as dependências RUN composer install --ignore-platform-reqs --no-dev -a # Compila o binário estático WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Alguns arquivos `.dockerignore` ignorarão o diretório `vendor/` e os > arquivos `.env`. > Certifique-se de ajustar ou remover o arquivo `.dockerignore` antes da > compilação. 2. Construa: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. Extraia o binário: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Popule os caches: ```console frankenphp php-cli artisan optimize ``` 5. Execute as migrações de banco de dados (se houver): ```console frankenphp php-cli artisan migrate ``` 6. Gere a chave secreta da aplicação: ```console frankenphp php-cli artisan key:generate ``` 7. Inicie o servidor: ```console frankenphp php-server ``` Agora sua aplicação está pronta! Saiba mais sobre as opções disponíveis e como compilar binários para outros sistemas operacionais na documentação de [incorporação de aplicações](embed.md). ### Alterando o caminho do armazenamento Por padrão, o Laravel armazena arquivos enviados, caches, logs, etc., no diretório `storage/` da aplicação. Isso não é adequado para aplicações embarcadas, pois cada nova versão será extraída para um diretório temporário diferente. Defina a variável de ambiente `LARAVEL_STORAGE_PATH` (por exemplo, no seu arquivo `.env`) ou chame o método `Illuminate\Foundation\Application::useStoragePath()` para usar um diretório fora do diretório temporário. ### Executando o Octane com binários independentes É possível até empacotar aplicações Octane do Laravel como binários independentes! Para fazer isso, [instale o Octane corretamente](#laravel-octane) e siga os passos descritos na [seção anterior](#aplicações-laravel-como-binários-independentes). Em seguida, para iniciar o FrankenPHP no modo worker através do Octane, execute: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > > Para que o comando funcione, o binário independente **deve** ser nomeado > `frankenphp` porque o Octane precisa de um programa chamado `frankenphp` > disponível no caminho. ================================================ FILE: docs/pt-br/mercure.md ================================================ # Tempo real O FrankenPHP vem com um hub [Mercure](https://mercure.rocks) integrado! O Mercure permite que você envie eventos em tempo real para todos os dispositivos conectados: eles receberão um evento JavaScript instantaneamente. Não é necessária nenhuma biblioteca JS ou SDK! ![Mercure](mercure-hub.png) Para habilitar o hub Mercure, atualize o `Caddyfile` conforme descrito [no site do Mercure](https://mercure.rocks/docs/hub/config). O caminho do hub Mercure é `/.well-known/mercure`. Ao executar o FrankenPHP dentro do Docker, a URL de envio completa seria `http://php/.well-known/mercure` (com `php` sendo o nome do contêiner que executa o FrankenPHP). Para enviar atualizações do Mercure a partir do seu código, recomendamos o [Componente Symfony Mercure](https://symfony.com/components/Mercure) (você não precisa do framework full-stack do Symfony para usá-lo). ================================================ FILE: docs/pt-br/metrics.md ================================================ # Métricas Quando as [métricas do Caddy](https://caddyserver.com/docs/metrics) estão habilitadas, o FrankenPHP expõe as seguintes métricas: - `frankenphp_total_threads`: O número total de threads PHP. - `frankenphp_busy_threads`: O número de threads PHP processando uma requisição no momento (workers em execução sempre consomem uma thread). - `frankenphp_queue_depth`: O número de requisições regulares na fila. - `frankenphp_total_workers{worker="[nome_do_worker]"}`: O número total de workers. - `frankenphp_busy_workers{worker="[nome_do_worker]"}`: O número de workers processando uma requisição no momento. - `frankenphp_worker_request_time{worker="[nome_do_worker]"}`: O tempo gasto no processamento de requisições por todos os workers. - `frankenphp_worker_request_count{worker="[nome_do_worker]"}`: O número de requisições processadas por todos os workers. - `frankenphp_ready_workers{worker="[nome_do_worker]"}`: O número de workers que chamaram `frankenphp_handle_request` pelo menos uma vez. - `frankenphp_worker_crashes{worker="[nome_do_worker]"}`: O número de vezes que um worker foi encerrado inesperadamente. - `frankenphp_worker_restarts{worker="[nome_do_worker]"}`: O número de vezes que um worker foi reiniciado deliberadamente. - `frankenphp_worker_queue_depth{worker="[nome_do_worker]"}`: O número de requisições na fila. Para métricas de worker, o placeholder `[nome_do_worker]` é substituído pelo nome do worker no Caddyfile; caso contrário, o caminho absoluto do arquivo do worker será usado. ================================================ FILE: docs/pt-br/performance.md ================================================ # Desempenho Por padrão, o FrankenPHP tenta oferecer um bom equilíbrio entre desempenho e facilidade de uso. No entanto, é possível melhorar substancialmente o desempenho usando uma configuração apropriada. ## Número de Threads e Workers Por padrão, o FrankenPHP inicia 2 vezes mais threads e workers (no modo worker) do que o número de núcleos de CPU disponíveis. Os valores apropriados dependem muito de como sua aplicação foi escrita, do que ela faz e do seu hardware. Recomendamos fortemente alterar esses valores. Para melhor estabilidade do sistema, recomenda-se ter `num_threads` x `memory_limit` < `available_memory`. Para encontrar os valores corretos, é melhor executar testes de carga simulando tráfego real. [k6](https://k6.io) e [Gatling](https://gatling.io) são boas ferramentas para isso. Para configurar o número de threads, use a opção `num_threads` das diretivas `php_server` e `php`. Para alterar o número de workers, use a opção `num` da seção `worker` da diretiva `frankenphp`. ### `max_threads` Embora seja sempre melhor saber exatamente como será o seu tráfego, aplicações reais tendem a ser mais imprevisíveis. A [configuração](config.md#configuracao-do-caddyfile) `max_threads` permite que o FrankenPHP crie threads adicionais automaticamente em tempo de execução até o limite especificado. `max_threads` pode ajudar você a descobrir quantas threads são necessárias para lidar com seu tráfego e pode tornar o servidor mais resiliente a picos de latência. Se definido como `auto`, o limite será estimado com base no `memory_limit` em seu `php.ini`. Se não for possível fazer isso, `auto` assumirá como padrão 2x `num_threads`. Lembre-se de que `auto` pode subestimar bastante o número de threads necessárias. `max_threads` é semelhante ao [pm.max_children](https://www.php.net/manual/pt_BR/install.fpm.configuration.php#pm.max-children) do PHP FPM. A principal diferença é que o FrankenPHP usa threads em vez de processos e as delega automaticamente entre diferentes worker scripts e o 'classic mode', conforme necessário. ## Modo worker Habilitar [o modo worker](worker.md) melhora drasticamente o desempenho, mas sua aplicação precisa ser adaptada para ser compatível com este modo: você precisa criar um worker script e garantir que a aplicação não esteja com vazamento de memória. ## Não use musl A variante Alpine Linux das imagens oficiais do Docker e os binários padrão que fornecemos usam [a biblioteca C musl](https://musl.libc.org). O PHP é conhecido por ser [mais lento](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) ao usar esta biblioteca C alternativa em vez da biblioteca GNU tradicional, especialmente quando compilado no modo ZTS (thread-safe), necessário para o FrankenPHP. A diferença pode ser significativa em um ambiente com muitas threads. Além disso, [alguns bugs só acontecem ao usar musl](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). Em ambientes de produção, recomendamos o uso do FrankenPHP vinculado à glibc, compilado com um nível de otimização apropriado. Isso pode ser feito usando as imagens Docker do Debian, usando [nossos pacotes .deb, .rpm ou .apk dos mantenedores](https://pkgs.henderkes.com), ou [compilando o FrankenPHP a partir do código-fonte](compile.md). Para contêineres mais leves ou seguros, você pode considerar [uma imagem Debian reforçada](docker.md#hardening-images) em vez de Alpine. ## Configuração do runtime do Go O FrankenPHP é escrito em Go. Em geral, o runtime do Go não requer nenhuma configuração especial, mas em certas circunstâncias, configurações específicas melhoram o desempenho. Você provavelmente deseja definir a variável de ambiente `GODEBUG` como `cgocheck=0` (o padrão nas imagens Docker do FrankenPHP). Se você executa o FrankenPHP em contêineres (Docker, Kubernetes, LXC...) e limita a memória disponível para os contêineres, defina a variável de ambiente `GOMEMLIMIT` para a quantidade de memória disponível. Para mais detalhes, [a página da documentação do Go dedicada a este assunto](https://pkg.go.dev/runtime#hdr-Environment_Variables) é uma leitura obrigatória para aproveitar ao máximo o runtime. ## `file_server` Por padrão, a diretiva `php_server` configura automaticamente um servidor de arquivos para servir arquivos estáticos (assets) armazenados no diretório raiz. Este recurso é conveniente, mas tem um custo. Para desativá-lo, use a seguinte configuração: ```caddyfile php_server { file_server off } ``` ## `try_files` Além de arquivos estáticos e arquivos PHP, `php_server` também tentará servir o arquivo de índice da sua aplicação e os arquivos de índice de diretório (`/path/` -> `/path/index.php`). Se você não precisa de arquivos de índice de diretório, pode desativá-los definindo explicitamente `try_files` assim: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # adicionar explicitamente o root aqui permite um melhor cache } ``` Isso pode reduzir significativamente o número de operações desnecessárias com arquivos. Um equivalente no modo worker da configuração anterior seria: ```caddyfile route { php_server { # use "php" em vez de "php_server" se você não precisar do servidor de arquivos root /root/to/your/app worker /path/to/worker.php { match * # envia todas as requisições diretamente para o worker } } } ``` Uma abordagem alternativa com 0 operações desnecessárias no sistema de arquivos seria usar a diretiva `php` e dividir os arquivos estáticos dos arquivos PHP por caminho. Essa abordagem funciona bem se toda a sua aplicação for servida por um arquivo de entrada. Um exemplo de [configuração](config.md#configuracao-do-caddyfile) que serve arquivos estáticos atrás de uma pasta `/assets` poderia ser assim: ```caddyfile route { @assets { path /assets/* } # tudo o que está em /assets é gerenciado pelo servidor de arquivos file_server @assets { root /root/to/your/app } # tudo o que não está em /assets é gerenciado pelo seu arquivo de índice ou worker PHP rewrite index.php php { root /root/to/your/app # adicionar explicitamente o root aqui permite um melhor cache } } ``` ## Placeholders Você pode usar [placeholders](https://caddyserver.com/docs/conventions#placeholders) nas diretivas `root` e `env`. No entanto, isso impede o armazenamento em cache desses valores e acarreta um custo significativo de desempenho. Se possível, evite placeholders nessas diretivas. ## `resolve_root_symlink` Por padrão, se o diretório raiz for um link simbólico, ele será resolvido automaticamente pelo FrankenPHP (isso é necessário para o funcionamento correto do PHP). Se o diretório raiz não for um link simbólico, você pode desativar esse recurso. ```caddyfile php_server { resolve_root_symlink false } ``` Isso melhorará o desempenho se a diretiva `root` contiver [placeholders](https://caddyserver.com/docs/conventions#placeholders). O ganho será insignificante em outros casos. ## Logs O logging é obviamente muito útil, mas, por definição, requer operações de E/S e alocações de memória, o que reduz consideravelmente o desempenho. Certifique-se de [definir o nível de logging](https://caddyserver.com/docs/caddyfile/options#log) corretamente e registrar em log apenas o necessário. ## Desempenho do PHP O FrankenPHP usa o interpretador PHP oficial. Todas as otimizações de desempenho usuais relacionadas ao PHP se aplicam ao FrankenPHP. Em particular: - Verifique se o [OPcache](https://www.php.net/manual/pt_BR/book.opcache.php) está instalado, habilitado e configurado corretamente; - Habilite as [otimizações do carregador automático do Composer](https://getcomposer.org/doc/articles/autoloader-optimization.md); - Certifique-se de que o cache do `realpath` seja grande o suficiente para as necessidades da sua aplicação; - Use [pré-carregamento](https://www.php.net/manual/pt_BR/opcache.preloading.php). Para mais detalhes, leia [a entrada dedicada na documentação do Symfony](https://symfony.com/doc/current/performance.html) (a maioria das dicas é útil mesmo se você não usa o Symfony). ## Dividindo o Pool de Threads É comum que aplicações interajam com serviços externos lentos, como uma API que tende a ser instável sob alta carga ou que consistentemente leva mais de 10 segundos para responder. Nesses casos, pode ser benéfico dividir o pool de threads para ter pools "lentos" dedicados. Isso impede que os endpoints lentos consumam todos os recursos/threads do servidor e limita a concorrência de requisições direcionadas ao endpoint lento, semelhante a um pool de conexões. ```caddyfile example.com { php_server { root /app/public # a raiz da sua aplicação worker index.php { match /slow-endpoint/* # todas as requisições com caminho /slow-endpoint/* são tratadas por este pool de threads num 1 # mínimo de 1 thread para requisições que correspondem a /slow-endpoint/* max_threads 20 # permite até 20 threads para requisições que correspondem a /slow-endpoint/*, se necessário } worker index.php { match * # todas as outras requisições são tratadas separadamente num 1 # mínimo de 1 thread para outras requisições, mesmo que os endpoints lentos comecem a travar max_threads 20 # permite até 20 threads para outras requisições, se necessário } } } ``` Geralmente, também é aconselhável lidar com endpoints muito lentos de forma assíncrona, usando mecanismos relevantes como filas de mensagens. ================================================ FILE: docs/pt-br/production.md ================================================ # Implantando em produção Neste tutorial, aprenderemos como implantar uma aplicação PHP em um único servidor usando o Docker Compose. Se você estiver usando o Symfony, leia a documentação [Implantar em produção](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md) do projeto Docker do Symfony (que usa FrankenPHP). Se você estiver usando a API Platform (que também usa FrankenPHP), consulte [a documentação de implantação do framework](https://api-platform.com/docs/deployment/). ## Preparando sua aplicação Primeiro, crie um `Dockerfile` no diretório raiz do seu projeto PHP: ```dockerfile FROM dunglas/frankenphp # Certifique-se de substituir "seu-nome-de-dominio.example.com" pelo seu nome de # domínio ENV SERVER_NAME=seu-nome-de-dominio.example.com # Se quiser desabilitar o HTTPS, use este valor: #ENV SERVER_NAME=:80 # Se o seu projeto não estiver usando o diretório "public" como diretório raiz, # você pode defini-lo aqui: # ENV SERVER_ROOT=web/ # Habilita as configurações de produção do PHP RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Copia os arquivos PHP do seu projeto para o diretório public COPY . /app/public # Se você usa Symfony ou Laravel, precisa copiar o projeto inteiro: #COPY . /app ``` Consulte [Construindo uma imagem Docker personalizada](docker.md) para mais detalhes e opções, e para aprender como personalizar a configuração, instalar extensões PHP e módulos Caddy. Se o seu projeto usa o Composer, certifique-se de incluí-lo na imagem Docker e instalar suas dependências. Em seguida, adicione um arquivo `compose.yaml`: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Volumes necessários para certificados e configuração do Caddy volumes: caddy_data: caddy_config: ``` > [!NOTE] > > Os exemplos anteriores são destinados ao uso em produção. > Em desenvolvimento, você pode querer usar um volume, uma configuração PHP > diferente e um valor diferente para a variável de ambiente `SERVER_NAME`. > > Consulte o projeto [Symfony Docker](https://github.com/dunglas/symfony-docker) > (que usa FrankenPHP) para um exemplo mais avançado usando imagens > multiestágio, Composer, extensões PHP extras, etc. Finalmente, se você usa Git, faça o commit e o push desses arquivos. ## Preparando um servidor Para implantar sua aplicação em produção, você precisa de um servidor. Neste tutorial, usaremos uma máquina virtual fornecida pela DigitalOcean, mas qualquer servidor Linux pode ser usado. Se você já possui um servidor Linux com o Docker instalado, pode pular direto para [a próxima seção](#configurando-um-nome-de-domínio). Caso contrário, use [este link de afiliado](https://m.do.co/c/5d8aabe3ab80) para obter US$ 200 em créditos gratuitos, crie uma conta e clique em "Create a Droplet". Em seguida, clique na aba "Marketplace" na seção "Choose an image" e procure a aplicação "Docker". Isso provisionará um servidor Ubuntu com as versões mais recentes do Docker e do Docker Compose já instaladas! Para fins de teste, os planos mais baratos serão suficientes. Para uso real em produção, você provavelmente escolherá um plano na seção "General Purpose" que atenda às suas necessidades. ![Implantando o FrankenPHP na DigitalOcean com Docker](digitalocean-droplet.png) Você pode manter os padrões para outras configurações ou ajustá-los de acordo com suas necessidades. Não se esqueça de adicionar sua chave SSH ou criar uma senha e, em seguida, clicar no botão "Finalize and create". Em seguida, aguarde alguns segundos enquanto seu Droplet é provisionado. Quando seu Droplet estiver pronto, use SSH para se conectar: ```console ssh root@ ``` ## Configurando um nome de domínio Na maioria dos casos, você precisará associar um nome de domínio ao seu site. Se você ainda não possui um nome de domínio, precisará comprar um por meio de um registrar. Em seguida, crie um registro DNS do tipo `A` para o seu nome de domínio, apontando para o endereço IP do seu servidor: ```dns seu-nome-de-dominio.example.com. IN A ``` Exemplo com o serviço DigitalOcean Domains ("Networking" > "Domains"): ![Configurando DNS na DigitalOcean](digitalocean-dns.png) > [!NOTE] > > O Let's Encrypt, o serviço usado por padrão pelo FrankenPHP para gerar > automaticamente um certificado TLS, não suporta o uso de endereços IP. > O uso de um nome de domínio é obrigatório para usar o Let's Encrypt. ## Implantando Copie seu projeto para o servidor usando `git clone`, `scp` ou qualquer outra ferramenta que atenda às suas necessidades. Se você usa o GitHub, pode ser útil usar [uma chave de implantação](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys). Chaves de implantação também são [suportadas pelo GitLab](https://docs.gitlab.com/ee/user/project/deploy_keys/). Exemplo com Git: ```console git clone git@github.com:/.git ``` Acesse o diretório que contém seu projeto (``) e inicie a aplicação em modo de produção: ```console docker compose up --wait ``` Seu servidor está funcionando e um certificado HTTPS foi gerado automaticamente para você. Acesse `https://seu-nome-de-dominio.example.com` e divirta-se! > [!CAUTION] > > O Docker pode ter uma camada de cache; certifique-se de ter a construção > correta para cada implantação ou reconstrua seu projeto com a opção > `--no-cache` para evitar problemas de cache. ## Implantando em múltiplos nós Se você deseja implantar sua aplicação em um cluster de máquinas, pode usar o [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), que é compatível com os arquivos Compose fornecidos. Para implantar no Kubernetes, consulte o [chart do Helm fornecido com a API Platform](https://api-platform.com/docs/deployment/kubernetes/), que usa FrankenPHP. ================================================ FILE: docs/pt-br/static.md ================================================ # Criar uma compilação estática Em vez de usar uma instalação local da biblioteca PHP, é possível criar uma compilação estática ou principalmente estática do FrankenPHP graças ao excelente [projeto static-php-cli](https://github.com/crazywhalecc/static-php-cli) (apesar do nome, este projeto suporta todas as SAPIs, não apenas CLI). Com este método, um único binário portátil conterá o interpretador PHP, o servidor web Caddy e o FrankenPHP! Executáveis nativos totalmente estáticos não requerem dependências e podem até ser executados na [imagem Docker `scratch`](https://docs.docker.com/build/building/base-images/#create-a-minimal-base-image-using-scratch). No entanto, eles não podem carregar extensões PHP dinâmicas (como o Xdebug) e têm algumas limitações por usarem a `libc` `musl`. A maioria dos binários estáticos requer apenas `glibc` e pode carregar extensões dinâmicas. Sempre que possível, recomendamos o uso de compilações principalmente estáticas baseadas na `glibc`. O FrankenPHP também suporta [a incorporação da aplicação PHP no binário estático](embed.md). ## Linux Fornecemos imagens Docker para compilar binários estáticos para Linux: ### Compilação totalmente estática baseada na `musl` Para um binário totalmente estático que roda em qualquer distribuição Linux sem dependências, mas não suporta carregamento dinâmico de extensões: ```console docker buildx bake --load static-builder-musl docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-musl ``` Para melhor desempenho em cenários com alta concorrência, considere usar o alocador [`mimalloc`](https://github.com/microsoft/mimalloc). ```console docker buildx bake --load --set static-builder-musl.args.MIMALLOC=1 static-builder-musl ``` ### Compilação principalmente estática baseada na `glibc` (com suporte a extensões dinâmicas) Para um binário que suporta o carregamento dinâmico de extensões PHP, mantendo as extensões selecionadas compiladas estaticamente: ```console docker buildx bake --load static-builder-gnu docker cp $(docker create --name static-builder-gnu dunglas/frankenphp:static-builder-gnu):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder-gnu ``` Este binário suporta todas as versões 2.17 e superiores da `glibc`, mas não roda em sistemas baseados em `musl` (como o Alpine Linux). O binário principalmente estático (exceto a `glibc`) resultante é chamado `frankenphp` e está disponível no diretório atual. Se você quiser compilar o binário estático sem o Docker, consulte as instruções para macOS, que também funcionam para Linux. ### Extensões personalizadas Por padrão, as extensões PHP mais populares são compiladas. Para reduzir o tamanho do binário e a superfície de ataque, você pode escolher a lista de extensões a serem compiladas usando o `ARG` `PHP_EXTENSIONS` do Docker. Por exemplo, execute o seguinte comando para compilar apenas a extensão `opcache`: ```console docker buildx bake --load --set static-builder-musl.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder-musl # ... ``` Para adicionar bibliotecas que habilitem funcionalidades adicionais às extensões habilitadas, você pode passar o `ARG` `PHP_EXTENSION_LIBS` do Docker: ```console docker buildx bake \ --load \ --set static-builder-musl.args.PHP_EXTENSIONS=gd \ --set static-builder-musl.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder-musl ``` ### Módulos Caddy extras Para adicionar módulos Caddy extras ou passar outros argumentos para o [`xcaddy`](https://github.com/caddyserver/xcaddy), use o `ARG` `XCADDY_ARGS` do Docker: ```console docker buildx bake \ --load \ --set static-builder-musl.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder-musl ``` Neste exemplo, adicionamos o módulo de cache HTTP [Souin](https://souin.io) para o Caddy, bem como os módulos [cbrotli](https://github.com/dunglas/caddy-cbrotli), [Mercure](https://mercure.rocks) e [Vulcain](https://vulcain.rocks). > [!TIP] > > Os módulos cbrotli, Mercure e Vulcain são incluídos por padrão se > `XCADDY_ARGS` estiver vazio ou não definido. > Se você personalizar o valor de `XCADDY_ARGS`, deverá incluí-los > explicitamente se desejar que sejam incluídos. Veja também como [personalizar a compilação](#personalizando-a-compilação). ### Token do GitHub Se você atingir o limite de taxa da API do GitHub, defina um Token de Acesso Pessoal do GitHub em uma variável de ambiente chamada `GITHUB_TOKEN`: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS Execute o seguinte script para criar um binário estático para macOS (você precisa ter o [Homebrew](https://brew.sh/) instalado): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Observação: este script também funciona no Linux (e provavelmente em outros sistemas Unix) e é usado internamente pelas imagens Docker que fornecemos. ## Personalizando a compilação As seguintes variáveis de ambiente podem ser passadas para `docker build` e para o script `build-static.sh` para personalizar a compilação estática: - `FRANKENPHP_VERSION`: a versão do FrankenPHP a ser usada; - `PHP_VERSION`: a versão do PHP a ser usada; - `PHP_EXTENSIONS`: as extensões PHP a serem compiladas ([lista de extensões suportadas](https://static-php.dev/en/guide/extensions.html)); - `PHP_EXTENSION_LIBS`: bibliotecas extras a serem compiladas que adicionam recursos às extensões; - `XCADDY_ARGS`: argumentos a passar para o [`xcaddy`](https://github.com/caddyserver/xcaddy), por exemplo, para adicionar módulos Caddy extras; - `EMBED`: caminho da aplicação PHP a ser incorporada no binário; - `CLEAN`: quando definida, a `libphp` e todas as suas dependências são compiladas do zero (sem cache); - `NO_COMPRESS`: não compacta o binário resultante usando UPX; - `DEBUG_SYMBOLS`: quando definida, os símbolos de depuração não serão removidos e serão adicionados ao binário; - `MIMALLOC`: (experimental, somente Linux) substitui `mallocng` da `musl` por [`mimalloc`](https://github.com/microsoft/mimalloc) para melhor desempenho. Recomendamos usar isso apenas para compilações direcionadas à `musl`; para `glibc`, prefira desabilitar essa opção e usar [`LD_PRELOAD`](https://microsoft.github.io/mimalloc/overrides.html) ao executar seu binário; - `RELEASE`: (somente pessoas mantenedoras) quando definida, o binário resultante será enviado para o GitHub. ## Extensões Com os binários baseados na `glibc` ou no macOS, você pode carregar extensões PHP dinamicamente. No entanto, essas extensões precisarão ser compiladas com suporte a ZTS. Como a maioria dos gerenciadores de pacotes não oferece atualmente versões ZTS de suas extensões, você terá que compilá-las você mesmo. Para isso, você pode compilar e executar o contêiner Docker `static-builder-gnu`, acessá-lo remotamente e compilar as extensões com `./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config`. Passos de exemplo para [a extensão Xdebug](https://xdebug.org): ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` Isso criará `frankenphp` e `xdebug-zts.so` no diretório atual. Se você mover `xdebug-zts.so` para o diretório de extensões, adicione `zend_extension=xdebug-zts.so` ao seu `php.ini` e execute o FrankenPHP, ele carregará o Xdebug. ================================================ FILE: docs/pt-br/worker.md ================================================ # Usando Workers do FrankenPHP Inicialize sua aplicação uma vez e mantenha-a na memória. O FrankenPHP processará as requisições recebidas em poucos milissegundos. ## Iniciando Worker Scripts ### Docker Defina o valor da variável de ambiente `FRANKENPHP_CONFIG` como `worker /path/to/your/worker/script.php`: ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Binário independente Use a opção `--worker` do comando `php-server` para servir o conteúdo do diretório atual usando um worker: ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` Se a sua aplicação PHP estiver [embutida no binário](embed.md), você pode adicionar um `Caddyfile` personalizado no diretório raiz da aplicação. Ele será usado automaticamente. Também é possível [reiniciar o worker em caso de alterações em arquivos](config.md#watching-for-file-changes) com a opção `--watch`. O comando a seguir acionará uma reinicialização se qualquer arquivo terminado em `.php` no diretório `/path/to/your/app/` ou subdiretórios for modificado: ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` Este recurso é frequentemente usado em combinação com [hot reloading](hot-reload.md). ## Symfony Runtime > [!TIP] > A seção a seguir é necessária apenas antes do Symfony 7.4, onde o suporte nativo para o modo worker do FrankenPHP foi introduzido. O modo worker do FrankenPHP é suportado pelo [Componente Symfony Runtime](https://symfony.com/doc/current/components/runtime.html). Para iniciar qualquer aplicação Symfony em um worker, instale o pacote FrankenPHP do [PHP Runtime](https://github.com/php-runtime/runtime): ```console composer require runtime/frankenphp-symfony ``` Inicie seu servidor de aplicações definindo a variável de ambiente `APP_RUNTIME` para usar o Symfony Runtime do FrankenPHP: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane Consulte [a documentação dedicada](laravel.md#laravel-octane). ## Aplicações personalizadas O exemplo a seguir mostra como criar seu próprio worker script sem depender de uma biblioteca de terceiros: ```php boot(); // Manipulador fora do loop para melhor desempenho (fazendo menos trabalho) $handler = static function () use ($myApp) { try { // Chamado quando uma requisição é recebida, // superglobais, php://input e similares são redefinidos echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` é chamado apenas quando o worker script termina, // o que pode não ser o que você espera, então capture e trate exceções aqui (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // Faz algo depois de enviar a resposta HTTP $myApp->terminate(); // Chama o coletor de lixo para reduzir as chances de ele ser acionado no meio da geração de uma página gc_collect_cycles(); if (!$keepRunning) break; } // Limpeza $myApp->shutdown(); ``` Em seguida, inicie sua aplicação e use a variável de ambiente `FRANKENPHP_CONFIG` para configurar seu worker: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Por padrão, são iniciados 2 workers por CPU. Você também pode configurar o número de workers a serem iniciados: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Reiniciar o Worker Após um Certo Número de Requisições Como o PHP não foi originalmente projetado para processos de longa duração, ainda existem muitas bibliotecas e códigos legados que vazam memória. Uma solução alternativa para usar esse tipo de código no modo worker é reiniciar o worker script após processar um certo número de requisições: O trecho de código de worker anterior permite configurar um número máximo de requisições a serem processadas, definindo uma variável de ambiente chamada `MAX_REQUESTS`. ### Reiniciar os Workers Manualmente Embora seja possível reiniciar os workers [em alterações de arquivo](config.md#watching-for-file-changes), também é possível reiniciar todos os workers graciosamente por meio da [API de administração do Caddy](https://caddyserver.com/docs/api). Se o administrador estiver habilitado no seu [Caddyfile](config.md#caddyfile-config), você pode acionar o endpoint de reinicialização com uma simples requisição POST como esta: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Falhas de Worker Se um worker script travar com um código de saída diferente de zero, o FrankenPHP o reiniciará com uma estratégia de backoff exponencial. Se o worker script permanecer ativo por mais tempo do que o último backoff \* 2, ele não irá penalizar o worker script e reiniciá-lo novamente. No entanto, se o worker script continuar a falhar com um código de saída diferente de zero em um curto período de tempo (por exemplo, com um erro de digitação em um script), o FrankenPHP travará com o erro: `too many consecutive failures`. O número de falhas consecutivas pode ser configurado no seu [Caddyfile](config.md#caddyfile-config) com a opção `max_consecutive_failures`: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Comportamento das Superglobais As [superglobais do PHP](https://www.php.net/manual/pt_BR/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) se comportam da seguinte maneira: - antes da primeira chamada para `frankenphp_handle_request()`, as superglobais contêm valores vinculados ao próprio worker script. - durante e após a chamada para `frankenphp_handle_request()`, as superglobais contêm valores gerados a partir da requisição HTTP processada. Cada chamada para `frankenphp_handle_request()` altera os valores das superglobais. Para acessar as superglobais do worker script dentro do retorno de chamada, você deve copiá-las e importar a cópia para o escopo do retorno de chamada: ```php > "$GITHUB_ENV" + - + run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - + uses: mxschmitt/action-tmate@v3 ``` 4. Подключитесь к контейнеру. 5. Откройте файл `frankenphp.go`. 6. Включите `cgosymbolizer`: ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Загрузите модуль: `go get`. 8. В контейнере используйте GDB и другие инструменты: ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. После исправления ошибки откатите все внесенные изменения. ## Дополнительные ресурсы для разработки - [Встраивание PHP в uWSGI](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [Встраивание PHP в NGINX Unit](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [Встраивание PHP в Go (go-php)](https://github.com/deuill/go-php) - [Встраивание PHP в Go (GoEmPHP)](https://github.com/mikespook/goemphp) - [Встраивание PHP в C++](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Книга "Extending and Embedding PHP" Сары Големан](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [Статья: Что такое TSRMLS_CC?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [SDL bindings](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Docker-ресурсы - [Определение файлов bake](https://docs.docker.com/build/customize/bake/file-definition/) - [Документация по команде `docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Полезные команды ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ## Перевод документации Чтобы перевести документацию и сайт на новый язык, выполните следующие шаги: 1. Создайте новую директорию с 2-буквенным ISO-кодом языка в папке `docs/`. 2. Скопируйте все `.md` файлы из корня папки `docs/` в новую директорию (используйте английскую версию как основу для перевода). 3. Скопируйте файлы `README.md` и `CONTRIBUTING.md` из корневой директории в новую папку. 4. Переведите содержимое файлов, но не изменяйте имена файлов. Не переводите строки, начинающиеся с `> [!`, это специальная разметка GitHub. 5. Создайте Pull Request с переводом. 6. В [репозитории сайта](https://github.com/dunglas/frankenphp-website/tree/main) скопируйте и переведите файлы в папках `content/`, `data/` и `i18n/`. 7. Переведите значения в созданных YAML-файлах. 8. Откройте Pull Request в репозитории сайта. ================================================ FILE: docs/ru/README.md ================================================ # FrankenPHP: Современный сервер приложений для PHP

FrankenPHP

**FrankenPHP** — это современный сервер приложений для PHP, построенный на базе веб-сервера [Caddy](https://caddyserver.com/). FrankenPHP добавляет новые возможности вашим PHP-приложениям благодаря следующим функциям: [_Early Hints_](https://frankenphp.dev/docs/early-hints/), [Worker режим](https://frankenphp.dev/docs/worker/), [Real-time режим](https://frankenphp.dev/docs/mercure/), автоматическая поддержка HTTPS, HTTP/2 и HTTP/3. FrankenPHP совместим с любыми PHP-приложениями и значительно ускоряет ваши проекты на Laravel и Symfony благодаря их официальной поддержке в worker режиме. FrankenPHP также может использоваться как автономная Go-библиотека для встраивания PHP в любое приложение с использованием `net/http`. [**Узнайте больше** на сайте _frankenphp.dev_](https://frankenphp.dev) или из этой презентации: Slides ## Начало работы В Windows используйте [WSL](https://learn.microsoft.com/windows/wsl/) для запуска FrankenPHP. ### Скрипт установки Скопируйте и выполните эту команду в терминале, чтобы автоматически установить подходящую версию для вашей платформы: ```console curl https://frankenphp.dev/install.sh | sh ``` ### Автономный бинарный файл Если вы предпочитаете не использовать Docker, мы предоставляем автономные статические бинарные файлы FrankenPHP для Linux и macOS, включающие [PHP 8.4](https://www.php.net/releases/8.4/en.php) и большинство популярных PHP‑расширений. [Скачать FrankenPHP](https://github.com/php/frankenphp/releases) **Установка расширений:** Наиболее распространенные расширения уже включены. Устанавливать дополнительные расширения невозможно. ### Пакеты rpm Наши мейнтейнеры предлагают rpm‑пакеты для всех систем с `dnf`. Для установки выполните: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # доступны 8.2–8.5 sudo dnf install frankenphp ``` **Установка расширений:** `sudo dnf install php-zts-` Для расширений, недоступных по умолчанию, используйте [PIE](https://github.com/php/pie): ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Пакеты deb Наши мейнтейнеры предлагают deb‑пакеты для всех систем с `apt`. Для установки выполните: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **Установка расширений:** `sudo apt install php-zts-` Для расширений, недоступных по умолчанию, используйте [PIE](https://github.com/php/pie): ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker ```console docker run -v .:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Перейдите по адресу `https://localhost` и наслаждайтесь! > [!TIP] > > Не используйте `https://127.0.0.1`. Используйте `https://localhost` и настройте самоподписанный сертификат. > Чтобы изменить используемый домен, настройте переменную окружения [`SERVER_NAME`](config.md#переменные-окружения). ### Homebrew FrankenPHP также доступен как пакет [Homebrew](https://brew.sh) для macOS и Linux. ```console brew install dunglas/frankenphp/frankenphp ``` **Установка расширений:** Используйте [PIE](https://github.com/php/pie). ### Использование Для запуска содержимого текущего каталога выполните: ```console frankenphp php-server ``` Также можно запускать CLI‑скрипты: ```console frankenphp php-cli /path/to/your/script.php ``` Для пакетов deb и rpm можно запустить сервис systemd: ```console sudo systemctl start frankenphp ``` ## Документация - [Worker режим](https://frankenphp.dev/docs/worker/) - [Поддержка Early Hints (103 HTTP статус код)](https://frankenphp.dev/docs/early-hints/) - [Real-time режим](https://frankenphp.dev/docs/mercure/) - [Конфигурация](https://frankenphp.dev/docs/config/) - [Docker-образы](https://frankenphp.dev/docs/docker/) - [Деплой в продакшен](https://frankenphp.dev/docs/production/) - [Оптимизация производительности](https://frankenphp.dev/docs/performance/) - [Создание автономного PHP-приложений](https://frankenphp.dev/docs/embed/) - [Создание статических бинарных файлов](https://frankenphp.dev/docs/static/) - [Компиляция из исходников](https://frankenphp.dev/docs/compile/) - [Интеграция с Laravel](https://frankenphp.dev/docs/laravel/) - [Известные проблемы](https://frankenphp.dev/docs/known-issues/) - [Демо-приложение (Symfony) и бенчмарки](https://github.com/dunglas/frankenphp-demo) - [Документация Go-библиотеки](https://pkg.go.dev/github.com/dunglas/frankenphp) - [Участие в проекте и отладка](https://frankenphp.dev/docs/contributing/) ## Примеры и шаблоны - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/symfony) - [Laravel](https://frankenphp.dev/docs/laravel/) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) ================================================ FILE: docs/ru/compile.md ================================================ # Компиляция из исходников Этот документ объясняет, как создать бинарный файл FrankenPHP, который будет загружать PHP как динамическую библиотеку. Это рекомендуемый способ. Альтернативно можно создать [статическую сборку](static.md). ## Установка PHP FrankenPHP совместим с PHP версии 8.2 и выше. Сначала [загрузите исходники PHP](https://www.php.net/downloads.php) и распакуйте их: ```console tar xf php-* cd php-*/ ``` Далее выполните скрипт `configure` с параметрами, необходимыми для вашей платформы. Следующие флаги `./configure` обязательны, но вы можете добавить и другие, например, для компиляции расширений или дополнительных функций. ### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` ### Mac Используйте пакетный менеджер [Homebrew](https://brew.sh/) для установки `libiconv`, `bison`, `re2c` и `pkg-config`: ```console brew install libiconv bison brotli re2c pkg-config echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` Затем выполните скрипт configure: ```console ./configure \ --enable-embed=static \ --enable-zts \ --disable-zend-signals \ --disable-opcache-jit \ --enable-static \ --enable-shared=no \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` ## Компиляция PHP Наконец, скомпилируйте и установите PHP: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Установка дополнительных зависимостей Некоторые функции FrankenPHP зависят от опциональных системных зависимостей. Альтернативно, эти функции можно отключить, передав соответствующие теги сборки компилятору Go. | Функция | Зависимость | Тег сборки для отключения | | ----------------------------------------------- | --------------------------------------------------------------------- | ------------------------- | | Сжатие Brotli | [Brotli](https://github.com/google/brotli) | nobrotli | | Перезапуск worker-скриптов при изменении файлов | [Watcher C](https://github.com/e-dant/watcher/tree/release/watcher-c) | nowatcher | ## Компиляция Go-приложения Теперь можно собрать итоговый бинарный файл: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build -tags=nobadger,nomysql,nopgx ``` ### Использование xcaddy Альтернативно, используйте [xcaddy](https://github.com/caddyserver/xcaddy) для компиляции FrankenPHP с [пользовательскими модулями Caddy](https://caddyserver.com/docs/modules/): ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Добавьте дополнительные модули Caddy здесь ``` > [!TIP] > > Если вы используете musl libc (по умолчанию в Alpine Linux) и Symfony, > возможно, потребуется увеличить размер стека. > В противном случае вы можете столкнуться с ошибками вроде > `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression`. > > Для этого измените значение переменной окружения `XCADDY_GO_BUILD_FLAGS`, например: > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (измените значение размера стека в зависимости от требований вашего приложения). ================================================ FILE: docs/ru/config.md ================================================ # Конфигурация FrankenPHP, Caddy, а также модули [Mercure](mercure.md) и [Vulcain](https://vulcain.rocks) могут быть настроены с использованием [форматов, поддерживаемых Caddy](https://caddyserver.com/docs/getting-started#your-first-config). Наиболее распространенным форматом является `Caddyfile`, который представляет собой простой, удобочитаемый текстовый формат. По умолчанию FrankenPHP будет искать `Caddyfile` в текущей директории. Вы можете указать пользовательский путь с помощью опции `-c` или `--config`. Ниже показан минимальный `Caddyfile` для обслуживания PHP-приложения: ```caddyfile # Хостнейм, на который будет отвечать сервер localhost # Опционально, директория для обслуживания файлов, иначе по умолчанию используется текущая директория #root public/ php_server ``` Более продвинутый `Caddyfile`, включающий дополнительные функции и предоставляющий удобные переменные окружения, можно найти [в репозитории FrankenPHP](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile), а также в Docker-образах. PHP можно настроить [с помощью файла `php.ini`](https://www.php.net/manual/en/configuration.file.php). В зависимости от метода установки, FrankenPHP и PHP-интерпретатор будут искать конфигурационные файлы в местах, описанных ниже. ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: основной файл конфигурации - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: дополнительные файлы конфигурации, которые загружаются автоматически PHP: - `php.ini`: `/usr/local/etc/php/php.ini` (по умолчанию `php.ini` не предоставляется) - дополнительные файлы конфигурации: `/usr/local/etc/php/conf.d/*.ini` - расширения PHP: `/usr/local/lib/php/extensions/no-debug-zts-/` - Вы должны скопировать официальный шаблон, предоставляемый проектом PHP: ```dockerfile FROM dunglas/frankenphp # Production: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Или development: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## RPM и Debian пакеты FrankenPHP: - `/etc/frankenphp/Caddyfile`: основной файл конфигурации - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: дополнительные файлы конфигурации, которые загружаются автоматически PHP: - `php.ini`: `/etc/php-zts/php.ini` (по умолчанию предоставляется файл `php.ini` с производственными настройками) - дополнительные файлы конфигурации: `/etc/php-zts/conf.d/*.ini` ## Статический бинарный файл FrankenPHP: - В текущей рабочей директории: `Caddyfile` PHP: - `php.ini`: Директория, в которой выполняется `frankenphp run` или `frankenphp php-server`, затем `/etc/frankenphp/php.ini` - дополнительные файлы конфигурации: `/etc/frankenphp/php.d/*.ini` - расширения PHP: не могут быть загружены, их следует встраивать в сам бинарный файл - скопируйте один из шаблонов `php.ini-production` или `php.ini-development`, предоставленных [в исходниках PHP](https://github.com/php/php-src/). ## Конфигурация Caddyfile [HTTP-директивы](https://caddyserver.com/docs/caddyfile/concepts#directives) `php_server` или `php` могут быть использованы в блоках сайта для обслуживания вашего PHP-приложения. Минимальный пример: ```caddyfile localhost { # Включить сжатие (опционально) encode zstd br gzip # Выполнять PHP-файлы в текущей директории и обслуживать ресурсы php_server } ``` Вы также можете явно настроить FrankenPHP, используя [глобальную опцию](https://caddyserver.com/docs/caddyfile/concepts#global-options) `frankenphp`: ```caddyfile { frankenphp { num_threads # Устанавливает количество запускаемых потоков PHP. По умолчанию: 2x от числа доступных CPU. max_threads # Ограничивает количество дополнительных потоков PHP, которые могут быть запущены во время выполнения. По умолчанию: num_threads. Может быть установлено в 'auto'. max_wait_time # Устанавливает максимальное время, в течение которого запрос может ожидать свободный поток PHP до истечения таймаута. По умолчанию: отключено. max_idle_time # Устанавливает максимальное время бездействия автоматически масштабируемого потока до его деактивации. По умолчанию: 5s. php_ini # Устанавливает директиву php.ini. Может использоваться несколько раз для установки нескольких директив. worker { file # Устанавливает путь к worker-скрипту. num # Устанавливает количество запускаемых потоков PHP, по умолчанию 2x от числа доступных CPU. env # Устанавливает дополнительную переменную окружения с заданным значением. Может быть указано несколько раз для нескольких переменных окружения. watch # Устанавливает путь для отслеживания изменений файлов. Может быть указано несколько раз для нескольких путей. name # Устанавливает имя worker, используемое в логах и метриках. По умолчанию: абсолютный путь к файлу worker. max_consecutive_failures # Устанавливает максимальное количество последовательных сбоев, после которых worker считается неработоспособным; -1 означает, что worker всегда будет перезапускаться. По умолчанию: 6. } } } # ... ``` В качестве альтернативы можно использовать однострочную краткую форму для опции `worker`: ```caddyfile { frankenphp { worker } } # ... ``` Вы также можете определить несколько workers, если обслуживаете несколько приложений на одном сервере: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # позволяет лучше кэшировать worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` Использование директивы `php_server` — это то, что нужно в большинстве случаев, но если требуется полный контроль, вы можете использовать более низкоуровневую директиву `php`. Директива `php` передает все входные данные PHP, не проверяя предварительно, является ли это PHP-файлом или нет. Подробнее об этом читайте на [странице производительности](performance.md#try_files). Использование директивы `php_server` эквивалентно следующей конфигурации: ```caddyfile route { # Добавить слэш в конец запросов к директориям @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # Если запрошенный файл не существует, попытаться использовать файлы index @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` Директивы `php_server` и `php` имеют следующие опции: ```caddyfile php_server [] { root # Устанавливает корневую папку для сайта. По умолчанию: директива `root`. split_path # Устанавливает подстроки для разделения URI на две части. Первая совпадающая подстрока будет использована для разделения "path info" от пути. Первая часть будет дополнена совпадающей подстрокой и будет считаться фактическим именем ресурса (CGI-скрипта). Вторая часть будет установлена как PATH_INFO для использования скриптом. По умолчанию: `.php`. resolve_root_symlink false # Отключает разрешение директории `root` до ее фактического значения путем оценки символической ссылки, если таковая существует (включено по умолчанию). env # Устанавливает дополнительную переменную окружения с заданным значением. Может быть указано несколько раз для нескольких переменных окружения. file_server off # Отключает встроенную директиву file_server. worker { # Создает worker, специфичный для этого сервера. Может быть указано несколько раз для нескольких workers. file # Устанавливает путь к worker-скрипту, может быть относительным к корню php_server num # Устанавливает количество запускаемых потоков PHP, по умолчанию 2x от числа доступных CPU. name # Устанавливает имя для worker, используемое в логах и метриках. По умолчанию: абсолютный путь к файлу worker. Всегда начинается с m# при определении в блоке php_server. watch # Устанавливает путь для отслеживания изменений файлов. Может быть указано несколько раз для нескольких путей. env # Устанавливает дополнительную переменную окружения с заданным значением. Может быть указано несколько раз для нескольких переменных окружения. Переменные окружения для этого worker также наследуются от родительского php_server, но могут быть переопределены здесь. match # сопоставляет worker с шаблоном пути. Переопределяет try_files и может использоваться только в директиве php_server. } worker # Также можно использовать краткую форму, как и в глобальном блоке frankenphp. } ``` ### Отслеживание изменений файлов Поскольку workers запускают ваше приложение только один раз и держат его в памяти, любые изменения в ваших PHP-файлах не будут отражены немедленно. Вместо этого workers могут быть перезапущены при изменении файлов с помощью директивы `watch`. Это полезно для сред разработки. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` Эта функция часто используется в сочетании с [горячей перезагрузкой](hot-reload.md). Если директория для `watch` не указана, по умолчанию будет использоваться `./**/*.{env,php,twig,yaml,yml}`, который отслеживает все файлы с расширениями `.env`, `.php`, `.twig`, `.yaml` и `.yml` в директории и поддиректориях, где был запущен процесс FrankenPHP. Вы также можете указать одну или несколько директорий с использованием [шаблона имён файлов оболочки](https://pkg.go.dev/path/filepath#Match): ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # отслеживает все файлы во всех поддиректориях /path/to/app watch /path/to/app/*.php # отслеживает файлы с расширением .php в /path/to/app watch /path/to/app/**/*.php # отслеживает PHP-файлы в /path/to/app и поддиректориях watch /path/to/app/**/*.{php,twig} # отслеживает PHP и Twig-файлы в /path/to/app и поддиректориях } } } ``` - Шаблон `**` указывает на рекурсивное отслеживание. - Директории также могут быть относительными (к месту запуска процесса FrankenPHP). - Если у вас определено несколько workers, все они будут перезапущены при изменении файлов. - Будьте осторожны с отслеживанием файлов, создаваемых во время выполнения (например, логов), так как это может вызвать нежелательные перезапуски workers. Механизм отслеживания файлов основан на [e-dant/watcher](https://github.com/e-dant/watcher). ## Сопоставление Worker с путем В традиционных PHP-приложениях скрипты всегда размещаются в публичной директории. Это также верно для worker-скриптов, которые обрабатываются как любые другие PHP-скрипты. Если вы хотите разместить worker-скрипт вне публичной директории, вы можете сделать это с помощью директивы `match`. Директива `match` является оптимизированной альтернативой `try_files`, доступной только внутри `php_server` и `php`. Следующий пример всегда будет обслуживать файл в публичной директории, если он присутствует, и в противном случае будет перенаправлять запрос worker, соответствующему шаблону пути. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # файл может находиться вне публичного пути match /api/* # все запросы, начинающиеся с /api/, будут обрабатываться этим worker } } } } ``` ## Переменные окружения Следующие переменные окружения могут быть использованы для внедрения директив Caddy в `Caddyfile` без его изменения: - `SERVER_NAME`: изменение [адресов для прослушивания](https://caddyserver.com/docs/caddyfile/concepts#addresses); предоставленные хостнеймы также будут использованы для генерации TLS-сертификата - `SERVER_ROOT`: изменение корневой директории сайта, по умолчанию `public/` - `CADDY_GLOBAL_OPTIONS`: внедрение [глобальных опций](https://caddyserver.com/docs/caddyfile/options) - `FRANKENPHP_CONFIG`: внедрение конфигурации под директиву `frankenphp` Как и для FPM и CLI SAPIs, переменные окружения по умолчанию доступны в суперглобальной переменной `$_SERVER`. Значение `S` в [директиве PHP `variables_order`](https://www.php.net/manual/en/ini.core.php#ini.variables-order) всегда эквивалентно `ES`, независимо от того, где расположена `E` в этой директиве. ## Конфигурация PHP Для загрузки [дополнительных конфигурационных файлов PHP](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan) можно использовать переменную окружения `PHP_INI_SCAN_DIR`. Если она установлена, PHP загрузит все файлы с расширением `.ini`, находящиеся в указанных директориях. Вы также можете изменить конфигурацию PHP с помощью директивы `php_ini` в `Caddyfile`: ```caddyfile { frankenphp { php_ini memory_limit 256M # или php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### Отключение HTTPS По умолчанию FrankenPHP автоматически включает HTTPS для всех хостнеймов, включая `localhost`. Если вы хотите отключить HTTPS (например, в среде разработки), вы можете установить переменную окружения `SERVER_NAME` в `http://` или `:80`: В качестве альтернативы вы можете использовать все другие методы, описанные в [документации Caddy](https://caddyserver.com/docs/automatic-https#activation). Если вы хотите использовать HTTPS с IP-адресом `127.0.0.1` вместо хостнейма `localhost`, пожалуйста, ознакомьтесь с разделом [известные проблемы](known-issues.md#using-https127001-with-docker). ### Полный дуплекс (HTTP/1) При использовании HTTP/1.x может быть желательно включить режим полного дуплекса, чтобы разрешить запись ответа до завершения чтения всего тела запроса. (например: [Mercure](mercure.md), WebSocket, Server-Sent Events и т.д.) Это конфигурация, которую необходимо добавить в глобальные опции в `Caddyfile`: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > Включение этой опции может привести к зависанию устаревших HTTP/1.x клиентов, которые не поддерживают полный дуплекс. > Это также можно настроить с помощью переменной окружения `CADDY_GLOBAL_OPTIONS`: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` Дополнительную информацию об этой настройке можно найти в [документации Caddy](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex). ## Включение режима отладки При использовании Docker-образа установите переменную окружения `CADDY_GLOBAL_OPTIONS` в `debug`, чтобы включить режим отладки: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Автодополнение команд оболочки FrankenPHP предоставляет встроенную поддержку автодополнения команд для Bash, Zsh, Fish и PowerShell. Это позволяет автоматически завершать все команды (включая пользовательские команды, такие как `php-server`, `php-cli` и `extension-init`) и их флаги. ### Bash Для загрузки автодополнения в текущую сессию оболочки: ```console source <(frankenphp completion bash) ``` Для загрузки автодополнения для каждой новой сессии выполните: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh Если автодополнение команд еще не включено в вашей среде, вам нужно будет его активировать. Вы можете выполнить следующее один раз: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` Чтобы загрузить автодополнение для каждой сессии, выполните один раз: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` Вам потребуется запустить новую оболочку, чтобы эти настройки вступили в силу. ### Fish Для загрузки автодополнения в текущую сессию оболочки: ```console frankenphp completion fish | source ``` Для загрузки автодополнения для каждой новой сессии выполните один раз: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell Для загрузки автодополнения в текущую сессию оболочки: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` Для загрузки автодополнения для каждой новой сессии выполните один раз: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` Вам потребуется запустить новую оболочку, чтобы эти настройки вступили в силу. Вам потребуется запустить новую оболочку, чтобы эти настройки вступили в силу. ================================================ FILE: docs/ru/docker.md ================================================ # Создание кастомных Docker-образов [Docker-образы FrankenPHP](https://hub.docker.com/r/dunglas/frankenphp) основаны на [официальных PHP-образах](https://hub.docker.com/_/php/). Доступны варианты для Debian и Alpine Linux для популярных архитектур. Рекомендуется использовать Debian-варианты. Доступны версии для PHP 8.2, 8.3, 8.4 и 8.5. Теги следуют следующему шаблону: `dunglas/frankenphp:-php-`. - `` и `` — версии FrankenPHP и PHP соответственно, начиная с мажорных (например, `1`), минорных (например, `1.2`) и заканчивая патч-версиями (например, `1.2.3`). - `` может быть `trixie` (для Debian Trixie), `bookworm` (для Debian Bookworm) или `alpine` (для последней стабильной версии Alpine). [Просмотреть доступные теги](https://hub.docker.com/r/dunglas/frankenphp/tags). ## Как использовать образы Создайте `Dockerfile` в вашем проекте: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Затем выполните следующие команды для сборки и запуска Docker-образа: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## Как настроить конфигурацию Для удобства в образе предоставлен [Caddyfile по умолчанию](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile), содержащий полезные переменные окружения. ## Как установить дополнительные PHP-расширения Скрипт [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) предоставляется в базовом образе. Установка дополнительных PHP-расширений осуществляется просто: ```dockerfile FROM dunglas/frankenphp # Добавьте дополнительные расширения здесь: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Как установить дополнительные модули Caddy FrankenPHP построен на базе Caddy, и все [модули Caddy](https://caddyserver.com/docs/modules/) можно использовать с FrankenPHP. Самый простой способ установить пользовательские модули Caddy — использовать [xcaddy](https://github.com/caddyserver/xcaddy): ```dockerfile FROM dunglas/frankenphp:builder AS builder # Копируем xcaddy в образ сборки COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # Для сборки FrankenPHP необходимо включить CGO RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure и Vulcain включены в официальный билд, но вы можете их удалить --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Добавьте дополнительные модули Caddy здесь FROM dunglas/frankenphp AS runner # Заменяем официальный бинарный файл на пользовательский с добавленными модулями COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` Образ `builder`, предоставляемый FrankenPHP, содержит скомпилированную версию `libphp`. [Образы builder](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) доступны для всех версий FrankenPHP и PHP, как для Debian, так и для Alpine. > [!TIP] > > Если вы используете Alpine Linux и Symfony, > возможно, потребуется [увеличить размер стека](compile.md#использование-xcaddy). ## Активировать worker режим по умолчанию Установите переменную окружения `FRANKENPHP_CONFIG`, чтобы запускать FrankenPHP с рабочим скриптом: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Использование тома в разработке Для удобной разработки с FrankenPHP смонтируйте директорию с исходным кодом приложения на хосте как том в Docker-контейнере: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > Опция `--tty` позволяет получать удобочитаемые логи вместо JSON-формата. С использованием Docker Compose: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # раскомментируйте следующую строку, если хотите использовать собственный Dockerfile #build: . # раскомментируйте следующую строку для работы в production-окружении # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # закомментируйте следующую строку в production — в dev она обеспечивает удобочитаемые логи tty: true # Тома, необходимые для сертификатов и конфигурации Caddy volumes: caddy_data: caddy_config: ``` ## Запуск под обычным пользователем FrankenPHP может запускаться под обычным пользователем в Docker. Пример `Dockerfile` для этого: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Для дистрибутивов на основе Alpine используйте "adduser -D ${USER}" useradd ${USER}; \ # Добавить возможность привязки к портам 80 и 443 setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # Предоставить доступ на запись в /config/caddy и /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Запуск без дополнительных прав Даже при запуске без root-прав, FrankenPHP требуется возможность `CAP_NET_BIND_SERVICE` для привязки веб-сервера к зарезервированным портам (80 и 443). Если вы открываете доступ к FrankenPHP на непривилегированном порту (1024 и выше), можно запустить веб-сервер от имени обычного пользователя без необходимости предоставления дополнительных возможностей: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Для дистрибутивов на основе Alpine используйте "adduser -D ${USER}" useradd ${USER}; \ # Удалить стандартные возможности setcap -r /usr/local/bin/frankenphp; \ # Предоставить доступ на запись в /config/caddy и /data/caddy chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Затем установите переменную окружения `SERVER_NAME`, чтобы использовать непривилегированный порт. Пример: `:8000`. ## Обновления Docker-образы собираются: - при выпуске новой версии; - ежедневно в 4 утра UTC, если доступны новые версии официальных PHP-образов. ## Укрепление образов Чтобы ещё больше уменьшить поверхность атаки и размер ваших Docker-образов FrankenPHP, также возможно создавать их на основе [Google Distroless](https://github.com/GoogleContainerTools/distroless) или [Docker Hardened](https://www.docker.com/products/hardened-images) образов. > [!WARNING] > Эти минимальные базовые образы не включают оболочку или менеджер пакетов, что значительно усложняет отладку. > Поэтому они рекомендуются только для продакшена, если безопасность является высоким приоритетом. При добавлении дополнительных PHP-расширений вам потребуется промежуточная стадия сборки: ```dockerfile FROM dunglas/frankenphp AS builder # Добавьте дополнительные PHP-расширения здесь RUN install-php-extensions pdo_mysql pdo_pgsql #... # Скопировать общие библиотеки frankenphp и всех установленных расширений во временное место # Этот шаг можно также выполнить вручную, проанализировав вывод ldd для бинарного файла frankenphp и каждого файла расширения .so RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Базовый образ Distroless Debian — убедитесь, что версия Debian совпадает с базовым образом FROM gcr.io/distroless/base-debian13 # Альтернатива: Docker Hardened Image # FROM dhi.io/debian:13 # Путь к приложению и Caddyfile для копирования в контейнер ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Скопировать приложение в /app # Для дополнительного усиления убедитесь, что только записываемые пути принадлежат пользователю nonroot COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # Скопировать frankenphp и необходимые библиотеки COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # Скопировать конфигурационные файлы php.ini COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Директории данных Caddy — должны быть доступны для записи пользователю nonroot даже в файловой системе только для чтения ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # Точка входа для запуска frankenphp с указанным Caddyfile ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Версии для разработки Версии для разработки доступны в Docker-репозитории [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev). Сборка запускается автоматически при каждом коммите в основную ветку GitHub-репозитория. Теги `latest*` указывают на голову ветки `main`. Также доступны теги в формате `sha-`. ================================================ FILE: docs/ru/early-hints.md ================================================ # Early Hints FrankenPHP изначально поддерживает [Early Hints (103 HTTP статус код)](https://developer.chrome.com/blog/early-hints/). Использование Early Hints может улучшить время загрузки ваших веб-страниц на 30%. ```php ; rel=preload; as=style'); headers_send(103); // ваши медленные алгоритмы и SQL-запросы 🤪 echo <<<'HTML' Hello FrankenPHP HTML; ``` Early Hints поддерживается как в обычном, так и в [worker режиме](worker.md). ================================================ FILE: docs/ru/embed.md ================================================ # PHP-приложения как автономные бинарные файлы FrankenPHP позволяет встраивать исходный код и ресурсы PHP-приложений в статический автономный бинарный файл. Благодаря этой функции PHP-приложения могут распространяться как автономные бинарные файлы, которые содержат само приложение, интерпретатор PHP и Caddy — веб-сервер уровня продакшн. Подробнее об этой функции [в презентации Кевина на SymfonyCon 2023](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/). Для встраивания Laravel-приложений ознакомьтесь с [документацией](laravel.md#laravel-приложения-как-автономные-бинарные-файлы). ## Подготовка приложения Перед созданием автономного бинарного файла убедитесь, что ваше приложение готово для встраивания. Например, вам может понадобиться: - Установить продакшн-зависимости приложения. - Сгенерировать автозагрузчик. - Включить продакшн-режим приложения (если он есть). - Удалить ненужные файлы, такие как `.git` или тесты, чтобы уменьшить размер итогового бинарного файла. Для приложения на Symfony это может выглядеть так: ```console # Экспорт проекта, чтобы избавиться от .git/ и других ненужных файлов mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # Установить соответствующие переменные окружения echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Удалить тесты и другие ненужные файлы rm -Rf tests/ # Установить зависимости composer install --ignore-platform-reqs --no-dev -a # Оптимизировать .env composer dump-env prod ``` ### Настройка конфигурации Чтобы настроить [конфигурацию](config.md), вы можете разместить файлы `Caddyfile` и `php.ini` в основной директории приложения (`$TMPDIR/my-prepared-app` в примере выше). ## Создание бинарного файла для Linux Самый простой способ создать бинарный файл для Linux — использовать предоставленный Docker-билдер. 1. Создайте файл `static-build.Dockerfile` в репозитории вашего приложения: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Если вы планируете запускать бинарный файл на системах с musl-libc, используйте static-builder-musl # Скопировать приложение WORKDIR /go/src/app/dist/app COPY . . # Сборка статического бинарного файла WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Некоторые `.dockerignore` файлы (например, [Symfony Docker `.dockerignore`](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > игнорируют директорию `vendor/` и файлы `.env`. Перед сборкой убедитесь, что `.dockerignore` файл настроен корректно или удалён. 2. Соберите образ: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. Извлеките бинарный файл: ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` Созданный бинарный файл сохранится в текущей директории под именем `my-app`. ## Создание бинарного файла для других ОС Если вы не хотите использовать Docker или хотите собрать бинарный файл для macOS, используйте предоставленный скрипт: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app ./build-static.sh ``` Итоговый бинарный файл будет находиться в директории `dist/` под именем `frankenphp--`. ## Использование бинарного файла Готово! Файл `my-app` (или `dist/frankenphp--` для других ОС) содержит ваше автономное приложение. Для запуска веб-приложения выполните: ```console ./my-app php-server ``` Если ваше приложение содержит [worker-скрипт](worker.md), запустите его следующим образом: ```console ./my-app php-server --worker public/index.php ``` Чтобы включить HTTPS (Let's Encrypt автоматически создаст сертификат), HTTP/2 и HTTP/3, укажите доменное имя: ```console ./my-app php-server --domain localhost ``` Вы также можете запускать PHP-скрипты CLI, встроенные в бинарный файл: ```console ./my-app php-cli bin/console ``` ## PHP-расширения По умолчанию скрипт собирает расширения, указанные в `composer.json` вашего проекта. Если файла `composer.json` нет, собираются стандартные расширения, как указано в [документации по статической сборке](static.md). Чтобы настроить список расширений, используйте переменную окружения `PHP_EXTENSIONS`. ## Настройка сборки [Ознакомьтесь с документацией по статической сборке](static.md), чтобы узнать, как настроить бинарный файл (расширения, версию PHP и т.д.). ## Распространение бинарного файла На Linux созданный бинарный файл сжимается с помощью [UPX](https://upx.github.io). На Mac для уменьшения размера файла перед отправкой его можно сжать. Рекомендуется использовать `xz`. ================================================ FILE: docs/ru/extension-workers.md ================================================ # Расширение Workers Расширение Workers позволяет вашему [расширению FrankenPHP](https://frankenphp.dev/docs/extensions/) управлять выделенным пулом PHP-потоков для выполнения фоновых задач, обработки асинхронных событий или реализации пользовательских протоколов. Полезно для систем очередей, слушателей событий, планировщиков и т. д. ## Регистрация Worker-а ### Статическая регистрация Если вам не нужно делать Worker-а настраиваемым пользователем (фиксированный путь к скрипту, фиксированное количество потоков), вы можете просто зарегистрировать Worker в функции `init()`. ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // Глобальный дескриптор для связи с пулом Worker-ов var worker frankenphp.Workers func init() { // Зарегистрировать Worker при загрузке модуля. worker = caddy.RegisterWorkers( "my-internal-worker", // Уникальное имя "worker.php", // Путь к скрипту (относительный или абсолютный) 2, // Фиксированное количество потоков // Дополнительные хуки жизненного цикла frankenphp.WithWorkerOnServerStartup(func() { // Глобальная логика настройки... }), ) } ``` ### В модуле Caddy (настраивается пользователем) Если вы планируете делиться своим расширением (например, универсальной очередью или слушателем событий), вам следует обернуть его в модуль Caddy. Это позволит пользователям настраивать путь к скрипту и количество потоков через свой `Caddyfile`. Это требует реализации интерфейса `caddy.Provisioner` и парсинга Caddyfile ([см. пример](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)). ### В чистом Go-приложении (встраивание) Если вы [встраиваете FrankenPHP в стандартное Go-приложение без Caddy](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), вы можете зарегистрировать Worker-ы расширения, используя `frankenphp.WithExtensionWorkers` при инициализации опций. ## Взаимодействие с Worker-ами Как только пул Worker-ов активен, вы можете отправлять ему задачи. Это можно сделать внутри [нативных функций, экспортированных в PHP](https://frankenphp.dev/docs/extensions/#writing-the-extension), или из любой Go-логики, такой как планировщик cron, слушатель событий (MQTT, Kafka) или любая другая горутина. ### Безголовый режим: `SendMessage` Используйте `SendMessage` для прямой передачи необработанных данных вашему скрипту Worker-а. Это идеально подходит для очередей или простых команд. #### Пример: Расширение асинхронной очереди ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. Убедитесь, что Worker готов if worker == nil { return false } // 2. Отправить фоновому Worker-у _, err := worker.SendMessage( context.Background(), // Стандартный Go-контекст unsafe.Pointer(data), // Данные для передачи Worker-у nil, // Опциональный http.ResponseWriter ) return err == nil } ``` ### Эмуляция HTTP: `SendRequest` Используйте `SendRequest`, если ваше расширение должно вызвать PHP-скрипт, который ожидает стандартную веб-среду (заполнение `$_SERVER`, `$_GET` и т. д.). ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. Подготовьте запрос и рекордер url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. Отправить Worker-у if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Вернуть захваченный ответ return frankenphp.PHPString(rr.Body.String(), false) } ``` ## Скрипт Worker-а PHP-скрипт Worker-а выполняется в цикле и может обрабатывать как необработанные сообщения, так и HTTP-запросы. ```php [!WARNING] > > Эта функция предназначена **только для сред разработки**. > Не включайте `hot_reload` в продакшене, так как эта функция небезопасна (раскрывает конфиденциальные внутренние детали) и замедляет работу приложения. > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` По умолчанию FrankenPHP будет отслеживать все файлы в текущем рабочем каталоге, соответствующие следующему глобальному шаблону: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` Можно явно задать файлы для отслеживания, используя синтаксис глобов: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Используйте полную форму `hot_reload`, чтобы указать используемый топик Mercure, а также каталоги или файлы для отслеживания: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## Интеграция на стороне клиента В то время как сервер обнаруживает изменения, браузер должен подписаться на эти события, чтобы обновить страницу. FrankenPHP предоставляет URL-адрес Mercure Hub для подписки на изменения файлов через переменную окружения `$_SERVER['FRANKENPHP_HOT_RELOAD']`. Удобная библиотека JavaScript, [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload), также доступна для обработки логики на стороне клиента. Чтобы использовать ее, добавьте следующее в ваш основной макет: ```php FrankenPHP Hot Reload ``` Библиотека автоматически подпишется на хаб Mercure, получит текущий URL-адрес в фоновом режиме при обнаружении изменения файла и морфирует DOM. Она доступна как [npm](https://www.npmjs.com/package/frankenphp-hot-reload) пакет и на [GitHub](https://github.com/dunglas/frankenphp-hot-reload). В качестве альтернативы вы можете реализовать свою собственную клиентскую логику, подписавшись непосредственно на хаб Mercure с помощью нативного JavaScript-класса `EventSource`. ### Сохранение существующих узлов DOM В редких случаях, например, при использовании инструментов разработки [таких как панель отладки Symfony web debug toolbar](https://github.com/symfony/symfony/pull/62970), вы можете захотеть сохранить определенные узлы DOM. Для этого добавьте атрибут `data-frankenphp-hot-reload-preserve` к соответствующему HTML-элементу: ```html
``` ## Режим Worker Если вы запускаете свое приложение в [режиме Worker](https://frankenphp.dev/docs/worker/), скрипт вашего приложения остается в памяти. Это означает, что изменения в вашем PHP-коде не будут отражены немедленно, даже если браузер перезагрузится. Для лучшего опыта разработчика вы должны объединить `hot_reload` с [поддирективой `watch` в директиве `worker`](config.md#watching-for-file-changes). - `hot_reload`: обновляет **браузер** при изменении файлов - `worker.watch`: перезапускает воркер при изменении файлов ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## Как это работает 1. **Отслеживание**: FrankenPHP отслеживает изменения файловой системы, используя библиотеку [`e-dant/watcher`](https://github.com/e-dant/watcher) (мы внесли вклад в Go-биндинг). 2. **Перезапуск (Режим Worker)**: если `watch` включен в конфигурации воркера, PHP-воркер перезапускается для загрузки нового кода. 3. **Отправка**: JSON-полезная нагрузка, содержащая список измененных файлов, отправляется во встроенный [Mercure hub](https://mercure.rocks). 4. **Получение**: Браузер, прослушивающий через JavaScript-библиотеку, получает событие Mercure. 5. **Обновление**: - Если обнаружен **Idiomorph**, он получает обновленное содержимое и морфирует текущий HTML, чтобы соответствовать новому состоянию, применяя изменения мгновенно без потери состояния. - В противном случае вызывается `window.location.reload()` для обновления страницы. ================================================ FILE: docs/ru/known-issues.md ================================================ # Известные проблемы ## Неподдерживаемые расширения PHP Следующие расширения не совместимы с FrankenPHP: | Название | Причина | Альтернативы | | ----------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/en/imap.installation.php) | Не поддерживает потокобезопасность | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | | [newrelic](https://docs.newrelic.com/docs/apm/agents/php-agent/getting-started/introduction-new-relic-php/) | Не поддерживает потокобезопасность | - | ## Проблемные расширения PHP Следующие расширения имеют известные ошибки или могут вести себя непредсказуемо при использовании с FrankenPHP: | Название | Проблема | | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [ext-openssl](https://www.php.net/manual/en/book.openssl.php) | При использовании статической сборки FrankenPHP (на базе musl libc) расширение OpenSSL может аварийно завершаться при высокой нагрузке. Решение — использовать динамически связанную сборку (например, ту, что используется в Docker-образах). Ошибка [отслеживается сообществом PHP](https://github.com/php/php-src/issues/13648). | ## `get_browser` Функция [get_browser()](https://www.php.net/manual/en/function.get-browser.php) начинает работать медленно через некоторое время. Решение — кэшировать результаты для каждого User-Agent, например, с помощью [APCu](https://www.php.net/manual/en/book.apcu.php), так как они статичны. ## Автономные бинарные файлы и образы на базе Alpine Автономные бинарные файлы и образы на базе Alpine (`dunglas/frankenphp:*-alpine`) используют [musl libc](https://musl.libc.org/) вместо [glibc](https://www.etalabs.net/compare_libcs.html) для уменьшения размера бинарных файлов. Это может вызвать проблемы совместимости. В частности, флаг `GLOB_BRACE` в функции glob [не поддерживается](https://www.php.net/manual/en/function.glob.php). ## Использование `https://127.0.0.1` с Docker По умолчанию FrankenPHP генерирует TLS-сертификат для `localhost`, что является самым простым и рекомендуемым вариантом для локальной разработки. Если вы всё же хотите использовать `127.0.0.1`, настройте генерацию сертификата, указав в переменной окружения `SERVER_NAME` значение `127.0.0.1`. Однако этого может не хватить при использовании Docker из-за [особенностей его сетевой системы](https://docs.docker.com/network/). Возможна ошибка TLS вида: `curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`. Если вы используете Linux, можно воспользоваться [host-драйвером](https://docs.docker.com/network/network-tutorial-host/): ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` Host-драйвер не поддерживается на Mac и Windows. На этих платформах нужно определить IP-адрес контейнера и включить его в `SERVER_NAME`. Выполните команду `docker network inspect bridge`, найдите ключ `Containers` и определите последний присвоенный IP из `IPv4Address`. Увеличьте его на единицу. Если контейнеров нет, первый IP обычно `172.17.0.2`. Включите этот IP в переменную окружения `SERVER_NAME`: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > Обязательно замените `172.17.0.3` на IP, который будет присвоен вашему контейнеру. Теперь вы должны иметь доступ к `https://127.0.0.1`. Если это не так, запустите FrankenPHP в режиме отладки: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Скрипты Composer с использованием `@php` [Скрипты Composer](https://getcomposer.org/doc/articles/scripts.md) могут вызывать PHP для выполнения задач, например, в [проекте Laravel](laravel.md) для команды `@php artisan package:discover --ansi`. Это [на данный момент не поддерживается](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) по двум причинам: - Composer не знает, как вызывать бинарный файл FrankenPHP; - Composer может добавлять настройки PHP через флаг `-d`, который FrankenPHP пока не поддерживает. Решение — создать shell-скрипт в `/usr/local/bin/php`, который удаляет неподдерживаемые параметры и вызывает FrankenPHP: ```bash #!/usr/bin/env bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Затем установите переменную окружения `PHP_BINARY` на путь к нашему скрипту `php` и запустите Composer: ```console export PHP_BINARY=/usr/local/bin/php composer install ``` ## TLS/SSL: проблемы со статическими бинарными файлами При использовании статических бинарных файлов могут возникать следующие ошибки TLS, например, при отправке писем через STARTTLS: ```text Unable to connect with STARTTLS: stream_socket_enable_crypto(): SSL operation failed with code 5. OpenSSL Error messages: error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:80000002:system library::No such file or directory error:0A000086:SSL routines::certificate verify failed ``` Статический бинарный файл не включает TLS-сертификаты, поэтому необходимо указать OpenSSL местоположение локальных сертификатов CA. Выполните [`openssl_get_cert_locations()`](https://www.php.net/manual/en/function.openssl-get-cert-locations.php), чтобы определить, где должны находиться сертификаты CA, и поместите их туда. > [!WARNING] > Веб и CLI контексты могут иметь разные настройки. > Запустите `openssl_get_cert_locations()` в нужном контексте. [Сертификаты CA, извлечённые из Mozilla, можно скачать с сайта cURL](https://curl.se/docs/caextract.html). Кроме того, многие дистрибутивы, такие как Debian, Ubuntu и Alpine, предоставляют пакеты `ca-certificates`, содержащие эти сертификаты. Также можно использовать переменные `SSL_CERT_FILE` и `SSL_CERT_DIR`, чтобы указать OpenSSL, где искать сертификаты CA: ```console # Установите переменные окружения для TLS-сертификатов export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt export SSL_CERT_DIR=/etc/ssl/certs ``` ================================================ FILE: docs/ru/laravel.md ================================================ # Laravel ## Docker Запустить [Laravel](https://laravel.com) веб-приложение с FrankenPHP очень просто: достаточно смонтировать проект в директорию `/app` официального Docker-образа. Выполните эту команду из корневой директории вашего Laravel-приложения: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` И наслаждайтесь! ## Локальная установка Вы также можете запустить ваши Laravel-проекты с FrankenPHP на локальной машине: 1. [Скачайте бинарный файл для вашей системы](README.md#автономный-бинарный-файл) 2. Добавьте следующую конфигурацию в файл с именем `Caddyfile` в корневой директории вашего Laravel-проекта: ```caddyfile { frankenphp } # Доменное имя вашего сервера localhost { # Укажите веб-корень как директорию public/ root public/ # Включите сжатие (опционально) encode zstd br gzip # Выполняйте PHP-файлы из директории public/ и обслуживайте статические файлы php_server } ``` 3. Запустите FrankenPHP из корневой директории вашего Laravel-проекта: `frankenphp run` ## Laravel Octane Octane можно установить с помощью менеджера пакетов Composer: ```console composer require laravel/octane ``` После установки Octane выполните Artisan-команду `octane:install`, которая создаст конфигурационный файл Octane в вашем приложении: ```console php artisan octane:install --server=frankenphp ``` Сервер Octane можно запустить с помощью Artisan-команды `octane:frankenphp`: ```console php artisan octane:frankenphp ``` Команда `octane:frankenphp` поддерживает следующие опции: - `--host`: IP-адрес, к которому должен привязаться сервер (по умолчанию: `127.0.0.1`) - `--port`: Порт, на котором сервер будет доступен (по умолчанию: `8000`) - `--admin-port`: Порт, на котором будет доступен административный сервер (по умолчанию: `2019`) - `--workers`: Количество worker-скриптов для обработки запросов (по умолчанию: `auto`) - `--max-requests`: Количество запросов, обрабатываемых перед перезагрузкой сервера (по умолчанию: `500`) - `--caddyfile`: Путь к файлу `Caddyfile` FrankenPHP (по умолчанию: [stubbed `Caddyfile` в Laravel Octane](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: Включить HTTPS, HTTP/2 и HTTP/3, а также автоматически генерировать и обновлять сертификаты - `--http-redirect`: Включить редирект с HTTP на HTTPS (включается только при передаче --https) - `--watch`: Автоматически перезагружать сервер при изменении приложения - `--poll`: Использовать опрос файловой системы для отслеживания изменений в файлах через сеть - `--log-level`: Установить уровень логирования, используя встроенный логгер Caddy > [!TIP] > Чтобы получить структурированные JSON-логи (полезно при использовании решений для анализа логов), явно укажите опцию `--log-level`. Подробнее о [Laravel Octane читайте в официальной документации](https://laravel.com/docs/octane). ## Laravel-приложения как автономные бинарные файлы Используя [возможность встраивания приложений в FrankenPHP](embed.md), можно распространять Laravel-приложения как автономные бинарные файлы. Следуйте этим шагам, чтобы упаковать ваше Laravel-приложение в автономный бинарный файл для Linux: 1. Создайте файл с именем `static-build.Dockerfile` в репозитории вашего приложения: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # Если вы планируете запускать бинарный файл на системах с musl-libc, используйте static-builder-musl # Скопируйте ваше приложение WORKDIR /go/src/app/dist/app COPY . . # Удалите тесты и другие ненужные файлы, чтобы сэкономить место # В качестве альтернативы добавьте эти файлы в .dockerignore RUN rm -Rf tests/ # Скопируйте файл .env RUN cp .env.example .env # Измените APP_ENV и APP_DEBUG для продакшна RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Внесите другие изменения в файл .env, если необходимо # Установите зависимости RUN composer install --ignore-platform-reqs --no-dev -a # Соберите статический бинарный файл WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > > Некоторые `.dockerignore` файлы могут игнорировать директорию `vendor/` и файлы `.env`. Убедитесь, что вы скорректировали или удалили `.dockerignore` перед сборкой. 2. Соберите: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. Извлеките бинарный файл: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Заполните кеши: ```console frankenphp php-cli artisan optimize ``` 5. Запустите миграции базы данных (если есть): ```console frankenphp php-cli artisan migrate ``` 6. Сгенерируйте секретный ключ приложения: ```console frankenphp php-cli artisan key:generate ``` 7. Запустите сервер: ```console frankenphp php-server ``` Ваше приложение готово! Узнайте больше о доступных опциях и о том, как собирать бинарные файлы для других ОС в [документации по встраиванию приложений](embed.md). ### Изменение пути хранения По умолчанию Laravel сохраняет загруженные файлы, кеши, логи и другие данные в директории `storage/` приложения. Это неудобно для встроенных приложений, так как каждая новая версия будет извлекаться в другую временную директорию. Установите переменную окружения `LARAVEL_STORAGE_PATH` (например, в вашем `.env` файле) или вызовите метод `Illuminate\Foundation\Application::useStoragePath()`, чтобы использовать директорию за пределами временной директории. ### Запуск Octane как автономный бинарный файл Можно даже упаковать приложения Laravel Octane как автономный бинарный файл! Для этого [установите Octane правильно](#laravel-octane) и следуйте шагам, описанным в [предыдущем разделе](#laravel-приложения-как-автономные-бинарные-файлы). Затем, чтобы запустить FrankenPHP в worker-режиме через Octane, выполните: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > Для работы команды автономный бинарник **обязательно** должен быть назван `frankenphp`, так как Octane требует наличия программы с именем `frankenphp` в PATH. ================================================ FILE: docs/ru/mercure.md ================================================ # Real-time режим FrankenPHP поставляется с встроенным хабом [Mercure](https://mercure.rocks)! Mercure позволяет отправлять события в режиме реального времени на все подключённые устройства: они мгновенно получат JavaScript-событие. Не требуются JS-библиотеки или SDK! ![Mercure](../mercure-hub.png) Чтобы включить хаб Mercure, обновите `Caddyfile` в соответствии с инструкциями [на сайте Mercure](https://mercure.rocks/docs/hub/config). Для отправки обновлений Mercure из вашего кода мы рекомендуем использовать [Symfony Mercure Component](https://symfony.com/components/Mercure) (для его использования не требуется полный стек Symfony). ================================================ FILE: docs/ru/metrics.md ================================================ # Метрики При включении [метрик Caddy](https://caddyserver.com/docs/metrics) FrankenPHP предоставляет следующие метрики: - `frankenphp_[worker]_total_workers`: Общее количество worker-скриптов. - `frankenphp_[worker]_busy_workers`: Количество worker-скриптов, которые в данный момент обрабатывают запрос. - `frankenphp_[worker]_worker_request_time`: Время, затраченное всеми worker-скриптами на обработку запросов. - `frankenphp_[worker]_worker_request_count`: Количество запросов, обработанных всеми worker-скриптами. - `frankenphp_[worker]_ready_workers`: Количество worker-скриптов, которые вызвали `frankenphp_handle_request` хотя бы один раз. - `frankenphp_[worker]_worker_crashes`: Количество случаев неожиданного завершения worker-скриптов. - `frankenphp_[worker]_worker_restarts`: Количество случаев, когда worker-скрипт был перезапущен целенаправленно. - `frankenphp_total_threads`: Общее количество потоков PHP. - `frankenphp_busy_threads`: Количество потоков PHP, которые в данный момент обрабатывают запрос (работающие worker-скрипты всегда используют поток). Для метрик worker-скриптов плейсхолдер `[worker]` заменяется на путь к Worker-скрипту, указанному в Caddyfile. ================================================ FILE: docs/ru/performance.md ================================================ # Производительность По умолчанию FrankenPHP стремится предложить хороший компромисс между производительностью и простотой использования. Однако, используя подходящую конфигурацию, можно существенно улучшить производительность. ## Количество потоков и воркеров По умолчанию FrankenPHP запускает в 2 раза больше потоков и воркеров (в режиме воркера), чем доступное количество ядер процессора. Подходящие значения сильно зависят от того, как написано ваше приложение, что оно делает, и от вашего оборудования. Мы настоятельно рекомендуем изменить эти значения. Для лучшей стабильности системы рекомендуется, чтобы `num_threads` x `memory_limit` < `available_memory`. Чтобы найти подходящие значения, лучше всего провести нагрузочные тесты, имитирующие реальный трафик. [k6](https://k6.io) и [Gatling](https://gatling.io) являются хорошими инструментами для этого. Чтобы настроить количество потоков, используйте опцию `num_threads` директив `php_server` и `php`. Для изменения количества воркеров используйте опцию `num` секции `worker` директивы `frankenphp`. ### `max_threads` Хотя всегда лучше точно знать, как будет выглядеть ваш трафик, реальные приложения, как правило, более непредсказуемы. [Конфигурация](config.md#конфигурация-caddyfile) `max_threads` позволяет FrankenPHP автоматически создавать дополнительные потоки во время выполнения до указанного предела. `max_threads` может помочь вам определить, сколько потоков требуется для обработки вашего трафика, и может сделать сервер более устойчивым к скачкам задержки. Если установлено значение `auto`, лимит будет оценен на основе `memory_limit` в вашем `php.ini`. Если это невозможно, `auto` вместо этого будет по умолчанию равно 2x `num_threads`. Имейте в виду, что `auto` может сильно недооценивать необходимое количество потоков. `max_threads` похожа на [pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children) в PHP FPM. Основное отличие состоит в том, что FrankenPHP использует потоки вместо процессов и автоматически распределяет их между различными скриптами воркеров и 'классическим режимом' по мере необходимости. ## Режим воркера Включение [режима воркера](worker.md) значительно улучшает производительность, но ваше приложение должно быть адаптировано для совместимости с этим режимом: необходимо создать скрипт воркера и убедиться, что приложение не имеет утечек памяти. ## Избегайте использования musl Вариант официальных Docker-образов для Alpine Linux и предоставляемые нами бинарные файлы по умолчанию используют [библиотеку musl libc](https://musl.libc.org). Известно, что PHP [работает медленнее](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) при использовании этой альтернативной библиотеки C вместо традиционной библиотеки GNU, особенно при компиляции в режиме ZTS (потокобезопасном режиме), который требуется для FrankenPHP. Разница может быть существенной в сильно многопоточной среде. Кроме того, [некоторые ошибки проявляются исключительно при использовании musl](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). В производственных средах мы рекомендуем использовать FrankenPHP, скомпилированный с glibc и с соответствующим уровнем оптимизации. Этого можно достичь, используя Docker-образы Debian, используя [пакеты .deb, .rpm или .apk от наших мейнтейнеров](https://pkgs.henderkes.com) или [компилируя FrankenPHP из исходников](compile.md). Для более компактных или безопасных контейнеров вы можете рассмотреть [усиленный образ Debian](docker.md#hardening-images) вместо Alpine. ## Настройка среды выполнения Go FrankenPHP написан на языке Go. В целом, среда выполнения Go не требует какой-либо особой настройки, но при определенных обстоятельствах специфическая конфигурация улучшает производительность. Вероятно, вы захотите установить переменную окружения `GODEBUG` в значение `cgocheck=0` (по умолчанию в Docker-образах FrankenPHP). Если вы запускаете FrankenPHP в контейнерах (Docker, Kubernetes, LXC...) и ограничиваете память, доступную для контейнеров, установите переменную окружения `GOMEMLIMIT` в значение доступного объёма памяти. Для получения более подробной информации [страница документации Go, посвященная этой теме](https://pkg.go.dev/runtime#hdr-Environment_Variables), обязательна к прочтению, чтобы максимально эффективно использовать среду выполнения. ## `file_server` По умолчанию директива `php_server` автоматически настраивает файловый сервер для обслуживания статических файлов (ресурсов), хранящихся в корневой директории. Эта функция удобна, но имеет издержки. Чтобы отключить её, используйте следующую конфигурацию: ```caddyfile php_server { file_server off } ``` ## `try_files` Помимо статических файлов и файлов PHP, `php_server` также попытается обслужить индекс вашего приложения и индексные файлы директорий (`/path/` -> `/path/index.php`). Если вам не нужны индексы директорий, вы можете отключить их, явно определив `try_files` следующим образом: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # явное указание корневой директории здесь обеспечивает лучшее кеширование } ``` Это может значительно сократить количество ненужных файловых операций. Эквивалент предыдущей конфигурации для воркера будет следующим: ```caddyfile route { php_server { # используйте "php" вместо "php_server", если вам вообще не нужен файловый сервер root /root/to/your/app worker /path/to/worker.php { match * # отправить все запросы напрямую воркеру } } } ``` Альтернативный подход с 0 ненужных операций файловой системы заключается в использовании директивы `php` и разделении файлов от PHP по пути. Этот подход хорошо работает, если все ваше приложение обслуживается одним входным файлом. Пример [конфигурации](config.md#конфигурация-caddyfile), которая обслуживает статические файлы за папкой `/assets`, может выглядеть так: ```caddyfile route { @assets { path /assets/* } # всё, что находится за /assets, обрабатывается файловым сервером file_server @assets { root /root/to/your/app } # всё, что не находится в /assets, обрабатывается вашим индексным или воркер PHP-файлом rewrite index.php php { root /root/to/your/app # явное указание корневой директории здесь обеспечивает лучшее кеширование } } ``` ## Плейсхолдеры Вы можете использовать [плейсхолдеры](https://caddyserver.com/docs/conventions#placeholders) в директивах `root` и `env`. Однако это предотвращает кеширование значений и существенно снижает производительность. По возможности избегайте использования плейсхолдеров в этих директивах. ## `resolve_root_symlink` По умолчанию, если корневая директория документа является символьной ссылкой, она автоматически разрешается FrankenPHP (это необходимо для корректной работы PHP). Если корневая директория документа не является символьной ссылкой, вы можете отключить эту функцию. ```caddyfile php_server { resolve_root_symlink false } ``` Это улучшит производительность, если директива `root` содержит [плейсхолдеры](https://caddyserver.com/docs/conventions#placeholders). В остальных случаях прирост производительности будет минимальным. ## Логи Логирование, безусловно, очень полезно, но, по определению, оно требует операций ввода-вывода и выделения памяти, что значительно снижает производительность. Убедитесь, что вы [правильно настроили уровень логирования](https://caddyserver.com/docs/caddyfile/options#log) и логируете только то, что необходимо. ## Производительность PHP FrankenPHP использует официальный интерпретатор PHP. Все обычные оптимизации производительности, связанные с PHP, применимы к FrankenPHP. В частности: - убедитесь, что [OPcache](https://www.php.net/manual/en/book.opcache.php) установлен, включён и настроен должным образом; - включите [оптимизацию автозагрузки Composer](https://getcomposer.org/doc/articles/autoloader-optimization.md); - убедитесь, что кеш `realpath` достаточно велик для нужд вашего приложения; - используйте [предварительную загрузку](https://www.php.net/manual/en/opcache.preloading.php). Для получения более подробной информации ознакомьтесь с [разделом документации Symfony, посвященным производительности](https://symfony.com/doc/current/performance.html) (большинство советов полезны, даже если вы не используете Symfony). ## Разделение пула потоков Приложениям часто приходится взаимодействовать с медленными внешними службами, такими как API, который имеет тенденцию быть ненадежным при высокой нагрузке или постоянно отвечает в течение 10+ секунд. В таких случаях может быть полезно разделить пул потоков, чтобы иметь выделенные "медленные" пулы. Это предотвращает потребление медленными конечными точками всех ресурсов/потоков сервера и ограничивает параллелизм запросов, направляемых к медленной конечной точке, подобно пулу соединений. ```caddyfile example.com { php_server { root /app/public # корень вашего приложения worker index.php { match /slow-endpoint/* # все запросы к /slow-endpoint/* обрабатываются этим пулом потоков num 1 # минимум 1 поток для запросов к /slow-endpoint/* max_threads 20 # при необходимости разрешить до 20 потоков для запросов к /slow-endpoint/* } worker index.php { match * # все остальные запросы обрабатываются отдельно num 1 # минимум 1 поток для остальных запросов, даже если медленные конечные точки начинают зависать max_threads 20 # при необходимости разрешить до 20 потоков для остальных запросов } } } ``` В целом, также рекомендуется обрабатывать очень медленные конечные точки асинхронно, используя соответствующие механизмы, такие как очереди сообщений. ================================================ FILE: docs/ru/production.md ================================================ # Деплой в продакшен В этом руководстве мы рассмотрим, как развернуть PHP-приложение на одном сервере с использованием Docker Compose. Если вы используете Symfony, рекомендуется прочитать раздел "[Deploy in production](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)" документации проекта Symfony Docker (в котором используется FrankenPHP). Если вы используете API Platform (который также работает с FrankenPHP), ознакомьтесь с [документацией по деплою этого фреймворка](https://api-platform.com/docs/deployment/). ## Подготовка приложения Сначала создайте файл `Dockerfile` в корневой директории вашего PHP-проекта: ```dockerfile FROM dunglas/frankenphp # Замените "your-domain-name.example.com" на ваш домен ENV SERVER_NAME=your-domain-name.example.com # Если вы хотите отключить HTTPS, используйте вместо этого: #ENV SERVER_NAME=:80 # Включите настройки PHP для продакшн RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Скопируйте файлы PHP вашего проекта в публичную директорию COPY . /app/public # Если вы используете Symfony или Laravel, необходимо скопировать весь проект: #COPY . /app ``` Ознакомьтесь с разделом "[Создание кастомных Docker-образов](docker.md)" для получения дополнительных подробностей и настроек, а также для установки PHP-расширений и модулей Caddy. Если ваш проект использует Composer, убедитесь, что он включён в Docker-образ, и установите все зависимости. Затем добавьте файл `compose.yaml`: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Томы, необходимые для сертификатов и конфигурации Caddy volumes: caddy_data: caddy_config: ``` > [!NOTE] > > Примеры выше предназначены для использования в продакшне. > В процессе разработки вы можете использовать том для монтирования, другую конфигурацию PHP и другое значение для переменной окружения `SERVER_NAME`. > > Посмотрите проект [Symfony Docker](https://github.com/dunglas/symfony-docker) (который использует FrankenPHP) для более сложного примера с использованием мультистейдж-образов, Composer, дополнительных PHP-расширений и т.д. Наконец, если вы используете Git, закоммитьте эти файлы и отправьте их в репозиторий. ## Подготовка сервера Для деплоя приложения в продакшн требуется сервер. В этом руководстве мы будем использовать виртуальную машину, предоставляемую DigitalOcean, но подойдёт любой Linux-сервер. Если у вас уже есть Linux-сервер с установленным Docker, вы можете сразу перейти к [следующему разделу](#настройка-доменного-имени). В противном случае, используйте [эту ссылку](https://m.do.co/c/5d8aabe3ab80), чтобы получить $200 на баланс, создайте аккаунт, затем нажмите "Create a Droplet". Перейдите во вкладку "Marketplace" в разделе "Choose an image" и найдите приложение "Docker". Это создаст сервер на Ubuntu с установленными Docker и Docker Compose. Для тестов подойдут самые дешёвые тарифы. Для реального продакшна выберите тариф из раздела "general purpose" в зависимости от ваших потребностей. ![Деплой FrankenPHP на DigitalOcean с Docker](../digitalocean-droplet.png) После этого подключитесь к серверу через SSH: ```console ssh root@ ``` ## Настройка доменного имени В большинстве случаев вам потребуется связать доменное имя с вашим сайтом. Создайте запись DNS типа `A`, указывающую на IP вашего сервера: ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` Пример настройки через DigitalOcean ("Networking" > "Domains"): ![Настройка DNS в DigitalOcean](../digitalocean-dns.png) > [!NOTE] > > Let's Encrypt, сервис, используемый FrankenPHP для автоматической генерации TLS-сертификатов, не поддерживает использование IP-адресов. Для работы необходим домен. ## Деплой Скопируйте ваш проект на сервер с помощью `git clone`, `scp` или любого другого инструмента. Если вы используете GitHub, настройте [ключи развёртывания](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys). Пример с использованием Git: ```console git clone git@github.com:/.git ``` Перейдите в директорию проекта и запустите приложение в режиме продакшн: ```console docker compose up -d --wait ``` Сервер готов, а HTTPS-сертификат был автоматически сгенерирован. Перейдите на `https://your-domain-name.example.com` и наслаждайтесь! > [!CAUTION] > > Docker может кэшировать слои. Убедитесь, что вы используете актуальную сборку, или используйте опцию `--no-cache` для предотвращения проблем с кэшем. ## Деплой на несколько узлов Если вам нужно развернуть приложение на кластер машин, используйте [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/), который совместим с предоставленными файлами Compose. Для деплоя на Kubernetes ознакомьтесь с [Helm-чартом API Platform](https://api-platform.com/docs/deployment/kubernetes/), который использует FrankenPHP. ================================================ FILE: docs/ru/static.md ================================================ # Создание статических бинарных файлов Вместо использования локальной установки библиотеки PHP, можно создать статическую сборку FrankenPHP благодаря проекту [static-php-cli](https://github.com/crazywhalecc/static-php-cli) (несмотря на название, проект поддерживает все SAPI, а не только CLI). С помощью этого метода создаётся единый переносимый бинарник, который включает PHP-интерпретатор, веб-сервер Caddy и FrankenPHP! FrankenPHP также поддерживает [встраивание PHP-приложений в статический бинарный файл](embed.md). ## Linux Мы предоставляем Docker-образ для сборки статического бинарника для Linux: ```console docker buildx bake --load static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder ``` Созданный статический бинарный файл называется `frankenphp` и будет доступен в текущей директории. Чтобы собрать статический бинарный файл без Docker, используйте инструкции для macOS — они подходят и для Linux. ### Дополнительные расширения По умолчанию компилируются самые популярные PHP-расширения. Чтобы уменьшить размер бинарного файла и сократить возможные векторы атак, можно указать список расширений, которые следует включить в сборку, используя Docker-аргумент `PHP_EXTENSIONS`. Например, выполните следующую команду, чтобы собрать только расширение `opcache`: ```console docker buildx bake --load --set static-builder.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder # ... ``` Чтобы добавить библиотеки, расширяющие функциональность включённых расширений, используйте Docker-аргумент `PHP_EXTENSION_LIBS`: ```console docker buildx bake \ --load \ --set static-builder.args.PHP_EXTENSIONS=gd \ --set static-builder.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder ``` ### Дополнительные модули Caddy Чтобы добавить дополнительные модули Caddy или передать аргументы в [xcaddy](https://github.com/caddyserver/xcaddy), используйте Docker-аргумент `XCADDY_ARGS`: ```console docker buildx bake \ --load \ --set static-builder.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder ``` В этом примере добавляются модуль HTTP-кэширования [Souin](https://souin.io) для Caddy, а также модули [cbrotli](https://github.com/dunglas/caddy-cbrotli), [Mercure](https://mercure.rocks) и [Vulcain](https://vulcain.rocks). > [!TIP] > > Модули cbrotli, Mercure и Vulcain включены по умолчанию, если `XCADDY_ARGS` пуст или не установлен. > Если вы изменяете значение `XCADDY_ARGS`, добавьте их явно, если хотите включить их в сборку. См. также, как [настроить сборку](#настройка-сборки). ### Токен GitHub Если вы достигли лимита запросов к API GitHub, задайте личный токен доступа GitHub в переменной окружения `GITHUB_TOKEN`: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder # ... ``` ## macOS Запустите следующий скрипт, чтобы создать статический бинарный файл для macOS (должен быть установлен [Homebrew](https://brew.sh/)): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Примечание: этот скрипт также работает на Linux (и, вероятно, на других Unix-системах) и используется внутри предоставленного Docker-образа для статической сборки. ## Настройка сборки Следующие переменные окружения можно передать в `docker build` и скрипт `build-static.sh`, чтобы настроить статическую сборку: - `FRANKENPHP_VERSION`: версия FrankenPHP - `PHP_VERSION`: версия PHP - `PHP_EXTENSIONS`: PHP-расширения для сборки ([список поддерживаемых расширений](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: дополнительные библиотеки, добавляющие функциональность расширениям - `XCADDY_ARGS`: аргументы для [xcaddy](https://github.com/caddyserver/xcaddy), например, для добавления модулей Caddy - `EMBED`: путь к PHP-приложению для встраивания в бинарник - `CLEAN`: если задано, libphp и все его зависимости будут пересобраны с нуля (без кэша) - `NO_COMPRESS`: отключает сжатие результирующего бинарника с помощью UPX - `DEBUG_SYMBOLS`: если задано, отладочные символы не будут удалены и будут добавлены в бинарник - `MIMALLOC`: (экспериментально, только для Linux) заменяет musl's mallocng на [mimalloc](https://github.com/microsoft/mimalloc) для повышения производительности - `RELEASE`: (только для мейнтейнеров) если задано, бинарник будет загружен на GitHub ================================================ FILE: docs/ru/worker.md ================================================ # Использование воркеров FrankenPHP Загрузите приложение один раз и держите его в памяти. FrankenPHP будет обрабатывать входящие запросы за несколько миллисекунд. ## Запуск worker-скриптов ### Docker Установите значение переменной окружения `FRANKENPHP_CONFIG` на `worker /path/to/your/worker/script.php`: ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Автономный бинарный файл Используйте опцию `--worker` команды `php-server` для обслуживания содержимого текущей директории в режиме воркера: ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` Если ваше PHP-приложение [встроено в бинарник](embed.md), вы можете добавить пользовательский `Caddyfile` в корневую директорию приложения. Он будет использоваться автоматически. Также можно [перезапускать воркер при изменении файлов](config.md#watching-for-file-changes) с помощью опции `--watch`. Следующая команда выполнит перезапуск, если будет изменён любой файл с расширением `.php` в директории `/path/to/your/app/` или её поддиректориях: ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` Эта функция часто используется в сочетании с [горячей перезагрузкой](hot-reload.md). ## Symfony Runtime > [!TIP] > Следующий раздел актуален только для версий Symfony до 7.4, где была введена нативная поддержка режима воркеров FrankenPHP. Worker режим FrankenPHP поддерживается компонентом [Symfony Runtime](https://symfony.com/doc/current/components/runtime.html). Чтобы запустить любое Symfony-приложение в worker режиме, установите пакет FrankenPHP для [PHP Runtime](https://github.com/php-runtime/runtime): ```console composer require runtime/frankenphp-symfony ``` Запустите сервер приложения, задав переменную окружения `APP_RUNTIME` для использования FrankenPHP Symfony Runtime: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane Подробнее см. в [отдельной документации](laravel.md#laravel-octane). ## Пользовательские приложения Следующий пример показывает, как создать собственный worker-скрипт без использования сторонних библиотек: ```php boot(); // Обработчик запросов за пределами цикла для повышения производительности (выполняет меньше работы) $handler = static function () use ($myApp) { try { // Выполняется при получении запроса, // суперглобальные переменные, php://input и прочие сбрасываются echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` вызывается только когда worker-скрипт завершается, // что может быть не тем, что вы ожидаете, поэтому перехватывайте и обрабатывайте исключения здесь (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // Действия после отправки HTTP-ответа $myApp->terminate(); // Вызов сборщика мусора, чтобы снизить вероятность его запуска в процессе генерации страницы gc_collect_cycles(); if (!$keepRunning) break; } // Очистка $myApp->shutdown(); ``` Запустите ваше приложение и используйте переменную окружения `FRANKENPHP_CONFIG` для настройки вашего воркера: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` По умолчанию запускается 2 воркера на каждый CPU. Вы также можете настроить количество запускаемых воркеров: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Перезапуск worker-скрипта после определённого количества запросов PHP изначально не предназначался для долгоживущих процессов, поэтому есть ещё много библиотек и устаревшего кода, которые вызывают утечки памяти. Обходной путь для использования такого кода в режиме воркера состоит в перезапуске скрипта воркера после обработки определённого количества запросов: Предыдущий сниппет воркера позволяет настроить максимальное количество запросов для обработки, установив переменную окружения с именем `MAX_REQUESTS`. ### Перезапуск воркеров вручную Хотя можно перезапускать воркеры [при изменении файлов](config.md#watching-for-file-changes), также можно корректно перезапустить все воркеры через [API администрирования Caddy](https://caddyserver.com/docs/api). Если администрирование включено в вашем [Caddyfile](config.md#caddyfile-config), вы можете отправить запрос POST на конечную точку перезапуска следующим образом: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Сбои worker-скрипта Если worker-скрипт завершится с ненулевым кодом выхода, FrankenPHP перезапустит его со стратегией экспоненциальной задержки. Если скрипт воркера остается активным дольше, чем время последней задержки \* 2, FrankenPHP не будет применять штраф к worker-скрипту и перезапустит его снова. Однако, если worker-скрипт продолжает завершаться с ненулевым кодом выхода в течение короткого промежутка времени (например, из-за опечатки в скрипте), FrankenPHP завершит работу с ошибкой: `too many consecutive failures`. Количество последовательных сбоев можно настроить в вашем [Caddyfile](config.md#caddyfile-config) с помощью опции `max_consecutive_failures`: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Поведение суперглобальных переменных [PHP суперглобальные переменные](https://www.php.net/manual/en/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) ведут себя следующим образом: - до первого вызова `frankenphp_handle_request()`, суперглобальные переменные содержат значения, связанные с самим worker-скриптом - во время и после вызова `frankenphp_handle_request()`, суперглобальные переменные содержат значения, сгенерированные на основе обработанного HTTP-запроса, каждый вызов `frankenphp_handle_request()` изменяет значения суперглобальных переменных Чтобы получить доступ к суперглобальным переменным worker-скрипта внутри колбэка, необходимо скопировать их и импортировать копию в область видимости колбэка: ```php [!TIP] > > The cbrotli, Mercure, and Vulcain modules are included by default if `XCADDY_ARGS` is empty or not set. > If you customize the value of `XCADDY_ARGS`, you must include them explicitly if you want them to be included. See also how to [customize the build](#customizing-the-build) ### GitHub Token If you hit the GitHub API rate limit, set a GitHub Personal Access Token in an environment variable named `GITHUB_TOKEN`: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder-musl # ... ``` ## macOS Run the following script to create a static binary for macOS (you must have [Homebrew](https://brew.sh/) installed): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Note: this script also works on Linux (and probably on other Unixes), and is used internally by the Docker images we provide. ## Customizing The Build The following environment variables can be passed to `docker build` and to the `build-static.sh` script to customize the static build: - `FRANKENPHP_VERSION`: the version of FrankenPHP to use - `PHP_VERSION`: the version of PHP to use - `PHP_EXTENSIONS`: the PHP extensions to build ([list of supported extensions](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: extra libraries to build that add features to the extensions - `XCADDY_ARGS`: arguments to pass to [xcaddy](https://github.com/caddyserver/xcaddy), for instance to add extra Caddy modules - `EMBED`: path of the PHP application to embed in the binary - `CLEAN`: when set, libphp and all its dependencies are built from scratch (no cache) - `NO_COMPRESS`: don't compress the resulting binary using UPX - `DEBUG_SYMBOLS`: when set, debug-symbols will not be stripped and will be added to the binary - `MIMALLOC`: (experimental, Linux-only) replace musl's mallocng by [mimalloc](https://github.com/microsoft/mimalloc) for improved performance. We only recommend using this for musl targeting builds, for glibc prefer disabling this option and using [`LD_PRELOAD`](https://microsoft.github.io/mimalloc/overrides.html) when you run your binary instead. - `RELEASE`: (maintainers only) when set, the resulting binary will be uploaded on GitHub ## Extensions With the glibc or macOS-based binaries, you can load PHP extensions dynamically. However, these extensions will have to be compiled with ZTS support. Since most package managers do not currently offer ZTS versions of their extensions, you will have to compile them yourself. For this, you can build and run the `static-builder-gnu` Docker container, remote into it, and compile the extensions with `./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config`. Example steps for [the Xdebug extension](https://xdebug.org): ```console docker build -t gnu-ext -f static-builder-gnu.Dockerfile --build-arg FRANKENPHP_VERSION=1.0 . docker create --name static-builder-gnu -it gnu-ext /bin/sh docker start static-builder-gnu docker exec -it static-builder-gnu /bin/sh cd /go/src/app/dist/static-php-cli/buildroot/bin git clone https://github.com/xdebug/xdebug.git && cd xdebug source scl_source enable devtoolset-10 ../phpize ./configure --with-php-config=/go/src/app/dist/static-php-cli/buildroot/bin/php-config make exit docker cp static-builder-gnu:/go/src/app/dist/static-php-cli/buildroot/bin/xdebug/modules/xdebug.so xdebug-zts.so docker cp static-builder-gnu:/go/src/app/dist/frankenphp-linux-$(uname -m) ./frankenphp docker stop static-builder-gnu docker rm static-builder-gnu docker rmi gnu-ext ``` This will have created `frankenphp` and `xdebug-zts.so` in the current directory. If you move the `xdebug-zts.so` into your extension directory, add `zend_extension=xdebug-zts.so` to your php.ini and run FrankenPHP, it will load Xdebug. ================================================ FILE: docs/tr/CONTRIBUTING.md ================================================ # Katkıda Bulunmak ## PHP Derleme ### Docker ile (Linux) Geliştirme Ortamı için Docker İmajını Oluşturun: ```console docker build -t frankenphp-dev -f dev.Dockerfile . docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -p 8080:8080 -p 443:443 -p 443:443/udp -v $PWD:/go/src/app -it frankenphp-dev ``` İmaj genel geliştirme araçlarını (Go, GDB, Valgrind, Neovim...) içerir ve aşağıdaki php ayar konumlarını kullanır - php.ini: `/etc/frankenphp/php.ini` Varsayılan olarak geliştirme ön ayarlarına sahip bir php.ini dosyası sağlanır. - ek yapılandırma dosyaları: `/etc/frankenphp/php.d/*.ini` - php uzantıları: `/usr/lib/frankenphp/modules/` Docker sürümünüz 23.0'dan düşükse, derleme dockerignore [pattern issue](https://github.com/moby/moby/pull/42676) nedeniyle başarısız olacaktır. Dizinleri `.dockerignore` dosyasına ekleyin. ```patch !testdata/*.php !testdata/*.txt +!caddy +!internal ``` ### Docker olmadan (Linux ve macOS) [Kaynaklardan derlemek için talimatları izleyin](https://frankenphp.dev/docs/compile/) ve `--debug` yapılandırma seçeneğini geçirin. ## Test senaryolarını çalıştırma ```console go test -race -v ./... ``` ## Caddy modülü FrankenPHP Caddy modülü ile Caddy'yi oluşturun: ```console cd caddy/frankenphp/ go build cd ../../ ``` Caddy'yi FrankenPHP Caddy modülü ile çalıştırın: ```console cd testdata/ ../caddy/frankenphp/frankenphp run ``` Sunucu `127.0.0.1:8080` adresini dinliyor: ```console curl -vk https://localhost/phpinfo.php ``` ## Minimal test sunucusu Minimal test sunucusunu oluşturun: ```console cd internal/testserver/ go build cd ../../ ``` Test sunucusunu çalıştırın: ```console cd testdata/ ../internal/testserver/testserver ``` Sunucu `127.0.0.1:8080` adresini dinliyor: ```console curl -v http://127.0.0.1:8080/phpinfo.php ``` ## Docker İmajlarını Yerel Olarak Oluşturma Bake (pişirme) planını yazdırın: ```console docker buildx bake -f docker-bake.hcl --print ``` Yerel olarak amd64 için FrankenPHP görüntüleri oluşturun: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/amd64" ``` Yerel olarak arm64 için FrankenPHP görüntüleri oluşturun: ```console docker buildx bake -f docker-bake.hcl --pull --load --set "*.platform=linux/arm64" ``` FrankenPHP imajlarını arm64 ve amd64 için sıfırdan oluşturun ve Docker Hub'a gönderin: ```console docker buildx bake -f docker-bake.hcl --pull --no-cache --push ``` ## Statik Derlemelerle Segmentasyon Hatalarında Hata Ayıklama 1. FrankenPHP binary dosyasının hata ayıklama sürümünü GitHub'dan indirin veya hata ayıklama seçeneklerini kullanarak özel statik derlemenizi oluşturun: ```console docker buildx bake \ --load \ --set static-builder.args.DEBUG_SYMBOLS=1 \ --set "static-builder.platform=linux/amd64" \ static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ``` 2. Mevcut `frankenphp` sürümünüzü hata ayıklama FrankenPHP çalıştırılabilir dosyasıyla değiştirin 3. FrankenPHP'yi her zamanki gibi başlatın (alternatif olarak FrankenPHP'yi doğrudan GDB ile başlatabilirsiniz: `gdb --args frankenphp run`) 4. GDB ile sürece bağlanın: ```console gdb -p `pidof frankenphp` ``` 5. Gerekirse, GDB kabuğuna `continue` yazın 6. FrankenPHP'nin çökmesini sağlayın 7. GDB kabuğuna `bt` yazın 8. Çıktıyı kopyalayın ## GitHub Eylemlerinde Segmentasyon Hatalarında Hata Ayıklama 1. `.github/workflows/tests.yml` dosyasını açın 2. PHP hata ayıklama seçeneklerini etkinleştirin ```patch - uses: shivammathur/setup-php@v2 # ... env: phpts: ts + debug: true ``` 3. Konteynere bağlanmak için `tmate`i etkinleştirin ```patch - name: Set CGO flags run: echo "CGO_CFLAGS=$(php-config --includes)" >> "$GITHUB_ENV" + - + run: | + sudo apt install gdb + mkdir -p /home/runner/.config/gdb/ + printf "set auto-load safe-path /\nhandle SIG34 nostop noprint pass" > /home/runner/.config/gdb/gdbinit + - + uses: mxschmitt/action-tmate@v3 ``` 4. Konteynere bağlanın 5. `frankenphp.go` dosyasını açın 6. `cgosymbolizer`'ı etkinleştirin ```patch - //_ "github.com/ianlancetaylor/cgosymbolizer" + _ "github.com/ianlancetaylor/cgosymbolizer" ``` 7. Modülü indirin: `go get` 8. Konteynerde GDB ve benzerlerini kullanabilirsiniz: ```console go test -c -ldflags=-w gdb --args frankenphp.test -test.run ^MyTest$ ``` 9. Hata düzeltildiğinde, tüm bu değişiklikleri geri alın ## Misc Dev Resources - [uWSGI içine PHP gömme](https://github.com/unbit/uwsgi/blob/master/plugins/php/php_plugin.c) - [NGINX Unit'te PHP gömme](https://github.com/nginx/unit/blob/master/src/nxt_php_sapi.c) - [Go (go-php) içinde PHP gömme](https://github.com/deuill/go-php) - [Go'da PHP gömme (GoEmPHP)](https://github.com/mikespook/goemphp) - [C++'da PHP gömme](https://gist.github.com/paresy/3cbd4c6a469511ac7479aa0e7c42fea7) - [Sara Golemon tarafından PHP'yi Genişletme ve Yerleştirme](https://books.google.fr/books?id=zMbGvK17_tYC&pg=PA254&lpg=PA254#v=onepage&q&f=false) - [TSRMLS_CC de neyin nesi?](http://blog.golemon.com/2006/06/what-heck-is-tsrmlscc-anyway.html) - [Mac'te PHP gömme](https://gist.github.com/jonnywang/61427ffc0e8dde74fff40f479d147db4) - [SDL bağları](https://pkg.go.dev/github.com/veandco/go-sdl2@v0.4.21/sdl#Main) ## Docker ile İlgili Kaynaklar - [Pişirme (bake) dosya tanımı](https://docs.docker.com/build/customize/bake/file-definition/) - [`docker buildx build`](https://docs.docker.com/engine/reference/commandline/buildx_build/) ## Faydalı Komut ```console apk add strace util-linux gdb strace -e 'trace=!futex,epoll_ctl,epoll_pwait,tgkill,rt_sigreturn' -p 1 ``` ================================================ FILE: docs/tr/README.md ================================================ # FrankenPHP: PHP için Modern Uygulama Sunucusu

FrankenPHP

FrankenPHP, [Caddy](https://caddyserver.com/) web sunucusunun üzerine inşa edilmiş PHP için modern bir uygulama sunucusudur. FrankenPHP, çarpıcı özellikleri sayesinde PHP uygulamalarınıza süper güçler kazandırır: [Early Hints\*](https://frankenphp.dev/docs/early-hints/), [worker modu](https://frankenphp.dev/docs/worker/), [real-time yetenekleri](https://frankenphp.dev/docs/mercure/), otomatik HTTPS, HTTP/2 ve HTTP/3 desteği... FrankenPHP herhangi bir PHP uygulaması ile çalışır ve worker modu ile resmi entegrasyonları sayesinde Laravel ve Symfony projelerinizi her zamankinden daha performanslı hale getirir. FrankenPHP, PHP'yi `net/http` kullanarak herhangi bir uygulamaya yerleştirmek için bağımsız bir Go kütüphanesi olarak da kullanılabilir. [_Frankenphp.dev_](https://frankenphp.dev) adresinden ve bu slayt üzerinden daha fazlasını öğrenin: Slides ## Başlarken Windows üzerinde FrankenPHP çalıştırmak için [WSL](https://learn.microsoft.com/windows/wsl/) kullanın. ### Kurulum Betiği Platformunuza uygun sürümü otomatik olarak kurmak için bu satırı terminalinize kopyalayabilirsiniz: ```console curl https://frankenphp.dev/install.sh | sh ``` ### Binary Çıktısı Docker kullanmayı tercih etmiyorsanız, Linux ve macOS için geliştirme amaçlı bağımsız (statik) FrankenPHP binary dosyaları sağlıyoruz; [PHP 8.4](https://www.php.net/releases/8.4/en.php) ve en popüler PHP eklentilerinin çoğu dahildir. [FrankenPHP'yi indirin](https://github.com/php/frankenphp/releases) **Eklenti kurulumu:** Yaygın eklentiler paketle birlikte gelir. Daha fazla eklenti yüklemek mümkün değildir. ### rpm Paketleri Bakımcılarımız `dnf` kullanan tüm sistemler için rpm paketleri sunuyor. Kurulum için: ```console sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm sudo dnf module enable php-zts:static-8.4 # 8.2-8.5 mevcut sudo dnf install frankenphp ``` **Eklenti kurulumu:** `sudo dnf install php-zts-` Varsayılan olarak mevcut olmayan eklentiler için [PIE](https://github.com/php/pie) kullanın: ```console sudo dnf install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### deb Paketleri Bakımcılarımız `apt` kullanan tüm sistemler için deb paketleri sunuyor. Kurulum için: ```console sudo curl -fsSL https://key.henderkes.com/static-php.gpg -o /usr/share/keyrings/static-php.gpg && \ echo "deb [signed-by=/usr/share/keyrings/static-php.gpg] https://deb.henderkes.com/ stable main" | sudo tee /etc/apt/sources.list.d/static-php.list && \ sudo apt update sudo apt install frankenphp ``` **Eklenti kurulumu:** `sudo apt install php-zts-` Varsayılan olarak mevcut olmayan eklentiler için [PIE](https://github.com/php/pie) kullanın: ```console sudo apt install pie-zts sudo pie-zts install asgrim/example-pie-extension ``` ### Docker ```console docker run -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` `https://localhost` adresine gidin ve keyfini çıkarın! > [!TIP] > > `https://127.0.0.1` kullanmaya çalışmayın. `https://localhost` kullanın ve kendinden imzalı sertifikayı kabul edin. > Kullanılacak alan adını değiştirmek için [`SERVER_NAME` ortam değişkenini](https://frankenphp.dev/tr/docs/config#ortam-değişkenleri) kullanın. ### Homebrew FrankenPHP, macOS ve Linux için [Homebrew](https://brew.sh) paketi olarak da mevcuttur. ```console brew install dunglas/frankenphp/frankenphp ``` **Eklenti kurulumu:** [PIE](https://github.com/php/pie) kullanın. ### Kullanım Geçerli dizinin içeriğini sunmak için çalıştırın: ```console frankenphp php-server ``` Komut satırı betiklerini şu şekilde çalıştırabilirsiniz: ```console frankenphp php-cli /path/to/your/script.php ``` deb ve rpm paketleri için systemd servisini de başlatabilirsiniz: ```console sudo systemctl start frankenphp ``` ## Docs - [Worker modu](worker.md) - [Early Hints desteği (103 HTTP durum kodu)](early-hints.md) - [Real-time](mercure.md) - [Konfigürasyon](config.md) - [Docker imajları](docker.md) - [Production'a dağıtım](production.md) - [**Bağımsız** kendiliğinden çalıştırılabilir PHP uygulamaları oluşturma](embed.md) - [Statik binary'leri oluşturma](static.md) - [Kaynak dosyalarından derleme](config.md) - [Laravel entegrasyonu](laravel.md) - [Bilinen sorunlar](known-issues.md) - [Demo uygulama (Symfony) ve kıyaslamalar](https://github.com/dunglas/frankenphp-demo) - [Go kütüphane dokümantasonu](https://pkg.go.dev/github.com/dunglas/frankenphp) - [Katkıda bulunma ve hata ayıklama](CONTRIBUTING.md) ## Örnekler ve İskeletler - [Symfony](https://github.com/dunglas/symfony-docker) - [API Platform](https://api-platform.com/docs/distribution/) - [Laravel](https://frankenphp.dev/docs/laravel/) - [Sulu](https://sulu.io/blog/running-sulu-with-frankenphp) - [WordPress](https://github.com/StephenMiracle/frankenwp) - [Drupal](https://github.com/dunglas/frankenphp-drupal) - [Joomla](https://github.com/alexandreelise/frankenphp-joomla) - [TYPO3](https://github.com/ochorocho/franken-typo3) - [Magento2](https://github.com/ekino/frankenphp-magento2) ================================================ FILE: docs/tr/compile.md ================================================ # Kaynak Kodlardan Derleme Bu doküman, PHP'yi dinamik bir kütüphane olarak yükleyecek bir FrankenPHP yapısının nasıl oluşturulacağını açıklamaktadır. Önerilen yöntem bu şekildedir. Alternatif olarak, [statik yapılar oluşturma](static.md) da mümkündür. ## PHP'yi yükleyin FrankenPHP, PHP 8.2 ve üstü ile uyumludur. İlk olarak, [PHP'nin kaynaklarını edinin](https://www.php.net/downloads.php) ve bunları çıkarın: ```console tar xf php-* cd php-*/ ``` Ardından, PHP'yi platformunuz için yapılandırın. Bu şekilde yapılandırma gereklidir, ancak başka opsiyonlar da ekleyebilirsiniz (örn. ekstra uzantılar) İhtiyaç halinde. ### Linux ```console ./configure \ --enable-embed \ --enable-zts \ --disable-zend-signals \ --enable-zend-max-execution-timers ``` ### Mac Yüklemek için [Homebrew](https://brew.sh/) paket yöneticisini kullanın `libiconv`, `bison`, `re2c` ve `pkg-config`: ```console brew install libiconv bison re2c pkg-config echo 'export PATH="/opt/homebrew/opt/bison/bin:$PATH"' >> ~/.zshrc ``` Ardından yapılandırma betiğini çalıştırın: ```console ./configure \ --enable-embed=static \ --enable-zts \ --disable-zend-signals \ --disable-opcache-jit \ --enable-static \ --enable-shared=no \ --with-iconv=/opt/homebrew/opt/libiconv/ ``` ## PHP Derleyin Son olarak, PHP'yi derleyin ve kurun: ```console make -j"$(getconf _NPROCESSORS_ONLN)" sudo make install ``` ## Go Uygulamasını Derleyin Artık Go kütüphanesini kullanabilir ve Caddy yapımızı derleyebilirsiniz: ```console curl -L https://github.com/php/frankenphp/archive/refs/heads/main.tar.gz | tar xz cd frankenphp-main/caddy/frankenphp CGO_CFLAGS=$(php-config --includes) CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" go build ``` ### Xcaddy kullanımı Alternatif olarak, FrankenPHP'yi [özel Caddy modülleri](https://caddyserver.com/docs/modules/) ile derlemek için [xcaddy](https://github.com/caddyserver/xcaddy) kullanın: ```console CGO_ENABLED=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags '-w -s'" \ xcaddy build \ --output frankenphp \ --with github.com/dunglas/frankenphp/caddy \ --with github.com/dunglas/caddy-cbrotli \ --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Add extra Caddy modules here ``` > [!TIP] > > Eğer musl libc (Alpine Linux'ta varsayılan) ve Symfony kullanıyorsanız, > varsayılan yığın boyutunu artırmanız gerekebilir. > Aksi takdirde, şu tarz hatalar alabilirsiniz `PHP Fatal error: Maximum call stack size of 83360 bytes reached during compilation. Try splitting expression` > > Bunu yapmak için, `XCADDY_GO_BUILD_FLAGS` ortam değişkenini bu şekilde değiştirin > `XCADDY_GO_BUILD_FLAGS=$'-ldflags "-w -s -extldflags \'-Wl,-z,stack-size=0x80000\'"'` > (yığın boyutunun değerini uygulamanızın ihtiyaçlarına göre değiştirin). ================================================ FILE: docs/tr/config.md ================================================ # Konfigürasyon FrankenPHP, Caddy'nin yanı sıra [Mercure](mercure.md) ve [Vulcain](https://vulcain.rocks) modülleri [Caddy tarafından desteklenen formatlar](https://caddyserver.com/docs/getting-started#your-first-config) kullanılarak yapılandırılabilir. En yaygın format, basit, insan tarafından okunabilir bir metin formatı olan `Caddyfile`'dır. Varsayılan olarak, FrankenPHP mevcut dizinde bir `Caddyfile` arar. Özel bir yol belirtmek için `-c` veya `--config` seçeneğini kullanabilirsiniz. Bir PHP uygulamasını sunmak için minimal bir `Caddyfile` aşağıda gösterilmiştir: ```caddyfile # Yanıt verilecek ana bilgisayar adı localhost # İsteğe bağlı olarak, dosyaların sunulacağı dizin, aksi takdirde mevcut dizin varsayılan olarak kullanılır #root public/ php_server ``` Daha fazla özellik sağlayan ve kullanışlı ortam değişkenleri sunan daha gelişmiş bir `Caddyfile`, [FrankenPHP deposunda](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) ve Docker imajlarıyla birlikte sağlanır. PHP'nin kendisi [bir `php.ini` dosyası kullanılarak yapılandırılabilir](https://www.php.net/manual/en/configuration.file.php). Kurulum yönteminize bağlı olarak, FrankenPHP ve PHP yorumlayıcısı, aşağıda açıklanan konumlardaki yapılandırma dosyalarını arayacaktır. ## Docker FrankenPHP: - `/etc/frankenphp/Caddyfile`: ana yapılandırma dosyası - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: otomatik olarak yüklenen ek yapılandırma dosyaları PHP: - `php.ini`: `/usr/local/etc/php/php.ini` (varsayılan olarak bir `php.ini` sağlanmaz) - ek yapılandırma dosyaları: `/usr/local/etc/php/conf.d/*.ini` - PHP uzantıları: `/usr/local/lib/php/extensions/no-debug-zts-/` - PHP projesi tarafından sağlanan resmi bir şablonu kopyalamalısınız: ```dockerfile FROM dunglas/frankenphp # Production: RUN cp $PHP_INI_DIR/php.ini-production $PHP_INI_DIR/php.ini # Veya development: RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini ``` ## RPM ve Debian paketleri FrankenPHP: - `/etc/frankenphp/Caddyfile`: ana yapılandırma dosyası - `/etc/frankenphp/Caddyfile.d/*.caddyfile`: otomatik olarak yüklenen ek yapılandırma dosyaları PHP: - `php.ini`: `/etc/php-zts/php.ini` (varsayılan olarak üretim ön ayarlarına sahip bir `php.ini` dosyası sağlanır) - ek yapılandırma dosyaları: `/etc/php-zts/conf.d/*.ini` ## Statik ikili FrankenPHP: - Mevcut çalışma dizininde: `Caddyfile` PHP: - `php.ini`: `frankenphp run` veya `frankenphp php-server` komutunun çalıştırıldığı dizin, ardından `/etc/frankenphp/php.ini` - ek yapılandırma dosyaları: `/etc/frankenphp/php.d/*.ini` - PHP uzantıları: yüklenemez, bunları doğrudan ikili dosyaya dahil edin - [PHP kaynak kodu](https://github.com/php/php-src/) ile birlikte verilen `php.ini-production` veya `php.ini-development` dosyalarından birini kopyalayın. ## Caddyfile Konfigürasyonu PHP uygulamanızı sunmak için site blokları içinde `php_server` veya `php` [HTTP yönergeleri](https://caddyserver.com/docs/caddyfile/concepts#directives) kullanılabilir. Minimal örnek: ```caddyfile localhost { # Sıkıştırmayı etkinleştir (isteğe bağlı) encode zstd br gzip # Geçerli dizindeki PHP dosyalarını çalıştırın ve varlıkları sunun php_server } ``` Ayrıca, FrankenPHP'yi [global seçenek](https://caddyserver.com/docs/caddyfile/concepts#global-options) olan `frankenphp` kullanarak açıkça yapılandırabilirsiniz: ```caddyfile { frankenphp { num_threads # Başlatılacak PHP iş parçacığı sayısını ayarlar. Varsayılan: Mevcut CPU'ların 2 katı. max_threads # Çalışma zamanında başlatılabilecek ek PHP iş parçacığı sayısını sınırlar. Varsayılan: num_threads. 'auto' olarak ayarlanabilir. max_wait_time # Bir isteğin boş bir PHP iş parçacığı bekleme süresinin zaman aşımına uğramadan önceki maksimum süresini ayarlar. Varsayılan: devre dışı. max_idle_time # Otomatik ölçeklenen bir iş parçacığının devre dışı bırakılmadan önce ne kadar süre boş kalabileceğini ayarlar. Varsayılan: 5s. php_ini # Bir php.ini yönergesi ayarlar. Birden fazla yönerge ayarlamak için birden fazla kez kullanılabilir. worker { file # Çalışan komut dosyasının yolunu ayarlar. num # Başlatılacak PHP iş parçacığı sayısını ayarlar, varsayılan değer mevcut CPU'ların 2 katıdır. env # Ek bir ortam değişkenini verilen değere ayarlar. Birden fazla ortam değişkeni için birden fazla kez belirtilebilir. watch # Dosya değişikliklerini izlemek için yolu ayarlar. Birden fazla yol için birden fazla kez belirtilebilir. name # İşçinin adını ayarlar, günlüklerde ve metriklerde kullanılır. Varsayılan: işçi dosyasının mutlak yolu. max_consecutive_failures # İşçinin sağlıksız kabul edilmeden önceki maksimum ardışık hata sayısını ayarlar, -1 işçinin her zaman yeniden başlayacağı anlamına gelir. Varsayılan: 6. } } } # ... ``` Alternatif olarak, `worker` seçeneğinin tek satırlık kısa formunu kullanabilirsiniz: ```caddyfile { frankenphp { worker } } # ... ``` Aynı sunucuda birden fazla uygulamaya hizmet veriyorsanız birden fazla işçi de tanımlayabilirsiniz: ```caddyfile app.example.com { root /path/to/app/public php_server { root /path/to/app/public # daha iyi önbelleğe almayı sağlar worker index.php } } other.example.com { root /path/to/other/public php_server { root /path/to/other/public worker index.php } } # ... ``` Genellikle ihtiyacınız olan şey `php_server` yönergesini kullanmaktır, ancak tam kontrole ihtiyacınız varsa, daha düşük seviyeli `php` yönergesini kullanabilirsiniz. `php` yönergesi, önce bir PHP dosyası olup olmadığını kontrol etmek yerine tüm girdiyi PHP'ye iletir. Daha fazla bilgiyi [performans sayfasında](performance.md#try_files) okuyun. `php_server` yönergesini kullanmak bu yapılandırmayla aynıdır: ```caddyfile route { # Dizin istekleri için sondaki eğik çizgiyi ekleyin @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # İstenen dosya mevcut değilse, dizin dosyalarını deneyin @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} # FrankenPHP! @phpFiles path *.php php @phpFiles file_server } ``` `php_server` ve `php` yönergeleri aşağıdaki seçeneklere sahiptir: ```caddyfile php_server [] { root # Sitenin kök klasörünü ayarlar. Varsayılan: `root` yönergesi. split_path # URI'yi iki parçaya bölmek için alt dizgeleri ayarlar. İlk eşleşen alt dizge "yol bilgisini" yoldan ayırmak için kullanılır. İlk parça eşleşen alt dizeyle sonlandırılır ve gerçek kaynak (CGI betiği) adı olarak kabul edilir. İkinci parça betiğin kullanması için PATH_INFO olarak ayarlanacaktır. Varsayılan: `.php` resolve_root_symlink false # Varsa, sembolik bir bağlantıyı değerlendirerek `root` dizininin gerçek değerine çözümlenmesini devre dışı bırakır (varsayılan olarak etkindir). env # Ek bir ortam değişkenini verilen değere ayarlar. Birden fazla ortam değişkeni için birden fazla kez belirtilebilir. file_server off # Yerleşik file_server yönergesini devre dışı bırakır. worker { # Bu sunucuya özgü bir worker oluşturur. Birden fazla worker için birden fazla kez belirtilebilir. file # Worker betiğinin yolunu ayarlar, php_server köküne göre göreceli olabilir num # Başlatılacak PHP iş parçacığı sayısını ayarlar, varsayılan değer mevcut CPU'ların 2 katıdır. name # Worker için günlüklerde ve metriklerde kullanılan bir ad ayarlar. Varsayılan: worker dosyasının mutlak yolu. Bir php_server bloğunda tanımlandığında her zaman m# ile başlar. watch # Dosya değişikliklerini izlemek için yolu ayarlar. Birden fazla yol için birden fazla kez belirtilebilir. env # Ek bir ortam değişkenini verilen değere ayarlar. Birden fazla ortam değişkeni için birden fazla kez belirtilebilir. Bu worker için ortam değişkenleri ayrıca php_server üst öğesinden devralınır, ancak burada geçersiz kılınabilir. match # İşçiyi bir yol desenine eşleştirir. try_files'ı geçersiz kılar ve yalnızca php_server yönergesinde kullanılabilir. } worker # Global frankenphp bloğundaki gibi kısa formu da kullanabilirsiniz. } ``` ### Dosya Değişikliklerini İzleme Workers yalnızca uygulamanızı bir kez başlatır ve bellekte tutar, bu nedenle PHP dosyalarınızdaki herhangi bir değişiklik hemen yansımaz. Bunun yerine işçiler, `watch` yönergesi aracılığıyla dosya değişikliklerinde yeniden başlatılabilir. Bu, geliştirme ortamları için kullanışlıdır. ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch } } } ``` Bu özellik genellikle [hot reload](hot-reload.md) ile birlikte kullanılır. Eğer `watch` dizini belirtilmezse, FrankenPHP sürecinin başlatıldığı dizin ve alt dizinlerdeki tüm `.env`, `.php`, `.twig`, `.yaml` ve `.yml` dosyalarını izleyen `./**/*.{env,php,twig,yaml,yml}` değerine geri döner. Bunun yerine, bir veya daha fazla dizini [kabuk dosya adı deseni](https://pkg.go.dev/path/filepath#Match) aracılığıyla da belirtebilirsiniz: ```caddyfile { frankenphp { worker { file /path/to/app/public/worker.php watch /path/to/app # /path/to/app'ın tüm alt dizinlerindeki tüm dosyaları izler watch /path/to/app/*.php # /path/to/app'da .php ile biten dosyaları izler watch /path/to/app/**/*.php # /path/to/app ve alt dizinlerindeki PHP dosyalarını izler watch /path/to/app/**/*.{php,twig} # /path/to/app ve alt dizinlerindeki PHP ve Twig dosyalarını izler } } } ``` - `**` deseni, özyinelemeli izlemeyi belirtir - Dizinler göreceli de olabilir (FrankenPHP sürecinin başlatıldığı yere göre) - Birden fazla işçi tanımladıysanız, bir dosya değiştiğinde hepsi yeniden başlatılacaktır. - Çalışma zamanında oluşturulan dosyaları (günlükler gibi) izlerken dikkatli olun, zira bunlar istenmeyen işçi yeniden başlatmalarına neden olabilir. Dosya izleyici [e-dant/watcher](https://github.com/e-dant/watcher) üzerine kuruludur. ## İşçiyi Yola Eşleştirme Geleneksel PHP uygulamalarında, betikler her zaman public dizininde bulunur. Bu, diğer tüm PHP betikleri gibi ele alınan işçi betikleri için de geçerlidir. İşçi betiğini public dizininin dışına koymak isterseniz, bunu `match` yönergesi aracılığıyla yapabilirsiniz. `match` yönergesi, yalnızca `php_server` ve `php` içinde bulunan `try_files`'a optimize edilmiş bir alternatiftir. Aşağıdaki örnek, varsa her zaman public dizinindeki bir dosyayı sunacak, aksi takdirde isteği yol desenine uyan işçiye iletecektir. ```caddyfile { frankenphp { php_server { worker { file /path/to/worker.php # dosya public yolunun dışında olabilir match /api/* # /api/ ile başlayan tüm istekler bu worker tarafından işlenecektir } } } } ``` ## Ortam Değişkenleri Aşağıdaki ortam değişkenleri `Caddyfile` içinde değişiklik yapmadan Caddy yönergelerini entegre etmek için kullanılabilir: - `SERVER_NAME`: [dinlenecek adresleri](https://caddyserver.com/docs/caddyfile/concepts#addresses) değiştirir, sağlanan ana bilgisayar adları oluşturulan TLS sertifikası için de kullanılacaktır - `SERVER_ROOT`: sitenin kök dizinini değiştirir, varsayılan olarak `public/`dir - `CADDY_GLOBAL_OPTIONS`: [global seçenekleri](https://caddyserver.com/docs/caddyfile/options) entegre eder - `FRANKENPHP_CONFIG`: `frankenphp` yönergesi altına yapılandırma entegre eder FPM ve CLI SAPI'lerinde olduğu gibi, ortam değişkenleri varsayılan olarak `$_SERVER` süper globalinde gösterilir. [`variables_order`'a ait PHP yönergesinin](https://www.php.net/manual/en/ini.core.php#ini.variables-order) `S` değeri bu yönergede `E`'nin başka bir yere yerleştirilmesinden bağımsız olarak her zaman `ES` ile eş değerdir. ## PHP konfigürasyonu Ek olarak [PHP yapılandırma dosyalarını](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan) yüklemek için, `PHP_INI_SCAN_DIR` ortam değişkeni kullanılabilir. Ayarlandığında, PHP verilen dizinlerde bulunan `.ini` uzantılı tüm dosyaları yükleyecektir. PHP yapılandırmasını `Caddyfile` içindeki `php_ini` yönergesini kullanarak da değiştirebilirsiniz: ```caddyfile { frankenphp { php_ini memory_limit 256M # veya php_ini { memory_limit 256M max_execution_time 15 } } } ``` ### HTTPS'i Devre Dışı Bırakma Varsayılan olarak, FrankenPHP tüm ana bilgisayar adları için (localhost dahil) HTTPS'i otomatik olarak etkinleştirir. HTTPS'i devre dışı bırakmak isterseniz (örneğin bir geliştirme ortamında), `SERVER_NAME` ortam değişkenini `http://` veya `:80` olarak ayarlayabilirsiniz: Alternatif olarak, [Caddy belgelerinde](https://caddyserver.com/docs/automatic-https#activation) açıklanan diğer tüm yöntemleri kullanabilirsiniz. Eğer `localhost` ana bilgisayar adı yerine `127.0.0.1` IP adresiyle HTTPS kullanmak isterseniz, lütfen [bilinen sorunlar](known-issues.md#using-https127001-with-docker) bölümünü okuyun. ### Tam Çift Yönlü (HTTP/1) HTTP/1.x kullanırken, tüm gövde okunmadan önce bir yanıt yazmaya izin vermek için tam çift yönlü modun etkinleştirilmesi istenebilir. (örneğin: [Mercure](mercure.md), WebSocket, Sunucu Tarafından Gönderilen Olaylar vb.) Bu, `Caddyfile`'daki global seçeneklere eklenmesi gereken isteğe bağlı bir yapılandırmadır: ```caddyfile { servers { enable_full_duplex } } ``` > [!CAUTION] > > Bu seçeneği etkinleştirmek, tam çift yönlü desteği olmayan eski HTTP/1.x istemcilerinin kilitlenmesine neden olabilir. > Bu, `CADDY_GLOBAL_OPTIONS` ortam yapılandırması kullanılarak da yapılandırılabilir: ```sh CADDY_GLOBAL_OPTIONS="servers { enable_full_duplex }" ``` Bu ayar hakkında daha fazla bilgiyi [Caddy belgelerinde](https://caddyserver.com/docs/caddyfile/options#enable-full-duplex) bulabilirsiniz. ## Hata Ayıklama Modunu Etkinleştirin Docker imajını kullanırken, hata ayıklama modunu etkinleştirmek için `CADDY_GLOBAL_OPTIONS` ortam değişkenini `debug` olarak ayarlayın: ```console docker run -v $PWD:/app/public \ -e CADDY_GLOBAL_OPTIONS=debug \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Shell Completion FrankenPHP, Bash, Zsh, Fish ve PowerShell için yerleşik kabuk tamamlama desteği sağlar. Bu, tüm komutlar ( `php-server`, `php-cli` ve `extension-init` gibi özel komutlar dahil) ve bunların bayrakları için otomatik tamamlama sağlar. ### Bash Geçerli kabuk oturumunuzda tamamlamaları yüklemek için: ```console source <(frankenphp completion bash) ``` Her yeni oturum için tamamlamaları yüklemek için şunu çalıştırın: **Linux:** ```console frankenphp completion bash > /usr/share/bash-completion/completions/frankenphp ``` **macOS:** ```console frankenphp completion bash > $(brew --prefix)/share/bash-completion/completions/frankenphp ``` ### Zsh Ortamınızda kabuk tamamlama zaten etkin değilse, bunu etkinleştirmeniz gerekecektir. Aşağıdakini bir kez çalıştırabilirsiniz: ```console echo "autoload -U compinit; compinit" >> ~/.zshrc ``` Her oturum için tamamlamaları yüklemek için, bir kez çalıştırın: ```console frankenphp completion zsh > "${fpath[1]}/_frankenphp" ``` Bu kurulumun etkili olması için yeni bir kabuk başlatmanız gerekecektir. ### Fish Geçerli kabuk oturumunuzda tamamlamaları yüklemek için: ```console frankenphp completion fish | source ``` Her yeni oturum için tamamlamaları yüklemek için, bir kez çalıştırın: ```console frankenphp completion fish > ~/.config/fish/completions/frankenphp.fish ``` ### PowerShell Geçerli kabuk oturumunuzda tamamlamaları yüklemek için: ```powershell frankenphp completion powershell | Out-String | Invoke-Expression ``` Her yeni oturum için tamamlamaları yüklemek için, bir kez çalıştırın: ```powershell frankenphp completion powershell | Out-File -FilePath (Join-Path (Split-Path $PROFILE) "frankenphp.ps1") Add-Content -Path $PROFILE -Value '. (Join-Path (Split-Path $PROFILE) "frankenphp.ps1")' ``` Bu kurulumun etkili olması için yeni bir kabuk başlatmanız gerekecektir. Bu kurulumun etkili olması için yeni bir kabuk başlatmanız gerekecektir. ================================================ FILE: docs/tr/docker.md ================================================ # Özel Docker İmajı Oluşturma [FrankenPHP Docker imajları](https://hub.docker.com/r/dunglas/frankenphp), [resmi PHP imajları](https://hub.docker.com/_/php/) temel alınarak hazırlanmıştır. Popüler mimariler için Debian ve Alpine Linux varyantları sağlanmıştır. Debian varyantları tavsiye edilir. PHP 8.2, 8.3, 8.4 ve 8.5 için varyantlar sağlanmıştır. Etiketler şu deseni takip eder: `dunglas/frankenphp:-php-` - `` ve ``, sırasıyla FrankenPHP ve PHP'nin ana (örn. `1`), ikincil (örn. `1.2`) ve yama sürümlerine (örn. `1.2.3`) kadar değişen sürüm numaralarıdır. - `` ise `trixie` (Debian Trixie için), `bookworm` (Debian Bookworm için) veya `alpine` (Alpine'ın en son kararlı sürümü için) olabilir. [Etiketlere göz atın](https://hub.docker.com/r/dunglas/frankenphp/tags). ## İmajlar Nasıl Kullanılır Projenizde bir `Dockerfile` oluşturun: ```dockerfile FROM dunglas/frankenphp COPY . /app/public ``` Ardından, Docker imajını oluşturmak ve çalıştırmak için bu komutları çalıştırın: ```console docker build -t my-php-app . docker run -it --rm --name my-running-app my-php-app ``` ## Yapılandırma Nasıl Ayarlanır Kolaylık sağlamak için, faydalı ortam değişkenleri içeren [varsayılan bir `Caddyfile`](https://github.com/php/frankenphp/blob/main/caddy/frankenphp/Caddyfile) imajda sağlanmıştır. ## Daha Fazla PHP Eklentisi Nasıl Kurulur [`docker-php-extension-installer`](https://github.com/mlocati/docker-php-extension-installer) betiği temel imajda sağlanmıştır. Ek PHP eklentileri eklemek basittir: ```dockerfile FROM dunglas/frankenphp # ek eklentileri buraya ekleyin: RUN install-php-extensions \ pdo_mysql \ gd \ intl \ zip \ opcache ``` ## Daha Fazla Caddy Modülü Nasıl Kurulur FrankenPHP, Caddy'nin üzerine inşa edilmiştir ve tüm [Caddy modülleri](https://caddyserver.com/docs/modules/) FrankenPHP ile kullanılabilir. Özel Caddy modüllerini kurmanın en kolay yolu [xcaddy](https://github.com/caddyserver/xcaddy) kullanmaktır: ```dockerfile FROM dunglas/frankenphp:builder AS builder # xcaddy'yi builder imajına kopyalayın COPY --from=caddy:builder /usr/bin/xcaddy /usr/bin/xcaddy # CGO, FrankenPHP oluşturmak için etkinleştirilmelidir RUN CGO_ENABLED=1 \ XCADDY_SETCAP=1 \ XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS=$(php-config --includes) \ CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \ xcaddy build \ --output /usr/local/bin/frankenphp \ --with github.com/dunglas/frankenphp=./ \ --with github.com/dunglas/frankenphp/caddy=./caddy/ \ --with github.com/dunglas/caddy-cbrotli \ # Mercure ve Vulcain resmi derlemeye dahildir, ancak bunları kaldırmaktan çekinmeyin --with github.com/dunglas/mercure/caddy \ --with github.com/dunglas/vulcain/caddy # Ek Caddy modüllerini buraya ekleyin FROM dunglas/frankenphp AS runner # Resmi binary dosyayı özel modüllerinizi içeren binary dosyayla değiştirin COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp ``` FrankenPHP tarafından sağlanan `builder` imajı `libphp`'nin derlenmiş bir sürümünü içerir. [Builder imajları](https://hub.docker.com/r/dunglas/frankenphp/tags?name=builder) hem Debian hem de Alpine için FrankenPHP ve PHP'nin tüm sürümleri için sağlanmıştır. > [!TIP] > > Eğer Alpine Linux ve Symfony kullanıyorsanız, > [varsayılan yığın boyutunu artırmanız](compile.md#xcaddy-kullanımı) gerekebilir. ## Varsayılan Olarak Worker Modunun Etkinleştirilmesi FrankenPHP'yi bir worker betiği ile başlatmak için `FRANKENPHP_CONFIG` ortam değişkenini ayarlayın: ```dockerfile FROM dunglas/frankenphp # ... ENV FRANKENPHP_CONFIG="worker ./public/index.php" ``` ## Geliştirme Sürecinde Volume Kullanma FrankenPHP ile kolayca geliştirme yapmak için, uygulamanın kaynak kodunu içeren dizini ana bilgisayarınızdan Docker konteynerine bir volume olarak bağlayın: ```console docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp --tty my-php-app ``` > [!TIP] > > `--tty` seçeneği JSON günlükleri yerine insan tarafından okunabilir güzel günlüklere sahip olmayı sağlar. Docker Compose ile: ```yaml # compose.yaml services: php: image: dunglas/frankenphp # özel bir Dockerfile kullanmak istiyorsanız aşağıdaki satırın yorumunu kaldırın #build: . # bunu bir üretim ortamında çalıştırmak istiyorsanız aşağıdaki satırın yorumunu kaldırın # restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - ./:/app/public - caddy_data:/data - caddy_config:/config # üretimde aşağıdaki satırı yorum satırı yapın; geliştirme ortamında ise güzel, insan tarafından okunabilir günlükler sağlar tty: true # Caddy sertifikaları ve yapılandırması için gereken volume'ler volumes: caddy_data: caddy_config: ``` ## Root Olmayan Kullanıcı Olarak Çalıştırma FrankenPHP, Docker'da root olmayan kullanıcı olarak çalışabilir. İşte bunu yapan örnek bir `Dockerfile`: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Alpine tabanlı dağıtımlar için "adduser -D ${USER}" kullanın useradd ${USER}; \ # 80 ve 443 numaralı bağlantı noktalarına bağlanmak için ek özellik ekleyin setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp; \ # /config/caddy ve /data/caddy dosyalarına yazma erişimi verin chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` ### Yetenek Olmadan Çalıştırma FrankenPHP, root yetkisi olmadan çalışırken bile, web sunucusunu ayrıcalıklı bağlantı noktalarında (80 ve 443) bağlamak için `CAP_NET_BIND_SERVICE` yeteneğine ihtiyaç duyar. FrankenPHP'yi ayrıcalıklı olmayan bir bağlantı noktasında (1024 ve üzeri) çalıştırırsanız, web sunucusunu root olmayan bir kullanıcı olarak ve herhangi bir yeteneğe ihtiyaç duymadan çalıştırmak mümkündür: ```dockerfile FROM dunglas/frankenphp ARG USER=appuser RUN \ # Alpine tabanlı dağıtımlar için "adduser -D ${USER}" kullanın useradd ${USER}; \ # Varsayılan yeteneği kaldırın setcap -r /usr/local/bin/frankenphp; \ # /config/caddy ve /data/caddy dosyalarına yazma erişimi verin chown -R ${USER}:${USER} /config/caddy /data/caddy USER ${USER} ``` Ardından, ayrıcalıklı olmayan bir bağlantı noktası kullanmak için `SERVER_NAME` ortam değişkenini ayarlayın. Örnek: `:8000` ## Güncellemeler Docker imajları oluşturulur: - Yeni bir sürüm etiketlendiğinde - Her gün UTC ile sabah 4'te, resmi PHP imajlarının yeni sürümleri mevcutsa ## İmajları Sertleştirme FrankenPHP Docker imajlarınızın saldırı yüzeyini ve boyutunu daha da azaltmak için, onları [Google distroless](https://github.com/GoogleContainerTools/distroless) veya [Docker hardened](https://www.docker.com/products/hardened-images) bir imaj üzerine inşa etmek de mümkündür. > [!WARNING] > Bu minimal temel imajlar, hata ayıklamayı zorlaştıran bir kabuk veya paket yöneticisi içermez. > Bu nedenle, güvenlik yüksek öncelikliyse yalnızca üretim için önerilirler. Ek PHP eklentileri eklerken, bir ara derleme aşamasına ihtiyacınız olacaktır: ```dockerfile FROM dunglas/frankenphp AS builder # Ek PHP eklentilerini buraya ekleyin RUN install-php-extensions pdo_mysql pdo_pgsql #... # frankenphp'nin paylaşılan kütüphanelerini ve kurulu tüm eklentileri geçici bir konuma kopyalayın # Bu adımı, frankenphp binary'sinin ve her bir eklenti .so dosyasının ldd çıktısını analiz ederek manuel olarak da yapabilirsiniz RUN apt-get update && apt-get install -y libtree && \ EXT_DIR="$(php -r 'echo ini_get("extension_dir");')" && \ FRANKENPHP_BIN="$(which frankenphp)"; \ LIBS_TMP_DIR="/tmp/libs"; \ mkdir -p "$LIBS_TMP_DIR"; \ for target in "$FRANKENPHP_BIN" $(find "$EXT_DIR" -maxdepth 2 -type f -name "*.so"); do \ libtree -pv "$target" | sed 's/.*── \(.*\) \[.*/\1/' | grep -v "^$target" | while IFS= read -r lib; do \ [ -z "$lib" ] && continue; \ base=$(basename "$lib"); \ destfile="$LIBS_TMP_DIR/$base"; \ if [ ! -f "$destfile" ]; then \ cp "$lib" "$destfile"; \ fi; \ done; \ done # Distroless debian temel imajı, bunun temel imajla aynı debian sürümü olduğundan emin olun FROM gcr.io/distroless/base-debian13 # Docker hardened imaj alternatifi # FROM dhi.io/debian:13 # Uygulamanızın ve Caddyfile'ınızın konteynere kopyalanacak konumu ARG PATH_TO_APP="." ARG PATH_TO_CADDYFILE="./Caddyfile" # Uygulamanızı /app'e kopyalayın # Daha fazla sertleştirme için, yalnızca yazılabilir yolların nonroot kullanıcısına ait olduğundan emin olun COPY --chown=nonroot:nonroot "$PATH_TO_APP" /app COPY "$PATH_TO_CADDYFILE" /etc/caddy/Caddyfile # frankenphp'yi ve gerekli kütüphaneleri kopyalayın COPY --from=builder /usr/local/bin/frankenphp /usr/local/bin/frankenphp COPY --from=builder /usr/local/lib/php/extensions /usr/local/lib/php/extensions COPY --from=builder /tmp/libs /usr/lib # php.ini yapılandırma dosyalarını kopyalayın COPY --from=builder /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d COPY --from=builder /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini # Caddy veri dizinleri — salt okunur bir kök dosya sisteminde bile nonroot için yazılabilir olmalıdır ENV XDG_CONFIG_HOME=/config \ XDG_DATA_HOME=/data COPY --from=builder --chown=nonroot:nonroot /data/caddy /data/caddy COPY --from=builder --chown=nonroot:nonroot /config/caddy /config/caddy USER nonroot WORKDIR /app # Sağlanan Caddyfile ile frankenphp'yi çalıştırmak için giriş noktası ENTRYPOINT ["/usr/local/bin/frankenphp", "run", "-c", "/etc/caddy/Caddyfile"] ``` ## Geliştirme Sürümleri Geliştirme sürümleri [`dunglas/frankenphp-dev`](https://hub.docker.com/repository/docker/dunglas/frankenphp-dev) Docker deposunda mevcuttur. GitHub deposunun `main` dalına her commit gönderildiğinde yeni bir derleme tetiklenir. `latest*` etiketleri `main` dalının başına işaret eder. `sha-` biçimindeki etiketler de mevcuttur. ================================================ FILE: docs/tr/early-hints.md ================================================ # Early Hints FrankenPHP [103 Early Hints durum kodunu](https://developer.chrome.com/blog/early-hints/) yerel olarak destekler. Early Hints kullanmak web sayfalarınızın yüklenme süresini %30 oranında artırabilir. ```php ; rel=preload; as=style'); headers_send(103); // yavaş algoritmalarınız ve SQL sorgularınız 🤪 echo <<<'HTML' Hello FrankenPHP HTML; ``` Early Hints hem normal hem de [worker](worker.md) modları tarafından desteklenir. ================================================ FILE: docs/tr/embed.md ================================================ # Binary Dosyası Olarak PHP Uygulamaları FrankenPHP, PHP uygulamalarının kaynak kodunu ve varlıklarını statik, kendi kendine yeten bir binary dosyaya yerleştirme yeteneğine sahiptir. Bu özellik sayesinde PHP uygulamaları, uygulamanın kendisini, PHP yorumlayıcısını ve üretim düzeyinde bir web sunucusu olan Caddy'yi içeren bağımsız bir binary dosyalar olarak çıktısı alınabilir ve dağıtılabilir. Bu özellik hakkında daha fazla bilgi almak için [Kévin tarafından SymfonyCon 2023'te yapılan sunuma](https://dunglas.dev/2023/12/php-and-symfony-apps-as-standalone-binaries/) göz atabilirsiniz. ## Preparing Your App Bağımsız binary dosyayı oluşturmadan önce uygulamanızın gömülmeye hazır olduğundan emin olun. Örneğin muhtemelen şunları yapmak istersiniz: - Uygulamanın üretim bağımlılıklarını yükleyin - Otomatik yükleyiciyi boşaltın - Uygulamanızın üretim modunu etkinleştirin (varsa) - Nihai binary dosyanızın boyutunu küçültmek için `.git` veya testler gibi gerekli olmayan dosyaları çıkarın Örneğin, bir Symfony uygulaması için aşağıdaki komutları kullanabilirsiniz: ```console # .git/, vb. dosyalarından kurtulmak için projeyi dışa aktarın mkdir $TMPDIR/my-prepared-app git archive HEAD | tar -x -C $TMPDIR/my-prepared-app cd $TMPDIR/my-prepared-app # Uygun ortam değişkenlerini ayarlayın echo APP_ENV=prod > .env.local echo APP_DEBUG=0 >> .env.local # Testleri kaldırın rm -Rf tests/ # Bağımlılıkları yükleyin composer install --ignore-platform-reqs --no-dev -a # .env'yi optimize edin composer dump-env prod ``` ## Linux Binary'si Oluşturma Bir Linux binary çıktısı almanın en kolay yolu, sağladığımız Docker tabanlı derleyiciyi kullanmaktır. 1. Hazırladığınız uygulamanın deposunda `static-build.Dockerfile` adlı bir dosya oluşturun: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # İkili dosyayı musl-libc sistemlerinde çalıştırmayı düşünüyorsanız static-builder-musl kullanın # Uygulamanızı kopyalayın WORKDIR /go/src/app/dist/app COPY . . # Statik binary dosyasını oluşturun, yalnızca istediğiniz PHP eklentilerini seçtiğinizden emin olun WORKDIR /go/src/app/ RUN EMBED=dist/app/ \ ./build-static.sh ``` > [!CAUTION] > > Bazı `.dockerignore` dosyaları (örneğin varsayılan [Symfony Docker `.dockerignore`](https://github.com/dunglas/symfony-docker/blob/main/.dockerignore)) > `vendor/` dizinini ve `.env` dosyalarını yok sayacaktır. Derlemeden önce `.dockerignore` dosyasını ayarladığınızdan veya kaldırdığınızdan emin olun. 2. Derleyin: ```console docker build -t static-app -f static-build.Dockerfile . ``` 3. Binary dosyasını çıkarın: ```console docker cp $(docker create --name static-app-tmp static-app):/go/src/app/dist/frankenphp-linux-x86_64 my-app ; docker rm static-app-tmp ``` Elde edilen binary dosyası, geçerli dizindeki `my-app` adlı dosyadır. ## Diğer İşletim Sistemleri için Binary Çıktısı Alma Docker kullanmak istemiyorsanız veya bir macOS binary dosyası oluşturmak istiyorsanız, sağladığımız kabuk betiğini kullanın: ```console git clone https://github.com/php/frankenphp cd frankenphp EMBED=/path/to/your/app \ ./build-static.sh ``` Elde edilen binary dosyası `dist/` dizinindeki `frankenphp--` adlı dosyadır. ## Binary Dosyasını Kullanma İşte bu kadar! `my-app` dosyası (veya diğer işletim sistemlerinde `dist/frankenphp--`) bağımsız uygulamanızı içerir! Web uygulamasını başlatmak için çalıştırın: ```console ./my-app php-server ``` Uygulamanız bir [worker betiği](worker.md) içeriyorsa, worker'ı aşağıdaki gibi bir şeyle başlatın: ```console ./my-app php-server --worker public/index.php ``` HTTPS (Let's Encrypt sertifikası otomatik olarak oluşturulur), HTTP/2 ve HTTP/3'ü etkinleştirmek için kullanılacak alan adını belirtin: ```console ./my-app php-server --domain localhost ``` Ayrıca binary dosyanıza gömülü PHP CLI betiklerini de çalıştırabilirsiniz: ```console ./my-app php-cli bin/console ``` ## Yapıyı Özelleştirme Binary dosyasının nasıl özelleştirileceğini (uzantılar, PHP sürümü...) görmek için [Statik derleme dokümanını okuyun](static.md). ## Binary Dosyasının Dağıtılması Linux'ta, oluşturulan ikili dosya [UPX](https://upx.github.io) kullanılarak sıkıştırılır. Mac'te, göndermeden önce dosyanın boyutunu küçültmek için sıkıştırabilirsiniz. Biz `xz` öneririz. ================================================ FILE: docs/tr/extension-workers.md ================================================ # Uzantı İşçileri Uzantı İşçileri, [FrankenPHP uzantınızın](https://frankenphp.dev/docs/extensions/) arka plan görevlerini yürütmek, eşzamansız olayları işlemek veya özel protokolleri uygulamak için özel bir PHP iş parçacığı havuzunu yönetmesini sağlar. Kuyruk sistemleri, olay dinleyicileri, zamanlayıcılar vb. için kullanışlıdır. ## İşçiyi Kaydetme ### Statik Kayıt İşçiyi kullanıcı tarafından yapılandırılabilir hale getirmeniz gerekmiyorsa (sabit komut dosyası yolu, sabit iş parçacığı sayısı), işçiyi `init()` fonksiyonunda basitçe kaydedebilirsiniz. ```go package myextension import ( "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/caddy" ) // İşçi havuzuyla iletişim kurmak için genel tanıtıcı var worker frankenphp.Workers func init() { // Modül yüklendiğinde işçiyi kaydet. worker = caddy.RegisterWorkers( "my-internal-worker", // Benzersiz isim "worker.php", // Komut dosyası yolu (çalışmaya göre veya mutlak) 2, // Sabit iş parçacığı sayısı // İsteğe bağlı Yaşam Döngüsü Kancaları frankenphp.WithWorkerOnServerStartup(func() { // Genel kurulum mantığı... }), ) } ``` ### Bir Caddy Modülünde (Kullanıcı tarafından yapılandırılabilir) Uzantınızı paylaşmayı planlıyorsanız (genel bir kuyruk veya olay dinleyici gibi), onu bir Caddy modülüne sarmalısınız. Bu, kullanıcıların `Caddyfile` aracılığıyla komut dosyası yolunu ve iş parçacığı sayısını yapılandırmasına olanak tanır. Bu, `caddy.Provisioner` arayüzünü uygulamayı ve Caddyfile'ı ayrıştırmayı gerektirir ([bir örnek görmek için](https://github.com/dunglas/frankenphp-queue/blob/989120d394d66dd6c8e2101cac73dd622fade334/caddy.go)). ### Saf Bir Go Uygulamasında (Gömme) FrankenPHP'yi [Caddy olmadan standart bir Go uygulamasına gömüyorsanız](https://pkg.go.dev/github.com/dunglas/frankenphp#example-ServeHTTP), seçenekleri başlatırken `frankenphp.WithExtensionWorkers` kullanarak uzantı işçilerini kaydedebilirsiniz. ## İşçilerle Etkileşim Kurma İşçi havuzu aktif hale geldiğinde, ona görevler gönderebilirsiniz. Bu, [PHP'ye dışa aktarılan yerel fonksiyonlar](https://frankenphp.dev/docs/extensions/#writing-the-extension) içinde veya bir cron zamanlayıcı, bir olay dinleyicisi (MQTT, Kafka) veya herhangi başka bir goroutine gibi herhangi bir Go mantığından yapılabilir. ### Başsız Mod : `SendMessage` Doğrudan işçi komut dosyanıza ham veri geçirmek için `SendMessage` kullanın. Bu, kuyruklar veya basit komutlar için idealdir. #### Örnek: Asenkron Bir Kuyruk Uzantısı ```go // #include import "C" import ( "context" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_queue_push(mixed $data): bool func my_queue_push(data *C.zval) bool { // 1. İşçinin hazır olduğundan emin olun if worker == nil { return false } // 2. Arka plan işçisine gönder _, err := worker.SendMessage( context.Background(), // Standart Go bağlamı unsafe.Pointer(data), // İşçiye iletilecek veri nil, // İsteğe bağlı http.ResponseWriter ) return err == nil } ``` ### HTTP Emülasyonu :`SendRequest` Uzantınızın standart bir web ortamı bekleyen ( `$_SERVER`, `$_GET` vb. dolduran) bir PHP komut dosyasını çağırması gerekiyorsa `SendRequest` kullanın. ```go // #include import "C" import ( "net/http" "net/http/httptest" "unsafe" "github.com/dunglas/frankenphp" ) //export_php:function my_worker_http_request(string $path): string func my_worker_http_request(path *C.zend_string) unsafe.Pointer { // 1. İsteği ve kaydediciyi hazırla url := frankenphp.GoString(unsafe.Pointer(path)) req, _ := http.NewRequest("GET", url, http.NoBody) rr := httptest.NewRecorder() // 2. İşçiye gönder if err := worker.SendRequest(rr, req); err != nil { return nil } // 3. Yakalanan yanıtı döndür return frankenphp.PHPString(rr.Body.String(), false) } ``` ## İşçi Komut Dosyası PHP işçi komut dosyası bir döngüde çalışır ve hem ham mesajları hem de HTTP isteklerini işleyebilir. ```php [!WARNING] > > Bu özellik **yalnızca geliştirme ortamları** içindir. > `hot_reload`'u üretimde etkinleştirmeyin, zira bu özellik güvenli değildir (hassas dahili ayrıntıları açığa çıkarır) ve uygulamanın yavaşlamasına neden olur. > ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload } ``` Varsayılan olarak, FrankenPHP mevcut çalışma dizinindeki şu glob desenine uyan tüm dosyaları izleyecektir: `./**/*.{css,env,gif,htm,html,jpg,jpeg,js,mjs,php,png,svg,twig,webp,xml,yaml,yml}` İzlenecek dosyaları glob sözdizimi kullanarak açıkça ayarlamak mümkündür: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload src/**/*{.php,.js} config/**/*.yaml } ``` Kullanılacak Mercure konusunu ve izlenecek dizin veya dosyaları belirtmek için `hot_reload`'un uzun biçimini kullanın: ```caddyfile localhost mercure { anonymous } root public/ php_server { hot_reload { topic hot-reload-topic watch src/**/*.php watch assets/**/*.{ts,json} watch templates/ watch public/css/ } } ``` ## İstemci Tarafı Entegrasyonu Sunucu değişiklikleri algılarken, tarayıcının sayfayı güncellemek için bu olaylara abone olması gerekir. FrankenPHP, dosya değişikliklerine abone olmak için kullanılacak Mercure Hub URL'sini `$_SERVER['FRANKENPHP_HOT_RELOAD']` ortam değişkeni aracılığıyla gösterir. İstemci tarafı mantığını yönetmek için kullanışlı bir JavaScript kütüphanesi olan [frankenphp-hot-reload](https://www.npmjs.com/package/frankenphp-hot-reload) da mevcuttur. Kullanmak için ana düzeninize aşağıdakileri ekleyin: ```php FrankenPHP Hot Reload ``` Kütüphane otomatik olarak Mercure hub'ına abone olacak, bir dosya değişikliği algılandığında arka planda mevcut URL'yi getirecek ve DOM'u dönüştürecektir. Bir [npm](https://www.npmjs.com/package/frankenphp-hot-reload) paketi olarak ve [GitHub](https://github.com/dunglas/frankenphp-hot-reload) üzerinden edinilebilir. Alternatif olarak, `EventSource` yerel JavaScript sınıfını kullanarak doğrudan Mercure hub'ına abone olarak kendi istemci tarafı mantığınızı uygulayabilirsiniz. ### Mevcut DOM Düğümlerini Korumak Nadir durumlarda, [Symfony web hata ayıklama araç çubuğu gibi](https://github.com/symfony/symfony/pull/62970) geliştirme araçları kullanırken olduğu gibi, belirli DOM düğümlerini korumak isteyebilirsiniz. Bunu yapmak için, ilgili HTML öğesine `data-frankenphp-hot-reload-preserve` özniteliğini ekleyin: ```html
``` ## Çalışan Modu Uygulamanızı [Çalışan Modunda](https://frankenphp.dev/docs/worker/) çalıştırıyorsanız, uygulama betiğiniz bellekte kalır. Bu, tarayıcı yeniden yüklense bile PHP kodunuzdaki değişikliklerin hemen yansımayacağı anlamına gelir. En iyi geliştirici deneyimi için `hot_reload`'u [worker yönergesindeki `watch` alt yönergesiyle](config.md#watching-for-file-changes) birleştirmelisiniz. - `hot_reload`: dosyalar değiştiğinde **tarayıcıyı** yeniler - `worker.watch`: dosyalar değiştiğinde çalışanı yeniden başlatır ```caddy localhost mercure { anonymous } root public/ php_server { hot_reload worker { file /path/to/my_worker.php watch } } ``` ## Nasıl Çalışır 1. **İzleme**: FrankenPHP, arka planda [`e-dant/watcher` kütüphanesini](https://github.com/e-dant/watcher) kullanarak (Go bağlayıcısını biz geliştirdik) dosya sistemindeki değişiklikleri izler. 2. **Yeniden Başlatma (Çalışan Modu)**: Çalışan yapılandırmasında `watch` etkinse, yeni kodu yüklemek için PHP çalışanı yeniden başlatılır. 3. **Gönderme**: Değiştirilen dosyaların listesini içeren bir JSON yükü, yerleşik [Mercure hub'ına](https://mercure.rocks) gönderilir. 4. **Alma**: JavaScript kütüphanesi aracılığıyla dinleyen tarayıcı, Mercure olayını alır. 5. **Güncelleme**: - **Idiomorph** algılanırsa, güncellenmiş içeriği getirir ve mevcut HTML'i yeni duruma uydurmak için dönüştürerek, durum kaybetmeden değişiklikleri anında uygular. - Aksi takdirde, sayfayı yenilemek için `window.location.reload()` çağrılır. ================================================ FILE: docs/tr/known-issues.md ================================================ # Bilinen Sorunlar ## Desteklenmeyen PHP Eklentileri Aşağıdaki eklentilerin FrankenPHP ile uyumlu olmadığı bilinmektedir: | Adı | Nedeni | Alternatifleri | | ----------------------------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------- | | [imap](https://www.php.net/manual/en/imap.installation.php) | İş parçacığı güvenli değil | [javanile/php-imap2](https://github.com/javanile/php-imap2), [webklex/php-imap](https://github.com/Webklex/php-imap) | ## Sorunlu PHP Eklentileri Aşağıdaki eklentiler FrankenPHP ile kullanıldığında bilinen hatalara ve beklenmeyen davranışlara sahiptir: | Adı | Problem | | --- | ------- | ## get_browser [get_browser()](https://www.php.net/manual/en/function.get-browser.php) fonksiyonu bir süre sonra kötü performans gösteriyor gibi görünüyor. Geçici bir çözüm, statik oldukları için User-Agent başına sonuçları önbelleğe almaktır (örneğin [APCu](https://www.php.net/manual/en/book.apcu.php) ile). ## Binary Çıktısı ve Alpine Tabanlı Docker İmajları Binary çıktısı ve Alpine tabanlı Docker imajları (dunglas/frankenphp:\*-alpine), daha küçük bir binary boyutu korumak için glibc ve arkadaşları yerine musl libc kullanır. Bu durum bazı uyumluluk sorunlarına yol açabilir. Özellikle, glob seçeneği GLOB_BRACE mevcut değildir. ## Docker ile `https://127.0.0.1` Kullanımı FrankenPHP varsayılan olarak `localhost` için bir TLS sertifikası oluşturur. Bu, yerel geliştirme için en kolay ve önerilen seçenektir. Bunun yerine ana bilgisayar olarak `127.0.0.1` kullanmak istiyorsanız, sunucu adını `127.0.0.1` şeklinde ayarlayarak bunun için bir sertifika oluşturacak yapılandırma yapmak mümkündür. Ne yazık ki, [ağ sistemi](https://docs.docker.com/network/) nedeniyle Docker kullanırken bu yeterli değildir. `Curl: (35) LibreSSL/3.3.6: error:1404B438:SSL routines:ST_CONNECT:tlsv1 alert internal error`'a benzer bir TLS hatası alırsınız. Linux kullanıyorsanız, [ana bilgisayar ağ sürücüsünü](https://docs.docker.com/network/network-tutorial-host/) kullanmak bir çözümdür: ```console docker run \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ --network host \ dunglas/frankenphp ``` Ana bilgisayar ağ sürücüsü Mac ve Windows'ta desteklenmez. Bu platformlarda, konteynerin IP adresini tahmin etmeniz ve bunu sunucu adlarına dahil etmeniz gerekecektir. `docker network inspect bridge`'i çalıştırın ve `IPv4Address` anahtarının altındaki son atanmış IP adresini belirlemek için `Containers` anahtarına bakın ve bir artırın. Eğer hiçbir konteyner çalışmıyorsa, ilk atanan IP adresi genellikle `172.17.0.2`dir. Ardından, bunu `SERVER_NAME` ortam değişkenine ekleyin: ```console docker run \ -e SERVER_NAME="127.0.0.1, 172.17.0.3" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` > [!CAUTION] > > 172.17.0.3`ü konteynerinize atanacak IP ile değiştirdiğinizden emin olun. Artık ana makineden `https://127.0.0.1` adresine erişebilmeniz gerekir. Eğer durum böyle değilse, sorunu anlamaya çalışmak için FrankenPHP'yi hata ayıklama modunda başlatın: ```console docker run \ -e CADDY_GLOBAL_OPTIONS="debug" \ -e SERVER_NAME="127.0.0.1" \ -v $PWD:/app/public \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## `@php` Referanslı Composer Betikler [Composer betikleri](https://getcomposer.org/doc/articles/scripts.md) bazı görevler için bir PHP binary çalıştırmak isteyebilir, örneğin [bir Laravel projesinde](laravel.md) `@php artisan package:discover --ansi` çalıştırmak. Bu [şu anda mümkün değil](https://github.com/php/frankenphp/issues/483#issuecomment-1899890915) ve 2 nedeni var: - Composer FrankenPHP binary dosyasını nasıl çağıracağını bilmiyor; - Composer, FrankenPHP'nin henüz desteklemediği `-d` bayrağını kullanarak PHP ayarlarını komuta ekleyebilir. Geçici bir çözüm olarak, `/usr/local/bin/php` içinde desteklenmeyen parametreleri silen ve ardından FrankenPHP'yi çağıran bir kabuk betiği oluşturabiliriz: ```bash #!/bin/bash args=("$@") index=0 for i in "$@" do if [ "$i" == "-d" ]; then unset 'args[$index]' unset 'args[$index+1]' fi index=$((index+1)) done /usr/local/bin/frankenphp php-cli ${args[@]} ``` Ardından `PHP_BINARY` ortam değişkenini PHP betiğimizin yoluna ayarlayın ve Composer bu yolla çalışacaktır: ```bash export PHP_BINARY=/usr/local/bin/php composer install ``` ================================================ FILE: docs/tr/laravel.md ================================================ # Laravel ## Docker Bir [Laravel](https://laravel.com) web uygulamasını FrankenPHP ile çalıştırmak, projeyi resmi Docker imajının `/app` dizinine monte etmek kadar kolaydır. Bu komutu Laravel uygulamanızın ana dizininden çalıştırın: ```console docker run -p 80:80 -p 443:443 -p 443:443/udp -v $PWD:/app dunglas/frankenphp ``` Ve tadını çıkarın! ## Yerel Kurulum Alternatif olarak, Laravel projelerinizi FrankenPHP ile yerel makinenizden çalıştırabilirsiniz: 1. [Sisteminize karşılık gelen ikili dosyayı indirin](../#standalone-binary) 2. Aşağıdaki yapılandırmayı Laravel projenizin kök dizinindeki `Caddyfile` adlı bir dosyaya ekleyin: ```caddyfile { frankenphp } # Sunucunuzun alan adı localhost { # Webroot'u public/ dizinine ayarlayın root public/ # Sıkıştırmayı etkinleştir (isteğe bağlı) encode zstd br gzip # public/ dizininden PHP dosyalarını çalıştırın ve statik dosyaları servis edin php_server { try_files {path} index.php } } ``` 3. FrankenPHP'yi Laravel projenizin kök dizininden başlatın: `frankenphp run` ## Laravel Octane Octane, Composer paket yöneticisi aracılığıyla kurulabilir: ```console composer require laravel/octane ``` Octane'ı kurduktan sonra, Octane'ın yapılandırma dosyasını uygulamanıza yükleyecek olan `octane:install` Artisan komutunu çalıştırabilirsiniz: ```console php artisan octane:install --server=frankenphp ``` Octane sunucusu `octane:frankenphp` Artisan komutu aracılığıyla başlatılabilir. ```console php artisan octane:frankenphp ``` `octane:frankenphp` komutu aşağıdaki seçenekleri alabilir: - `--host`: Sunucunun bağlanması gereken IP adresi (varsayılan: `127.0.0.1`) - `--port`: Sunucunun erişilebilir olması gereken port (varsayılan: `8000`) - `--admin-port`: Yönetici sunucusunun erişilebilir olması gereken port (varsayılan: `2019`) - `--workers`: İstekleri işlemek için hazır olması gereken worker sayısı (varsayılan: `auto`) - `--max-requests`: Sunucu yeniden yüklenmeden önce işlenecek istek sayısı (varsayılan: `500`) - `--caddyfile`: FrankenPHP `Caddyfile` dosyasının yolu (varsayılan: [Laravel Octane içinde bulunan şablon `Caddyfile`](https://github.com/laravel/octane/blob/2.x/src/Commands/stubs/Caddyfile)) - `--https`: HTTPS, HTTP/2 ve HTTP/3'ü etkinleştirin ve sertifikaları otomatik olarak oluşturup yenileyin - `--http-redirect`: HTTP'den HTTPS'ye yeniden yönlendirmeyi etkinleştir (yalnızca --https ile birlikte geçilirse etkinleşir) - `--watch`: Uygulama değiştirildiğinde sunucuyu otomatik olarak yeniden yükle - `--poll`: Dosyaları bir ağ üzerinden izlemek için izleme sırasında dosya sistemi yoklamasını kullanın - `--log-level`: Yerel Caddy günlüğünü kullanarak belirtilen günlük seviyesinde veya üzerinde mesajları kaydedin > [!TIP] > Yapılandırılmış JSON günlükleri elde etmek için (log analitik çözümleri kullanırken faydalıdır), `--log-level` seçeneğini açıkça geçin. [Laravel Octane hakkında daha fazla bilgiyi resmi belgelerde bulabilirsiniz](https://laravel.com/docs/octane). ## Laravel Uygulamalarını Bağımsız Çalıştırılabilir Dosyalar Olarak Dağıtma [FrankenPHP'nin uygulama gömme özelliğini](embed.md) kullanarak, Laravel uygulamalarını bağımsız çalıştırılabilir dosyalar olarak dağıtmak mümkündür. Linux için Laravel uygulamanızı bağımsız bir çalıştırılabilir olarak paketlemek için şu adımları izleyin: 1. Uygulamanızın deposunda `static-build.Dockerfile` adında bir dosya oluşturun: ```dockerfile FROM --platform=linux/amd64 dunglas/frankenphp:static-builder-gnu # İkiliyi musl-libc sistemlerinde çalıştırmayı düşünüyorsanız, bunun yerine static-builder-musl kullanın # Uygulamanızı kopyalayın WORKDIR /go/src/app/dist/app COPY . . # Yer kaplamamak için testleri ve diğer gereksiz dosyaları kaldırın # Alternatif olarak, bu dosyaları bir .dockerignore dosyasına ekleyin RUN rm -Rf tests/ # .env dosyasını kopyalayın RUN cp .env.example .env # APP_ENV ve APP_DEBUG değerlerini production için uygun hale getirin RUN sed -i'' -e 's/^APP_ENV=.*/APP_ENV=production/' -e 's/^APP_DEBUG=.*/APP_DEBUG=false/' .env # Gerekirse .env dosyanıza diğer değişiklikleri yapın # Bağımlılıkları yükleyin RUN composer install --ignore-platform-reqs --no-dev -a # Statik ikiliyi derleyin WORKDIR /go/src/app/ RUN EMBED=dist/app/ ./build-static.sh ``` > [!CAUTION] > Bazı `.dockerignore` dosyaları > `vendor/` dizinini ve `.env` dosyalarını yok sayar. Derlemeden önce `.dockerignore` dosyasını buna göre ayarladığınızdan veya kaldırdığınızdan emin olun. 2. İmajı oluşturun: ```console docker build -t static-laravel-app -f static-build.Dockerfile . ``` 3. İkili dosyayı dışa aktarın: ```console docker cp $(docker create --name static-laravel-app-tmp static-laravel-app):/go/src/app/dist/frankenphp-linux-x86_64 frankenphp ; docker rm static-laravel-app-tmp ``` 4. Önbellekleri doldurun: ```console frankenphp php-cli artisan optimize ``` 5. Veritabanı migration'larını çalıştırın (varsa): ```console frankenphp php-cli artisan migrate ``` 6. Uygulamanın gizli anahtarını oluşturun: ```console frankenphp php-cli artisan key:generate ``` 7. Sunucuyu başlatın: ```console frankenphp php-server ``` Uygulamanız artık hazır! Mevcut seçenekler hakkında daha fazla bilgi edinin ve diğer işletim sistemleri için nasıl ikili derleneceğini [uygulama gömme](embed.md) belgelerinde öğrenin. ### Depolama Yolunu Değiştirme Varsayılan olarak, Laravel yüklenen dosyaları, önbellekleri, logları vb. uygulamanın `storage/` dizininde saklar. Gömülü uygulamalar için bu uygun değildir, çünkü her yeni sürüm farklı bir geçici dizine çıkarılacaktır. Geçici dizin dışında bir dizin kullanmak için `LARAVEL_STORAGE_PATH` ortam değişkenini ayarlayın (örneğin, `.env` dosyanızda) veya `Illuminate\Foundation\Application::useStoragePath()` metodunu çağırın. ### Bağımsız Çalıştırılabilir Dosyalarla Octane'i Çalıştırma Laravel Octane uygulamalarını bağımsız çalıştırılabilir dosyalar olarak paketlemek bile mümkündür! Bunu yapmak için, [Octane'i doğru şekilde kurun](#laravel-octane) ve [önceki bölümde](#laravel-uygulamalarını-bağımsız-çalıştırılabilir-dosyalar-olarak-dağıtma) açıklanan adımları izleyin. Ardından, Octane üzerinden FrankenPHP'yi worker modunda başlatmak için şunu çalıştırın: ```console PATH="$PWD:$PATH" frankenphp php-cli artisan octane:frankenphp ``` > [!CAUTION] > Komutun çalışması için, bağımsız ikili dosya mutlaka `frankenphp` olarak adlandırılmış olmalıdır, > çünkü Octane, yol üzerinde `frankenphp` adlı bir programın mevcut olmasını bekler. ================================================ FILE: docs/tr/mercure.md ================================================ # Gerçek Zamanlı FrankenPHP yerleşik bir [Mercure](https://mercure.rocks) hub ile birlikte gelir! Mercure, olayları tüm bağlı cihazlara gerçek zamanlı olarak göndermeye olanak tanır: anında bir JavaScript olayı alırlar. JS kütüphanesi veya SDK gerekmez! ![Mercure](../mercure-hub.png) Mercure hub'ını etkinleştirmek için [Mercure'ün sitesinde](https://mercure.rocks/docs/hub/config) açıklandığı gibi `Caddyfile`'ı güncelleyin. Mercure güncellemelerini kodunuzdan göndermek için [Symfony Mercure Bileşenini](https://symfony.com/components/Mercure) öneririz (kullanmak için Symfony tam yığın çerçevesine ihtiyacınız yoktur). ================================================ FILE: docs/tr/performance.md ================================================ # Performans Varsayılan olarak, FrankenPHP performans ve kullanım kolaylığı arasında iyi bir denge sunmaya çalışır. Ancak, uygun bir yapılandırma kullanılarak performansı önemli ölçüde artırmak mümkündür. ## İş Parçacığı ve İşçi Sayısı Varsayılan olarak, FrankenPHP mevcut CPU çekirdeği sayısının 2 katı kadar iş parçacığı ve işçi (işçi modunda) başlatır. Uygun değerler, uygulamanızın nasıl yazıldığına, ne yaptığına ve donanımınıza büyük ölçüde bağlıdır. Bu değerleri değiştirmenizi şiddetle tavsiye ederiz. En iyi sistem kararlılığı için, `num_threads` x `memory_limit` < `available_memory` olması önerilir. Doğru değerleri bulmak için gerçek trafiği simüle eden yük testleri yapmak en iyisidir. [k6](https://k6.io) ve [Gatling](https://gatling.io) bunun için iyi araçlardır. İş parçacığı sayısını yapılandırmak için `php_server` ve `php` yönergelerinin `num_threads` seçeneğini kullanın. İşçi sayısını değiştirmek için `frankenphp` yönergesinin `worker` bölümünün `num` seçeneğini kullanın. ### `max_threads` Trafiğinizin neye benzeyeceğini tam olarak bilmek her zaman daha iyi olsa da, gerçek dünya uygulamaları daha tahmin edilemez olma eğilimindedir. `max_threads` [yapılandırması](config.md#caddyfile-konfigürasyonu), FrankenPHP'nin çalışma zamanında belirtilen sınıra kadar ek iş parçacıkları otomatik olarak oluşturmasına olanak tanır. `max_threads`, trafiğinizi yönetmek için kaç iş parçacığına ihtiyacınız olduğunu anlamanıza yardımcı olabilir ve sunucuyu gecikme artışlarına karşı daha dirençli hale getirebilir. Eğer `auto` olarak ayarlanırsa, sınır `php.ini` dosyanızdaki `memory_limit` değerine göre tahmin edilecektir. Bunu yapamazsa, `auto` bunun yerine varsayılan olarak 2x `num_threads` olacaktır. `auto`'nun ihtiyaç duyulan iş parçacığı sayısını büyük ölçüde küçümseyebileceğini unutmayın. `max_threads`, PHP FPM'nin [pm.max_children](https://www.php.net/manual/en/install.fpm.configuration.php#pm.max-children) ile benzerdir. Temel fark, FrankenPHP'nin süreçler yerine iş parçacıkları kullanması ve gerektiğinde bunları farklı işçi komut dosyaları ve 'klasik mod' arasında otomatik olarak devretmesidir. ## İşçi Modu [İşçi modunu](worker.md) etkinleştirmek performansı önemli ölçüde artırır, ancak uygulamanızın bu modla uyumlu olacak şekilde uyarlanması gerekir: bir işçi komut dosyası oluşturmanız ve uygulamanın bellek sızdırmadığından emin olmanız gerekir. ## musl Kullanmayın Resmi Docker imajlarının Alpine Linux varyantı ve sağladığımız varsayılan ikili dosyalar [musl libc](https://musl.libc.org) kullanmaktadır. PHP'nin, geleneksel GNU kitaplığı yerine bu alternatif C kitaplığını kullandığında [daha yavaş olduğu](https://gitlab.alpinelinux.org/alpine/aports/-/issues/14381) bilinmektedir, özellikle de FrankenPHP için gerekli olan ZTS modunda (iş parçacığı güvenli) derlendiğinde. Fark, yoğun iş parçacıklı bir ortamda önemli olabilir. Ayrıca, [bazı hatalar yalnızca musl kullanıldığında ortaya çıkar](https://github.com/php/php-src/issues?q=sort%3Aupdated-desc+is%3Aissue+is%3Aopen+label%3ABug+musl). Üretim ortamlarında, glibc'ye bağlı, uygun bir optimizasyon seviyesiyle derlenmiş FrankenPHP kullanmanızı öneririz. Bu, Debian Docker imajlarını kullanarak, [bakımcılarımızın .deb, .rpm veya .apk paketlerini](https://pkgs.henderkes.com) kullanarak veya [FrankenPHP'yi kaynak koddan derleyerek](compile.md) başarılabilir. Daha yalın veya daha güvenli konteynerler için Alpine yerine [güçlendirilmiş bir Debian imajı](docker.md#hardening-images) kullanmayı düşünebilirsiniz. ## Go Çalışma Zamanı Yapılandırması FrankenPHP Go ile yazılmıştır. Genel olarak, Go çalışma zamanı özel bir yapılandırma gerektirmez, ancak belirli durumlarda, özel yapılandırma performansı artırır. Muhtemelen `GODEBUG` ortam değişkenini `cgocheck=0` olarak ayarlamak isteyeceksiniz (FrankenPHP Docker imajlarındaki varsayılan değer). FrankenPHP'yi konteynerlerde (Docker, Kubernetes, LXC...) çalıştırıyorsanız ve konteynerler için ayrılan belleği sınırlıyorsanız, `GOMEMLIMIT` ortam değişkenini mevcut bellek miktarına ayarlayın. Daha fazla ayrıntı için, [Go dokümantasyon sayfasının bu konuya ayrılmış bölümünü](https://pkg.go.dev/runtime#hdr-Environment_Variables) okumanız, çalışma zamanından en iyi şekilde yararlanmak için zorunludur. ## `file_server` Varsayılan olarak, `php_server` yönergesi, kök dizinde depolanan statik dosyaları (varlıkları) sunmak için otomatik olarak bir dosya sunucusu kurar. Bu özellik kullanışlıdır, ancak bir maliyeti vardır. Bunu devre dışı bırakmak için aşağıdaki yapılandırmayı kullanın: ```caddyfile php_server { file_server off } ``` ## `try_files` Statik dosyalar ve PHP dosyaları dışında, `php_server` uygulamanızın dizin dizini ve dizin dizini dosyalarını (`/path/` -> `/path/index.php`) da sunmaya çalışacaktır. Dizin dizinlerine ihtiyacınız yoksa, `try_files` değerini açıkça şu şekilde tanımlayarak bunları devre dışı bırakabilirsiniz: ```caddyfile php_server { try_files {path} index.php root /root/to/your/app # kökü buraya açıkça eklemek daha iyi önbelleğe alma sağlar } ``` Bu, gereksiz dosya işlemlerinin sayısını önemli ölçüde azaltabilir. Önceki yapılandırmanın bir işçi eşdeğeri şöyle olacaktır: ```caddyfile route { php_server { # dosya sunucusuna hiç ihtiyacınız yoksa "php_server" yerine "php" kullanın root /root/to/your/app worker /path/to/worker.php { match * # tüm istekleri doğrudan işçiye gönder } } } ``` 0 gereksiz dosya sistemi işlemiyle alternatif bir yaklaşım, bunun yerine `php` yönergesini kullanmak ve dosyaları PHP'den yola göre ayırmaktır. Bu yaklaşım, tüm uygulamanızın tek bir giriş dosyası tarafından sunulması durumunda iyi çalışır. Statik dosyaları bir `/assets` klasörünün arkasında sunan bir örnek [yapılandırma](config.md#caddyfile-konfigürasyonu) şöyle görünebilir: ```caddyfile route { @assets { path /assets/* } # /assets arkasındaki her şey dosya sunucusu tarafından işlenir file_server @assets { root /root/to/your/app } # /assets içinde olmayan her şey dizininiz veya işçi PHP dosyanız tarafından işlenir rewrite index.php php { root /root/to/your/app # kökü buraya açıkça eklemek daha iyi önbelleğe alma sağlar } } ``` ## Yer Tutucular `root` ve `env` yönergelerinde [yer tutucular](https://caddyserver.com/docs/conventions#placeholders) kullanabilirsiniz. Ancak bu, bu değerlerin önbelleğe alınmasını engeller ve önemli bir performans maliyetiyle birlikte gelir. Mümkünse, bu yönergelerde yer tutuculardan kaçının. ## `resolve_root_symlink` Varsayılan olarak, belge kökü sembolik bir bağlantıysa, FrankenPHP tarafından otomatik olarak çözümlenir (PHP'nin düzgün çalışması için bu gereklidir). Belge kökü bir sembolik bağlantı değilse, bu özelliği devre dışı bırakabilirsiniz. ```caddyfile php_server { resolve_root_symlink false } ``` Bu, `root` yönergesi [yer tutucular](https://caddyserver.com/docs/conventions#placeholders) içeriyorsa performansı artıracaktır. Diğer durumlarda kazanç ihmal edilebilir olacaktır. ## Günlükler Günlük kaydı açıkça çok faydalıdır, ancak tanım gereği, giriş/çıkış işlemleri ve bellek ayırmaları gerektirir, bu da performansı önemli ölçüde azaltır. [Günlük seviyesini](https://caddyserver.com/docs/caddyfile/options#log) doğru bir şekilde ayarladığınızdan emin olun, ve yalnızca gerekli olanı günlüğe kaydedin. ## PHP Performansı FrankenPHP resmi PHP yorumlayıcısını kullanır. Tüm olağan PHP ile ilgili performans optimizasyonları FrankenPHP ile de geçerlidir. Özellikle: - [OPcache](https://www.php.net/manual/en/book.opcache.php)'in kurulu, etkin ve doğru şekilde yapılandırıldığını kontrol edin - [Composer otomatik yükleyici optimizasyonlarını](https://getcomposer.org/doc/articles/autoloader-optimization.md) etkinleştirin - `realpath` önbelleğinin uygulamanızın ihtiyaçları için yeterince büyük olduğundan emin olun - [ön yüklemeyi](https://www.php.net/manual/en/opcache.preloading.php) kullanın Daha fazla ayrıntı için, [Symfony'nin bu konuya ayrılmış dokümantasyon girişini](https://symfony.com/doc/current/performance.html) okuyun (ipuçlarının çoğu Symfony kullanmasanız bile faydalıdır). ## İş Parçacığı Havuzunu Bölme Uygulamaların, yüksek yük altında güvenilmez olma eğiliminde olan veya sürekli olarak 10 saniyeden fazla yanıt veren bir API gibi yavaş harici hizmetlerle etkileşime girmesi yaygındır. Bu gibi durumlarda, özel "yavaş" havuzlara sahip olmak için iş parçacığı havuzunu bölmek faydalı olabilir. Bu, yavaş uç noktaların tüm sunucu kaynaklarını/iş parçacıklarını tüketmesini önler ve bağlantı havuzuna benzer şekilde, yavaş uç noktaya giden isteklerin eş zamanlılığını sınırlar. ```caddyfile example.com { php_server { root /app/public # uygulamanızın kök dizini worker index.php { match /slow-endpoint/* # /slow-endpoint/* yoluyla eşleşen tüm istekler bu iş parçacığı havuzu tarafından işlenir num 1 # /slow-endpoint/* ile eşleşen istekler için minimum 1 iş parçacığı max_threads 20 # /slow-endpoint/* ile eşleşen istekler için gerektiğinde 20 iş parçacığına kadar izin ver } worker index.php { match * # diğer tüm istekler ayrı ayrı işlenir num 1 # diğer istekler için minimum 1 iş parçacığı, yavaş uç noktalar asılı kalmaya başlasa bile max_threads 20 # diğer istekler için gerektiğinde 20 iş parçacığına kadar izin ver } } } ``` Genel olarak, çok yavaş uç noktaları, mesaj kuyrukları gibi ilgili mekanizmalar kullanarak eşzamansız olarak ele almak da tavsiye edilir. ================================================ FILE: docs/tr/production.md ================================================ # Production Ortamına Dağıtım Bu dokümanda, Docker Compose kullanarak bir PHP uygulamasını tek bir sunucuya nasıl dağıtacağımızı öğreneceğiz. Symfony kullanıyorsanız, Symfony Docker projesinin (FrankenPHP kullanan) "[Production ortamına dağıtım](https://github.com/dunglas/symfony-docker/blob/main/docs/production.md)" dokümanını okumayı tercih edebilirsiniz. API Platform (FrankenPHP de kullanır) tercih ediyorsanız, [çerçevenin dağıtım dokümanına](https://api-platform.com/docs/deployment/) bakabilirsiniz. ## Uygulamanızı Hazırlama İlk olarak, PHP projenizin kök dizininde bir `Dockerfile` oluşturun: ```dockerfile FROM dunglas/frankenphp # "your-domain-name.example.com" yerine kendi alan adınızı yazdığınızdan emin olun ENV SERVER_NAME=your-domain-name.example.com # HTTPS'yi devre dışı bırakmak istiyorsanız, bunun yerine bu değeri kullanın: #ENV SERVER_NAME=:80 # PHP production ayarlarını etkinleştirin RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" # Projenizin PHP dosyalarını genel dizine kopyalayın COPY . /app/public # Symfony veya Laravel kullanıyorsanız, bunun yerine tüm projeyi kopyalamanız gerekir: #COPY . /app ``` Daha fazla ayrıntı ve seçenek için "[Özel Docker İmajı Oluşturma](docker.md)" bölümüne bakın, ve yapılandırmayı nasıl özelleştireceğinizi öğrenmek için PHP eklentilerini ve Caddy modüllerini yükleyin. Projeniz Composer kullanıyorsa, Docker imajına dahil ettiğinizden ve bağımlılıklarınızı yüklediğinizden emin olun. Ardından, bir `compose.yaml` dosyası ekleyin: ```yaml services: php: image: dunglas/frankenphp restart: always ports: - "80:80" # HTTP - "443:443" # HTTPS - "443:443/udp" # HTTP/3 volumes: - caddy_data:/data - caddy_config:/config # Caddy sertifikaları ve yapılandırması için gereken yığınlar (volumes) volumes: caddy_data: caddy_config: ``` > [!NOTE] > > Önceki örnekler production kullanımı için tasarlanmıştır. > Geliştirme aşamasında, bir yığın (volume), farklı bir PHP yapılandırması ve `SERVER_NAME` ortam değişkeni için farklı bir değer kullanmak isteyebilirsiniz. > > (FrankenPHP kullanan) çok aşamalı Composer, ekstra PHP eklentileri vb. içeren imajlara başvuran daha gelişmiş bir örnek için [Symfony Docker](https://github.com/dunglas/symfony-docker) projesine bir göz atın. Son olarak, eğer Git kullanıyorsanız, bu dosyaları commit edin ve push edin. ## Sunucu Hazırlama Uygulamanızı production ortamına dağıtmak için bir sunucuya ihtiyacınız vardır. Bu dokümanda, DigitalOcean tarafından sağlanan bir sanal makine kullanacağız, ancak herhangi bir Linux sunucusu çalışabilir. Docker yüklü bir Linux sunucunuz varsa, doğrudan [bir sonraki bölüme](#alan-adı-yapılandırma) geçebilirsiniz. Aksi takdirde, 200 $ ücretsiz kredi almak için [bu ortaklık bağlantısını](https://m.do.co/c/5d8aabe3ab80) kullanın, bir hesap oluşturun ve ardından "Create a Droplet" seçeneğine tıklayın. Ardından, "Bir imaj seçin" bölümünün altındaki "Marketplace" sekmesine tıklayın ve "Docker" adlı uygulamayı bulun. Bu, Docker ve Docker Compose'un en son sürümlerinin zaten yüklü olduğu bir Ubuntu sunucusu sağlayacaktır! Test amaçlı kullanım için en ucuz planlar yeterli olacaktır. Gerçek production kullanımı için, muhtemelen ihtiyaçlarınıza uyacak şekilde "genel amaçlı" bölümünden bir plan seçmek isteyeceksiniz. ![Docker ile DigitalOcean FrankenPHP](../digitalocean-droplet.png) Diğer ayarlar için varsayılanları koruyabilir veya ihtiyaçlarınıza göre değiştirebilirsiniz. SSH anahtarınızı eklemeyi veya bir parola oluşturmayı unutmayın, ardından "Sonlandır ve oluştur" düğmesine basın. Ardından, Droplet'iniz hazırlanırken birkaç saniye bekleyin. Droplet'iniz hazır olduğunda, bağlanmak için SSH kullanın: ```console ssh root@ ``` ## Alan Adı Yapılandırma Çoğu durumda sitenizle bir alan adını ilişkilendirmek isteyeceksiniz. Henüz bir alan adınız yoksa, bir kayıt şirketi aracılığıyla bir alan adı satın almanız gerekir. Daha sonra alan adınız için sunucunuzun IP adresini işaret eden `A` türünde bir DNS kaydı oluşturun: ```dns your-domain-name.example.com. IN A 207.154.233.113 ``` DigitalOcean Alan Adları hizmetiyle ilgili örnek ("Networking" > "Domains"): ![DigitalOcean'da DNS Yapılandırma](../digitalocean-dns.png) > [!NOTE] > > FrankenPHP tarafından varsayılan olarak otomatik olarak TLS sertifikası oluşturmak için kullanılan hizmet olan Let's Encrypt, direkt IP adreslerinin kullanılmasını desteklemez. Let's Encrypt'i kullanmak için alan adı kullanmak zorunludur. ## Dağıtım Projenizi `git clone`, `scp` veya ihtiyacınıza uygun başka bir araç kullanarak sunucuya kopyalayın. GitHub kullanıyorsanız [bir dağıtım anahtarı](https://docs.github.com/en/free-pro-team@latest/developers/overview/managing-deploy-keys#deploy-keys) kullanmak isteyebilirsiniz. Dağıtım anahtarları ayrıca [GitLab tarafından desteklenir](https://docs.gitlab.com/ee/user/project/deploy_keys/). Git ile örnek: ```console git clone git@github.com:/.git ``` Projenizi içeren dizine gidin (``) ve uygulamayı production modunda başlatın: ```console docker compose up -d --wait ``` Sunucunuz hazır ve çalışıyor. Sizin için otomatik olarak bir HTTPS sertifikası oluşturuldu. `https://your-domain-name.example.com` adresine gidin ve keyfini çıkarın! > [!CAUTION] > > Docker bir önbellek katmanına sahip olabilir, her dağıtım için doğru derlemeye sahip olduğunuzdan emin olun veya önbellek sorununu önlemek için projenizi `--no-cache` seçeneği ile yeniden oluşturun. ## Birden Fazla Düğümde Dağıtım Uygulamanızı bir makine kümesine dağıtmak istiyorsanız, [Docker Swarm](https://docs.docker.com/engine/swarm/stack-deploy/) kullanabilirsiniz, sağlanan Compose dosyaları ile uyumludur. Kubernetes üzerinde dağıtım yapmak için FrankenPHP kullanan [API Platformu ile sağlanan Helm grafiğine](https://api-platform.com/docs/deployment/kubernetes/) göz atın. ================================================ FILE: docs/tr/static.md ================================================ # Statik Yapı Oluşturun PHP kütüphanesinin yerel kurulumunu kullanmak yerine, harika [static-php-cli projesi](https://github.com/crazywhalecc/static-php-cli) sayesinde FrankenPHP'nin statik bir yapısını oluşturmak mümkündür (adına rağmen, bu proje sadece CLI'yi değil, tüm SAPI'leri destekler). Bu yöntemle, tek, taşınabilir bir ikili PHP yorumlayıcısını, Caddy web sunucusunu ve FrankenPHP'yi içerecektir! FrankenPHP ayrıca [PHP uygulamasının statik binary gömülmesini](embed.md) destekler. ## Linux Linux statik binary dosyası oluşturmak için bir Docker imajı sağlıyoruz: ```console docker buildx bake --load static-builder docker cp $(docker create --name static-builder-musl dunglas/frankenphp:static-builder-musl):/go/src/app/dist/frankenphp-linux-$(uname -m) frankenphp ; docker rm static-builder ``` Elde edilen statik binary `frankenphp` olarak adlandırılır ve geçerli dizinde kullanılabilir. Statik binary dosyasını Docker olmadan oluşturmak istiyorsanız, Linux için de çalışan macOS talimatlarına bir göz atın. ### Özel Eklentiler Varsayılan olarak, en popüler PHP eklentileri zaten derlenir. Binary dosyanın boyutunu küçültmek ve saldırı yüzeyini azaltmak için `PHP_EXTENSIONS` Docker ARG'sini kullanarak derlenecek eklentilerin listesini seçebilirsiniz. Örneğin, yalnızca `opcache` eklentisini derlemek için aşağıdaki komutu çalıştırın: ```console docker buildx bake --load --set static-builder.args.PHP_EXTENSIONS=opcache,pdo_sqlite static-builder # ... ``` Etkinleştirdiğiniz eklentilere ek işlevler sağlayan kütüphaneler eklemek için `PHP_EXTENSION_LIBS` Docker ARG'sini kullanabilirsiniz: ```console docker buildx bake \ --load \ --set static-builder.args.PHP_EXTENSIONS=gd \ --set static-builder.args.PHP_EXTENSION_LIBS=libjpeg,libwebp \ static-builder ``` ### Ekstra Caddy Modülleri Ekstra Caddy modülleri eklemek veya [xcaddy](https://github.com/caddyserver/xcaddy) adresine başka argümanlar iletmek için `XCADDY_ARGS` Docker ARG'sini kullanın: ```console docker buildx bake \ --load \ --set static-builder.args.XCADDY_ARGS="--with github.com/darkweak/souin/plugins/caddy --with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy" \ static-builder ``` Bu örnekte, Caddy için [Souin](https://souin.io) HTTP önbellek modülünün yanı sıra [cbrotli](https://github.com/dunglas/caddy-cbrotli), [Mercure](https://mercure.rocks) ve [Vulcain](https://vulcain.rocks) modüllerini ekliyoruz. > [!TIP] > > cbrotli, Mercure ve Vulcain modülleri, `XCADDY_ARGS` boşsa veya ayarlanmamışsa varsayılan olarak dahil edilir. > Eğer `XCADDY_ARGS` değerini özelleştirirseniz, dahil edilmelerini istiyorsanız bunları açıkça dahil etmelisiniz. Derlemeyi nasıl [özelleştireceğinize](#yapıyı-özelleştirme) de bakın. ### GitHub Token GitHub API kullanım limitine ulaşırsanız, `GITHUB_TOKEN` adlı bir ortam değişkeninde bir GitHub Personal Access Token ayarlayın: ```console GITHUB_TOKEN="xxx" docker --load buildx bake static-builder # ... ``` ## macOS macOS için statik bir binary oluşturmak için aşağıdaki betiği çalıştırın ([Homebrew](https://brew.sh/) yüklü olmalıdır): ```console git clone https://github.com/php/frankenphp cd frankenphp ./build-static.sh ``` Not: Bu betik Linux'ta (ve muhtemelen diğer Unix'lerde) da çalışır ve sağladığımız Docker tabanlı statik derleyici tarafından dahili olarak kullanılır. ## Yapıyı Özelleştirme Aşağıdaki ortam değişkenleri `docker build` ve `build-static.sh` dosyalarına aktarılabilir statik derlemeyi özelleştirmek için betik: - `FRANKENPHP_VERSION`: kullanılacak FrankenPHP sürümü - `PHP_VERSION`: kullanılacak PHP sürümü - `PHP_EXTENSIONS`: oluşturulacak PHP eklentileri ([desteklenen eklentiler listesi](https://static-php.dev/en/guide/extensions.html)) - `PHP_EXTENSION_LIBS`: eklentilere özellikler ekleyen oluşturulacak ekstra kütüphaneler - `XCADDY_ARGS`: [xcaddy](https://github.com/caddyserver/xcaddy) adresine iletilecek argümanlar, örneğin ekstra Caddy modülleri eklemek için - `EMBED`: binary dosyaya gömülecek PHP uygulamasının yolu - `CLEAN`: ayarlandığında, libphp ve tüm bağımlılıkları sıfırdan oluşturulur (önbellek yok) - `DEBUG_SYMBOLS`: ayarlandığında, hata ayıklama sembolleri ayıklanmayacak ve binary dosyaya eklenecektir - `RELEASE`: (yalnızca bakımcılar) ayarlandığında, ortaya çıkan binary dosya GitHub'a yüklenecektir ================================================ FILE: docs/tr/worker.md ================================================ # FrankenPHP Worker'ları Kullanma Uygulamanızı bir kez önyükleyin ve bellekte tutun. FrankenPHP gelen istekleri birkaç milisaniye içinde halledecektir. ## Çalışan Komut Dosyalarının Başlatılması ### Docker `FRANKENPHP_CONFIG` ortam değişkeninin değerini `worker /path/to/your/worker/script.php` olarak ayarlayın: ```console docker run \ -e FRANKENPHP_CONFIG="worker /app/path/to/your/worker/script.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Bağımsız İkili Geçerli dizinin içeriğini bir worker kullanarak sunmak için `php-server` komutunun `--worker` seçeneğini kullanın: ```console frankenphp php-server --worker /path/to/your/worker/script.php ``` PHP uygulamanız [ikili dosyaya gömülü](embed.md) ise, uygulamanın kök dizinine özel bir `Caddyfile` ekleyebilirsiniz. Otomatik olarak kullanılacaktır. Dosya değişikliklerinde worker'ı yeniden başlatmak ([dosya değişikliklerini izleme](config.md#watching-for-file-changes)) `--watch` seçeneğiyle de mümkündür. Aşağıdaki komut, `/path/to/your/app/` dizininde veya alt dizinlerde `.php` ile biten herhangi bir dosya değiştirilirse yeniden başlatmayı tetikleyecektir: ```console frankenphp php-server --worker /path/to/your/worker/script.php --watch="/path/to/your/app/**/*.php" ``` Bu özellik genellikle [hot reloading](hot-reload.md) ile birlikte kullanılır. ## Symfony Çalışma Zamanı > [!TIP] > Bu bölüm, FrankenPHP worker moduna yerel desteğin sunulduğu Symfony 7.4 öncesi için gereklidir. FrankenPHP'nin worker modu [Symfony Runtime Component](https://symfony.com/doc/current/components/runtime.html) tarafından desteklenmektedir. Herhangi bir Symfony uygulamasını bir worker'da başlatmak için [PHP Runtime](https://github.com/php-runtime/runtime)'ın FrankenPHP paketini yükleyin: ```console composer require runtime/frankenphp-symfony ``` FrankenPHP Symfony Runtime'ı kullanmak için `APP_RUNTIME` ortam değişkenini tanımlayarak uygulama sunucunuzu başlatın: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane Bkz. [özel dokümantasyon](laravel.md#laravel-octane). ## Özel Uygulamalar Aşağıdaki örnek, üçüncü taraf bir kütüphaneye güvenmeden kendi worker betiğinizi nasıl oluşturacağınızı göstermektedir: ```php boot(); // Daha iyi performans için döngü dışında işleyici (daha az iş yapıyor) $handler = static function () use ($myApp) { try { // Bir istek alındığında çağrılır, // süper küresel değişkenler, php://input ve benzerleri sıfırlanır echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` yalnızca worker betiği sona erdiğinde çağrılır, // bu beklediğiniz gibi olmayabilir, bu yüzden istisnaları burada yakalayın ve ele alın (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // HTTP yanıtını gönderdikten sonra bir şey yapın $myApp->terminate(); // Bir sayfa oluşturmanın ortasında tetiklenme olasılığını azaltmak için çöp toplayıcıyı çağırın gc_collect_cycles(); if (!$keepRunning) break; } // Temizleme $myApp->shutdown(); ``` Ardından, uygulamanızı başlatın ve worker'ınızı yapılandırmak için `FRANKENPHP_CONFIG` ortam değişkenini kullanın: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` Varsayılan olarak, CPU başına 2 worker başlatılır. Başlatılacak worker sayısını da yapılandırabilirsiniz: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Belirli Sayıda İstekten Sonra Worker'ı Yeniden Başlatın PHP başlangıçta uzun süreli işlemler için tasarlanmadığından, hala bellek sızdıran birçok kütüphane ve eski kod vardır. Bu tür kodları worker modunda kullanmak için geçici bir çözüm, belirli sayıda isteği işledikten sonra worker betiğini yeniden başlatmaktır: Önceki worker kod parçacığı, `MAX_REQUESTS` adlı bir ortam değişkeni ayarlayarak işlenecek maksimum istek sayısını yapılandırmaya izin verir. ### Worker'ları Manuel Olarak Yeniden Başlatma Worker'ları [dosya değişikliklerinde](config.md#watching-for-file-changes) yeniden başlatmak mümkünken, tüm worker'ları [Caddy admin API](https://caddyserver.com/docs/api) aracılığıyla sorunsuz bir şekilde yeniden başlatmak da mümkündür. Yönetici [Caddyfile](config.md#caddyfile-config)'ınızda etkinleştirilmişse, yeniden başlatma uç noktasına aşağıdaki gibi basit bir POST isteği gönderebilirsiniz: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Worker Hataları Bir worker betiği sıfır olmayan bir çıkış koduyla çökerse, FrankenPHP onu üstel bir geri çekilme (exponential backoff) stratejisiyle yeniden başlatacaktır. Worker betiği, son geri çekilme süresinin 2 katından daha uzun süre çalışır durumda kalırsa, worker betiğini cezalandırmayacak ve tekrar yeniden başlatacaktır. Ancak, worker betiği kısa bir süre içinde sıfır olmayan bir çıkış koduyla başarısız olmaya devam ederse (örneğin, bir betikte yazım hatası olması durumunda), FrankenPHP `too many consecutive failures` hatasıyla çökecektir. Ardışık hata sayısı, [Caddyfile](config.md#caddyfile-config)'ınızda `max_consecutive_failures` seçeneği ile yapılandırılabilir: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Süper Küresel Değişkenlerin Davranışı [PHP süper küresel değişkenleri](https://www.php.net/manual/en/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) aşağıdaki gibi davranır: - `frankenphp_handle_request()`'e ilk çağrıdan önce, süper küresel değişkenler worker betiğinin kendisine bağlı değerleri içerir - `frankenphp_handle_request()` çağrısı sırasında ve sonrasında, süper küresel değişkenler işlenen HTTP isteğinden üretilen değerleri içerir, `frankenphp_handle_request()`'e yapılan her çağrı süper küresel değişken değerlerini değiştirir Geri çağırım içinde worker betiğinin süper küresel değişkenlerine erişmek için, bunları kopyalamalı ve kopyayı geri çağırımın kapsamına aktarmalısınız: ```php 'Chinese', 'fr' => 'French', 'ja' => 'Japanese', 'pt-br' => 'Portuguese (Brazilian)', 'ru' => 'Russian', 'tr' => 'Turkish', ]; const SYSTEM_PROMPT = << [ ["role" => "model", "parts" => ['text' => $systemPrompt]], ["role" => "user", "parts" => ['text' => $userPrompt]] ], ]); $response = @file_get_contents($url, false, stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => "Content-Type: application/json\r\nX-Goog-Api-Key: $apiKey\r\nContent-Length: " . strlen($body) . "\r\n", 'content' => $body, 'timeout' => 300, ] ])); $generatedDocs = json_decode($response, true)['candidates'][0]['content']['parts'][0]['text'] ?? ''; if (!$response || !$generatedDocs) { print_r(error_get_last()); print_r($response); if ($reties > 0) { echo "Retrying... ($reties retries left)\n"; sleep(SLEEP_SECONDS_BETWEEN_REQUESTS); return makeGeminiRequest($systemPrompt, $userPrompt, $model, $apiKey, $reties - 1); } exit(1); } return $generatedDocs; } function createPrompt(string $language, string $englishFile, string $currentTranslation): array { $languageName = LANGUAGES[$language]; $userPrompt = << trim($filename), $fileToTranslate); $apiKey = $_SERVER['GEMINI_API_KEY'] ?? $_ENV['GEMINI_API_KEY'] ?? ''; if (!$apiKey) { echo 'Enter gemini api key ($GEMINI_API_KEY): '; $apiKey = trim(fgets(STDIN)); } $files = array_filter(scandir(__DIR__), fn($filename) => str_ends_with($filename, '.md')); foreach ($files as $file) { $englishFile = file_get_contents(__DIR__ . "/$file"); if ($fileToTranslate && !in_array($file, $fileToTranslate)) { continue; } foreach (LANGUAGES as $language => $languageName) { echo "Translating $file to $languageName\n"; $currentTranslation = file_get_contents(__DIR__ . "/$language/$file") ?: ''; [$systemPrompt, $userPrompt] = createPrompt($language, $englishFile, $currentTranslation); $markdown = makeGeminiRequest($systemPrompt, $userPrompt, MODEL, $apiKey); echo "Writing translated file to $language/$file\n"; file_put_contents(__DIR__ . "/$language/$file", sanitizeMarkdown($markdown)); echo "sleeping to avoid rate limiting...\n"; sleep(SLEEP_SECONDS_BETWEEN_REQUESTS); } } ================================================ FILE: docs/wordpress.md ================================================ # WordPress Run [WordPress](https://wordpress.org/) with FrankenPHP to enjoy a modern, high-performance stack with automatic HTTPS, HTTP/3, and Zstandard compression. ## Minimal Installation 1. [Download WordPress](https://wordpress.org/download/) 2. Extract the ZIP archive and open a terminal in the extracted directory 3. Run: ```console frankenphp php-server ``` 4. Go to `http://localhost/wp-admin/` and follow the installation instructions 5. Enjoy! For a production-ready setup, prefer using `frankenphp run` with a `Caddyfile` like this one: ```caddyfile example.com php_server encode zstd br gzip log ``` ## Hot Reload To use the [hot reload](hot-reload.md) feature with WordPress, enable [Mercure](mercure.md) and add the `hot_reload` sub-directive to the `php_server` directive in your `Caddyfile`: ```caddyfile localhost mercure { anonymous } php_server { hot_reload } ``` Then, add the code needed to load the JavaScript libraries in the `functions.php` file of your WordPress theme: ```php function hot_reload() { ?> [!TIP] > The following section is only necessary prior to Symfony 7.4, where native support for FrankenPHP worker mode was introduced. The worker mode of FrankenPHP is supported by the [Symfony Runtime Component](https://symfony.com/doc/current/components/runtime.html). To start any Symfony application in a worker, install the FrankenPHP package of [PHP Runtime](https://github.com/php-runtime/runtime): ```console composer require runtime/frankenphp-symfony ``` Start your app server by defining the `APP_RUNTIME` environment variable to use the FrankenPHP Symfony Runtime: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -e APP_RUNTIME=Runtime\\FrankenPhpSymfony\\Runtime \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ## Laravel Octane See [the dedicated documentation](laravel.md#laravel-octane). ## Custom Apps The following example shows how to create your own worker script without relying on a third-party library: ```php boot(); // Handler outside the loop for better performance (doing less work) $handler = static function () use ($myApp) { try { // Called when a request is received, // superglobals, php://input and the like are reset echo $myApp->handle($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); } catch (\Throwable $exception) { // `set_exception_handler` is called only when the worker script ends, // which may not be what you expect, so catch and handle exceptions here (new \MyCustomExceptionHandler)->handleException($exception); } }; $maxRequests = (int)($_SERVER['MAX_REQUESTS'] ?? 0); for ($nbRequests = 0; !$maxRequests || $nbRequests < $maxRequests; ++$nbRequests) { $keepRunning = \frankenphp_handle_request($handler); // Do something after sending the HTTP response $myApp->terminate(); // Call the garbage collector to reduce the chances of it being triggered in the middle of a page generation gc_collect_cycles(); if (!$keepRunning) break; } // Cleanup $myApp->shutdown(); ``` Then, start your app and use the `FRANKENPHP_CONFIG` environment variable to configure your worker: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` By default, 2 workers per CPU are started. You can also configure the number of workers to start: ```console docker run \ -e FRANKENPHP_CONFIG="worker ./public/index.php 42" \ -v $PWD:/app \ -p 80:80 -p 443:443 -p 443:443/udp \ dunglas/frankenphp ``` ### Restart the Worker After a Certain Number of Requests As PHP was not originally designed for long-running processes, there are still many libraries and legacy codes that leak memory. A workaround to using this type of code in worker mode is to restart the worker script after processing a certain number of requests: The previous worker snippet allows configuring a maximum number of request to handle by setting an environment variable named `MAX_REQUESTS`. ### Restart Workers Manually While it's possible to restart workers [on file changes](config.md#watching-for-file-changes), it's also possible to restart all workers gracefully via the [Caddy admin API](https://caddyserver.com/docs/api). If the admin is enabled in your [Caddyfile](config.md#caddyfile-config), you can ping the restart endpoint with a simple POST request like this: ```console curl -X POST http://localhost:2019/frankenphp/workers/restart ``` ### Worker Failures If a worker script crashes with a non-zero exit code, FrankenPHP will restart it with an exponential backoff strategy. If the worker script stays up longer than the last backoff \* 2, it will not penalize the worker script and restart it again. However, if the worker script continues to fail with a non-zero exit code in a short period of time (for example, having a typo in a script), FrankenPHP will crash with the error: `too many consecutive failures`. The number of consecutive failures can be configured in your [Caddyfile](config.md#caddyfile-config) with the `max_consecutive_failures` option: ```caddyfile frankenphp { worker { # ... max_consecutive_failures 10 } } ``` ## Superglobals Behavior [PHP superglobals](https://www.php.net/manual/en/language.variables.superglobals.php) (`$_SERVER`, `$_ENV`, `$_GET`...) behave as follows: - before the first call to `frankenphp_handle_request()`, superglobals contain values bound to the worker script itself - during and after the call to `frankenphp_handle_request()`, superglobals contain values generated from the processed HTTP request, each call to `frankenphp_handle_request()` changes the superglobals values To access the superglobals of the worker script inside the callback, you must copy them and import the copy in the scope of the callback: ```php #include #include #include #include #include #include #ifdef HAVE_PHP_SESSION #include #endif #include #include #ifdef PHP_WIN32 #include #else #include #endif #include #include #include #include #include #include #include #include #include #include #ifndef ZEND_WIN32 #include #endif #if defined(__linux__) #include #elif defined(__FreeBSD__) || defined(__OpenBSD__) #include #endif #include "_cgo_export.h" #include "frankenphp_arginfo.h" #if defined(PHP_WIN32) && defined(ZTS) ZEND_TSRMLS_CACHE_DEFINE() #endif /** * The list of modules to reload on each request. If an external module * requires to be reloaded between requests, it is possible to hook on * `sapi_module.activate` and `sapi_module.deactivate`. * * @see https://github.com/DataDog/dd-trace-php/pull/3169 for an example */ static const char *MODULES_TO_RELOAD[] = {"filter", NULL}; frankenphp_version frankenphp_get_version() { return (frankenphp_version){ PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION, PHP_EXTRA_VERSION, PHP_VERSION, PHP_VERSION_ID, }; } frankenphp_config frankenphp_get_config() { return (frankenphp_config){ #ifdef ZTS true, #else false, #endif #ifdef ZEND_SIGNALS true, #else false, #endif #ifdef ZEND_MAX_EXECUTION_TIMERS true, #else false, #endif }; } bool should_filter_var = 0; bool original_user_abort_setting = 0; frankenphp_interned_strings_t frankenphp_strings = {0}; HashTable *main_thread_env = NULL; __thread uintptr_t thread_index; __thread bool is_worker_thread = false; __thread HashTable *sandboxed_env = NULL; void frankenphp_update_local_thread_context(bool is_worker) { is_worker_thread = is_worker; /* workers should keep running if the user aborts the connection */ PG(ignore_user_abort) = is_worker ? 1 : original_user_abort_setting; } static void frankenphp_update_request_context() { /* the server context is stored on the go side, still SG(server_context) needs * to not be NULL */ SG(server_context) = (void *)1; /* status It is not reset by zend engine, set it to 200. */ SG(sapi_headers).http_response_code = 200; char *authorization_header = go_update_request_info(thread_index, &SG(request_info)); /* let PHP handle basic auth */ php_handle_auth_data(authorization_header); } static void frankenphp_free_request_context() { if (SG(request_info).cookie_data != NULL) { free(SG(request_info).cookie_data); SG(request_info).cookie_data = NULL; } /* freed via thread.Unpin() */ SG(request_info).request_method = NULL; SG(request_info).query_string = NULL; SG(request_info).content_type = NULL; SG(request_info).path_translated = NULL; SG(request_info).request_uri = NULL; } /* reset all 'auto globals' in worker mode except of $_ENV * see: php_hash_environment() */ static void frankenphp_reset_super_globals() { zend_try { /* only $_FILES needs to be flushed explicitly * $_GET, $_POST, $_COOKIE and $_SERVER are flushed on reimport * $_ENV is not flushed * for more info see: php_startup_auto_globals() */ zval *files = &PG(http_globals)[TRACK_VARS_FILES]; zval_ptr_dtor_nogc(files); memset(files, 0, sizeof(*files)); /* $_SESSION must be explicitly deleted from the symbol table. * Unlike other superglobals, $_SESSION is stored in EG(symbol_table) * with a reference to PS(http_session_vars). The session RSHUTDOWN * only decrements the refcount but doesn't remove it from the symbol * table, causing data to leak between requests. */ zend_hash_str_del(&EG(symbol_table), "_SESSION", sizeof("_SESSION") - 1); } zend_end_try(); zend_auto_global *auto_global; zend_string *_env = ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_ENV); zend_string *_server = ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER); ZEND_HASH_MAP_FOREACH_PTR(CG(auto_globals), auto_global) { if (auto_global->name == _env) { /* skip $_ENV */ } else if (auto_global->name == _server) { /* always reimport $_SERVER */ auto_global->armed = auto_global->auto_global_callback(auto_global->name); } else if (auto_global->jit) { /* JIT globals ($_REQUEST, $GLOBALS) need special handling: * - $GLOBALS will always be handled by the application, we skip it * For $_REQUEST: * - If in symbol_table: re-initialize with current request data * - If not: do nothing, it may be armed by jit later */ if (auto_global->name == ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_REQUEST) && zend_hash_exists(&EG(symbol_table), auto_global->name)) { auto_global->armed = auto_global->auto_global_callback(auto_global->name); } } else if (auto_global->auto_global_callback) { /* $_GET, $_POST, $_COOKIE, $_FILES are reimported here */ auto_global->armed = auto_global->auto_global_callback(auto_global->name); } else { /* $_SESSION will land here (not an http_global) */ auto_global->armed = 0; } } ZEND_HASH_FOREACH_END(); } /* * free php_stream resources that are temporary (php_stream_temp_ops) * streams are globally registered in EG(regular_list), see zend_list.c * this fixes a leak when reading the body of a request */ static void frankenphp_release_temporary_streams() { zend_resource *val; int stream_type = php_file_le_stream(); ZEND_HASH_FOREACH_PTR(&EG(regular_list), val) { /* verify the resource is a stream */ if (val->type == stream_type) { php_stream *stream = (php_stream *)val->ptr; if (stream != NULL && stream->ops == &php_stream_temp_ops && stream->__exposed == 0 && GC_REFCOUNT(val) == 1) { ZEND_ASSERT(!stream->is_persistent); zend_list_delete(val); } } } ZEND_HASH_FOREACH_END(); } #ifdef HAVE_PHP_SESSION /* Reset session state between worker requests, preserving user handlers. * Based on php_rshutdown_session_globals() + php_rinit_session_globals(). */ static void frankenphp_reset_session_state(void) { if (PS(session_status) == php_session_active) { php_session_flush(1); } if (!Z_ISUNDEF(PS(http_session_vars))) { zval_ptr_dtor(&PS(http_session_vars)); ZVAL_UNDEF(&PS(http_session_vars)); } if (PS(mod_data) || PS(mod_user_implemented)) { zend_try { PS(mod)->s_close(&PS(mod_data)); } zend_end_try(); } if (PS(id)) { zend_string_release_ex(PS(id), 0); PS(id) = NULL; } if (PS(session_vars)) { zend_string_release_ex(PS(session_vars), 0); PS(session_vars) = NULL; } /* PS(mod_user_class_name) and PS(mod_user_names) are preserved */ #if PHP_VERSION_ID >= 80300 if (PS(session_started_filename)) { zend_string_release(PS(session_started_filename)); PS(session_started_filename) = NULL; PS(session_started_lineno) = 0; } #endif PS(session_status) = php_session_none; PS(in_save_handler) = 0; PS(set_handler) = 0; PS(mod_data) = NULL; PS(mod_user_is_open) = 0; PS(define_sid) = 1; } #endif /* Adapted from php_request_shutdown */ static void frankenphp_worker_request_shutdown() { /* Flush all output buffers */ zend_try { php_output_end_all(); } zend_end_try(); const char **module_name; zend_module_entry *module; for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) { if ((module = zend_hash_str_find_ptr(&module_registry, *module_name, strlen(*module_name)))) { module->request_shutdown_func(module->type, module->module_number); } } #ifdef HAVE_PHP_SESSION frankenphp_reset_session_state(); #endif /* Shutdown output layer (send the set HTTP headers, cleanup output handlers, * etc.) */ zend_try { php_output_deactivate(); } zend_end_try(); /* SAPI related shutdown (free stuff) */ zend_try { sapi_deactivate(); } zend_end_try(); frankenphp_free_request_context(); zend_set_memory_limit(PG(memory_limit)); } // shutdown the dummy request that starts the worker script bool frankenphp_shutdown_dummy_request(void) { if (SG(server_context) == NULL) { return false; } frankenphp_worker_request_shutdown(); return true; } void get_full_env(zval *track_vars_array) { zend_hash_extend(Z_ARR_P(track_vars_array), zend_hash_num_elements(main_thread_env), 0); zend_hash_copy(Z_ARR_P(track_vars_array), main_thread_env, NULL); } /* Adapted from php_request_startup() */ static int frankenphp_worker_request_startup() { int retval = SUCCESS; frankenphp_update_request_context(); zend_try { frankenphp_release_temporary_streams(); php_output_activate(); /* initialize global variables */ PG(header_is_being_sent) = 0; PG(connection_status) = PHP_CONNECTION_NORMAL; /* Keep the current execution context */ sapi_activate(); #ifdef ZEND_MAX_EXECUTION_TIMERS if (PG(max_input_time) == -1) { zend_set_timeout(EG(timeout_seconds), 1); } else { zend_set_timeout(PG(max_input_time), 1); } #endif if (PG(expose_php)) { sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER) - 1, 1); } if (PG(output_handler) && PG(output_handler)[0]) { zval oh; ZVAL_STRING(&oh, PG(output_handler)); php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS); zval_ptr_dtor(&oh); } else if (PG(output_buffering)) { php_output_start_user(NULL, PG(output_buffering) > 1 ? PG(output_buffering) : 0, PHP_OUTPUT_HANDLER_STDFLAGS); } else if (PG(implicit_flush)) { php_output_set_implicit_flush(1); } frankenphp_reset_super_globals(); const char **module_name; zend_module_entry *module; for (module_name = MODULES_TO_RELOAD; *module_name; module_name++) { if ((module = zend_hash_str_find_ptr(&module_registry, *module_name, strlen(*module_name))) && module->request_startup_func) { module->request_startup_func(module->type, module->module_number); } } } zend_catch { retval = FAILURE; } zend_end_try(); SG(sapi_started) = 1; return retval; } PHP_FUNCTION(frankenphp_finish_request) { /* {{{ */ ZEND_PARSE_PARAMETERS_NONE(); if (go_is_context_done(thread_index)) { RETURN_FALSE; } php_output_end_all(); php_header(); go_frankenphp_finish_php_request(thread_index); RETURN_TRUE; } /* }}} */ /* {{{ Call go's putenv to prevent race conditions */ PHP_FUNCTION(frankenphp_putenv) { char *setting; size_t setting_len; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STRING(setting, setting_len) ZEND_PARSE_PARAMETERS_END(); // Cast str_len to int (ensure it fits in an int) if (setting_len > INT_MAX) { php_error(E_WARNING, "String length exceeds maximum integer value"); RETURN_FALSE; } if (setting_len == 0 || setting[0] == '=') { zend_argument_value_error(1, "must have a valid syntax"); RETURN_THROWS(); } if (sandboxed_env == NULL) { sandboxed_env = zend_array_dup(main_thread_env); } /* cut at null byte to stay consistent with regular putenv */ char *null_pos = memchr(setting, '\0', setting_len); if (null_pos != NULL) { setting_len = null_pos - setting; } /* cut the string at the first '=' */ char *eq_pos = memchr(setting, '=', setting_len); bool success = true; /* no '=' found, delete the variable */ if (eq_pos == NULL) { success = go_putenv(setting, (int)setting_len, NULL, 0); if (success) { zend_hash_str_del(sandboxed_env, setting, setting_len); } RETURN_BOOL(success); } size_t name_len = eq_pos - setting; size_t value_len = (setting_len > name_len + 1) ? (setting_len - name_len - 1) : 0; success = go_putenv(setting, (int)name_len, eq_pos + 1, (int)value_len); if (success) { zval val = {0}; ZVAL_STRINGL(&val, eq_pos + 1, value_len); zend_hash_str_update(sandboxed_env, setting, name_len, &val); } RETURN_BOOL(success); } /* }}} */ /* {{{ Get the env from the sandboxed environment */ PHP_FUNCTION(frankenphp_getenv) { zend_string *name = NULL; bool local_only = 0; ZEND_PARSE_PARAMETERS_START(0, 2) Z_PARAM_OPTIONAL Z_PARAM_STR_OR_NULL(name) Z_PARAM_BOOL(local_only) ZEND_PARSE_PARAMETERS_END(); HashTable *ht = sandboxed_env ? sandboxed_env : main_thread_env; if (!name) { RETURN_ARR(zend_array_dup(ht)); return; } zval *env_val = zend_hash_find(ht, name); if (env_val && Z_TYPE_P(env_val) == IS_STRING) { zend_string *str = Z_STR_P(env_val); zend_string_addref(str); RETVAL_STR(str); } else { RETVAL_FALSE; } } /* }}} */ /* {{{ Fetch all HTTP request headers */ PHP_FUNCTION(frankenphp_request_headers) { ZEND_PARSE_PARAMETERS_NONE(); struct go_apache_request_headers_return headers = go_apache_request_headers(thread_index); array_init_size(return_value, headers.r1); for (size_t i = 0; i < headers.r1; i++) { go_string key = headers.r0[i * 2]; go_string val = headers.r0[i * 2 + 1]; add_assoc_stringl_ex(return_value, key.data, key.len, val.data, val.len); } } /* }}} */ /* add_response_header and apache_response_headers are copied from * https://github.com/php/php-src/blob/master/sapi/cli/php_cli_server.c * Copyright (c) The PHP Group * Licensed under The PHP License * Original authors: Moriyoshi Koizumi and Xinchen Hui * */ static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */ { if (h->header_len > 0) { char *s; size_t len = 0; ALLOCA_FLAG(use_heap) char *p = strchr(h->header, ':'); if (NULL != p) { len = p - h->header; } if (len > 0) { while (len != 0 && (h->header[len - 1] == ' ' || h->header[len - 1] == '\t')) { len--; } if (len) { s = do_alloca(len + 1, use_heap); memcpy(s, h->header, len); s[len] = 0; do { p++; } while (*p == ' ' || *p == '\t'); add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header)); free_alloca(s, use_heap); } } } } /* }}} */ PHP_FUNCTION(frankenphp_response_headers) /* {{{ */ { ZEND_PARSE_PARAMETERS_NONE(); array_init(return_value); zend_llist_apply_with_argument( &SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value); } /* }}} */ PHP_FUNCTION(frankenphp_handle_request) { zend_fcall_info fci; zend_fcall_info_cache fcc; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_FUNC(fci, fcc) ZEND_PARSE_PARAMETERS_END(); if (!is_worker_thread) { /* not a worker, throw an error */ zend_throw_exception( spl_ce_RuntimeException, "frankenphp_handle_request() called while not in worker mode", 0); RETURN_THROWS(); } #ifdef ZEND_MAX_EXECUTION_TIMERS /* Disable timeouts while waiting for a request to handle */ zend_unset_timeout(); #endif struct go_frankenphp_worker_handle_request_start_return result = go_frankenphp_worker_handle_request_start(thread_index); if (frankenphp_worker_request_startup() == FAILURE /* Shutting down */ || !result.r0) { RETURN_FALSE; } #ifdef ZEND_MAX_EXECUTION_TIMERS /* * Reset default timeout */ if (PG(max_input_time) != -1) { zend_set_timeout(INI_INT("max_execution_time"), 0); } #endif /* Call the PHP func passed to frankenphp_handle_request() */ zval retval = {0}; zval *callback_ret = NULL; fci.size = sizeof fci; fci.retval = &retval; fci.params = result.r1; fci.param_count = result.r1 == NULL ? 0 : 1; if (zend_call_function(&fci, &fcc) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) { callback_ret = &retval; /* pass NULL instead of the NULL zval as return value */ if (Z_TYPE(retval) == IS_NULL) { callback_ret = NULL; } } /* * If an exception occurred, print the message to the client before * closing the connection. */ if (EG(exception)) { if (!zend_is_unwind_exit(EG(exception)) && !zend_is_graceful_exit(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } else { /* exit() will jump directly to after php_execute_script */ zend_bailout(); } } frankenphp_worker_request_shutdown(); go_frankenphp_finish_worker_request(thread_index, callback_ret); if (result.r1 != NULL) { zval_ptr_dtor(result.r1); } if (callback_ret != NULL) { zval_ptr_dtor(&retval); } RETURN_TRUE; } PHP_FUNCTION(headers_send) { zend_long response_code = 200; ZEND_PARSE_PARAMETERS_START(0, 1) Z_PARAM_OPTIONAL Z_PARAM_LONG(response_code) ZEND_PARSE_PARAMETERS_END(); int previous_status_code = SG(sapi_headers).http_response_code; SG(sapi_headers).http_response_code = response_code; if (response_code >= 100 && response_code < 200) { int ret = sapi_module.send_headers(&SG(sapi_headers)); SG(sapi_headers).http_response_code = previous_status_code; RETURN_LONG(ret); } RETURN_LONG(sapi_send_headers()); } PHP_FUNCTION(mercure_publish) { zval *topics; zend_string *data = NULL, *id = NULL, *type = NULL; zend_bool private = 0; zend_long retry = 0; bool retry_is_null = 1; ZEND_PARSE_PARAMETERS_START(1, 6) Z_PARAM_ZVAL(topics) Z_PARAM_OPTIONAL Z_PARAM_STR_OR_NULL(data) Z_PARAM_BOOL(private) Z_PARAM_STR_OR_NULL(id) Z_PARAM_STR_OR_NULL(type) Z_PARAM_LONG_OR_NULL(retry, retry_is_null) ZEND_PARSE_PARAMETERS_END(); if (Z_TYPE_P(topics) != IS_ARRAY && Z_TYPE_P(topics) != IS_STRING) { zend_argument_type_error(1, "must be of type array|string"); RETURN_THROWS(); } struct go_mercure_publish_return result = go_mercure_publish(thread_index, topics, data, private, id, type, retry); switch (result.r1) { case 0: RETURN_STR(result.r0); case 1: zend_throw_exception(spl_ce_RuntimeException, "No Mercure hub configured", 0); RETURN_THROWS(); case 2: zend_throw_exception(spl_ce_RuntimeException, "Publish failed", 0); RETURN_THROWS(); } zend_throw_exception(spl_ce_RuntimeException, "FrankenPHP not built with Mercure support", 0); RETURN_THROWS(); } PHP_FUNCTION(frankenphp_log) { zend_string *message = NULL; zend_long level = 0; zval *context = NULL; ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_STR(message) Z_PARAM_OPTIONAL Z_PARAM_LONG(level) Z_PARAM_ARRAY(context) ZEND_PARSE_PARAMETERS_END(); char *ret = NULL; ret = go_log_attrs(thread_index, message, level, context); if (ret != NULL) { zend_throw_exception(spl_ce_RuntimeException, ret, 0); free(ret); RETURN_THROWS(); } } PHP_MINIT_FUNCTION(frankenphp) { register_frankenphp_symbols(module_number); zend_function *func; // Override putenv func = zend_hash_str_find_ptr(CG(function_table), "putenv", sizeof("putenv") - 1); if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) { ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_putenv); } else { php_error(E_WARNING, "Failed to find built-in putenv function"); } // Override getenv func = zend_hash_str_find_ptr(CG(function_table), "getenv", sizeof("getenv") - 1); if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) { ((zend_internal_function *)func)->handler = ZEND_FN(frankenphp_getenv); } else { php_error(E_WARNING, "Failed to find built-in getenv function"); } return SUCCESS; } static zend_module_entry frankenphp_module = { STANDARD_MODULE_HEADER, "frankenphp", ext_functions, /* function table */ PHP_MINIT(frankenphp), /* initialization */ NULL, /* shutdown */ NULL, /* request initialization */ NULL, /* request shutdown */ NULL, /* information */ TOSTRING(FRANKENPHP_VERSION), STANDARD_MODULE_PROPERTIES}; static int frankenphp_startup(sapi_module_struct *sapi_module) { php_import_environment_variables = get_full_env; return php_module_startup(sapi_module, &frankenphp_module); } static int frankenphp_deactivate(void) { return SUCCESS; } static size_t frankenphp_ub_write(const char *str, size_t str_length) { struct go_ub_write_return result = go_ub_write(thread_index, (char *)str, str_length); if (result.r1) { php_handle_aborted_connection(); } return result.r0; } static int frankenphp_send_headers(sapi_headers_struct *sapi_headers) { if (SG(request_info).no_headers == 1) { return SAPI_HEADER_SENT_SUCCESSFULLY; } int status; if (SG(sapi_headers).http_status_line) { status = atoi((SG(sapi_headers).http_status_line) + 9); } else { status = SG(sapi_headers).http_response_code; if (!status) { status = 200; } } bool success = go_write_headers(thread_index, status, &sapi_headers->headers); if (success) { return SAPI_HEADER_SENT_SUCCESSFULLY; } return SAPI_HEADER_SEND_FAILED; } static void frankenphp_sapi_flush(void *server_context) { sapi_send_headers(); if (go_sapi_flush(thread_index)) { php_handle_aborted_connection(); } } static size_t frankenphp_read_post(char *buffer, size_t count_bytes) { return go_read_post(thread_index, buffer, count_bytes); } static char *frankenphp_read_cookies(void) { return go_read_cookies(thread_index); } /* all variables with well defined keys can safely be registered like this */ static inline void frankenphp_register_trusted_var(zend_string *z_key, char *value, size_t val_len, HashTable *ht) { if (value == NULL) { zval empty; ZVAL_EMPTY_STRING(&empty); zend_hash_update_ind(ht, z_key, &empty); return; } size_t new_val_len = val_len; if (!should_filter_var || sapi_module.input_filter(PARSE_SERVER, ZSTR_VAL(z_key), &value, new_val_len, &new_val_len)) { zval z_value; ZVAL_STRINGL_FAST(&z_value, value, new_val_len); zend_hash_update_ind(ht, z_key, &z_value); } } /* Register known $_SERVER variables in bulk to avoid cgo overhead */ void frankenphp_register_server_vars(zval *track_vars_array, frankenphp_server_vars vars) { HashTable *ht = Z_ARRVAL_P(track_vars_array); zend_hash_extend(ht, vars.total_num_vars, 0); zend_hash_copy(ht, main_thread_env, NULL); // update values with variable strings #define FRANKENPHP_REGISTER_VAR(name) \ frankenphp_register_trusted_var(frankenphp_strings.name, vars.name, \ vars.name##_len, ht) FRANKENPHP_REGISTER_VAR(remote_addr); FRANKENPHP_REGISTER_VAR(remote_host); FRANKENPHP_REGISTER_VAR(remote_port); FRANKENPHP_REGISTER_VAR(document_root); FRANKENPHP_REGISTER_VAR(path_info); FRANKENPHP_REGISTER_VAR(php_self); FRANKENPHP_REGISTER_VAR(document_uri); FRANKENPHP_REGISTER_VAR(script_filename); FRANKENPHP_REGISTER_VAR(script_name); FRANKENPHP_REGISTER_VAR(ssl_cipher); FRANKENPHP_REGISTER_VAR(server_name); FRANKENPHP_REGISTER_VAR(server_port); FRANKENPHP_REGISTER_VAR(content_length); FRANKENPHP_REGISTER_VAR(server_protocol); FRANKENPHP_REGISTER_VAR(http_host); FRANKENPHP_REGISTER_VAR(request_uri); #undef FRANKENPHP_REGISTER_VAR /* update values with hard-coded zend_strings */ zval zv; ZVAL_STR(&zv, frankenphp_strings.cgi11); zend_hash_update_ind(ht, frankenphp_strings.gateway_interface, &zv); ZVAL_STR(&zv, frankenphp_strings.frankenphp); zend_hash_update_ind(ht, frankenphp_strings.server_software, &zv); ZVAL_STR(&zv, vars.request_scheme); zend_hash_update_ind(ht, frankenphp_strings.request_scheme, &zv); ZVAL_STR(&zv, vars.ssl_protocol); zend_hash_update_ind(ht, frankenphp_strings.ssl_protocol, &zv); ZVAL_STR(&zv, vars.https); zend_hash_update_ind(ht, frankenphp_strings.https, &zv); /* update values with always empty strings */ ZVAL_EMPTY_STRING(&zv); zend_hash_update_ind(ht, frankenphp_strings.auth_type, &zv); zend_hash_update_ind(ht, frankenphp_strings.remote_ident, &zv); } /** Create an immutable zend_string that lasts for the whole process **/ zend_string *frankenphp_init_persistent_string(const char *string, size_t len) { /* persistent strings will be ignored by the GC at the end of a request */ zend_string *z_string = zend_string_init(string, len, 1); zend_string_hash_val(z_string); /* interned strings will not be ref counted by the GC */ GC_ADD_FLAGS(z_string, IS_STR_INTERNED); return z_string; } /* initialize all hard-coded zend_strings once per process */ static void frankenphp_init_interned_strings(void) { if (frankenphp_strings.remote_addr != NULL) { return; /* already initialized */ } #define F_INITIALIZE_FIELD(name, str) \ frankenphp_strings.name = \ frankenphp_init_persistent_string(str, sizeof(str) - 1); FRANKENPHP_INTERNED_STRINGS_LIST(F_INITIALIZE_FIELD) #undef F_INITIALIZE_FIELD } /* Register variables from SG(request_info) into $_SERVER */ static inline void frankenphp_register_variable_from_request_info(zend_string *zKey, char *value, bool must_be_present, zval *track_vars_array) { if (value != NULL) { frankenphp_register_trusted_var(zKey, value, strlen(value), Z_ARRVAL_P(track_vars_array)); } else if (must_be_present) { frankenphp_register_trusted_var(zKey, NULL, 0, Z_ARRVAL_P(track_vars_array)); } } static void frankenphp_register_variables_from_request_info(zval *track_vars_array) { frankenphp_register_variable_from_request_info( frankenphp_strings.content_type, (char *)SG(request_info).content_type, true, track_vars_array); frankenphp_register_variable_from_request_info( frankenphp_strings.path_translated, (char *)SG(request_info).path_translated, false, track_vars_array); frankenphp_register_variable_from_request_info( frankenphp_strings.query_string, SG(request_info).query_string, true, track_vars_array); frankenphp_register_variable_from_request_info( frankenphp_strings.remote_user, (char *)SG(request_info).auth_user, false, track_vars_array); frankenphp_register_variable_from_request_info( frankenphp_strings.request_method, (char *)SG(request_info).request_method, false, track_vars_array); } /* Only hard-coded keys may be registered this way */ void frankenphp_register_known_variable(zend_string *z_key, char *value, size_t val_len, zval *track_vars_array) { frankenphp_register_trusted_var(z_key, value, val_len, Z_ARRVAL_P(track_vars_array)); } /* variables with user-defined keys must be registered safely * see: php_variables.c -> php_register_variable_ex (#1106) */ void frankenphp_register_variable_safe(char *key, char *val, size_t val_len, zval *track_vars_array) { if (key == NULL) { return; } if (val == NULL) { val = ""; } size_t new_val_len = val_len; if (!should_filter_var || sapi_module.input_filter(PARSE_SERVER, key, &val, new_val_len, &new_val_len)) { php_register_variable_safe(key, val, new_val_len, track_vars_array); } } static inline void register_server_variable_filtered(const char *key, char **val, size_t *val_len, zval *track_vars_array) { if (sapi_module.input_filter(PARSE_SERVER, key, val, *val_len, val_len)) { php_register_variable_safe(key, *val, *val_len, track_vars_array); } } static void frankenphp_register_variables(zval *track_vars_array) { /* https://www.php.net/manual/en/reserved.variables.server.php */ /* In CGI mode, the environment is part of the $_SERVER variables. * $_SERVER and $_ENV should only contain values from the original * environment, not values added though putenv */ /* import environment and CGI variables from the request context in go */ go_register_server_variables(thread_index, track_vars_array); /* Some variables are already present in SG(request_info) */ frankenphp_register_variables_from_request_info(track_vars_array); } static void frankenphp_log_message(const char *message, int syslog_type_int) { go_log(thread_index, (char *)message, syslog_type_int); } static char *frankenphp_getenv(const char *name, size_t name_len) { HashTable *ht = sandboxed_env ? sandboxed_env : main_thread_env; zval *env_val = zend_hash_str_find(ht, name, name_len); if (env_val && Z_TYPE_P(env_val) == IS_STRING) { zend_string *str = Z_STR_P(env_val); return ZSTR_VAL(str); } return NULL; } sapi_module_struct frankenphp_sapi_module = { "frankenphp", /* name */ "FrankenPHP", /* pretty name */ frankenphp_startup, /* startup */ php_module_shutdown_wrapper, /* shutdown */ NULL, /* activate */ frankenphp_deactivate, /* deactivate */ frankenphp_ub_write, /* unbuffered write */ frankenphp_sapi_flush, /* flush */ NULL, /* get uid */ frankenphp_getenv, /* getenv */ php_error, /* error handler */ NULL, /* header handler */ frankenphp_send_headers, /* send headers handler */ NULL, /* send header handler */ frankenphp_read_post, /* read POST data */ frankenphp_read_cookies, /* read Cookies */ frankenphp_register_variables, /* register server variables */ frankenphp_log_message, /* Log message */ NULL, /* Get request time */ NULL, /* Child terminate */ STANDARD_SAPI_MODULE_PROPERTIES}; /* Sets thread name for profiling and debugging. * * Adapted from https://github.com/Pithikos/C-Thread-Pool * Copyright: Johan Hanssen Seferidis * License: MIT */ static void set_thread_name(char *thread_name) { #if defined(__linux__) /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit * declaration */ prctl(PR_SET_NAME, thread_name); #elif defined(__APPLE__) && defined(__MACH__) pthread_setname_np(thread_name); #elif defined(__FreeBSD__) || defined(__OpenBSD__) pthread_set_name_np(pthread_self(), thread_name); #endif } static void *php_thread(void *arg) { thread_index = (uintptr_t)arg; char thread_name[16] = {0}; snprintf(thread_name, 16, "php-%" PRIxPTR, thread_index); set_thread_name(thread_name); #ifdef ZTS /* initial resource fetch */ (void)ts_resource(0); #ifdef PHP_WIN32 ZEND_TSRMLS_CACHE_UPDATE(); #endif #endif // loop until Go signals to stop char *scriptName = NULL; while ((scriptName = go_frankenphp_before_script_execution(thread_index))) { go_frankenphp_after_script_execution(thread_index, frankenphp_execute_script(scriptName)); } #ifdef ZTS ts_free_thread(); #endif go_frankenphp_on_thread_shutdown(thread_index); return NULL; } static void *php_main(void *arg) { #ifndef ZEND_WIN32 /* * SIGPIPE must be masked in non-Go threads: * https://pkg.go.dev/os/signal#hdr-Go_programs_that_use_cgo_or_SWIG */ sigset_t set; sigemptyset(&set); sigaddset(&set, SIGPIPE); if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) { perror("failed to block SIGPIPE"); exit(EXIT_FAILURE); } #endif set_thread_name("php-main"); #ifdef ZTS #if (PHP_VERSION_ID >= 80300) php_tsrm_startup_ex((intptr_t)arg); #else php_tsrm_startup(); #endif /*tsrm_error_set(TSRM_ERROR_LEVEL_INFO, NULL);*/ #ifdef PHP_WIN32 ZEND_TSRMLS_CACHE_UPDATE(); #endif #endif sapi_startup(&frankenphp_sapi_module); /* TODO: adapted from https://github.com/php/php-src/pull/16958, remove when * merged. */ #ifdef PHP_WIN32 { const DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; HMODULE module; /* Use a larger buffer to support long module paths on Windows. */ wchar_t filename[32768]; if (GetModuleHandleExW(flags, (LPCWSTR)&frankenphp_sapi_module, &module)) { const DWORD filename_capacity = (DWORD)_countof(filename); DWORD len = GetModuleFileNameW(module, filename, filename_capacity); if (len > 0 && len < filename_capacity) { wchar_t *slash = wcsrchr(filename, L'\\'); if (slash) { *slash = L'\0'; if (!SetDllDirectoryW(filename)) { fprintf(stderr, "Warning: SetDllDirectoryW failed (error %lu)\n", GetLastError()); } } } } } #endif #ifdef ZEND_MAX_EXECUTION_TIMERS /* overwrite php.ini with custom user settings */ char *php_ini_overrides = go_get_custom_php_ini(false); #else /* overwrite php.ini with custom user settings and disable * max_execution_timers */ char *php_ini_overrides = go_get_custom_php_ini(true); #endif if (php_ini_overrides != NULL) { frankenphp_sapi_module.ini_entries = php_ini_overrides; } frankenphp_init_interned_strings(); /* take a snapshot of the environment for sandboxing */ if (main_thread_env == NULL) { main_thread_env = pemalloc(sizeof(HashTable), 1); zend_hash_init(main_thread_env, 8, NULL, NULL, 1); go_init_os_env(main_thread_env); } frankenphp_sapi_module.startup(&frankenphp_sapi_module); /* check if a default filter is set in php.ini and only filter if * it is, this is deprecated and will be removed in PHP 9 */ char *default_filter; cfg_get_string("filter.default", &default_filter); should_filter_var = default_filter != NULL; original_user_abort_setting = PG(ignore_user_abort); go_frankenphp_main_thread_is_ready(); /* channel closed, shutdown gracefully */ frankenphp_sapi_module.shutdown(&frankenphp_sapi_module); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif if (frankenphp_sapi_module.ini_entries) { free((char *)frankenphp_sapi_module.ini_entries); frankenphp_sapi_module.ini_entries = NULL; } go_frankenphp_shutdown_main_thread(); return NULL; } int frankenphp_new_main_thread(int num_threads) { pthread_t thread; if (pthread_create(&thread, NULL, &php_main, (void *)(intptr_t)num_threads) != 0) { return -1; } return pthread_detach(thread); } bool frankenphp_new_php_thread(uintptr_t thread_index) { pthread_t thread; if (pthread_create(&thread, NULL, &php_thread, (void *)thread_index) != 0) { return false; } pthread_detach(thread); return true; } static int frankenphp_request_startup() { frankenphp_update_request_context(); if (php_request_startup() == SUCCESS) { return SUCCESS; } php_request_shutdown((void *)0); frankenphp_free_request_context(); return FAILURE; } int frankenphp_execute_script(char *file_name) { if (frankenphp_request_startup() == FAILURE) { return FAILURE; } int status = SUCCESS; zend_file_handle file_handle; zend_stream_init_filename(&file_handle, file_name); file_handle.primary_script = 1; zend_first_try { EG(exit_status) = 0; php_execute_script(&file_handle); status = EG(exit_status); } zend_catch { status = EG(exit_status); } zend_end_try(); zend_destroy_file_handle(&file_handle); /* Reset the sandboxed environment if it is in use */ if (sandboxed_env != NULL) { zend_hash_release(sandboxed_env); sandboxed_env = NULL; } php_request_shutdown((void *)0); frankenphp_free_request_context(); return status; } /* Use global variables to store CLI arguments to prevent useless allocations */ static char *cli_script; static int cli_argc; static char **cli_argv; /* * CLI code is adapted from * https://github.com/php/php-src/blob/master/sapi/cli/php_cli.c Copyright (c) * The PHP Group Licensed under The PHP License Original uthors: Edin Kadribasic * , Marcus Boerger and Johannes Schlueter * Parts based on CGI SAPI Module by Rasmus Lerdorf, Stig * Bakken and Zeev Suraski */ static void cli_register_file_handles(void) { php_stream *s_in, *s_out, *s_err; php_stream_context *sc_in = NULL, *sc_out = NULL, *sc_err = NULL; zend_constant ic, oc, ec; s_in = php_stream_open_wrapper_ex("php://stdin", "rb", 0, NULL, sc_in); s_out = php_stream_open_wrapper_ex("php://stdout", "wb", 0, NULL, sc_out); s_err = php_stream_open_wrapper_ex("php://stderr", "wb", 0, NULL, sc_err); /* Release stream resources, but don't free the underlying handles. Othewrise, * extensions which write to stderr or company during mshutdown/gshutdown * won't have the expected functionality. */ if (s_in) s_in->flags |= PHP_STREAM_FLAG_NO_RSCR_DTOR_CLOSE; if (s_out) s_out->flags |= PHP_STREAM_FLAG_NO_RSCR_DTOR_CLOSE; if (s_err) s_err->flags |= PHP_STREAM_FLAG_NO_RSCR_DTOR_CLOSE; if (s_in == NULL || s_out == NULL || s_err == NULL) { if (s_in) php_stream_close(s_in); if (s_out) php_stream_close(s_out); if (s_err) php_stream_close(s_err); return; } /*s_in_process = s_in;*/ php_stream_to_zval(s_in, &ic.value); php_stream_to_zval(s_out, &oc.value); php_stream_to_zval(s_err, &ec.value); ZEND_CONSTANT_SET_FLAGS(&ic, CONST_CS, 0); ic.name = zend_string_init_interned("STDIN", sizeof("STDIN") - 1, 0); zend_register_constant(&ic); ZEND_CONSTANT_SET_FLAGS(&oc, CONST_CS, 0); oc.name = zend_string_init_interned("STDOUT", sizeof("STDOUT") - 1, 0); zend_register_constant(&oc); ZEND_CONSTANT_SET_FLAGS(&ec, CONST_CS, 0); ec.name = zend_string_init_interned("STDERR", sizeof("STDERR") - 1, 0); zend_register_constant(&ec); } static void sapi_cli_register_variables(zval *track_vars_array) /* {{{ */ { size_t len = strlen(cli_script); char *docroot = ""; /* * In CGI mode, we consider the environment to be a part of the server * variables */ php_import_environment_variables(track_vars_array); /* Build the special-case PHP_SELF variable for the CLI version */ register_server_variable_filtered("PHP_SELF", &cli_script, &len, track_vars_array); register_server_variable_filtered("SCRIPT_NAME", &cli_script, &len, track_vars_array); /* filenames are empty for stdin */ register_server_variable_filtered("SCRIPT_FILENAME", &cli_script, &len, track_vars_array); register_server_variable_filtered("PATH_TRANSLATED", &cli_script, &len, track_vars_array); /* just make it available */ len = 0U; register_server_variable_filtered("DOCUMENT_ROOT", &docroot, &len, track_vars_array); } /* }}} */ static void *execute_script_cli(void *arg) { void *exit_status; bool eval = (bool)arg; /* * The SAPI name "cli" is hardcoded into too many programs... let's usurp it. */ php_embed_module.name = "cli"; php_embed_module.pretty_name = "PHP CLI embedded in FrankenPHP"; php_embed_module.register_server_variables = sapi_cli_register_variables; php_embed_init(cli_argc, cli_argv); cli_register_file_handles(); zend_first_try { if (eval) { /* evaluate the cli_script as literal PHP code (php-cli -r "...") */ zend_eval_string_ex(cli_script, NULL, "Command line code", 1); } else { zend_file_handle file_handle; zend_stream_init_filename(&file_handle, cli_script); CG(skip_shebang) = 1; php_execute_script(&file_handle); } } zend_end_try(); exit_status = (void *)(intptr_t)EG(exit_status); php_embed_shutdown(); return exit_status; } int frankenphp_execute_script_cli(char *script, int argc, char **argv, bool eval) { pthread_t thread; int err; void *exit_status; cli_script = script; cli_argc = argc; cli_argv = argv; /* * Start the script in a dedicated thread to prevent conflicts between Go and * PHP signal handlers */ err = pthread_create(&thread, NULL, execute_script_cli, (void *)eval); if (err != 0) { return err; } err = pthread_join(thread, &exit_status); if (err != 0) { return err; } return (intptr_t)exit_status; } int frankenphp_reset_opcache(void) { zend_function *opcache_reset = zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); if (opcache_reset) { zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); } return 0; } int frankenphp_get_current_memory_limit() { return PG(memory_limit); } static zend_module_entry **modules = NULL; static int modules_len = 0; static int (*original_php_register_internal_extensions_func)(void) = NULL; int register_internal_extensions(void) { if (original_php_register_internal_extensions_func != NULL && original_php_register_internal_extensions_func() != SUCCESS) { return FAILURE; } for (int i = 0; i < modules_len; i++) { if (zend_register_internal_module(modules[i]) == NULL) { return FAILURE; } } modules = NULL; modules_len = 0; return SUCCESS; } void register_extensions(zend_module_entry **m, int len) { modules = m; modules_len = len; original_php_register_internal_extensions_func = php_register_internal_extensions_func; php_register_internal_extensions_func = register_internal_extensions; } ================================================ FILE: frankenphp.go ================================================ // Package frankenphp embeds PHP in Go projects and provides a SAPI for net/http. // // This is the core of the [FrankenPHP app server], and can be used in any Go program. // // [FrankenPHP app server]: https://frankenphp.dev package frankenphp // Use PHP includes corresponding to your PHP installation by running: // // export CGO_CFLAGS=$(php-config --includes) // export CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" // // We also set these flags for hardening: https://github.com/docker-library/php/blob/master/8.2/bookworm/zts/Dockerfile#L57-L59 // #include // #include // #include "frankenphp.h" // #include // #include // #include import "C" import ( "bytes" "context" "errors" "fmt" "io" "log/slog" "net/http" "os" "os/signal" "runtime" "strings" "sync" "syscall" "time" "unsafe" // debug on Linux //_ "github.com/ianlancetaylor/cgosymbolizer" ) type contextKeyStruct struct{} var ( ErrInvalidRequest = errors.New("not a FrankenPHP request") ErrAlreadyStarted = errors.New("FrankenPHP is already started") ErrInvalidPHPVersion = errors.New("FrankenPHP is only compatible with PHP 8.2+") ErrMainThreadCreation = errors.New("error creating the main thread") ErrScriptExecution = errors.New("error during PHP script execution") ErrNotRunning = errors.New("FrankenPHP is not running. For proper configuration visit: https://frankenphp.dev/docs/config/#caddyfile-config") ErrInvalidRequestPath = ErrRejected{"invalid request path", http.StatusBadRequest} ErrInvalidContentLengthHeader = ErrRejected{"invalid Content-Length header", http.StatusBadRequest} ErrMaxWaitTimeExceeded = ErrRejected{"maximum request handling time exceeded", http.StatusServiceUnavailable} contextKey = contextKeyStruct{} serverHeader = []string{"FrankenPHP"} isRunning bool onServerShutdown []func() // Set default values to make Shutdown() idempotent globalMu sync.Mutex globalCtx = context.Background() globalLogger = slog.Default() metrics Metrics = nullMetrics{} maxWaitTime time.Duration ) type ErrRejected struct { message string status int } func (e ErrRejected) Error() string { return e.message } type syslogLevel int const ( syslogLevelEmerg syslogLevel = iota // system is unusable syslogLevelAlert // action must be taken immediately syslogLevelCrit // critical conditions syslogLevelErr // error conditions syslogLevelWarn // warning conditions syslogLevelNotice // normal but significant condition syslogLevelInfo // informational syslogLevelDebug // debug-level messages ) func (l syslogLevel) String() string { switch l { case syslogLevelEmerg: return "emerg" case syslogLevelAlert: return "alert" case syslogLevelCrit: return "crit" case syslogLevelErr: return "err" case syslogLevelWarn: return "warning" case syslogLevelNotice: return "notice" case syslogLevelDebug: return "debug" default: return "info" } } type PHPVersion struct { MajorVersion int MinorVersion int ReleaseVersion int ExtraVersion string Version string VersionID int } type PHPConfig struct { Version PHPVersion ZTS bool ZendSignals bool ZendMaxExecutionTimers bool } // Version returns infos about the PHP version. func Version() PHPVersion { cVersion := C.frankenphp_get_version() return PHPVersion{ int(cVersion.major_version), int(cVersion.minor_version), int(cVersion.release_version), C.GoString(cVersion.extra_version), C.GoString(cVersion.version), int(cVersion.version_id), } } func Config() PHPConfig { cConfig := C.frankenphp_get_config() return PHPConfig{ Version: Version(), ZTS: bool(cConfig.zts), ZendSignals: bool(cConfig.zend_signals), ZendMaxExecutionTimers: bool(cConfig.zend_max_execution_timers), } } func calculateMaxThreads(opt *opt) (numWorkers int, _ error) { maxProcs := runtime.GOMAXPROCS(0) * 2 maxThreadsFromWorkers := 0 for i, w := range opt.workers { if w.num <= 0 { // https://github.com/php/frankenphp/issues/126 opt.workers[i].num = maxProcs } metrics.TotalWorkers(w.name, w.num) numWorkers += opt.workers[i].num if w.maxThreads > 0 { if w.maxThreads < w.num { return 0, fmt.Errorf("worker max_threads (%d) must be greater or equal to worker num (%d) (%q)", w.maxThreads, w.num, w.fileName) } if w.maxThreads > opt.maxThreads && opt.maxThreads > 0 { return 0, fmt.Errorf("worker max_threads (%d) cannot be greater than total max_threads (%d) (%q)", w.maxThreads, opt.maxThreads, w.fileName) } maxThreadsFromWorkers += w.maxThreads - w.num } } numThreadsIsSet := opt.numThreads > 0 maxThreadsIsSet := opt.maxThreads != 0 maxThreadsIsAuto := opt.maxThreads < 0 // maxthreads < 0 signifies auto mode (see phpmaintread.go) // if max_threads is only defined in workers, scale up to the sum of all worker max_threads if !maxThreadsIsSet && maxThreadsFromWorkers > 0 { maxThreadsIsSet = true if numThreadsIsSet { opt.maxThreads = opt.numThreads + maxThreadsFromWorkers } else { opt.maxThreads = numWorkers + 1 + maxThreadsFromWorkers } } if numThreadsIsSet && !maxThreadsIsSet { opt.maxThreads = opt.numThreads if opt.numThreads <= numWorkers { return 0, fmt.Errorf("num_threads (%d) must be greater than the number of worker threads (%d)", opt.numThreads, numWorkers) } return numWorkers, nil } if maxThreadsIsSet && !numThreadsIsSet { opt.numThreads = numWorkers + 1 if !maxThreadsIsAuto && opt.numThreads > opt.maxThreads { return 0, fmt.Errorf("max_threads (%d) must be greater than the number of worker threads (%d)", opt.maxThreads, numWorkers) } return numWorkers, nil } if !numThreadsIsSet { if numWorkers >= maxProcs { // Start at least as many threads as workers, and keep a free thread to handle requests in non-worker mode opt.numThreads = numWorkers + 1 } else { opt.numThreads = maxProcs } opt.maxThreads = opt.numThreads return numWorkers, nil } // both num_threads and max_threads are set if opt.numThreads <= numWorkers { return 0, fmt.Errorf("num_threads (%d) must be greater than the number of worker threads (%d)", opt.numThreads, numWorkers) } if !maxThreadsIsAuto && opt.maxThreads < opt.numThreads { return 0, fmt.Errorf("max_threads (%d) must be greater than or equal to num_threads (%d)", opt.maxThreads, opt.numThreads) } return numWorkers, nil } // Init starts the PHP runtime and the configured workers. func Init(options ...Option) error { if isRunning { return ErrAlreadyStarted } isRunning = true // Ignore all SIGPIPE signals to prevent weird issues with systemd: https://github.com/php/frankenphp/issues/1020 // Docker/Moby has a similar hack: https://github.com/moby/moby/blob/d828b032a87606ae34267e349bf7f7ccb1f6495a/cmd/dockerd/docker.go#L87-L90 signal.Ignore(syscall.SIGPIPE) registerExtensions() opt := &opt{} for _, o := range options { if err := o(opt); err != nil { Shutdown() return err } } globalMu.Lock() if opt.ctx != nil { globalCtx = opt.ctx opt.ctx = nil } if opt.logger != nil { globalLogger = opt.logger opt.logger = nil } globalMu.Unlock() if opt.metrics != nil { metrics = opt.metrics } maxWaitTime = opt.maxWaitTime if opt.maxIdleTime > 0 { maxIdleTime = opt.maxIdleTime } workerThreadCount, err := calculateMaxThreads(opt) if err != nil { Shutdown() return err } metrics.TotalThreads(opt.numThreads) config := Config() if config.Version.MajorVersion < 8 || (config.Version.MajorVersion == 8 && config.Version.MinorVersion < 2) { Shutdown() return ErrInvalidPHPVersion } if config.ZTS { if !config.ZendMaxExecutionTimers && runtime.GOOS == "linux" { if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, `Zend Max Execution Timers are not enabled, timeouts (e.g. "max_execution_time") are disabled, recompile PHP with the "--enable-zend-max-execution-timers" configuration option to fix this issue`) } } } else { opt.numThreads = 1 if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, `ZTS is not enabled, only 1 thread will be available, recompile PHP using the "--enable-zts" configuration option or performance will be degraded`) } } mainThread, err := initPHPThreads(opt.numThreads, opt.maxThreads, opt.phpIni) if err != nil { Shutdown() return err } regularRequestChan = make(chan contextHolder) regularThreads = make([]*phpThread, 0, opt.numThreads-workerThreadCount) for i := 0; i < opt.numThreads-workerThreadCount; i++ { convertToRegularThread(getInactivePHPThread()) } if err := initWorkers(opt.workers); err != nil { Shutdown() return err } if err := initWatchers(opt); err != nil { Shutdown() return err } initAutoScaling(mainThread) if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "FrankenPHP started 🐘", slog.String("php_version", Version().Version), slog.Int("num_threads", mainThread.numThreads), slog.Int("max_threads", mainThread.maxThreads)) if EmbeddedAppPath != "" { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "embedded PHP app 📦", slog.String("path", EmbeddedAppPath)) } } // register the startup/shutdown hooks (mainly useful for extensions) onServerShutdown = nil for _, w := range opt.workers { if w.onServerStartup != nil { w.onServerStartup() } if w.onServerShutdown != nil { onServerShutdown = append(onServerShutdown, w.onServerShutdown) } } return nil } // Shutdown stops the workers and the PHP runtime. func Shutdown() { if !isRunning { return } // call the shutdown hooks (mainly useful for extensions) for _, fn := range onServerShutdown { fn() } drainWatchers() drainAutoScaling() drainPHPThreads() metrics.Shutdown() // Remove the installed app if EmbeddedAppPath != "" { _ = os.RemoveAll(EmbeddedAppPath) } isRunning = false if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "FrankenPHP shut down") } resetGlobals() } // ServeHTTP executes a PHP script according to the given context. func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error { h := responseWriter.Header() if h["Server"] == nil { h["Server"] = serverHeader } if !isRunning { return ErrNotRunning } ctx := request.Context() fc, ok := fromContext(ctx) ch := contextHolder{ctx, fc} if !ok { return ErrInvalidRequest } fc.responseWriter = responseWriter if err := fc.validate(); err != nil { return err } // Detect if a worker is available to handle this request if fc.worker != nil { return fc.worker.handleRequest(ch) } // If no worker was available, send the request to non-worker threads return handleRequestWithRegularPHPThreads(ch) } //export go_ub_write func go_ub_write(threadIndex C.uintptr_t, cBuf *C.char, length C.size_t) (C.size_t, C.bool) { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() if fc.isDone { return 0, C.bool(true) } var writer io.Writer if fc.responseWriter == nil { var b bytes.Buffer // log the output of the worker writer = &b } else { writer = fc.responseWriter } var ctx context.Context i, e := writer.Write(unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), length)) if e != nil { ctx = thread.context() if fc.logger.Enabled(ctx, slog.LevelWarn) { fc.logger.LogAttrs(ctx, slog.LevelWarn, "write error", slog.Any("error", e)) } } if fc.responseWriter == nil { // probably starting a worker script, log the output if ctx == nil { ctx = thread.context() } if fc.logger.Enabled(ctx, slog.LevelInfo) { fc.logger.LogAttrs(ctx, slog.LevelInfo, writer.(*bytes.Buffer).String()) } } return C.size_t(i), C.bool(fc.clientHasClosed()) } //export go_apache_request_headers func go_apache_request_headers(threadIndex C.uintptr_t) (*C.go_string, C.size_t) { thread := phpThreads[threadIndex] ctx := thread.context() fc := thread.frankenPHPContext() if fc.responseWriter == nil { // worker mode, not handling a request if globalLogger.Enabled(ctx, slog.LevelDebug) { globalLogger.LogAttrs(ctx, slog.LevelDebug, "apache_request_headers() called in non-HTTP context", slog.String("worker", fc.worker.name)) } return nil, 0 } headers := make([]C.go_string, 0, len(fc.request.Header)*2) for field, val := range fc.request.Header { fd := unsafe.StringData(field) thread.Pin(fd) cv := strings.Join(val, ", ") vd := unsafe.StringData(cv) thread.Pin(vd) headers = append( headers, C.go_string{C.size_t(len(field)), (*C.char)(unsafe.Pointer(fd))}, C.go_string{C.size_t(len(cv)), (*C.char)(unsafe.Pointer(vd))}, ) } sd := unsafe.SliceData(headers) thread.Pin(sd) return sd, C.size_t(len(fc.request.Header)) } func addHeader(ctx context.Context, fc *frankenPHPContext, h *C.sapi_header_struct) { key, val := splitRawHeader(h.header, int(h.header_len)) if key == "" { if fc.logger.Enabled(ctx, slog.LevelDebug) { fc.logger.LogAttrs(ctx, slog.LevelDebug, "invalid header", slog.String("header", C.GoStringN(h.header, C.int(h.header_len)))) } return } fc.responseWriter.Header().Add(key, val) } // split the raw header coming from C with minimal allocations func splitRawHeader(rawHeader *C.char, length int) (string, string) { buf := unsafe.Slice((*byte)(unsafe.Pointer(rawHeader)), length) // Search for the colon in 'Header-Key: value' var i int for i = 0; i < length; i++ { if buf[i] == ':' { break } } if i == length { return "", "" // No colon found, invalid header } headerKey := C.GoStringN(rawHeader, C.int(i)) // skip whitespaces after the colon j := i + 1 for j < length && buf[j] == ' ' { j++ } // anything left is the header value valuePtr := (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(rawHeader)) + uintptr(j))) headerValue := C.GoStringN(valuePtr, C.int(length-j)) return headerKey, headerValue } //export go_write_headers func go_write_headers(threadIndex C.uintptr_t, status C.int, headers *C.zend_llist) C.bool { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() if fc == nil { return C.bool(false) } if fc.isDone { return C.bool(false) } if fc.responseWriter == nil { // probably starting a worker script, pretend we wrote headers so PHP still calls ub_write return C.bool(true) } current := headers.head for current != nil { h := (*C.sapi_header_struct)(unsafe.Pointer(&(current.data))) addHeader(thread.context(), fc, h) current = current.next } goStatus := int(status) // go panics on invalid status code // https://github.com/golang/go/blob/9b8742f2e79438b9442afa4c0a0139d3937ea33f/src/net/http/server.go#L1162 if goStatus < 100 || goStatus > 999 { ctx := thread.context() if globalLogger.Enabled(ctx, slog.LevelWarn) { globalLogger.LogAttrs(ctx, slog.LevelWarn, "Invalid response status code", slog.Int("status_code", goStatus)) } goStatus = 500 } fc.responseWriter.WriteHeader(goStatus) if goStatus < 200 { // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses h := fc.responseWriter.Header() for k := range h { delete(h, k) } } return C.bool(true) } //export go_sapi_flush func go_sapi_flush(threadIndex C.uintptr_t) bool { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() if fc == nil { return false } if fc.responseWriter == nil { return false } if fc.clientHasClosed() && !fc.isDone { return true } if fc.responseController == nil { fc.responseController = http.NewResponseController(fc.responseWriter) } if err := fc.responseController.Flush(); err != nil { ctx := thread.context() if globalLogger.Enabled(ctx, slog.LevelWarn) { globalLogger.LogAttrs(ctx, slog.LevelWarn, "the current responseWriter is not a flusher, if you are not using a custom build, please report this issue", slog.Any("error", err)) } } return false } //export go_read_post func go_read_post(threadIndex C.uintptr_t, cBuf *C.char, countBytes C.size_t) (readBytes C.size_t) { fc := phpThreads[threadIndex].frankenPHPContext() if fc.responseWriter == nil { return 0 } p := unsafe.Slice((*byte)(unsafe.Pointer(cBuf)), countBytes) var err error for readBytes < countBytes && err == nil { var n int n, err = fc.request.Body.Read(p[readBytes:]) readBytes += C.size_t(n) } return } //export go_read_cookies func go_read_cookies(threadIndex C.uintptr_t) *C.char { request := phpThreads[threadIndex].frankenPHPContext().request if request == nil { return nil } cookie := strings.Join(request.Header.Values("Cookie"), "; ") if cookie == "" { return nil } // remove potential null bytes cookie = strings.ReplaceAll(cookie, "\x00", "") // freed in frankenphp_free_request_context() return C.CString(cookie) } func getLogger(threadIndex C.uintptr_t) (*slog.Logger, context.Context) { ctxHolder := phpThreads[threadIndex] if ctxHolder == nil { return globalLogger, globalCtx } ctx := ctxHolder.context() if ctxHolder.handler == nil { return globalLogger, ctx } fCtx := ctxHolder.frankenPHPContext() if fCtx == nil || fCtx.logger == nil { return globalLogger, ctx } return fCtx.logger, ctx } //export go_log func go_log(threadIndex C.uintptr_t, message *C.char, level C.int) { logger, ctx := getLogger(threadIndex) le := syslogLevelInfo if level >= C.int(syslogLevelEmerg) && level <= C.int(syslogLevelDebug) { le = syslogLevel(level) } var slogLevel slog.Level switch le { case syslogLevelEmerg, syslogLevelAlert, syslogLevelCrit, syslogLevelErr: slogLevel = slog.LevelError case syslogLevelWarn: slogLevel = slog.LevelWarn case syslogLevelDebug: slogLevel = slog.LevelDebug default: slogLevel = slog.LevelInfo } if !logger.Enabled(ctx, slogLevel) { return } logger.LogAttrs(ctx, slogLevel, C.GoString(message), slog.String("syslog_level", le.String())) } //export go_log_attrs func go_log_attrs(threadIndex C.uintptr_t, message *C.zend_string, cLevel C.zend_long, cAttrs *C.zval) *C.char { logger, ctx := getLogger(threadIndex) level := slog.Level(cLevel) if !logger.Enabled(ctx, level) { return nil } var attrs map[string]any if cAttrs != nil { var err error if attrs, err = GoMap[any](unsafe.Pointer(*(**C.zend_array)(unsafe.Pointer(&cAttrs.value[0])))); err != nil { // PHP exception message. return C.CString("Failed to log message: converting attrs: " + err.Error()) } } logger.LogAttrs(ctx, level, GoString(unsafe.Pointer(message)), mapToAttr(attrs)...) return nil } func mapToAttr(input map[string]any) []slog.Attr { out := make([]slog.Attr, 0, len(input)) for key, val := range input { out = append(out, slog.Any(key, val)) } return out } //export go_is_context_done func go_is_context_done(threadIndex C.uintptr_t) C.bool { return C.bool(phpThreads[threadIndex].frankenPHPContext().isDone) } func convertArgs(args []string) (C.int, []*C.char) { argc := C.int(len(args)) argv := make([]*C.char, argc) for i, arg := range args { argv[i] = C.CString(arg) } return argc, argv } func freeArgs(argv []*C.char) { for _, arg := range argv { C.free(unsafe.Pointer(arg)) } } func timeoutChan(timeout time.Duration) <-chan time.Time { if timeout == 0 { return nil } return time.After(timeout) } func resetGlobals() { globalMu.Lock() globalCtx = context.Background() globalLogger = slog.Default() workers = nil workersByName = nil workersByPath = nil watcherIsEnabled = false maxIdleTime = defaultMaxIdleTime globalMu.Unlock() } ================================================ FILE: frankenphp.h ================================================ #ifndef _FRANKENPHP_H #define _FRANKENPHP_H #ifdef _WIN32 // Define this to prevent windows.h from including legacy winsock.h #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif // Explicitly include Winsock2 BEFORE windows.h #include #include #include #include // Fix for missing IntSafe functions (LongLongAdd) when building with Clang #ifdef __clang__ #ifndef INTSAFE_E_ARITHMETIC_OVERFLOW #define INTSAFE_E_ARITHMETIC_OVERFLOW ((HRESULT)0x80070216L) #endif #ifndef LongLongAdd static inline HRESULT LongLongAdd(LONGLONG llAugend, LONGLONG llAddend, LONGLONG *pllResult) { if (__builtin_add_overflow(llAugend, llAddend, pllResult)) { return INTSAFE_E_ARITHMETIC_OVERFLOW; } return S_OK; } #endif #ifndef LongLongSub static inline HRESULT LongLongSub(LONGLONG llMinuend, LONGLONG llSubtrahend, LONGLONG *pllResult) { if (__builtin_sub_overflow(llMinuend, llSubtrahend, pllResult)) { return INTSAFE_E_ARITHMETIC_OVERFLOW; } return S_OK; } #endif #endif #endif #include #include #include #include #ifndef FRANKENPHP_VERSION #define FRANKENPHP_VERSION dev #endif #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) typedef struct go_string { size_t len; char *data; } go_string; typedef struct frankenphp_server_vars { size_t total_num_vars; char *remote_addr; size_t remote_addr_len; char *remote_host; size_t remote_host_len; char *remote_port; size_t remote_port_len; char *document_root; size_t document_root_len; char *path_info; size_t path_info_len; char *php_self; size_t php_self_len; char *document_uri; size_t document_uri_len; char *script_filename; size_t script_filename_len; char *script_name; size_t script_name_len; char *server_name; size_t server_name_len; char *server_port; size_t server_port_len; char *content_length; size_t content_length_len; char *server_protocol; size_t server_protocol_len; char *http_host; size_t http_host_len; char *request_uri; size_t request_uri_len; char *ssl_cipher; size_t ssl_cipher_len; zend_string *request_scheme; zend_string *ssl_protocol; zend_string *https; } frankenphp_server_vars; /** * Cached interned strings for memory and performance benefits * Add more hard-coded strings here if needed */ #define FRANKENPHP_INTERNED_STRINGS_LIST(X) \ X(remote_addr, "REMOTE_ADDR") \ X(remote_host, "REMOTE_HOST") \ X(remote_port, "REMOTE_PORT") \ X(document_root, "DOCUMENT_ROOT") \ X(path_info, "PATH_INFO") \ X(php_self, "PHP_SELF") \ X(document_uri, "DOCUMENT_URI") \ X(script_filename, "SCRIPT_FILENAME") \ X(script_name, "SCRIPT_NAME") \ X(https, "HTTPS") \ X(httpsLowercase, "https") \ X(httpLowercase, "http") \ X(ssl_protocol, "SSL_PROTOCOL") \ X(request_scheme, "REQUEST_SCHEME") \ X(server_name, "SERVER_NAME") \ X(server_port, "SERVER_PORT") \ X(content_length, "CONTENT_LENGTH") \ X(server_protocol, "SERVER_PROTOCOL") \ X(http_host, "HTTP_HOST") \ X(request_uri, "REQUEST_URI") \ X(ssl_cipher, "SSL_CIPHER") \ X(server_software, "SERVER_SOFTWARE") \ X(frankenphp, "FrankenPHP") \ X(gateway_interface, "GATEWAY_INTERFACE") \ X(cgi11, "CGI/1.1") \ X(auth_type, "AUTH_TYPE") \ X(remote_ident, "REMOTE_IDENT") \ X(content_type, "CONTENT_TYPE") \ X(path_translated, "PATH_TRANSLATED") \ X(query_string, "QUERY_STRING") \ X(remote_user, "REMOTE_USER") \ X(request_method, "REQUEST_METHOD") \ X(tls1, "TLSv1") \ X(tls11, "TLSv1.1") \ X(tls12, "TLSv1.2") \ X(tls13, "TLSv1.3") \ X(on, "on") \ X(empty, "") typedef struct frankenphp_interned_strings_t { #define F_DEFINE_STRUCT_FIELD(name, str) zend_string *name; FRANKENPHP_INTERNED_STRINGS_LIST(F_DEFINE_STRUCT_FIELD) #undef F_DEFINE_STRUCT_FIELD } frankenphp_interned_strings_t; extern frankenphp_interned_strings_t frankenphp_strings; typedef struct frankenphp_version { unsigned char major_version; unsigned char minor_version; unsigned char release_version; const char *extra_version; const char *version; unsigned long version_id; } frankenphp_version; frankenphp_version frankenphp_get_version(); typedef struct frankenphp_config { bool zts; bool zend_signals; bool zend_max_execution_timers; } frankenphp_config; frankenphp_config frankenphp_get_config(); int frankenphp_new_main_thread(int num_threads); bool frankenphp_new_php_thread(uintptr_t thread_index); bool frankenphp_shutdown_dummy_request(void); int frankenphp_execute_script(char *file_name); void frankenphp_update_local_thread_context(bool is_worker); int frankenphp_execute_script_cli(char *script, int argc, char **argv, bool eval); void frankenphp_register_known_variable(zend_string *z_key, char *value, size_t val_len, zval *track_vars_array); void frankenphp_register_variable_safe(char *key, char *var, size_t val_len, zval *track_vars_array); void frankenphp_register_server_vars(zval *track_vars_array, frankenphp_server_vars vars); zend_string *frankenphp_init_persistent_string(const char *string, size_t len); int frankenphp_reset_opcache(void); int frankenphp_get_current_memory_limit(); void register_extensions(zend_module_entry **m, int len); #endif ================================================ FILE: frankenphp.stub.php ================================================ $context Values of the array will be converted to the corresponding Go type (if supported by FrankenPHP) and added to the context of the structured logs using https://pkg.go.dev/log/slog#Attr */ function frankenphp_log(string $message, int $level = 0, array $context = []): void {} ================================================ FILE: frankenphp_arginfo.h ================================================ /* This is a generated file, edit the .stub.php file instead. * Stub hash: 60f0d27c04f94d7b24c052e91ef294595a2bc421 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_handle_request, 0, 1, _IS_BOOL, 0) ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_headers_send, 0, 0, IS_LONG, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, status, IS_LONG, 0, "200") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_finish_request, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() #define arginfo_fastcgi_finish_request arginfo_frankenphp_finish_request ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_request_headers, 0, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() #define arginfo_apache_request_headers arginfo_frankenphp_request_headers #define arginfo_getallheaders arginfo_frankenphp_request_headers ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_frankenphp_response_headers, 0, 0, MAY_BE_ARRAY|MAY_BE_BOOL) ZEND_END_ARG_INFO() #define arginfo_apache_response_headers arginfo_frankenphp_response_headers ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_mercure_publish, 0, 1, IS_STRING, 0) ZEND_ARG_TYPE_MASK(0, topics, MAY_BE_STRING|MAY_BE_ARRAY, NULL) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, data, IS_STRING, 0, "\'\'") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, private, _IS_BOOL, 0, "false") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, id, IS_STRING, 1, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, type, IS_STRING, 1, "null") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, retry, IS_LONG, 1, "null") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_frankenphp_log, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, level, IS_LONG, 0, "0") ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, context, IS_ARRAY, 0, "[]") ZEND_END_ARG_INFO() ZEND_FUNCTION(frankenphp_handle_request); ZEND_FUNCTION(headers_send); ZEND_FUNCTION(frankenphp_finish_request); ZEND_FUNCTION(frankenphp_request_headers); ZEND_FUNCTION(frankenphp_response_headers); ZEND_FUNCTION(mercure_publish); ZEND_FUNCTION(frankenphp_log); static const zend_function_entry ext_functions[] = { ZEND_FE(frankenphp_handle_request, arginfo_frankenphp_handle_request) ZEND_FE(headers_send, arginfo_headers_send) ZEND_FE(frankenphp_finish_request, arginfo_frankenphp_finish_request) ZEND_FALIAS(fastcgi_finish_request, frankenphp_finish_request, arginfo_fastcgi_finish_request) ZEND_FE(frankenphp_request_headers, arginfo_frankenphp_request_headers) ZEND_FALIAS(apache_request_headers, frankenphp_request_headers, arginfo_apache_request_headers) ZEND_FALIAS(getallheaders, frankenphp_request_headers, arginfo_getallheaders) ZEND_FE(frankenphp_response_headers, arginfo_frankenphp_response_headers) ZEND_FALIAS(apache_response_headers, frankenphp_response_headers, arginfo_apache_response_headers) ZEND_FE(mercure_publish, arginfo_mercure_publish) ZEND_FE(frankenphp_log, arginfo_frankenphp_log) ZEND_FE_END }; static void register_frankenphp_symbols(int module_number) { REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_DEBUG", -4, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_INFO", 0, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_WARN", 4, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FRANKENPHP_LOG_LEVEL_ERROR", 8, CONST_PERSISTENT); } ================================================ FILE: frankenphp_test.go ================================================ // In all tests, headers added to requests are copied on the heap using strings.Clone. // This was originally a workaround for https://github.com/golang/go/issues/65286#issuecomment-1920087884 (fixed in Go 1.22), // but this allows to catch panics occurring in real life but not when the string is in the internal binary memory. package frankenphp_test import ( "bytes" "context" "errors" "flag" "fmt" "io" "log" "log/slog" "mime/multipart" "net/http" "net/http/cookiejar" "net/http/httptest" "net/http/httptrace" "net/textproto" "net/url" "os" "os/exec" "os/user" "path/filepath" "strconv" "strings" "sync" "testing" "time" "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type testOptions struct { workerScript string watch []string nbWorkers int env map[string]string nbParallelRequests int realServer bool logger *slog.Logger initOpts []frankenphp.Option requestOpts []frankenphp.RequestOption phpIni map[string]string } func runTest(t *testing.T, test func(func(http.ResponseWriter, *http.Request), *httptest.Server, int), opts *testOptions) { if opts == nil { opts = &testOptions{} } if opts.nbParallelRequests == 0 { opts.nbParallelRequests = 100 } cwd, _ := os.Getwd() testDataDir := cwd + "/testdata/" initOpts := []frankenphp.Option{frankenphp.WithLogger(opts.logger)} if opts.workerScript != "" { workerOpts := []frankenphp.WorkerOption{ frankenphp.WithWorkerEnv(opts.env), frankenphp.WithWorkerWatchMode(opts.watch), } initOpts = append(initOpts, frankenphp.WithWorkers("workerName", testDataDir+opts.workerScript, opts.nbWorkers, workerOpts...)) } initOpts = append(initOpts, opts.initOpts...) if opts.phpIni != nil { initOpts = append(initOpts, frankenphp.WithPhpIni(opts.phpIni)) } err := frankenphp.Init(initOpts...) require.NoError(t, err) defer frankenphp.Shutdown() opts.requestOpts = append(opts.requestOpts, frankenphp.WithRequestDocumentRoot(testDataDir, false)) handler := func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, opts.requestOpts...) assert.NoError(t, err) err = frankenphp.ServeHTTP(w, req) if err != nil && !errors.As(err, &frankenphp.ErrRejected{}) { assert.Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err)) } } var ts *httptest.Server if opts.realServer { ts = httptest.NewServer(http.HandlerFunc(handler)) defer ts.Close() } var wg sync.WaitGroup wg.Add(opts.nbParallelRequests) for i := 0; i < opts.nbParallelRequests; i++ { go func(i int) { test(handler, ts, i) wg.Done() }(i) } wg.Wait() } func testRequest(req *http.Request, handler func(http.ResponseWriter, *http.Request), t *testing.T) (string, *http.Response) { t.Helper() w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, err := io.ReadAll(resp.Body) require.NoError(t, err) return string(body), resp } func testGet(url string, handler func(http.ResponseWriter, *http.Request), t *testing.T) (string, *http.Response) { t.Helper() req := httptest.NewRequest(http.MethodGet, url, nil) return testRequest(req, handler, t) } func testPost(url string, body string, handler func(http.ResponseWriter, *http.Request), t *testing.T) (string, *http.Response) { t.Helper() req := httptest.NewRequest(http.MethodPost, url, nil) req.Body = io.NopCloser(strings.NewReader(body)) return testRequest(req, handler, t) } func TestMain(m *testing.M) { flag.Parse() if !testing.Verbose() { slog.SetDefault(slog.New(slog.DiscardHandler)) } // setup custom environment var for TestWorkerHasOSEnvironmentVariableInSERVER and TestPhpIni if os.Setenv("CUSTOM_OS_ENV_VARIABLE", "custom_env_variable_value") != nil || os.Setenv("LITERAL_ZERO", "0") != nil { fmt.Println("Failed to set environment variable for tests") os.Exit(1) } os.Exit(m.Run()) } func TestHelloWorld_module(t *testing.T) { testHelloWorld(t, nil) } func TestHelloWorld_worker(t *testing.T) { testHelloWorld(t, &testOptions{workerScript: "index.php"}) } func testHelloWorld(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/index.php?i=%d", i), handler, t) assert.Equal(t, fmt.Sprintf("I am by birth a Genevese (%d)", i), body) }, opts) } func TestEnvVarsInPhpIni(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) { body, _ := testGet("http://example.com/ini.php?key=opcache.enable", handler, t) assert.Equal(t, "opcache.enable:0", body) }, &testOptions{ phpIni: map[string]string{ "opcache.enable": "${LITERAL_ZERO}", }, }) } func TestFinishRequest_module(t *testing.T) { testFinishRequest(t, nil) } func TestFinishRequest_worker(t *testing.T) { testFinishRequest(t, &testOptions{workerScript: "finish-request.php"}) } func testFinishRequest(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/finish-request.php?i=%d", i), handler, t) assert.Equal(t, fmt.Sprintf("This is output %d\n", i), body) }, opts) } func TestServerVariable_module(t *testing.T) { testServerVariable(t, nil) } func TestServerVariable_worker(t *testing.T) { testServerVariable(t, &testOptions{workerScript: "server-variable.php"}) } func testServerVariable(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("POST", fmt.Sprintf("http://example.com/server-variable.php/baz/bat?foo=a&bar=b&i=%d#hash", i), strings.NewReader("foo")) req.SetBasicAuth(strings.Clone("kevin"), strings.Clone("password")) req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain")) body, _ := testRequest(req, handler, t) assert.Contains(t, body, "[REMOTE_HOST]") assert.Contains(t, body, "[REMOTE_USER] => kevin") assert.Contains(t, body, "[PHP_AUTH_USER] => kevin") assert.Contains(t, body, "[PHP_AUTH_PW] => password") assert.Contains(t, body, "[HTTP_AUTHORIZATION] => Basic a2V2aW46cGFzc3dvcmQ=") assert.Contains(t, body, "[DOCUMENT_ROOT]") assert.Contains(t, body, "[PHP_SELF] => /server-variable.php/baz/bat") assert.Contains(t, body, "[CONTENT_TYPE] => text/plain") assert.Contains(t, body, fmt.Sprintf("[QUERY_STRING] => foo=a&bar=b&i=%d#hash", i)) assert.Contains(t, body, fmt.Sprintf("[REQUEST_URI] => /server-variable.php/baz/bat?foo=a&bar=b&i=%d#hash", i)) assert.Contains(t, body, "[CONTENT_LENGTH]") assert.Contains(t, body, "[REMOTE_ADDR]") assert.Contains(t, body, "[REMOTE_PORT]") assert.Contains(t, body, "[REQUEST_SCHEME] => http") assert.Contains(t, body, "[DOCUMENT_URI]") assert.Contains(t, body, "[AUTH_TYPE]") assert.Contains(t, body, "[REMOTE_IDENT]") assert.Contains(t, body, "[REQUEST_METHOD] => POST") assert.Contains(t, body, "[SERVER_NAME] => example.com") assert.Contains(t, body, "[SERVER_PROTOCOL] => HTTP/1.1") assert.Contains(t, body, "[SCRIPT_FILENAME]") assert.Contains(t, body, "[SERVER_SOFTWARE] => FrankenPHP") assert.Contains(t, body, "[REQUEST_TIME_FLOAT]") assert.Contains(t, body, "[REQUEST_TIME]") assert.Contains(t, body, "[SERVER_PORT] => 80") }, opts) } func TestPathInfo_module(t *testing.T) { testPathInfo(t, nil) } func TestPathInfo_worker(t *testing.T) { testPathInfo(t, &testOptions{workerScript: "server-variable.php"}) } func testPathInfo(t *testing.T, opts *testOptions) { cwd, _ := os.Getwd() testDataDir := cwd + strings.Clone("/testdata/") path := strings.Clone("/server-variable.php/pathinfo") runTest(t, func(_ func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { handler := func(w http.ResponseWriter, r *http.Request) { requestURI := r.URL.RequestURI() r.URL.Path = path rewriteRequest, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot(testDataDir, false), frankenphp.WithRequestEnv(map[string]string{"REQUEST_URI": requestURI}), ) assert.NoError(t, err) err = frankenphp.ServeHTTP(w, rewriteRequest) assert.NoError(t, err) } body, _ := testGet(fmt.Sprintf("http://example.com/pathinfo/%d", i), handler, t) assert.Contains(t, body, "[PATH_INFO] => /pathinfo") assert.Contains(t, body, fmt.Sprintf("[REQUEST_URI] => /pathinfo/%d", i)) assert.Contains(t, body, "[PATH_TRANSLATED] =>") assert.Contains(t, body, "[SCRIPT_NAME] => /server-variable.php") }, opts) } func TestHeaders_module(t *testing.T) { testHeaders(t, nil) } func TestHeaders_worker(t *testing.T) { testHeaders(t, &testOptions{workerScript: "headers.php"}) } func testHeaders(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, resp := testGet(fmt.Sprintf("http://example.com/headers.php?i=%d", i), handler, t) assert.Equal(t, "Hello", body) assert.Equal(t, 201, resp.StatusCode) assert.Equal(t, "bar", resp.Header.Get("Foo")) assert.Equal(t, "bar2", resp.Header.Get("Foo2")) assert.Equal(t, "bar3", resp.Header.Get("Foo3"), "header without whitespace after colon") assert.Empty(t, resp.Header.Get("Invalid")) assert.Equal(t, fmt.Sprintf("%d", i), resp.Header.Get("I")) }, opts) } func TestResponseHeaders_module(t *testing.T) { testResponseHeaders(t, nil) } func TestResponseHeaders_worker(t *testing.T) { testResponseHeaders(t, &testOptions{workerScript: "response-headers.php"}) } func testResponseHeaders(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, resp := testGet(fmt.Sprintf("http://example.com/response-headers.php?i=%d", i), handler, t) if i%3 != 0 { assert.Equal(t, i+100, resp.StatusCode) } else { assert.Equal(t, 200, resp.StatusCode) } assert.Contains(t, body, "'X-Powered-By' => 'PH") assert.Contains(t, body, "'Foo' => 'bar',") assert.Contains(t, body, "'Foo2' => 'bar2',") assert.Contains(t, body, fmt.Sprintf("'I' => '%d',", i)) assert.NotContains(t, body, "Invalid") }, opts) } func TestInput_module(t *testing.T) { testInput(t, nil) } func TestInput_worker(t *testing.T) { testInput(t, &testOptions{workerScript: "input.php"}) } func testInput(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, resp := testPost("http://example.com/input.php", fmt.Sprintf("post data %d", i), handler, t) assert.Equal(t, fmt.Sprintf("post data %d", i), body) assert.Equal(t, "bar", resp.Header.Get("Foo")) }, opts) } func TestPostSuperGlobals_module(t *testing.T) { testPostSuperGlobals(t, nil) } func TestPostSuperGlobals_worker(t *testing.T) { testPostSuperGlobals(t, &testOptions{workerScript: "super-globals.php"}) } func testPostSuperGlobals(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { formData := url.Values{"baz": {"bat"}, "i": {fmt.Sprintf("%d", i)}} req := httptest.NewRequest("POST", fmt.Sprintf("http://example.com/super-globals.php?foo=bar&iG=%d", i), strings.NewReader(formData.Encode())) req.Header.Set("Content-Type", strings.Clone("application/x-www-form-urlencoded")) body, _ := testRequest(req, handler, t) assert.Contains(t, body, "'foo' => 'bar'") assert.Contains(t, body, fmt.Sprintf("'i' => '%d'", i)) assert.Contains(t, body, "'baz' => 'bat'") assert.Contains(t, body, fmt.Sprintf("'iG' => '%d'", i)) }, opts) } func TestRequestSuperGlobal_module(t *testing.T) { testRequestSuperGlobal(t, nil) } func TestRequestSuperGlobal_worker(t *testing.T) { phpIni := make(map[string]string) phpIni["auto_globals_jit"] = "1" testRequestSuperGlobal(t, &testOptions{workerScript: "request-superglobal.php", phpIni: phpIni}) } func testRequestSuperGlobal(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { // Test with both GET and POST parameters // $_REQUEST should contain merged data from both formData := url.Values{"post_key": {fmt.Sprintf("post_value_%d", i)}} req := httptest.NewRequest("POST", fmt.Sprintf("http://example.com/request-superglobal.php?get_key=get_value_%d", i), strings.NewReader(formData.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") body, _ := testRequest(req, handler, t) // Verify $_REQUEST contains both GET and POST data for the current request assert.Contains(t, body, fmt.Sprintf("'get_key' => 'get_value_%d'", i)) assert.Contains(t, body, fmt.Sprintf("'post_key' => 'post_value_%d'", i)) }, opts) } func TestRequestSuperGlobalConditional_worker(t *testing.T) { // This test verifies that $_REQUEST works correctly when accessed conditionally // in worker mode. The first request does NOT access $_REQUEST, but subsequent // requests do. This tests the "re-arm" mechanism for JIT auto globals. // // The bug scenario: // - Request 1 (i=1): includes file, $_REQUEST initialized with val=1 // - Request 3 (i=3): includes file from cache, $_REQUEST should have val=3 // If the bug exists, $_REQUEST would still have val=1 from request 1. phpIni := make(map[string]string) phpIni["auto_globals_jit"] = "1" runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { if i%2 == 0 { // Even requests: don't use $_REQUEST body, _ := testGet(fmt.Sprintf("http://example.com/request-superglobal-conditional.php?val=%d", i), handler, t) assert.Contains(t, body, "SKIPPED") assert.Contains(t, body, fmt.Sprintf("'val' => '%d'", i)) } else { // Odd requests: use $_REQUEST body, _ := testGet(fmt.Sprintf("http://example.com/request-superglobal-conditional.php?use_request=1&val=%d", i), handler, t) assert.Contains(t, body, "REQUEST:") assert.Contains(t, body, "REQUEST_COUNT:2", "$_REQUEST should have ONLY current request's data (2 keys: use_request and val)") assert.Contains(t, body, fmt.Sprintf("'val' => '%d'", i), "request data is not present") assert.Contains(t, body, "'use_request' => '1'") assert.Contains(t, body, "VAL_CHECK:MATCH", "BUG: $_REQUEST contains stale data from previous request! Body: "+body) } }, &testOptions{workerScript: "request-superglobal-conditional.php", phpIni: phpIni}) } func TestCookies_module(t *testing.T) { testCookies(t, nil) } func TestCookies_worker(t *testing.T) { testCookies(t, &testOptions{workerScript: "cookies.php"}) } func testCookies(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/cookies.php", nil) req.AddCookie(&http.Cookie{Name: "foo", Value: "bar"}) req.AddCookie(&http.Cookie{Name: "i", Value: fmt.Sprintf("%d", i)}) body, _ := testRequest(req, handler, t) assert.Contains(t, body, "'foo' => 'bar'") assert.Contains(t, body, fmt.Sprintf("'i' => '%d'", i)) }, opts) } func TestMalformedCookie(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/cookies.php", nil) req.Header.Add("Cookie", "foo =bar; ===;;==; .dot.=val ;\x00 ; PHPSESSID=1234") // Multiple Cookie header should be joined https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.5 req.Header.Add("Cookie", "secondCookie=test; secondCookie=overwritten") body, _ := testRequest(req, handler, t) assert.Contains(t, body, "'foo_' => 'bar'") assert.Contains(t, body, "'_dot_' => 'val '") // PHPSESSID should still be present since we remove the null byte assert.Contains(t, body, "'PHPSESSID' => '1234'") // The cookie in the second headers should be present, // but it should not be overwritten by following values assert.Contains(t, body, "'secondCookie' => 'test'") }, &testOptions{nbParallelRequests: 1}) } func TestSession_module(t *testing.T) { testSession(t, nil) } func TestSession_worker(t *testing.T) { testSession(t, &testOptions{workerScript: "session.php"}) } func testSession(t *testing.T, opts *testOptions) { if opts == nil { opts = &testOptions{} } opts.realServer = true runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) { jar, err := cookiejar.New(&cookiejar.Options{}) assert.NoError(t, err) client := &http.Client{Jar: jar} resp1, err := client.Get(ts.URL + "/session.php") assert.NoError(t, err) body1, _ := io.ReadAll(resp1.Body) assert.Equal(t, "Count: 0\n", string(body1)) resp2, err := client.Get(ts.URL + "/session.php") assert.NoError(t, err) body2, _ := io.ReadAll(resp2.Body) assert.Equal(t, "Count: 1\n", string(body2)) }, opts) } func TestPhpInfo_module(t *testing.T) { testPhpInfo(t, nil) } func TestPhpInfo_worker(t *testing.T) { testPhpInfo(t, &testOptions{workerScript: "phpinfo.php"}) } func testPhpInfo(t *testing.T, opts *testOptions) { var logOnce sync.Once runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/phpinfo.php?i=%d", i), handler, t) logOnce.Do(func() { t.Log(body) }) assert.Contains(t, body, "frankenphp") assert.Contains(t, body, fmt.Sprintf("i=%d", i)) }, opts) } func TestPersistentObject_module(t *testing.T) { testPersistentObject(t, nil) } func TestPersistentObject_worker(t *testing.T) { testPersistentObject(t, &testOptions{workerScript: "persistent-object.php"}) } func testPersistentObject(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/persistent-object.php?i=%d", i), handler, t) assert.Equal(t, fmt.Sprintf(`request: %d class exists: 1 id: obj1 object id: 1`, i), body) }, opts) } func TestAutoloader_module(t *testing.T) { testAutoloader(t, nil) } func TestAutoloader_worker(t *testing.T) { testAutoloader(t, &testOptions{workerScript: "autoloader.php"}) } func testAutoloader(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/autoloader.php?i=%d", i), handler, t) assert.Equal(t, fmt.Sprintf(`request %d my_autoloader`, i), body) }, opts) } func TestLog_error_log_module(t *testing.T) { testLog_error_log(t, &testOptions{}) } func TestLog_error_log_worker(t *testing.T) { testLog_error_log(t, &testOptions{workerScript: "log-error_log.php"}) } func testLog_error_log(t *testing.T, opts *testOptions) { var buf fmt.Stringer opts.logger, buf = newTestLogger(t) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/log-error_log.php?i=%d", i), nil) w := httptest.NewRecorder() handler(w, req) assert.Contains(t, buf.String(), fmt.Sprintf("request %d", i)) }, opts) } func TestLog_frankenphp_log_module(t *testing.T) { testLog_frankenphp_log(t, &testOptions{}) } func TestLog_frankenphp_log_worker(t *testing.T) { testLog_frankenphp_log(t, &testOptions{workerScript: "log-frankenphp_log.php"}) } func testLog_frankenphp_log(t *testing.T, opts *testOptions) { var buf fmt.Stringer opts.logger, buf = newTestLogger(t) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/log-frankenphp_log.php?i=%d", i), nil) w := httptest.NewRecorder() handler(w, req) logs := buf.String() for _, message := range []string{ `level=INFO msg="default level message"`, fmt.Sprintf(`level=DEBUG msg="some debug message %d" "key int"=1`, i), fmt.Sprintf(`level=INFO msg="some info message %d" "key string"=string`, i), fmt.Sprintf(`level=WARN msg="some warn message %d"`, i), fmt.Sprintf(`level=ERROR msg="some error message %d" err="[a v]"`, i), } { assert.Contains(t, logs, message) } }, opts) } func TestConnectionAbort_module(t *testing.T) { testConnectionAbort(t, &testOptions{}) } func TestConnectionAbort_worker(t *testing.T) { testConnectionAbort(t, &testOptions{workerScript: "connection_status.php"}) } func testConnectionAbort(t *testing.T, opts *testOptions) { testFinish := func(finish string) { t.Run(fmt.Sprintf("finish=%s", finish), func(t *testing.T) { var buf syncBuffer opts.logger = slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo})) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/connection_status.php?i=%d&finish=%s", i, finish), nil) w := httptest.NewRecorder() ctx, cancel := context.WithCancel(req.Context()) req = req.WithContext(ctx) cancel() handler(w, req) for !strings.Contains(buf.String(), fmt.Sprintf("request %d: 1", i)) { } }, opts) }) } testFinish("0") testFinish("1") } func TestException_module(t *testing.T) { testException(t, &testOptions{}) } func TestException_worker(t *testing.T) { testException(t, &testOptions{workerScript: "exception.php"}) } func testException(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/exception.php?i=%d", i), handler, t) assert.Contains(t, body, "hello") assert.Contains(t, body, fmt.Sprintf(`Uncaught Exception: request %d`, i)) }, opts) } func TestEarlyHints_module(t *testing.T) { testEarlyHints(t, &testOptions{}) } func TestEarlyHints_worker(t *testing.T) { testEarlyHints(t, &testOptions{workerScript: "early-hints.php"}) } func testEarlyHints(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { var earlyHintReceived bool trace := &httptrace.ClientTrace{ Got1xxResponse: func(code int, header textproto.MIMEHeader) error { switch code { case http.StatusEarlyHints: assert.Equal(t, "; rel=preload; as=style", header.Get("Link")) assert.Equal(t, strconv.Itoa(i), header.Get("Request")) earlyHintReceived = true } return nil }, } req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/early-hints.php?i=%d", i), nil) w := NewRecorder() w.ClientTrace = trace handler(w, req) assert.Equal(t, strconv.Itoa(i), w.Header().Get("Request")) assert.Equal(t, "", w.Header().Get("Link")) assert.True(t, earlyHintReceived) }, opts) } type streamResponseRecorder struct { *httptest.ResponseRecorder writeCallback func(buf []byte) } func (srr *streamResponseRecorder) Write(buf []byte) (int, error) { srr.writeCallback(buf) return srr.ResponseRecorder.Write(buf) } func TestFlush_module(t *testing.T) { testFlush(t, &testOptions{}) } func TestFlush_worker(t *testing.T) { testFlush(t, &testOptions{workerScript: "flush.php"}) } func testFlush(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { var j int req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/flush.php?i=%d", i), nil) w := &streamResponseRecorder{httptest.NewRecorder(), func(buf []byte) { if j == 0 { assert.Equal(t, []byte("He"), buf) } else { assert.Equal(t, fmt.Appendf(nil, "llo %d", i), buf) } j++ }} handler(w, req) assert.Equal(t, 2, j) }, opts) } func TestLargeRequest_module(t *testing.T) { testLargeRequest(t, &testOptions{}) } func TestLargeRequest_worker(t *testing.T) { testLargeRequest(t, &testOptions{workerScript: "large-request.php"}) } func testLargeRequest(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testPost( fmt.Sprintf("http://example.com/large-request.php?i=%d", i), strings.Repeat("f", 6_048_576), handler, t, ) assert.Contains(t, body, fmt.Sprintf("Request body size: 6048576 (%d)", i)) }, opts) } func TestVersion(t *testing.T) { v := frankenphp.Version() assert.GreaterOrEqual(t, v.MajorVersion, 8) assert.GreaterOrEqual(t, v.MinorVersion, 0) assert.GreaterOrEqual(t, v.ReleaseVersion, 0) assert.GreaterOrEqual(t, v.VersionID, 0) assert.NotEmpty(t, v.Version, 0) } func TestFiberNoCgo_module(t *testing.T) { testFiberNoCgo(t, &testOptions{}) } func TestFiberNonCgo_worker(t *testing.T) { testFiberNoCgo(t, &testOptions{workerScript: "fiber-no-cgo.php"}) } func testFiberNoCgo(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/fiber-no-cgo.php?i=%d", i), handler, t) assert.Equal(t, body, fmt.Sprintf("Fiber %d", i)) }, opts) } func TestFiberBasic_module(t *testing.T) { testFiberBasic(t, &testOptions{}) } func TestFiberBasic_worker(t *testing.T) { testFiberBasic(t, &testOptions{workerScript: "fiber-basic.php"}) } func testFiberBasic(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/fiber-basic.php?i=%d", i), handler, t) assert.Equal(t, body, fmt.Sprintf("Fiber %d", i)) }, opts) } func TestRequestHeaders_module(t *testing.T) { testRequestHeaders(t, &testOptions{}) } func TestRequestHeaders_worker(t *testing.T) { testRequestHeaders(t, &testOptions{workerScript: "request-headers.php"}) } func testRequestHeaders(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/request-headers.php?i=%d", i), nil) req.Header.Add(strings.Clone("Content-Type"), strings.Clone("text/plain")) req.Header.Add(strings.Clone("Frankenphp-I"), strings.Clone(strconv.Itoa(i))) body, _ := testRequest(req, handler, t) assert.Contains(t, body, "[Content-Type] => text/plain") assert.Contains(t, body, fmt.Sprintf("[Frankenphp-I] => %d", i)) }, opts) } func TestFailingWorker(t *testing.T) { t.Cleanup(frankenphp.Shutdown) err := frankenphp.Init( frankenphp.WithWorkers("failing worker", "testdata/failing-worker.php", 4, frankenphp.WithWorkerMaxFailures(1)), frankenphp.WithNumThreads(5), ) assert.Error(t, err, "should return an immediate error if workers fail on startup") } func TestEnv_module(t *testing.T) { testEnv(t, &testOptions{nbParallelRequests: 1, phpIni: map[string]string{"variables_order": "EGPCS"}}) } func TestEnv_worker(t *testing.T) { testEnv(t, &testOptions{nbParallelRequests: 1, workerScript: "env/test-env.php", phpIni: map[string]string{"variables_order": "EGPCS"}}) } // testEnv cannot be run in parallel due to https://github.com/golang/go/issues/63567 func testEnv(t *testing.T, opts *testOptions) { assert.NoError(t, os.Setenv("EMPTY", "")) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("http://example.com/env/test-env.php?var=%d", i), handler, t) // execute the script as regular php script cmd := exec.Command("php", "testdata/env/test-env.php", strconv.Itoa(i)) stdoutStderr, err := cmd.CombinedOutput() if err != nil { // php is not installed or other issue, use the hardcoded output below: stdoutStderr = []byte("Set MY_VAR successfully.\nMY_VAR = HelloWorld\nMY_VAR not found in $_ENV.\nMY_VAR not found in $_SERVER.\nUnset MY_VAR successfully.\nMY_VAR is unset.\nMY_VAR set to empty successfully.\nMY_VAR = \nUnset NON_EXISTING_VAR successfully.\nInvalid value was not inserted.\n") } assert.Equal(t, string(stdoutStderr), body) }, opts) } func TestEnvIsResetInNonWorkerMode(t *testing.T) { assert.NoError(t, os.Setenv("test", "")) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { putResult, _ := testGet(fmt.Sprintf("http://example.com/env/putenv.php?key=test&put=%d", i), handler, t) assert.Equal(t, fmt.Sprintf("test=%d", i), putResult, "putenv and then echo getenv") getResult, _ := testGet("http://example.com/env/putenv.php?key=test", handler, t) assert.Equal(t, "test=", getResult, "putenv should be reset across requests") }, &testOptions{}) } // TODO: should it actually get reset in worker mode? func TestEnvIsNotResetInWorkerMode(t *testing.T) { assert.NoError(t, os.Setenv("index", "")) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { putResult, _ := testGet(fmt.Sprintf("http://example.com/env/remember-env.php?index=%d", i), handler, t) assert.Equal(t, "success", putResult, "putenv and then echo getenv") getResult, _ := testGet("http://example.com/env/remember-env.php", handler, t) assert.Equal(t, "success", getResult, "putenv should not be reset across worker requests") }, &testOptions{workerScript: "env/remember-env.php"}) } // reproduction of https://github.com/php/frankenphp/issues/1061 func TestModificationsToEnvPersistAcrossRequests(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { for range 3 { result, _ := testGet("http://example.com/env/overwrite-env.php", handler, t) assert.Equal(t, "custom_value", result, "a var directly added to $_ENV should persist") } }, &testOptions{ workerScript: "env/overwrite-env.php", phpIni: map[string]string{"variables_order": "EGPCS"}, }) } func TestFileUpload_module(t *testing.T) { testFileUpload(t, &testOptions{}) } func TestFileUpload_worker(t *testing.T) { testFileUpload(t, &testOptions{workerScript: "file-upload.php"}) } func testFileUpload(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { requestBody := &bytes.Buffer{} writer := multipart.NewWriter(requestBody) part, _ := writer.CreateFormFile("file", "foo.txt") _, err := part.Write([]byte("bar")) require.NoError(t, err) require.NoError(t, writer.Close()) req := httptest.NewRequest("POST", "http://example.com/file-upload.php", requestBody) req.Header.Add("Content-Type", writer.FormDataContentType()) body, _ := testRequest(req, handler, t) assert.Contains(t, string(body), "Upload OK") }, opts) } func ExampleServeHTTP() { if err := frankenphp.Init(); err != nil { panic(err) } defer frankenphp.Shutdown() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false)) if err != nil { panic(err) } if err := frankenphp.ServeHTTP(w, req); err != nil { panic(err) } }) log.Fatal(http.ListenAndServe(":8080", nil)) } func BenchmarkHelloWorld(b *testing.B) { require.NoError(b, frankenphp.Init()) b.Cleanup(frankenphp.Shutdown) cwd, _ := os.Getwd() testDataDir := cwd + "/testdata/" opt := frankenphp.WithRequestDocumentRoot(testDataDir, false) handler := func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, opt) require.NoError(b, err) require.NoError(b, frankenphp.ServeHTTP(w, req)) } req := httptest.NewRequest("GET", "http://example.com/index.php", nil) w := httptest.NewRecorder() for b.Loop() { handler(w, req) } } func BenchmarkEcho(b *testing.B) { require.NoError(b, frankenphp.Init()) b.Cleanup(frankenphp.Shutdown) cwd, _ := os.Getwd() testDataDir := cwd + "/testdata/" opt := frankenphp.WithRequestDocumentRoot(testDataDir, false) handler := func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, opt) require.NoError(b, err) require.NoError(b, frankenphp.ServeHTTP(w, req)) } const body = `{ "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdentity": "Dan Jukes", "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"] }, { "name": "Madame Uppercut", "age": 39, "secretIdentity": "Jane Wilson", "powers": [ "Million tonne punch", "Damage resistance", "Superhuman reflexes" ] }, { "name": "Eternal Flame", "age": 1000000, "secretIdentity": "Unknown", "powers": [ "Immortality", "Heat Immunity", "Inferno", "Teleportation", "Interdimensional travel" ] } ] }` r := strings.NewReader(body) req := httptest.NewRequest("POST", "http://example.com/echo.php", r) w := httptest.NewRecorder() for b.Loop() { r.Reset(body) handler(w, req) } } func BenchmarkServerSuperGlobal(b *testing.B) { require.NoError(b, frankenphp.Init()) b.Cleanup(frankenphp.Shutdown) cwd, _ := os.Getwd() testDataDir := cwd + "/testdata/" // Mimics headers of a request sent by Firefox to GitHub headers := http.Header{} headers.Add(strings.Clone("Accept"), strings.Clone("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")) headers.Add(strings.Clone("Accept-Encoding"), strings.Clone("gzip, deflate, br")) headers.Add(strings.Clone("Accept-Language"), strings.Clone("fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3")) headers.Add(strings.Clone("Cache-Control"), strings.Clone("no-cache")) headers.Add(strings.Clone("Connection"), strings.Clone("keep-alive")) headers.Add(strings.Clone("Cookie"), strings.Clone("user_session=myrandomuuid; __Host-user_session_same_site=myotherrandomuuid; dotcom_user=dunglas; logged_in=yes; _foo=barbarbarbarbarbar; _device_id=anotherrandomuuid; color_mode=foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar; preferred_color_mode=light; tz=Europe%2FParis; has_recent_activity=1")) headers.Add(strings.Clone("DNT"), strings.Clone("1")) headers.Add(strings.Clone("Host"), strings.Clone("example.com")) headers.Add(strings.Clone("Pragma"), strings.Clone("no-cache")) headers.Add(strings.Clone("Sec-Fetch-Dest"), strings.Clone("document")) headers.Add(strings.Clone("Sec-Fetch-Mode"), strings.Clone("navigate")) headers.Add(strings.Clone("Sec-Fetch-Site"), strings.Clone("cross-site")) headers.Add(strings.Clone("Sec-GPC"), strings.Clone("1")) headers.Add(strings.Clone("Upgrade-Insecure-Requests"), strings.Clone("1")) headers.Add(strings.Clone("User-Agent"), strings.Clone("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:122.0) Gecko/20100101 Firefox/122.0")) // Env vars available in a typical Docker container env := map[string]string{ "HOSTNAME": "a88e81aa22e4", "PHP_INI_DIR": "/usr/local/etc/php", "HOME": "/root", "GODEBUG": "cgocheck=0", "PHP_LDFLAGS": "-Wl,-O1 -pie", "PHP_CFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64", "PHP_VERSION": "8.3.2", "GPG_KEYS": "1198C0117593497A5EC5C199286AF1F9897469DC C28D937575603EB4ABB725861C0779DC5C0A9DE4 AFD8691FDAEDF03BDF6E460563F15A9B715376CA", "PHP_CPPFLAGS": "-fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64", "PHP_ASC_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz.asc", "PHP_URL": "https://www.php.net/distributions/php-8.3.2.tar.xz", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "XDG_CONFIG_HOME": "/config", "XDG_DATA_HOME": "/data", "PHPIZE_DEPS": "autoconf dpkg-dev file g++ gcc libc-dev make pkg-config re2c", "PWD": "/app", "PHP_SHA256": "4ffa3e44afc9c590e28dc0d2d31fc61f0139f8b335f11880a121b9f9b9f0634e", } preparedEnv := frankenphp.PrepareEnv(env) opts := []frankenphp.RequestOption{frankenphp.WithRequestDocumentRoot(testDataDir, false), frankenphp.WithRequestPreparedEnv(preparedEnv)} handler := func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, opts...) require.NoError(b, err) r.Header = headers require.NoError(b, frankenphp.ServeHTTP(w, req)) } req := httptest.NewRequest("GET", "http://example.com/server-variable.php", nil) w := httptest.NewRecorder() for b.Loop() { handler(w, req) } } func BenchmarkUncommonHeaders(b *testing.B) { require.NoError(b, frankenphp.Init()) b.Cleanup(frankenphp.Shutdown) cwd, _ := os.Getwd() testDataDir := cwd + "/testdata/" // Mimics headers of a request sent by Firefox to GitHub headers := http.Header{} headers.Add(strings.Clone("Accept"), strings.Clone("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")) headers.Add(strings.Clone("Accept-Encoding"), strings.Clone("gzip, deflate, br")) headers.Add(strings.Clone("Accept-Language"), strings.Clone("fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3")) headers.Add(strings.Clone("Cache-Control"), strings.Clone("no-cache")) headers.Add(strings.Clone("Connection"), strings.Clone("keep-alive")) headers.Add(strings.Clone("Cookie"), strings.Clone("user_session=myrandomuuid; __Host-user_session_same_site=myotherrandomuuid; dotcom_user=dunglas; logged_in=yes; _foo=barbarbarbarbarbar; _device_id=anotherrandomuuid; color_mode=foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar; preferred_color_mode=light; tz=Europe%2FParis; has_recent_activity=1")) headers.Add(strings.Clone("DNT"), strings.Clone("1")) headers.Add(strings.Clone("Host"), strings.Clone("example.com")) headers.Add(strings.Clone("Pragma"), strings.Clone("no-cache")) headers.Add(strings.Clone("Sec-Fetch-Dest"), strings.Clone("document")) headers.Add(strings.Clone("Sec-Fetch-Mode"), strings.Clone("navigate")) headers.Add(strings.Clone("Sec-Fetch-Site"), strings.Clone("cross-site")) headers.Add(strings.Clone("Sec-GPC"), strings.Clone("1")) headers.Add(strings.Clone("Upgrade-Insecure-Requests"), strings.Clone("1")) headers.Add(strings.Clone("User-Agent"), strings.Clone("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:122.0) Gecko/20100101 Firefox/122.0")) // Some uncommon headers headers.Add(strings.Clone("X-Super-Custom"), strings.Clone("Foo")) headers.Add(strings.Clone("Super-Super-Custom"), strings.Clone("Foo")) headers.Add(strings.Clone("Super-Super-Custom"), strings.Clone("Bar")) headers.Add(strings.Clone("Very-Custom"), strings.Clone("1")) opt := frankenphp.WithRequestDocumentRoot(testDataDir, false) handler := func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, opt) require.NoError(b, err) r.Header = headers require.NoError(b, frankenphp.ServeHTTP(w, req)) } req := httptest.NewRequest("GET", "http://example.com/server-variable.php", nil) w := httptest.NewRecorder() for b.Loop() { handler(w, req) } } func TestRejectInvalidHeaders_module(t *testing.T) { testRejectInvalidHeaders(t, &testOptions{}) } func TestRejectInvalidHeaders_worker(t *testing.T) { testRejectInvalidHeaders(t, &testOptions{workerScript: "headers.php"}) } func testRejectInvalidHeaders(t *testing.T, opts *testOptions) { invalidHeaders := [][]string{ {"Content-Length", "-1"}, {"Content-Length", "something"}, } for _, header := range invalidHeaders { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) { req := httptest.NewRequest("GET", "http://example.com/headers.php", nil) req.Header.Add(header[0], header[1]) body, resp := testRequest(req, handler, t) assert.Equal(t, 400, resp.StatusCode) assert.Contains(t, body, "invalid") }, opts) } } func TestFlushEmptyResponse_module(t *testing.T) { testFlushEmptyResponse(t, &testOptions{}) } func TestFlushEmptyResponse_worker(t *testing.T) { testFlushEmptyResponse(t, &testOptions{workerScript: "only-headers.php"}) } func testFlushEmptyResponse(t *testing.T, opts *testOptions) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) { _, resp := testGet("http://example.com/only-headers.php", handler, t) assert.Equal(t, 204, resp.StatusCode) }, opts) } // Worker mode will clean up unreferenced streams between requests // Make sure referenced streams are not cleaned up func TestFileStreamInWorkerMode(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) { resp1, _ := testGet("http://example.com/file-stream.php", handler, t) assert.Equal(t, resp1, "word1") resp2, _ := testGet("http://example.com/file-stream.php", handler, t) assert.Equal(t, resp2, "word2") resp3, _ := testGet("http://example.com/file-stream.php", handler, t) assert.Equal(t, resp3, "word3") }, &testOptions{workerScript: "file-stream.php", nbParallelRequests: 1, nbWorkers: 1}) } // To run this fuzzing test use: go test -fuzz FuzzRequest // TODO: Cover more potential cases func FuzzRequest(f *testing.F) { absPath, _ := fastabs.FastAbs("./testdata/") f.Add("hello world") f.Add("😀😅🙃🤩🥲🤪😘😇😉🐘🧟") f.Add("%00%11%%22%%33%%44%%55%%66%%77%%88%%99%%aa%%bb%%cc%%dd%%ee%%ff") f.Add("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f") f.Fuzz(func(t *testing.T, fuzzedString string) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, _ int) { req := httptest.NewRequest("GET", "http://example.com/server-variable", nil) req.URL = &url.URL{RawQuery: "test=" + fuzzedString, Path: "/server-variable.php/" + fuzzedString} req.Header.Add(strings.Clone("Fuzzed"), strings.Clone(fuzzedString)) req.Header.Add(strings.Clone("Content-Type"), fuzzedString) body, resp := testRequest(req, handler, t) // The response status must be 400 if the request path contains null bytes if strings.Contains(req.URL.Path, "\x00") { assert.Equal(t, 400, resp.StatusCode) assert.Contains(t, body, "invalid request path") return } // The fuzzed string must be present in the path assert.Contains(t, body, fmt.Sprintf("[PATH_INFO] => /%s", fuzzedString)) assert.Contains(t, body, fmt.Sprintf("[PATH_TRANSLATED] => %s", filepath.Join(absPath, fuzzedString))) // Headers should always be present even if empty assert.Contains(t, body, fmt.Sprintf("[CONTENT_TYPE] => %s", fuzzedString)) assert.Contains(t, body, fmt.Sprintf("[HTTP_FUZZED] => %s", fuzzedString)) }, &testOptions{workerScript: "request-headers.php"}) }) } func TestSessionHandlerReset_worker(t *testing.T) { runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) { // Request 1: Set a custom session handler and start session resp1, err := http.Get(ts.URL + "/session-handler.php?action=set_handler_and_start&value=test1") assert.NoError(t, err) body1, _ := io.ReadAll(resp1.Body) _ = resp1.Body.Close() body1Str := string(body1) assert.Contains(t, body1Str, "HANDLER_SET_AND_STARTED") assert.Contains(t, body1Str, "session.save_handler=user") // Request 2: Start session without setting a custom handler // The user handler from request 1 is preserved (mod_user_names persist), // so session_start() should work without crashing. resp2, err := http.Get(ts.URL + "/session-handler.php?action=start_without_handler") assert.NoError(t, err) body2, _ := io.ReadAll(resp2.Body) _ = resp2.Body.Close() body2Str := string(body2) // session_start() should succeed (handlers are preserved) assert.Contains(t, body2Str, "SESSION_START_RESULT=true", "session_start() should succeed.\nResponse: %s", body2Str) // No errors or exceptions should occur assert.NotContains(t, body2Str, "ERROR:", "No errors expected.\nResponse: %s", body2Str) assert.NotContains(t, body2Str, "EXCEPTION:", "No exceptions expected.\nResponse: %s", body2Str) }, &testOptions{ workerScript: "session-handler.php", nbWorkers: 1, nbParallelRequests: 1, realServer: true, }) } func TestSessionHandlerPreLoopPreserved_worker(t *testing.T) { runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) { // Request 1: Check that the pre-loop session handler is preserved resp1, err := http.Get(ts.URL + "/worker-with-session-handler.php?action=check") assert.NoError(t, err) body1, _ := io.ReadAll(resp1.Body) _ = resp1.Body.Close() body1Str := string(body1) t.Logf("Request 1 response: %s", body1Str) assert.Contains(t, body1Str, "HANDLER_PRESERVED", "Session handler set before loop should be preserved") assert.Contains(t, body1Str, "save_handler=user", "session.save_handler should remain 'user'") // Request 2: Use the session - should work with pre-loop handler resp2, err := http.Get(ts.URL + "/worker-with-session-handler.php?action=use_session") assert.NoError(t, err) body2, _ := io.ReadAll(resp2.Body) _ = resp2.Body.Close() body2Str := string(body2) t.Logf("Request 2 response: %s", body2Str) assert.Contains(t, body2Str, "SESSION_OK", "Session should work with pre-loop handler.\nResponse: %s", body2Str) assert.NotContains(t, body2Str, "ERROR:", "No errors expected.\nResponse: %s", body2Str) assert.NotContains(t, body2Str, "EXCEPTION:", "No exceptions expected.\nResponse: %s", body2Str) // Request 3: Check handler is still preserved after using session resp3, err := http.Get(ts.URL + "/worker-with-session-handler.php?action=check") assert.NoError(t, err) body3, _ := io.ReadAll(resp3.Body) _ = resp3.Body.Close() body3Str := string(body3) t.Logf("Request 3 response: %s", body3Str) assert.Contains(t, body3Str, "HANDLER_PRESERVED", "Session handler should still be preserved after use") }, &testOptions{ workerScript: "worker-with-session-handler.php", nbWorkers: 1, nbParallelRequests: 1, realServer: true, }) } func TestSessionNoLeakBetweenRequests_worker(t *testing.T) { runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) { // Client A: Set a secret value in session clientA := &http.Client{} resp1, err := clientA.Get(ts.URL + "/session-leak.php?action=set&value=secret_A&client_id=clientA") assert.NoError(t, err) body1, _ := io.ReadAll(resp1.Body) _ = resp1.Body.Close() body1Str := string(body1) t.Logf("Client A set session: %s", body1Str) assert.Contains(t, body1Str, "SESSION_SET") assert.Contains(t, body1Str, "secret=secret_A") // Client B: Check that session is empty (no cookie, should not see Client A's data) clientB := &http.Client{} resp2, err := clientB.Get(ts.URL + "/session-leak.php?action=check_empty") assert.NoError(t, err) body2, _ := io.ReadAll(resp2.Body) _ = resp2.Body.Close() body2Str := string(body2) t.Logf("Client B check empty: %s", body2Str) assert.Contains(t, body2Str, "SESSION_CHECK") assert.Contains(t, body2Str, "SESSION_EMPTY=true", "Client B should have empty session, not see Client A's data.\nResponse: %s", body2Str) assert.NotContains(t, body2Str, "secret_A", "Client A's secret should not leak to Client B.\nResponse: %s", body2Str) // Client C: Read session without cookie (should also be empty) clientC := &http.Client{} resp3, err := clientC.Get(ts.URL + "/session-leak.php?action=get") assert.NoError(t, err) body3, _ := io.ReadAll(resp3.Body) _ = resp3.Body.Close() body3Str := string(body3) t.Logf("Client C get session: %s", body3Str) assert.Contains(t, body3Str, "SESSION_READ") assert.Contains(t, body3Str, "secret=NOT_FOUND", "Client C should not find any secret.\nResponse: %s", body3Str) assert.Contains(t, body3Str, "client_id=NOT_FOUND", "Client C should not find any client_id.\nResponse: %s", body3Str) }, &testOptions{ workerScript: "session-leak.php", nbWorkers: 1, nbParallelRequests: 1, realServer: true, }) } func TestSessionNoLeakAfterExit_worker(t *testing.T) { runTest(t, func(_ func(http.ResponseWriter, *http.Request), ts *httptest.Server, i int) { // Client A: Set a secret value in session and call exit(1) clientA := &http.Client{} resp1, err := clientA.Get(ts.URL + "/session-leak.php?action=set_and_exit&value=exit_secret&client_id=exitClient") assert.NoError(t, err) body1, _ := io.ReadAll(resp1.Body) _ = resp1.Body.Close() body1Str := string(body1) t.Logf("Client A set and exit: %s", body1Str) // The response may be incomplete due to exit(1) assert.Contains(t, body1Str, "BEFORE_EXIT") // Client B: Check that session is empty (should not see Client A's data) // Retry until the worker has restarted after exit(1) clientB := &http.Client{} var body2Str string assert.Eventually(t, func() bool { resp2, err := clientB.Get(ts.URL + "/session-leak.php?action=check_empty") if err != nil { return false } body2, _ := io.ReadAll(resp2.Body) _ = resp2.Body.Close() body2Str = string(body2) return strings.Contains(body2Str, "SESSION_CHECK") }, 2*time.Second, 10*time.Millisecond, "Worker did not restart in time after exit(1)") t.Logf("Client B check empty after exit: %s", body2Str) assert.Contains(t, body2Str, "SESSION_EMPTY=true", "Client B should have empty session after Client A's exit(1).\nResponse: %s", body2Str) assert.NotContains(t, body2Str, "exit_secret", "Client A's secret should not leak to Client B after exit(1).\nResponse: %s", body2Str) // Client C: Try to read session (should also be empty) clientC := &http.Client{} resp3, err := clientC.Get(ts.URL + "/session-leak.php?action=get") assert.NoError(t, err) body3, _ := io.ReadAll(resp3.Body) _ = resp3.Body.Close() body3Str := string(body3) t.Logf("Client C get session after exit: %s", body3Str) assert.Contains(t, body3Str, "SESSION_READ") assert.Contains(t, body3Str, "secret=NOT_FOUND", "Client C should not find any secret after exit(1).\nResponse: %s", body3Str) }, &testOptions{ workerScript: "session-leak.php", nbWorkers: 1, nbParallelRequests: 1, realServer: true, }) } func TestOpcachePreload_module(t *testing.T) { testOpcachePreload(t, &testOptions{env: map[string]string{"TEST": "123"}, realServer: true}) } func TestOpcachePreload_worker(t *testing.T) { testOpcachePreload(t, &testOptions{workerScript: "preload-check.php", env: map[string]string{"TEST": "123"}, realServer: true}) } func testOpcachePreload(t *testing.T, opts *testOptions) { if frankenphp.Version().VersionID <= 80300 { t.Skip("This test is only supported in PHP 8.3 and above") return } cwd, _ := os.Getwd() preloadScript := cwd + "/testdata/preload.php" u, err := user.Current() require.NoError(t, err) // use opcache.log_verbosity_level:4 for debugging opts.phpIni = map[string]string{ "opcache.enable": "1", "opcache.preload": preloadScript, "opcache.preload_user": u.Username, } runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet("http://example.com/preload-check.php", handler, t) assert.Equal(t, "I am preloaded", body) }, opts) } ================================================ FILE: go.mod ================================================ module github.com/dunglas/frankenphp go 1.26.0 retract v1.0.0-rc.1 // Human error require ( github.com/Masterminds/sprig/v3 v3.3.0 github.com/dunglas/mercure v0.21.11 github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be github.com/maypok86/otter/v2 v2.3.0 github.com/prometheus/client_golang v1.23.2 github.com/stretchr/testify v1.11.1 golang.org/x/net v0.51.0 golang.org/x/text v0.34.0 ) require ( dario.cat/mergo v1.0.2 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145 // indirect github.com/RoaringBitmap/roaring/v2 v2.15.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bits-and-blooms/bitset v1.24.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dunglas/skipfilter v1.0.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/gofrs/uuid/v5 v5.4.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/handlers v1.5.2 // indirect github.com/gorilla/mux v1.8.1 // indirect github.com/huandu/xstrings v1.5.0 // indirect github.com/klauspost/compress v1.18.4 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/mschoch/smat v0.2.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/procfs v0.20.1 // indirect github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/rs/cors v1.11.1 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/shopspring/decimal v1.4.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/viper v1.21.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/unrolled/secure v1.17.0 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.etcd.io/bbolt v1.4.3 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/sys v0.42.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: go.sh ================================================ #!/bin/sh # Runs the go command with the proper Go and cgo flags. GOFLAGS="$GOFLAGS -tags=nobadger,nomysql,nopgx" \ CGO_CFLAGS="$CGO_CFLAGS $(php-config --includes)" \ CGO_LDFLAGS="$CGO_LDFLAGS $(php-config --ldflags) $(php-config --libs)" \ go "$@" ================================================ FILE: go.sum ================================================ dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145 h1:1yw6O62BReQ+uA1oyk9XaQTvLhcoHWmoQAgXmDFXpIY= github.com/MauriceGit/skiplist v0.0.0-20211105230623-77f5c8d3e145/go.mod h1:877WBceefKn14QwVVn4xRFUsHsZb9clICgdeTj4XsUg= github.com/RoaringBitmap/roaring/v2 v2.15.0 h1:gCbixa3UiG7g6WUZNVOfEEg2HTc1vR4OVdMkX8t1ZFc= github.com/RoaringBitmap/roaring/v2 v2.15.0/go.mod h1:eq4wdNXxtJIS/oikeCzdX1rBzek7ANzbth041hrU8Q4= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bits-and-blooms/bitset v1.24.4 h1:95H15Og1clikBrKr/DuzMXkQzECs1M6hhoGXLwLQOZE= github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dunglas/mercure v0.21.11 h1:4Sd/Q77j8uh9SI5D9ZMg5sePlWs336+9CKxDQC1FV34= github.com/dunglas/mercure v0.21.11/go.mod h1:WPMgfqonUiO1qB+W8Tya63Ngag9ZwplGMXSOy8P/uMg= github.com/dunglas/skipfilter v1.0.0 h1:JG9SgGg4n6BlFwuTYzb9RIqjH7PfwszvWehanrYWPF4= github.com/dunglas/skipfilter v1.0.0/go.mod h1:ryhr8j7CAHSjzeN7wI6YEuwoArQ3OQmRqWWVCEAfb9w= github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be h1:vqHrvilasyJcnru/0Z4FoojsQJUIfXGVplte7JtupfY= github.com/e-dant/watcher v0.0.0-20260223030516-06f84a1314be/go.mod h1:PmV4IVmBJVqT2NcfTGN4+sZ+qGe3PA0qkphAtOHeFG0= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0= github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c= github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/maypok86/otter/v2 v2.3.0 h1:8H8AVVFUSzJwIegKwv1uF5aGitTY+AIrtktg7OcLs8w= github.com/maypok86/otter/v2 v2.3.0/go.mod h1:XgIdlpmL6jYz882/CAx1E4C1ukfgDKSaw4mWq59+7l8= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM= github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbWU= github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: hotreload.go ================================================ //go:build !nomercure && !nowatcher package frankenphp import ( "encoding/json" "log/slog" "github.com/dunglas/frankenphp/internal/watcher" "github.com/dunglas/mercure" watcherGo "github.com/e-dant/watcher/watcher-go" ) // WithHotReload sets files to watch for file changes to trigger a hot reload update. func WithHotReload(topic string, hub *mercure.Hub, patterns []string) Option { return func(o *opt) error { o.hotReload = append(o.hotReload, &watcher.PatternGroup{ Patterns: patterns, Callback: func(events []*watcherGo.Event) { // Wait for workers to restart before sending the update go func() { data, err := json.Marshal(events) if err != nil { if globalLogger.Enabled(globalCtx, slog.LevelError) { globalLogger.LogAttrs(globalCtx, slog.LevelError, "error marshaling watcher events", slog.Any("error", err)) } return } if err := hub.Publish(globalCtx, &mercure.Update{ Topics: []string{topic}, Event: mercure.Event{Data: string(data)}, Debug: globalLogger.Enabled(globalCtx, slog.LevelDebug), }); err != nil && globalLogger.Enabled(globalCtx, slog.LevelError) { globalLogger.LogAttrs(globalCtx, slog.LevelError, "error publishing hot reloading Mercure update", slog.Any("error", err)) } }() }, }) return nil } } ================================================ FILE: install.ps1 ================================================ #Requires -Version 5.1 <# .SYNOPSIS Downloads and installs the latest FrankenPHP release for Windows. .DESCRIPTION This script downloads the latest FrankenPHP Windows release from GitHub and extracts it to the specified directory (~\.frankenphp by default). Usage as a one-liner: irm https://github.com/php/frankenphp/raw/refs/heads/main/install.ps1 | iex Custom install directory: $env:FRANKENPHP_INSTALL = 'C:\frankenphp'; irm https://github.com/php/frankenphp/raw/refs/heads/main/install.ps1 | iex #> $ErrorActionPreference = "Stop" if ($env:FRANKENPHP_INSTALL) { $BinDir = $env:FRANKENPHP_INSTALL } else { $BinDir = Join-Path $HOME ".frankenphp" } Write-Host "Downloading FrankenPHP for Windows (x64)..." -ForegroundColor Cyan $tmpZip = Join-Path $env:TEMP "frankenphp-windows-$PID.zip" try { Invoke-WebRequest -Uri "https://github.com/php/frankenphp/releases/latest/download/frankenphp-windows-x86_64.zip" -OutFile $tmpZip } catch { Write-Host "Download failed: $_" -ForegroundColor Red exit 1 } Write-Host "Extracting to $BinDir..." -ForegroundColor Cyan if (-not (Test-Path $BinDir)) { New-Item -ItemType Directory -Path $BinDir -Force | Out-Null } try { Expand-Archive -Force -Path $tmpZip -DestinationPath $BinDir } finally { Remove-Item $tmpZip -Force -ErrorAction SilentlyContinue } Write-Host "" Write-Host "FrankenPHP downloaded successfully to $BinDir" -ForegroundColor Green # Check if the directory is in PATH $inPath = $env:PATH -split ";" | Where-Object { $_ -eq $BinDir -or $_ -eq "$BinDir\" } if (-not $inPath) { Write-Host "Add $BinDir to your PATH to use frankenphp.exe globally:" -ForegroundColor Yellow Write-Host " [Environment]::SetEnvironmentVariable('PATH', `"$BinDir;`" + [Environment]::GetEnvironmentVariable('PATH', 'User'), 'User')" -ForegroundColor Gray } Write-Host "" Write-Host "If you like FrankenPHP, please give it a star on GitHub: https://github.com/php/frankenphp" -ForegroundColor Cyan ================================================ FILE: install.sh ================================================ #!/bin/sh set -e SUDO="" if [ -z "${BIN_DIR}" ]; then BIN_DIR=$(pwd) fi THE_ARCH_BIN="" DEST=${BIN_DIR}/frankenphp OS=$(uname -s) ARCH=$(uname -m) GNU="" if ! command -v curl >/dev/null 2>&1; then echo "❗ Please install curl to download FrankenPHP" exit 1 fi if type "tput" >/dev/null 2>&1; then bold=$(tput bold || true) italic=$(tput sitm || true) normal=$(tput sgr0 || true) fi case ${OS} in Linux*) if [ "${ARCH}" = "aarch64" ] || [ "${ARCH}" = "x86_64" ]; then if command -v dnf >/dev/null 2>&1; then echo "📦 Detected dnf. Installing FrankenPHP from RPM repository..." if [ "$(id -u)" -ne 0 ]; then SUDO="sudo" echo "❗ Enter your password to grant sudo powers for package installation" ${SUDO} -v || true fi ${SUDO} dnf -y install https://rpm.henderkes.com/static-php-1-1.noarch.rpm ${SUDO} dnf -y module enable php-zts:static-8.5 || true ${SUDO} dnf -y install frankenphp echo echo "🥳 FrankenPHP installed to ${italic}/usr/bin/frankenphp${normal} successfully." echo "❗ The systemd service uses the Caddyfile in ${italic}/etc/frankenphp/Caddyfile${normal}" echo "❗ Your php.ini is found in ${italic}/etc/php-zts/php.ini${normal}" echo echo "⭐ If you like FrankenPHP, please give it a star on GitHub: ${italic}https://github.com/php/frankenphp${normal}" exit 0 fi if command -v apt-get >/dev/null 2>&1; then echo "📦 Detected apt-get. Installing FrankenPHP from DEB repository..." if [ "$(id -u)" -ne 0 ]; then SUDO="sudo" echo "❗ Enter your password to grant sudo powers for package installation" ${SUDO} -v || true fi ${SUDO} sh -c 'curl -fsSL https://pkg.henderkes.com/api/packages/85/debian/repository.key -o /etc/apt/keyrings/static-php85.asc' ${SUDO} sh -c 'echo "deb [signed-by=/etc/apt/keyrings/static-php85.asc] https://pkg.henderkes.com/api/packages/85/debian php-zts main" | sudo tee -a /etc/apt/sources.list.d/static-php85.list' ${SUDO} apt-get update ${SUDO} apt-get -y install frankenphp echo echo "🥳 FrankenPHP installed to ${italic}/usr/bin/frankenphp${normal} successfully." echo "❗ The systemd service uses the Caddyfile in ${italic}/etc/frankenphp/Caddyfile${normal}" echo "❗ Your php.ini is found in ${italic}/etc/php-zts/php.ini${normal}" echo echo "⭐ If you like FrankenPHP, please give it a star on GitHub: ${italic}https://github.com/php/frankenphp${normal}" exit 0 fi if command -v apk >/dev/null 2>&1; then echo "📦 Detected apk. Installing FrankenPHP from APK repository..." if [ "$(id -u)" -ne 0 ]; then SUDO="sudo" echo "❗ Enter your password to grant sudo powers for package installation" ${SUDO} -v || true fi KEY_URL="https://pkg.henderkes.com/api/packages/85/alpine/key" ${SUDO} sh -c "cd /etc/apk/keys && curl -JOsS \"$KEY_URL\" 2>/dev/null || true" REPO_URL="https://pkg.henderkes.com/api/packages/85/alpine/main/php-zts" if grep -q "$REPO_URL" /etc/apk/repositories 2>/dev/null; then echo "Repository already exists in /etc/apk/repositories" else ${SUDO} sh -c "echo \"$REPO_URL\" >> /etc/apk/repositories" ${SUDO} apk update echo "Repository added to /etc/apk/repositories" fi ${SUDO} apk add frankenphp echo echo "🥳 FrankenPHP installed to ${italic}/usr/bin/frankenphp${normal} successfully." echo "❗ The OpenRC service uses the Caddyfile in ${italic}/etc/frankenphp/Caddyfile${normal}" echo "❗ Your php.ini is found in ${italic}/etc/php-zts/php.ini${normal}" echo echo "⭐ If you like FrankenPHP, please give it a star on GitHub: ${italic}https://github.com/php/frankenphp${normal}" exit 0 fi fi case ${ARCH} in aarch64) THE_ARCH_BIN="frankenphp-linux-aarch64" ;; x86_64) THE_ARCH_BIN="frankenphp-linux-x86_64" ;; *) THE_ARCH_BIN="" ;; esac if getconf GNU_LIBC_VERSION >/dev/null 2>&1; then THE_ARCH_BIN="${THE_ARCH_BIN}-gnu" GNU=" (glibc)" fi ;; Darwin*) case ${ARCH} in arm64) THE_ARCH_BIN="frankenphp-mac-arm64" ;; *) THE_ARCH_BIN="frankenphp-mac-x86_64" ;; esac ;; CYGWIN_NT* | MSYS_NT* | MINGW*) if ! command -v unzip >/dev/null 2>&1 && ! command -v powershell.exe >/dev/null 2>&1; then echo "❗ Please install unzip or ensure PowerShell is available to extract FrankenPHP" exit 1 fi echo "📦 Downloading ${bold}FrankenPHP${normal} for Windows (x64):" TMPZIP="/tmp/frankenphp-windows-$$.zip" if ! curl -f -L --progress-bar "https://github.com/php/frankenphp/releases/latest/download/frankenphp-windows-x86_64.zip" -o "${TMPZIP}"; then echo "❗ Failed to download FrankenPHP for Windows. Please check your internet connection or download it manually from:" echo " https://github.com/php/frankenphp/releases/latest" exit 1 fi echo "📂 Extracting to ${italic}${BIN_DIR}${normal}..." if command -v unzip >/dev/null 2>&1; then unzip -o -q "${TMPZIP}" -d "${BIN_DIR}" else powershell.exe -Command "Expand-Archive -Force -Path '$(cygpath -w "${TMPZIP}")' -DestinationPath '$(cygpath -w "${BIN_DIR}")'" fi rm -f "${TMPZIP}" echo echo "🥳 FrankenPHP downloaded successfully to ${italic}${BIN_DIR}${normal}" echo "🔧 Add ${italic}$(cygpath -w "${BIN_DIR}")${normal} to your Windows PATH to use ${italic}frankenphp.exe${normal} globally." echo echo "⭐ If you like FrankenPHP, please give it a star on GitHub: ${italic}https://github.com/php/frankenphp${normal}" exit 0 ;; *) THE_ARCH_BIN="" ;; esac if [ -z "${THE_ARCH_BIN}" ]; then echo "❗ Precompiled binaries are not available for ${ARCH}-${OS}" echo "❗ You can compile from sources by following the documentation at: https://frankenphp.dev/docs/compile/" exit 1 fi echo "📦 Downloading ${bold}FrankenPHP${normal} for ${OS}${GNU} (${ARCH}):" # check if $DEST is writable and suppress an error message touch "${DEST}" 2>/dev/null # we need sudo powers to write to DEST if [ $? -eq 1 ]; then echo "❗ You do not have permission to write to ${italic}${DEST}${normal}, enter your password to grant sudo powers" SUDO="sudo" fi curl -L --progress-bar "https://github.com/php/frankenphp/releases/latest/download/${THE_ARCH_BIN}" -o "${DEST}" ${SUDO} chmod +x "${DEST}" # Allow binding to ports 80/443 without running as root (if setcap is available) if command -v setcap >/dev/null 2>&1; then ${SUDO} setcap 'cap_net_bind_service=+ep' "${DEST}" || true else echo "❗ install setcap (e.g. libcap2-bin) to allow FrankenPHP to bind to ports 80/443 without root:" echo " ${bold}sudo setcap 'cap_net_bind_service=+ep' \"${DEST}\"${normal}" fi echo echo "🥳 FrankenPHP downloaded successfully to ${italic}${DEST}${normal}" echo "❗ It uses ${italic}/etc/frankenphp/php.ini${normal} if found." case ":$PATH:" in *":$DEST:"*) ;; *) echo "🔧 Move the binary to ${italic}/usr/local/bin/${normal} or another directory in your ${italic}PATH${normal} to use it globally:" echo " ${bold}sudo mv ${DEST} /usr/local/bin/${normal}" ;; esac echo echo "⭐ If you like FrankenPHP, please give it a star on GitHub: ${italic}https://github.com/php/frankenphp${normal}" ================================================ FILE: internal/cpu/cpu_unix.go ================================================ //go:build unix package cpu // #include import "C" import ( "runtime" "time" ) var cpuCount = runtime.GOMAXPROCS(0) // ProbeCPUs probes the CPU usage of the process // if CPUs are not busy, most threads are likely waiting for I/O, so we should scale // if CPUs are already busy we won't gain much by scaling and want to avoid the overhead of doing so func ProbeCPUs(probeTime time.Duration, maxCPUUsage float64, abort chan struct{}) bool { var cpuStart, cpuEnd C.struct_timespec // note: clock_gettime is a POSIX function // on Windows we'd need to use QueryPerformanceCounter instead start := time.Now() C.clock_gettime(C.CLOCK_PROCESS_CPUTIME_ID, &cpuStart) select { case <-abort: return false case <-time.After(probeTime): } C.clock_gettime(C.CLOCK_PROCESS_CPUTIME_ID, &cpuEnd) elapsedTime := float64(time.Since(start).Nanoseconds()) elapsedCpuTime := float64(cpuEnd.tv_sec-cpuStart.tv_sec)*1e9 + float64(cpuEnd.tv_nsec-cpuStart.tv_nsec) cpuUsage := elapsedCpuTime / elapsedTime / float64(cpuCount) return cpuUsage < maxCPUUsage } ================================================ FILE: internal/cpu/cpu_windows.go ================================================ package cpu import ( "time" ) // ProbeCPUs fallback that always determines that the CPU limits are not reached func ProbeCPUs(probeTime time.Duration, _ float64, abort chan struct{}) bool { select { case <-abort: return false case <-time.After(probeTime): return true } } ================================================ FILE: internal/extgen/arginfo.go ================================================ package extgen import ( "fmt" "log" "os" "os/exec" "path/filepath" "strings" ) type arginfoGenerator struct { generator *Generator } func (ag *arginfoGenerator) generate() error { genStubPath := os.Getenv("GEN_STUB_SCRIPT") if genStubPath == "" { genStubPath = "/usr/local/src/php/build/gen_stub.php" } if _, err := os.Stat(genStubPath); err != nil { return fmt.Errorf(`the PHP "gen_stub.php" file couldn't be found under %q, you can set the "GEN_STUB_SCRIPT" environment variable to set a custom location`, genStubPath) } stubFile := ag.generator.BaseName + ".stub.php" cmd := exec.Command("php", genStubPath, filepath.Join(ag.generator.BuildDir, stubFile)) output, err := cmd.CombinedOutput() if err != nil { log.Print("gen_stub.php output:\n", string(output)) return fmt.Errorf("running gen_stub script: %w\nOutput: %s", err, string(output)) } return ag.fixArginfoFile(stubFile) } func (ag *arginfoGenerator) fixArginfoFile(stubFile string) error { arginfoFile := strings.TrimSuffix(stubFile, ".stub.php") + "_arginfo.h" arginfoPath := filepath.Join(ag.generator.BuildDir, arginfoFile) content, err := readFile(arginfoPath) if err != nil { return fmt.Errorf("reading arginfo file: %w", err) } // FIXME: the script generate "zend_register_internal_class_with_flags" but it is not recognized by the compiler fixedContent := strings.ReplaceAll(content, "zend_register_internal_class_with_flags(&ce, NULL, 0)", "zend_register_internal_class(&ce)") return writeFile(arginfoPath, fixedContent) } ================================================ FILE: internal/extgen/cfile.go ================================================ package extgen import ( "github.com/Masterminds/sprig/v3" "bytes" _ "embed" "path/filepath" "strings" "text/template" ) //go:embed templates/extension.c.tpl var cFileContent string type cFileGenerator struct { generator *Generator } type cTemplateData struct { BaseName string Functions []phpFunction Classes []phpClass Constants []phpConstant Namespace string } func (cg *cFileGenerator) generate() error { filename := filepath.Join(cg.generator.BuildDir, cg.generator.BaseName+".c") content, err := cg.buildContent() if err != nil { return err } return writeFile(filename, content) } func (cg *cFileGenerator) buildContent() (string, error) { var builder strings.Builder templateContent, err := cg.getTemplateContent() if err != nil { return "", err } builder.WriteString(templateContent) for _, fn := range cg.generator.Functions { fnGen := PHPFuncGenerator{ paramParser: &ParameterParser{}, namespace: cg.generator.Namespace, } builder.WriteString(fnGen.generate(fn)) } return builder.String(), nil } func (cg *cFileGenerator) getTemplateContent() (string, error) { funcMap := sprig.FuncMap() funcMap["namespacedClassName"] = NamespacedName funcMap["cString"] = escapeCString tmpl := template.Must(template.New("cfile").Funcs(funcMap).Parse(cFileContent)) var buf bytes.Buffer if err := tmpl.Execute(&buf, cTemplateData{ BaseName: cg.generator.BaseName, Functions: cg.generator.Functions, Classes: cg.generator.Classes, Constants: cg.generator.Constants, Namespace: cg.generator.Namespace, }); err != nil { return "", err } return buf.String(), nil } // escapeCString escapes backslashes for C string literals func escapeCString(s string) string { return strings.ReplaceAll(s, `\`, `\\`) } ================================================ FILE: internal/extgen/cfile_namespace_test.go ================================================ package extgen import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNamespacedClassName(t *testing.T) { tests := []struct { name string namespace string className string expected string }{ { name: "no namespace", namespace: "", className: "MySuperClass", expected: "MySuperClass", }, { name: "single level namespace", namespace: "MyNamespace", className: "MySuperClass", expected: "MyNamespace_MySuperClass", }, { name: "multi level namespace", namespace: `Go\Extension`, className: "MySuperClass", expected: "Go_Extension_MySuperClass", }, { name: "deep namespace", namespace: `My\Deep\Nested\Namespace`, className: "TestClass", expected: "My_Deep_Nested_Namespace_TestClass", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := NamespacedName(tt.namespace, tt.className) require.Equal(t, tt.expected, result, "expected %q, got %q", tt.expected, result) }) } } func TestCFileGenerationWithNamespace(t *testing.T) { content := `package main //export_php:namespace Go\Extension //export_php:class MySuperClass type MySuperClass struct{} //export_php:method MySuperClass test(): string func (m *MySuperClass) Test() string { return "test" } ` tmpfile, err := os.CreateTemp("", "test_cfile_namespace_*.go") require.NoError(t, err, "Failed to create temp file") defer func() { err := os.Remove(tmpfile.Name()) assert.NoError(t, err, "Failed to remove temp file: %v", err) }() _, err = tmpfile.Write([]byte(content)) require.NoError(t, err, "Failed to write to temp file") err = tmpfile.Close() require.NoError(t, err, "Failed to close temp file") generator := &Generator{ BaseName: "test_extension", SourceFile: tmpfile.Name(), BuildDir: t.TempDir(), Namespace: `Go\Extension`, Classes: []phpClass{ { Name: "MySuperClass", GoStruct: "MySuperClass", Methods: []phpClassMethod{ { Name: "test", PhpName: "test", Signature: "test(): string", ReturnType: "string", ClassName: "MySuperClass", }, }, }, }, } cFileGen := cFileGenerator{generator: generator} contentResult, err := cFileGen.getTemplateContent() require.NoError(t, err, "error generating C file") expectedCall := "register_class_Go_Extension_MySuperClass()" require.Contains(t, contentResult, expectedCall, "C file should contain the standard function call") oldCall := "register_class_MySuperClass()" require.NotContains(t, contentResult, oldCall, "C file should not contain old non-namespaced call") } func TestCFileGenerationWithoutNamespace(t *testing.T) { generator := &Generator{ BaseName: "test_extension", BuildDir: t.TempDir(), Namespace: "", Classes: []phpClass{ { Name: "MySuperClass", GoStruct: "MySuperClass", }, }, } cFileGen := cFileGenerator{generator: generator} contentResult, err := cFileGen.getTemplateContent() require.NoError(t, err, "error generating C file") expectedCall := "register_class_MySuperClass()" require.Contains(t, contentResult, expectedCall, "C file should not contain the standard function call") } func TestCFileGenerationWithNamespacedConstants(t *testing.T) { tests := []struct { name string namespace string constants []phpConstant contains []string }{ { name: "integer constant with namespace", namespace: `Go\Extension`, constants: []phpConstant{ {Name: "TEST_INT", Value: "42", PhpType: phpInt}, }, contains: []string{ `REGISTER_NS_LONG_CONSTANT("Go\\Extension", "TEST_INT", 42, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "string constant with namespace", namespace: `Go\Extension`, constants: []phpConstant{ {Name: "TEST_STRING", Value: `"hello"`, PhpType: phpString}, }, contains: []string{ `REGISTER_NS_STRING_CONSTANT("Go\\Extension", "TEST_STRING", "hello", CONST_CS | CONST_PERSISTENT);`, }, }, { name: "float constant with namespace", namespace: `Go\Extension`, constants: []phpConstant{ {Name: "TEST_FLOAT", Value: "3.14", PhpType: phpFloat}, }, contains: []string{ `REGISTER_NS_DOUBLE_CONSTANT("Go\\Extension", "TEST_FLOAT", 3.14, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "bool constant with namespace", namespace: `Go\Extension`, constants: []phpConstant{ {Name: "TEST_BOOL", Value: "true", PhpType: phpBool}, }, contains: []string{ `REGISTER_NS_BOOL_CONSTANT("Go\\Extension", "TEST_BOOL", true, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "iota constant with namespace", namespace: `Go\Extension`, constants: []phpConstant{ {Name: "STATUS_OK", Value: "STATUS_OK", PhpType: phpInt, IsIota: true}, }, contains: []string{ `REGISTER_NS_LONG_CONSTANT("Go\\Extension", "STATUS_OK", STATUS_OK, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "multiple constants with deep namespace", namespace: `My\Deep\Namespace`, constants: []phpConstant{ {Name: "CONST_INT", Value: "100", PhpType: phpInt}, {Name: "CONST_STR", Value: `"value"`, PhpType: phpString}, {Name: "CONST_FLOAT", Value: "1.5", PhpType: phpFloat}, }, contains: []string{ `REGISTER_NS_LONG_CONSTANT("My\\Deep\\Namespace", "CONST_INT", 100, CONST_CS | CONST_PERSISTENT);`, `REGISTER_NS_STRING_CONSTANT("My\\Deep\\Namespace", "CONST_STR", "value", CONST_CS | CONST_PERSISTENT);`, `REGISTER_NS_DOUBLE_CONSTANT("My\\Deep\\Namespace", "CONST_FLOAT", 1.5, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "single level namespace", namespace: `TestNamespace`, constants: []phpConstant{ {Name: "MY_CONST", Value: "999", PhpType: phpInt}, }, contains: []string{ `REGISTER_NS_LONG_CONSTANT("TestNamespace", "MY_CONST", 999, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "namespace with trailing backslash", namespace: `TestIntegration\Extension`, constants: []phpConstant{ {Name: "VERSION", Value: `"1.0.0"`, PhpType: phpString}, }, contains: []string{ `REGISTER_NS_STRING_CONSTANT("TestIntegration\\Extension", "VERSION", "1.0.0", CONST_CS | CONST_PERSISTENT);`, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: "test_ext", Namespace: tt.namespace, Constants: tt.constants, } cGen := cFileGenerator{generator: generator} content, err := cGen.buildContent() require.NoError(t, err, "Failed to build C file content") for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated C content should contain '%s'", expected) } }) } } func TestCFileGenerationWithoutNamespacedConstants(t *testing.T) { tests := []struct { name string namespace string constants []phpConstant contains []string }{ { name: "integer constant without namespace", namespace: "", constants: []phpConstant{ {Name: "GLOBAL_INT", Value: "42", PhpType: phpInt}, }, contains: []string{ `REGISTER_LONG_CONSTANT("GLOBAL_INT", 42, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "string constant without namespace", namespace: "", constants: []phpConstant{ {Name: "GLOBAL_STRING", Value: `"test"`, PhpType: phpString}, }, contains: []string{ `REGISTER_STRING_CONSTANT("GLOBAL_STRING", "test", CONST_CS | CONST_PERSISTENT);`, }, }, { name: "float constant without namespace", namespace: "", constants: []phpConstant{ {Name: "GLOBAL_FLOAT", Value: "2.71", PhpType: phpFloat}, }, contains: []string{ `REGISTER_DOUBLE_CONSTANT("GLOBAL_FLOAT", 2.71, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "bool constant without namespace", namespace: "", constants: []phpConstant{ {Name: "GLOBAL_BOOL", Value: "false", PhpType: phpBool}, }, contains: []string{ `REGISTER_BOOL_CONSTANT("GLOBAL_BOOL", false, CONST_CS | CONST_PERSISTENT);`, }, }, { name: "iota constant without namespace", namespace: "", constants: []phpConstant{ {Name: "ERROR_CODE", Value: "ERROR_CODE", PhpType: phpInt, IsIota: true}, }, contains: []string{ `REGISTER_LONG_CONSTANT("ERROR_CODE", ERROR_CODE, CONST_CS | CONST_PERSISTENT);`, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: "test_ext", Namespace: tt.namespace, Constants: tt.constants, } cGen := cFileGenerator{generator: generator} content, err := cGen.buildContent() require.NoError(t, err, "Failed to build C file content") for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated C content should contain '%s'", expected) } assert.NotContains(t, content, "REGISTER_NS_", "Content should NOT contain namespaced constant macros when namespace is empty") }) } } func TestCFileTemplateFunctionMapCString(t *testing.T) { generator := &Generator{ BaseName: "test_ext", Namespace: `My\Namespace\Test`, Constants: []phpConstant{ {Name: "MY_CONST", Value: "123", PhpType: phpInt}, }, } cGen := cFileGenerator{generator: generator} content, err := cGen.getTemplateContent() require.NoError(t, err, "Failed to get template content") assert.Contains(t, content, `"My\\Namespace\\Test"`, "Template should properly escape namespace backslashes using cString filter") assert.NotContains(t, content, `"My\Namespace\Test"`, "Template should not contain unescaped namespace (single backslashes)") } ================================================ FILE: internal/extgen/cfile_phpmethod_test.go ================================================ package extgen import ( "testing" "github.com/stretchr/testify/require" ) func TestCFile_NamespacedPHPMethods(t *testing.T) { tests := []struct { name string namespace string classes []phpClass expected []string }{ { name: "no namespace - regular PHP_METHOD", namespace: "", classes: []phpClass{ { Name: "TestClass", GoStruct: "TestClass", Methods: []phpClassMethod{ {Name: "testMethod", PhpName: "testMethod", ClassName: "TestClass"}, }, }, }, expected: []string{ "PHP_METHOD(TestClass, __construct)", "PHP_METHOD(TestClass, testMethod)", }, }, { name: "single level namespace", namespace: "MyNamespace", classes: []phpClass{ { Name: "TestClass", GoStruct: "TestClass", Methods: []phpClassMethod{ {Name: "testMethod", PhpName: "testMethod", ClassName: "TestClass"}, }, }, }, expected: []string{ "PHP_METHOD(MyNamespace_TestClass, __construct)", "PHP_METHOD(MyNamespace_TestClass, testMethod)", }, }, { name: "multi level namespace", namespace: `Go\Extension`, classes: []phpClass{ { Name: "MySuperClass", GoStruct: "MySuperClass", Methods: []phpClassMethod{ {Name: "getName", PhpName: "getName", ClassName: "MySuperClass"}, {Name: "setName", PhpName: "setName", ClassName: "MySuperClass"}, }, }, }, expected: []string{ "PHP_METHOD(Go_Extension_MySuperClass, __construct)", "PHP_METHOD(Go_Extension_MySuperClass, getName)", "PHP_METHOD(Go_Extension_MySuperClass, setName)", }, }, { name: "multiple classes with namespace", namespace: `Go\Extension`, classes: []phpClass{ { Name: "ClassA", GoStruct: "ClassA", Methods: []phpClassMethod{ {Name: "methodA", PhpName: "methodA", ClassName: "ClassA"}, }, }, { Name: "ClassB", GoStruct: "ClassB", Methods: []phpClassMethod{ {Name: "methodB", PhpName: "methodB", ClassName: "ClassB"}, }, }, }, expected: []string{ "PHP_METHOD(Go_Extension_ClassA, __construct)", "PHP_METHOD(Go_Extension_ClassA, methodA)", "PHP_METHOD(Go_Extension_ClassB, __construct)", "PHP_METHOD(Go_Extension_ClassB, methodB)", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: "test_extension", Namespace: tt.namespace, Classes: tt.classes, BuildDir: t.TempDir(), } cFileGen := cFileGenerator{generator: generator} content, err := cFileGen.getTemplateContent() require.NoError(t, err, "error generating C template content: %v", err) for _, expected := range tt.expected { require.Contains(t, content, expected, "Expected to find %q in C template content", expected) } if tt.namespace != "" { for _, class := range tt.classes { oldConstructor := "PHP_METHOD(" + class.Name + ", __construct)" require.NotContains(t, content, oldConstructor, "Did not expect to find old constructor declaration %q in namespaced content", oldConstructor) for _, method := range class.Methods { oldMethod := "PHP_METHOD(" + class.Name + ", " + method.PhpName + ")" require.NotContains(t, content, oldMethod, "Did not expect to find old method declaration %q in namespaced content", oldMethod) } } } }) } } func TestCFile_PHP_METHOD_Integration(t *testing.T) { generator := &Generator{ BaseName: "test_extension", Namespace: `Go\Extension`, Functions: []phpFunction{ {Name: "testFunc", ReturnType: "void"}, }, Classes: []phpClass{ { Name: "MySuperClass", GoStruct: "MySuperClass", Methods: []phpClassMethod{ { Name: "getName", PhpName: "getName", ReturnType: "string", ClassName: "MySuperClass", }, { Name: "setName", PhpName: "setName", ReturnType: "void", ClassName: "MySuperClass", Params: []phpParameter{ {Name: "name", PhpType: "string"}, }, }, }, }, }, BuildDir: t.TempDir(), } cFileGen := cFileGenerator{generator: generator} fullContent, err := cFileGen.buildContent() require.NoError(t, err, "error generating full C file: %v", err) expectedDeclarations := []string{ "PHP_FUNCTION(Go_Extension_testFunc)", "PHP_METHOD(Go_Extension_MySuperClass, __construct)", "PHP_METHOD(Go_Extension_MySuperClass, getName)", "PHP_METHOD(Go_Extension_MySuperClass, setName)", } for _, expected := range expectedDeclarations { require.Contains(t, fullContent, expected, "Expected to find %q in full C file content", expected) } oldDeclarations := []string{ "PHP_FUNCTION(testFunc)", "PHP_METHOD(MySuperClass, __construct)", "PHP_METHOD(MySuperClass, getName)", "PHP_METHOD(MySuperClass, setName)", } for _, old := range oldDeclarations { require.NotContains(t, fullContent, old, "Did not expect to find old declaration %q in full C file content", old) } } func TestCFile_ClassMethodStringReturn(t *testing.T) { generator := &Generator{ BaseName: "test_extension", Classes: []phpClass{ { Name: "TestClass", GoStruct: "TestClass", Methods: []phpClassMethod{ { Name: "getString", PhpName: "getString", ReturnType: "string", ClassName: "TestClass", }, }, }, }, BuildDir: t.TempDir(), } cFileGen := cFileGenerator{generator: generator} content, err := cFileGen.getTemplateContent() require.NoError(t, err) require.Contains(t, content, "if (result)", "Expected NULL check for string return") require.Contains(t, content, "RETURN_STR(result)", "Expected RETURN_STR macro") require.Contains(t, content, "RETURN_EMPTY_STRING()", "Expected RETURN_EMPTY_STRING fallback") } ================================================ FILE: internal/extgen/cfile_test.go ================================================ package extgen import ( "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCFileGenerator_Generate(t *testing.T) { tmpDir := t.TempDir() generator := &Generator{ BaseName: "test_extension", BuildDir: tmpDir, Functions: []phpFunction{ { Name: "simpleFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "input", PhpType: phpString}, }, }, { Name: "complexFunction", ReturnType: phpArray, Params: []phpParameter{ {Name: "data", PhpType: phpString}, {Name: "count", PhpType: phpInt, IsNullable: true}, {Name: "options", PhpType: phpArray, HasDefault: true, DefaultValue: "[]"}, }, }, }, Classes: []phpClass{ { Name: "TestClass", GoStruct: "TestStruct", Properties: []phpClassProperty{ {Name: "id", PhpType: phpInt}, {Name: "name", PhpType: phpString}, }, }, }, } cGen := cFileGenerator{generator} require.NoError(t, cGen.generate()) expectedFile := filepath.Join(tmpDir, "test_extension.c") require.FileExists(t, expectedFile, "Expected C file was not created: %s", expectedFile) content, err := readFile(expectedFile) require.NoError(t, err) testCFileBasicStructure(t, content, "test_extension") testCFileFunctions(t, content, generator.Functions) testCFileClasses(t, content, generator.Classes) } func TestCFileGenerator_BuildContent(t *testing.T) { tests := []struct { name string baseName string functions []phpFunction classes []phpClass contains []string notContains []string }{ { name: "empty extension", baseName: "empty", contains: []string{ "#include ", "#include ", `#include "empty.h"`, "PHP_MINIT_FUNCTION(empty)", "empty_module_entry", "return SUCCESS;", }, }, { name: "extension with functions only", baseName: "func_only", functions: []phpFunction{ {Name: "testFunc", ReturnType: phpString}, }, contains: []string{ "PHP_FUNCTION(testFunc)", `#include "func_only.h"`, "func_only_module_entry", "PHP_MINIT_FUNCTION(func_only)", }, }, { name: "extension with classes only", baseName: "class_only", classes: []phpClass{ {Name: "MyClass", GoStruct: "MyStruct"}, }, contains: []string{ "register_all_classes()", "register_class_MyClass();", "PHP_METHOD(MyClass, __construct)", `#include "class_only.h"`, }, }, { name: "extension with functions and classes", baseName: "full", functions: []phpFunction{ {Name: "doSomething", ReturnType: phpVoid}, }, classes: []phpClass{ {Name: "FullClass", GoStruct: "FullStruct"}, }, contains: []string{ "PHP_FUNCTION(doSomething)", "PHP_METHOD(FullClass, __construct)", "register_all_classes()", "register_class_FullClass();", `#include "full.h"`, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: tt.baseName, Functions: tt.functions, Classes: tt.classes, } cGen := cFileGenerator{generator} content, err := cGen.buildContent() require.NoError(t, err) for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated C content should contain '%s'", expected) } }) } } func TestCFileGenerator_GetTemplateContent(t *testing.T) { tests := []struct { name string baseName string classes []phpClass contains []string notContains []string }{ { name: "extension without classes", baseName: "myext", contains: []string{ `#include "myext.h"`, `#include "myext_arginfo.h"`, "PHP_MINIT_FUNCTION(myext)", "myext_module_entry", "return SUCCESS;", }, }, { name: "extension with classes", baseName: "complex_name", classes: []phpClass{ {Name: "TestClass", GoStruct: "TestStruct"}, {Name: "AnotherClass", GoStruct: "AnotherStruct"}, }, contains: []string{ `#include "complex_name.h"`, `#include "complex_name_arginfo.h"`, "PHP_MINIT_FUNCTION(complex_name)", "complex_name_module_entry", "register_all_classes()", "register_class_TestClass();", "register_class_AnotherClass();", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: tt.baseName, Classes: tt.classes, } cGen := cFileGenerator{generator} content, err := cGen.getTemplateContent() require.NoError(t, err) for _, expected := range tt.contains { assert.Contains(t, content, expected, "Template content should contain '%s'", expected) } for _, notExpected := range tt.notContains { assert.NotContains(t, content, notExpected, "Template content should NOT contain '%s'", notExpected) } }) } } func TestCFileIntegrationWithGenerators(t *testing.T) { tmpDir := t.TempDir() functions := []phpFunction{ { Name: "processData", ReturnType: phpArray, IsReturnNullable: true, Params: []phpParameter{ {Name: "input", PhpType: phpString}, {Name: "options", PhpType: phpArray, HasDefault: true, DefaultValue: "[]"}, {Name: "callback", PhpType: phpObject, IsNullable: true}, }, }, { Name: "validateInput", ReturnType: phpBool, Params: []phpParameter{ {Name: "data", PhpType: phpString, IsNullable: true}, {Name: "strict", PhpType: phpBool, HasDefault: true, DefaultValue: "false"}, }, }, } classes := []phpClass{ { Name: "DataProcessor", GoStruct: "DataProcessorStruct", Properties: []phpClassProperty{ {Name: "mode", PhpType: phpString}, {Name: "timeout", PhpType: phpInt, IsNullable: true}, {Name: "options", PhpType: phpArray}, }, }, { Name: "Result", GoStruct: "ResultStruct", Properties: []phpClassProperty{ {Name: "success", PhpType: phpBool}, {Name: "data", PhpType: phpMixed, IsNullable: true}, {Name: "errors", PhpType: phpArray}, }, }, } generator := &Generator{ BaseName: "integration_test", BuildDir: tmpDir, Functions: functions, Classes: classes, } cGen := cFileGenerator{generator} require.NoError(t, cGen.generate()) content, err := readFile(filepath.Join(tmpDir, "integration_test.c")) require.NoError(t, err) for _, fn := range functions { expectedFunc := "PHP_FUNCTION(" + fn.Name + ")" assert.Contains(t, content, expectedFunc, "Generated C file should contain function: %s", expectedFunc) } for _, class := range classes { expectedMethod := "PHP_METHOD(" + class.Name + ", __construct)" assert.Contains(t, content, expectedMethod, "Generated C file should contain class method: %s", expectedMethod) } assert.Contains(t, content, "register_all_classes()", "Generated C file should contain class registration call") assert.Contains(t, content, "integration_test_module_entry", "Generated C file should contain integration_test_module_entry") } func TestCFileErrorHandling(t *testing.T) { // Test with invalid build directory generator := &Generator{ BaseName: "test", BuildDir: "/invalid/readonly/path", Functions: []phpFunction{ {Name: "test", ReturnType: phpVoid}, }, } cGen := cFileGenerator{generator} err := cGen.generate() assert.Error(t, err, "Expected error when writing to invalid directory") } func TestCFileSpecialCharacters(t *testing.T) { tests := []struct { baseName string expected string }{ {"simple", "simple"}, {"my_extension", "my_extension"}, {"ext-with-dashes", "ext-with-dashes"}, } for _, tt := range tests { t.Run(tt.baseName, func(t *testing.T) { generator := &Generator{ BaseName: tt.baseName, Functions: []phpFunction{ {Name: "test", ReturnType: phpVoid}, }, } cGen := cFileGenerator{generator} content, err := cGen.buildContent() require.NoError(t, err) expectedInclude := `#include "` + tt.expected + `.h"` assert.Contains(t, content, expectedInclude, "Content should contain include: %s", expectedInclude) }) } } func testCFileBasicStructure(t *testing.T, content, baseName string) { requiredElements := []string{ "#include ", "#include ", `#include "_cgo_export.h"`, `#include "` + baseName + `.h"`, `#include "` + baseName + `_arginfo.h"`, "PHP_MINIT_FUNCTION(" + baseName + ")", baseName + "_module_entry", } for _, element := range requiredElements { assert.Contains(t, content, element, "C file should contain: %s", element) } } func testCFileFunctions(t *testing.T, content string, functions []phpFunction) { for _, fn := range functions { phpFunc := "PHP_FUNCTION(" + fn.Name + ")" assert.Contains(t, content, phpFunc, "C file should contain function declaration: %s", phpFunc) } } func testCFileClasses(t *testing.T, content string, classes []phpClass) { if len(classes) == 0 { // Si pas de classes, ne devrait pas contenir register_all_classes assert.NotContains(t, content, "register_all_classes()", "C file should NOT contain register_all_classes call when no classes") return } assert.Contains(t, content, "void register_all_classes() {", "C file should contain register_all_classes function") assert.Contains(t, content, "register_all_classes();", "C file should contain register_all_classes call in MINIT") for _, class := range classes { expectedCall := "register_class_" + class.Name + "();" assert.Contains(t, content, expectedCall, "C file should contain class registration call: %s", expectedCall) constructor := "PHP_METHOD(" + class.Name + ", __construct)" assert.Contains(t, content, constructor, "C file should contain constructor: %s", constructor) } } func TestCFileContentValidation(t *testing.T) { generator := &Generator{ BaseName: "syntax_test", Functions: []phpFunction{ { Name: "testFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "param", PhpType: phpString}, }, }, }, Classes: []phpClass{ {Name: "TestClass", GoStruct: "TestStruct"}, }, } cGen := cFileGenerator{generator} content, err := cGen.buildContent() require.NoError(t, err) syntaxElements := []string{ "{", "}", "(", ")", ";", "static", "void", "int", "#include", } for _, element := range syntaxElements { assert.Contains(t, content, element, "Generated C content should contain basic C syntax: %s", element) } openBraces := strings.Count(content, "{") closeBraces := strings.Count(content, "}") assert.Equal(t, openBraces, closeBraces, "Unbalanced braces in generated C code: %d open, %d close", openBraces, closeBraces) assert.False(t, strings.Contains(content, ";;"), "Generated C code contains double semicolons") assert.False(t, strings.Contains(content, "{{") || strings.Contains(content, "}}"), "Generated C code contains unresolved template syntax") } func TestCFileConstants(t *testing.T) { tests := []struct { name string baseName string constants []phpConstant classes []phpClass contains []string }{ { name: "global constants only", baseName: "const_test", constants: []phpConstant{ { Name: "GLOBAL_INT", Value: "42", PhpType: phpInt, }, { Name: "GLOBAL_STRING", Value: `"test"`, PhpType: phpString, }, }, contains: []string{ `REGISTER_LONG_CONSTANT("GLOBAL_INT", 42, CONST_CS | CONST_PERSISTENT);`, `REGISTER_STRING_CONSTANT("GLOBAL_STRING", "test", CONST_CS | CONST_PERSISTENT);`, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: tt.baseName, Constants: tt.constants, Classes: tt.classes, } cGen := cFileGenerator{generator} content, err := cGen.buildContent() require.NoError(t, err) for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated C content should contain '%s'", expected) } }) } } func TestCFileTemplateErrorHandling(t *testing.T) { generator := &Generator{ BaseName: "error_test", } cGen := cFileGenerator{generator} _, err := cGen.getTemplateContent() assert.NoError(t, err, "getTemplateContent() should not fail with valid template") } func TestEscapeCString(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "simple namespace with single backslash", input: `Go\Extension`, expected: `Go\\Extension`, }, { name: "namespace with multiple backslashes", input: `My\Deep\Namespace`, expected: `My\\Deep\\Namespace`, }, { name: "complex nested namespace", input: `TestIntegration\Extension\Module`, expected: `TestIntegration\\Extension\\Module`, }, { name: "empty string", input: "", expected: "", }, { name: "single backslash", input: `\`, expected: `\\`, }, { name: "multiple consecutive backslashes", input: `\\\`, expected: `\\\\\\`, }, { name: "string without backslashes", input: "TestNamespace", expected: "TestNamespace", }, { name: "leading backslash", input: `\Leading`, expected: `\\Leading`, }, { name: "trailing backslash", input: `Trailing\`, expected: `Trailing\\`, }, { name: "mixed alphanumeric with backslashes", input: `Path123\To456\File789`, expected: `Path123\\To456\\File789`, }, { name: "unicode characters with backslashes", input: `Namespace\Über\Test`, expected: `Namespace\\Über\\Test`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := escapeCString(tt.input) assert.Equal(t, tt.expected, result, "escapeCString(%q) should return %q, got %q", tt.input, tt.expected, result) }) } } ================================================ FILE: internal/extgen/classparser.go ================================================ package extgen import ( "bufio" "fmt" "go/ast" "go/parser" "go/token" "os" "regexp" "strings" ) var phpClassRegex = regexp.MustCompile(`//\s*export_php:class\s+(\w+)`) var phpMethodRegex = regexp.MustCompile(`//\s*export_php:method\s+(\w+)::([^{}\n]+)(?:\s*{\s*})?`) var methodSignatureRegex = regexp.MustCompile(`(\w+)\s*\(([^)]*)\)\s*:\s*(\??[\w|]+)`) var methodParamTypeNameRegex = regexp.MustCompile(`(\??[\w|]+)\s+\$?(\w+)`) type exportDirective struct { line int className string } type classParser struct{} func (cp *classParser) Parse(filename string) ([]phpClass, error) { return cp.parse(filename) } func (cp *classParser) parse(filename string) (classes []phpClass, err error) { fset := token.NewFileSet() node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) if err != nil { return nil, fmt.Errorf("parsing file: %w", err) } validator := Validator{} exportDirectives := cp.collectExportDirectives(node, fset) methods, err := cp.parseMethods(filename) if err != nil { return nil, fmt.Errorf("parsing methods: %w", err) } // match structs to directives matchedDirectives := make(map[int]bool) var genDecl *ast.GenDecl var ok bool for _, decl := range node.Decls { if genDecl, ok = decl.(*ast.GenDecl); !ok || genDecl.Tok != token.TYPE { continue } for _, spec := range genDecl.Specs { var typeSpec *ast.TypeSpec if typeSpec, ok = spec.(*ast.TypeSpec); !ok { continue } var structType *ast.StructType if structType, ok = typeSpec.Type.(*ast.StructType); !ok { continue } var phpCl string var directiveLine int if phpCl, directiveLine = cp.extractPHPClassCommentWithLine(genDecl.Doc, fset); phpCl == "" { continue } matchedDirectives[directiveLine] = true class := phpClass{ Name: phpCl, GoStruct: typeSpec.Name.Name, } class.Properties = cp.parseStructFields(structType.Fields.List) // associate methods with this class for _, method := range methods { if method.ClassName == phpCl { class.Methods = append(class.Methods, method) } } if err := validator.validateClass(class); err != nil { fmt.Printf("Warning: Invalid class '%s': %v\n", class.Name, err) continue } classes = append(classes, class) } } for _, directive := range exportDirectives { if !matchedDirectives[directive.line] { return nil, fmt.Errorf("//export_php class directive at line %d is not followed by a struct declaration", directive.line) } } return classes, nil } func (cp *classParser) collectExportDirectives(node *ast.File, fset *token.FileSet) []exportDirective { var directives []exportDirective for _, commentGroup := range node.Comments { for _, comment := range commentGroup.List { if matches := phpClassRegex.FindStringSubmatch(comment.Text); matches != nil { pos := fset.Position(comment.Pos()) directives = append(directives, exportDirective{ line: pos.Line, className: matches[1], }) } } } return directives } func (cp *classParser) extractPHPClassCommentWithLine(commentGroup *ast.CommentGroup, fset *token.FileSet) (string, int) { if commentGroup == nil { return "", 0 } for _, comment := range commentGroup.List { if matches := phpClassRegex.FindStringSubmatch(comment.Text); matches != nil { pos := fset.Position(comment.Pos()) return matches[1], pos.Line } } return "", 0 } func (cp *classParser) parseStructFields(fields []*ast.Field) []phpClassProperty { var properties []phpClassProperty for _, field := range fields { for _, name := range field.Names { prop := cp.parseStructField(name.Name, field) properties = append(properties, prop) } } return properties } func (cp *classParser) parseStructField(fieldName string, field *ast.Field) phpClassProperty { prop := phpClassProperty{Name: fieldName} // check if field is a pointer (nullable) if starExpr, isPointer := field.Type.(*ast.StarExpr); isPointer { prop.IsNullable = true prop.GoType = cp.typeToString(starExpr.X) } else { prop.IsNullable = false prop.GoType = cp.typeToString(field.Type) } prop.PhpType = cp.goTypeToPHPType(prop.GoType) return prop } func (cp *classParser) typeToString(expr ast.Expr) string { switch t := expr.(type) { case *ast.Ident: return t.Name case *ast.StarExpr: return "*" + cp.typeToString(t.X) case *ast.ArrayType: return "[]" + cp.typeToString(t.Elt) case *ast.MapType: return "map[" + cp.typeToString(t.Key) + "]" + cp.typeToString(t.Value) default: return "any" } } var goToPhpTypeMap = map[string]phpType{ "string": phpString, "int": phpInt, "int64": phpInt, "int32": phpInt, "int16": phpInt, "int8": phpInt, "uint": phpInt, "uint64": phpInt, "uint32": phpInt, "uint16": phpInt, "uint8": phpInt, "float64": phpFloat, "float32": phpFloat, "bool": phpBool, "any": phpMixed, } func (cp *classParser) goTypeToPHPType(goType string) phpType { goType = strings.TrimPrefix(goType, "*") if phpType, exists := goToPhpTypeMap[goType]; exists { return phpType } if strings.HasPrefix(goType, "[]") || strings.HasPrefix(goType, "map[") { return phpArray } return phpMixed } func (cp *classParser) parseMethods(filename string) (methods []phpClassMethod, err error) { file, err := os.Open(filename) if err != nil { return nil, err } defer func() { e := file.Close() if err != nil { err = e } }() scanner := bufio.NewScanner(file) var currentMethod *phpClassMethod lineNumber := 0 for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if matches := phpMethodRegex.FindStringSubmatch(line); matches != nil { className := strings.TrimSpace(matches[1]) signature := strings.TrimSpace(matches[2]) method, err := cp.parseMethodSignature(className, signature) if err != nil { fmt.Printf("Warning: Error parsing method signature %q: %v\n", signature, err) continue } validator := Validator{} phpFunc := phpFunction{ Name: method.Name, Signature: method.Signature, Params: method.Params, ReturnType: method.ReturnType, IsReturnNullable: method.isReturnNullable, } if err := validator.validateTypes(phpFunc); err != nil { fmt.Printf("Warning: Method \"%s::%s\" uses unsupported types: %v\n", className, method.Name, err) continue } method.lineNumber = lineNumber currentMethod = method } if currentMethod != nil && strings.HasPrefix(line, "func ") { goFunc, err := cp.extractGoMethodFunction(scanner, line) if err != nil { return nil, fmt.Errorf("extracting Go method function: %w", err) } currentMethod.GoFunction = goFunc validator := Validator{} phpFunc := phpFunction{ Name: currentMethod.Name, Signature: currentMethod.Signature, GoFunction: currentMethod.GoFunction, Params: currentMethod.Params, ReturnType: currentMethod.ReturnType, IsReturnNullable: currentMethod.isReturnNullable, } if err := validator.validateGoFunctionSignatureWithOptions(phpFunc, true); err != nil { fmt.Printf("Warning: Go method signature mismatch for '%s::%s': %v\n", currentMethod.ClassName, currentMethod.Name, err) currentMethod = nil continue } methods = append(methods, *currentMethod) currentMethod = nil } } if currentMethod != nil { return nil, fmt.Errorf("//export_php:method directive at line %d is not followed by a function declaration", currentMethod.lineNumber) } return methods, scanner.Err() } func (cp *classParser) parseMethodSignature(className, signature string) (*phpClassMethod, error) { matches := methodSignatureRegex.FindStringSubmatch(signature) if len(matches) != 4 { return nil, fmt.Errorf("invalid method signature format") } methodName := matches[1] paramsStr := strings.TrimSpace(matches[2]) returnTypeStr := strings.TrimSpace(matches[3]) isReturnNullable := strings.HasPrefix(returnTypeStr, "?") returnType := strings.TrimPrefix(returnTypeStr, "?") var params []phpParameter if paramsStr != "" { paramParts := strings.SplitSeq(paramsStr, ",") for part := range paramParts { param, err := cp.parseMethodParameter(strings.TrimSpace(part)) if err != nil { return nil, fmt.Errorf("parsing parameter '%s': %w", part, err) } params = append(params, param) } } return &phpClassMethod{ Name: methodName, PhpName: methodName, ClassName: className, Signature: signature, Params: params, ReturnType: phpType(returnType), isReturnNullable: isReturnNullable, }, nil } func (cp *classParser) parseMethodParameter(paramStr string) (phpParameter, error) { parts := strings.Split(paramStr, "=") typePart := strings.TrimSpace(parts[0]) param := phpParameter{HasDefault: len(parts) > 1} if param.HasDefault { param.DefaultValue = cp.sanitizeDefaultValue(strings.TrimSpace(parts[1])) } matches := methodParamTypeNameRegex.FindStringSubmatch(typePart) if len(matches) < 3 { return phpParameter{}, fmt.Errorf("invalid parameter format: %s", paramStr) } typeStr := strings.TrimSpace(matches[1]) param.Name = strings.TrimSpace(matches[2]) param.IsNullable = strings.HasPrefix(typeStr, "?") param.PhpType = phpType(strings.TrimPrefix(typeStr, "?")) return param, nil } func (cp *classParser) sanitizeDefaultValue(value string) string { if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") { return value } if strings.ToLower(value) == "null" { return "null" } return strings.Trim(value, `'"`) } func (cp *classParser) extractGoMethodFunction(scanner *bufio.Scanner, firstLine string) (string, error) { goFunc := firstLine + "\n" braceCount := 1 for scanner.Scan() { line := scanner.Text() goFunc += line + "\n" for _, char := range line { switch char { case '{': braceCount++ case '}': braceCount-- } } if braceCount == 0 { break } } return goFunc, nil } ================================================ FILE: internal/extgen/classparser_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestClassParser(t *testing.T) { tests := []struct { name string input string expected int }{ { name: "single class", input: `package main //export_php:class User type UserStruct struct { name string Age int }`, expected: 1, }, { name: "multiple classes", input: `package main //export_php:class User type UserStruct struct { name string Age int } //export_php:class Product type ProductStruct struct { Title string Price float64 }`, expected: 2, }, { name: "no php classes", input: `package main type RegularStruct struct { Data string }`, expected: 0, }, { name: "class with nullable fields", input: `package main //export_php:class OptionalData type OptionalStruct struct { Required string Optional *string Count *int }`, expected: 1, }, { name: "class with methods", input: `package main //export_php:class User type UserStruct struct { name string Age int } //export_php:method User::getName(): string func GetUserName(u UserStruct) string { return u.name } //export_php:method User::setAge(int $age): void func SetUserAge(u *UserStruct, age int) { u.Age = age }`, expected: 1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0644)) parser := classParser{} classes, err := parser.parse(fileName) require.NoError(t, err) assert.Len(t, classes, tt.expected, "parse() got wrong number of classes") if tt.name == "single class" && len(classes) > 0 { class := classes[0] assert.Equal(t, "User", class.Name, "Expected class name 'User'") assert.Equal(t, "UserStruct", class.GoStruct, "Expected Go struct 'UserStruct'") assert.Len(t, class.Properties, 2, "Expected 2 properties") } if tt.name == "class with nullable fields" && len(classes) > 0 { class := classes[0] if len(class.Properties) >= 3 { assert.False(t, class.Properties[0].IsNullable, "Required field should not be nullable") assert.True(t, class.Properties[1].IsNullable, "Optional field should be nullable") assert.True(t, class.Properties[2].IsNullable, "Count field should be nullable") } } }) } } func TestClassMethods(t *testing.T) { var input = []byte(`package main //export_php:class User type UserStruct struct { name string Age int } //export_php:method User::getName(): string func GetUserName(u UserStruct) unsafe.Pointer { return nil } //export_php:method User::setAge(int $age): void func SetUserAge(u *UserStruct, age int64) { u.Age = int(age) } //export_php:method User::getInfo(string $prefix = "User"): string func GetUserInfo(u UserStruct, prefix *C.zend_string) unsafe.Pointer { return nil }`) tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, input, 0644)) parser := classParser{} classes, err := parser.parse(fileName) require.NoError(t, err) require.Len(t, classes, 1, "Expected 1 class") class := classes[0] require.Len(t, class.Methods, 3, "Expected 3 methods") getName := class.Methods[0] assert.Equal(t, "getName", getName.Name, "Expected method name 'getName'") assert.Equal(t, phpString, getName.ReturnType, "Expected return type 'string'") assert.Empty(t, getName.Params, "Expected 0 params") assert.Equal(t, "User", getName.ClassName, "Expected class name 'User'") setAge := class.Methods[1] assert.Equal(t, "setAge", setAge.Name, "Expected method name 'setAge'") assert.Equal(t, phpVoid, setAge.ReturnType, "Expected return type 'void'") require.Len(t, setAge.Params, 1, "Expected 1 param") param := setAge.Params[0] assert.Equal(t, "age", param.Name, "Expected param name 'age'") assert.Equal(t, phpInt, param.PhpType, "Expected param type 'int'") assert.False(t, param.IsNullable, "Expected param to not be nullable") assert.False(t, param.HasDefault, "Expected param to not have default value") getInfo := class.Methods[2] assert.Equal(t, "getInfo", getInfo.Name, "Expected method name 'getInfo'") assert.Equal(t, phpString, getInfo.ReturnType, "Expected return type 'string'") require.Len(t, getInfo.Params, 1, "Expected 1 param") param = getInfo.Params[0] assert.Equal(t, "prefix", param.Name, "Expected param name 'prefix'") assert.Equal(t, phpString, param.PhpType, "Expected param type 'string'") assert.True(t, param.HasDefault, "Expected param to have default value") assert.Equal(t, "User", param.DefaultValue, "Expected default value 'User'") } func TestMethodParameterParsing(t *testing.T) { tests := []struct { name string paramStr string expectedParam phpParameter expectError bool }{ { name: "simple int parameter", paramStr: "int $age", expectedParam: phpParameter{ Name: "age", PhpType: phpInt, IsNullable: false, HasDefault: false, }, expectError: false, }, { name: "nullable string parameter", paramStr: "?string $name", expectedParam: phpParameter{ Name: "name", PhpType: phpString, IsNullable: true, HasDefault: false, }, expectError: false, }, { name: "parameter with default value", paramStr: `string $prefix = "default"`, expectedParam: phpParameter{ Name: "prefix", PhpType: phpString, IsNullable: false, HasDefault: true, DefaultValue: "default", }, expectError: false, }, { name: "nullable parameter with default null", paramStr: "?int $count = null", expectedParam: phpParameter{ Name: "count", PhpType: phpInt, IsNullable: true, HasDefault: true, DefaultValue: "null", }, expectError: false, }, { name: "invalid parameter format", paramStr: "invalid", expectError: true, }, } parser := classParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { param, err := parser.parseMethodParameter(tt.paramStr) if tt.expectError { assert.Error(t, err, "Expected error for parameter '%s', but got none", tt.paramStr) return } require.NoError(t, err, "parseMethodParameter(%s) error", tt.paramStr) assert.Equal(t, tt.expectedParam.Name, param.Name, "Expected name '%s'", tt.expectedParam.Name) assert.Equal(t, tt.expectedParam.PhpType, param.PhpType, "Expected type '%s'", tt.expectedParam.PhpType) assert.Equal(t, tt.expectedParam.IsNullable, param.IsNullable, "Expected isNullable %v", tt.expectedParam.IsNullable) assert.Equal(t, tt.expectedParam.HasDefault, param.HasDefault, "Expected hasDefault %v", tt.expectedParam.HasDefault) assert.Equal(t, tt.expectedParam.DefaultValue, param.DefaultValue, "Expected defaultValue '%s'", tt.expectedParam.DefaultValue) }) } } func TestGoTypeToPHPType(t *testing.T) { tests := []struct { goType string expected phpType }{ {"string", phpString}, {"*string", phpString}, {"int", phpInt}, {"int64", phpInt}, {"*int", phpInt}, {"float64", phpFloat}, {"*float32", phpFloat}, {"bool", phpBool}, {"*bool", phpBool}, {"[]string", phpArray}, {"map[string]int", phpArray}, {"*[]int", phpArray}, {"any", phpMixed}, {"CustomType", phpMixed}, } parser := classParser{} for _, tt := range tests { t.Run(tt.goType, func(t *testing.T) { result := parser.goTypeToPHPType(tt.goType) assert.Equal(t, tt.expected, result, "goTypeToPHPType(%s) = %s, want %s", tt.goType, result, tt.expected) }) } } func TestTypeToString(t *testing.T) { tests := []struct { name string input string expected []phpType }{ { name: "basic types", input: `package main //export_php:class TestClass type TestStruct struct { StringField string IntField int FloatField float64 BoolField bool }`, expected: []phpType{phpString, phpInt, phpFloat, phpBool}, }, { name: "pointer types", input: `package main //export_php:class NullableClass type NullableStruct struct { NullableString *string NullableInt *int NullableFloat *float64 NullableBool *bool }`, expected: []phpType{phpString, phpInt, phpFloat, phpBool}, }, { name: "collection types", input: `package main //export_php:class CollectionClass type CollectionStruct struct { StringSlice []string IntMap map[string]int MixedSlice []any }`, expected: []phpType{phpArray, phpArray, phpArray}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0o644)) parser := classParser{} classes, err := parser.parse(fileName) require.NoError(t, err) require.Len(t, classes, 1, "Expected 1 class") class := classes[0] require.Len(t, class.Properties, len(tt.expected), "Expected %d properties", len(tt.expected)) for i, expectedType := range tt.expected { assert.Equal(t, expectedType, class.Properties[i].PhpType, "Property %d: expected type %s", i, expectedType) } }) } } func TestClassParserUnsupportedTypes(t *testing.T) { tests := []struct { name string input string expectedClasses int expectedMethods int hasWarning bool }{ { name: "method with array parameter should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::arrayMethod(array $data): string func (tc *TestClass) arrayMethod(data any) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method with object parameter should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::objectMethod(object $obj): string func (tc *TestClass) objectMethod(obj any) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method with mixed parameter should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::mixedMethod(mixed $value): string func (tc *TestClass) mixedMethod(value any) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method with array return type should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::arrayReturn(string $name): array func (tc *TestClass) arrayReturn(name *C.zend_string) any { return []string{"result"} }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method with object return type should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::objectReturn(string $name): object func (tc *TestClass) objectReturn(name *C.zend_string) any { return map[string]any{"key": "value"} }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "valid scalar types should pass", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::validMethod(string $name, int $count, float $rate, bool $active): string func validMethod(tc *TestClass, name *C.zend_string, count int64, rate float64, active bool) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 1, hasWarning: false, }, { name: "valid void return should pass", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::voidMethod(string $message): void func voidMethod(tc *TestClass, message *C.zend_string) { // Do something }`, expectedClasses: 1, expectedMethods: 1, hasWarning: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0644)) parser := &classParser{} classes, err := parser.parse(fileName) require.NoError(t, err) assert.Len(t, classes, tt.expectedClasses, "parse() got wrong number of classes") if len(classes) > 0 { assert.Len(t, classes[0].Methods, tt.expectedMethods, "parse() got wrong number of methods") } }) } } func TestClassParserGoTypeMismatch(t *testing.T) { tests := []struct { name string input string expectedClasses int expectedMethods int hasWarning bool }{ { name: "method parameter count mismatch should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::countMismatch(string $name, int $count): string func (tc *TestClass) countMismatch(name *C.zend_string) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method parameter type mismatch should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::typeMismatch(string $name, int $count): string func (tc *TestClass) typeMismatch(name *C.zend_string, count string) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "method return type mismatch should be rejected", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::returnMismatch(string $name): int func (tc *TestClass) returnMismatch(name *C.zend_string) string { return "" }`, expectedClasses: 1, expectedMethods: 0, hasWarning: true, }, { name: "valid matching types should pass", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::validMatch(string $name, int $count): string func validMatch(tc *TestClass, name *C.zend_string, count int64) unsafe.Pointer { return nil }`, expectedClasses: 1, expectedMethods: 1, hasWarning: false, }, { name: "valid bool types should pass", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::validBool(bool $flag): bool func validBool(tc *TestClass, flag bool) bool { return flag }`, expectedClasses: 1, expectedMethods: 1, hasWarning: false, }, { name: "valid float types should pass", input: `package main //export_php:class TestClass type TestClass struct { Name string } //export_php:method TestClass::validFloat(float $value): float func validFloat(tc *TestClass, value float64) float64 { return value }`, expectedClasses: 1, expectedMethods: 1, hasWarning: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0644)) parser := &classParser{} classes, err := parser.parse(fileName) require.NoError(t, err) assert.Len(t, classes, tt.expectedClasses, "parse() got wrong number of classes") if len(classes) > 0 { assert.Len(t, classes[0].Methods, tt.expectedMethods, "parse() got wrong number of methods") } }) } } ================================================ FILE: internal/extgen/constants_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConstantsIntegration(t *testing.T) { tmpDir := t.TempDir() testFile := filepath.Join(tmpDir, "test.go") content := `package main //export_php:const const STATUS_OK = iota //export_php:const const MAX_CONNECTIONS = 100 //export_php:const: function test(): void func Test() { // Implementation } func main() {} ` require.NoError(t, os.WriteFile(testFile, []byte(content), 0644)) generator := &Generator{ BaseName: "testext", SourceFile: testFile, BuildDir: filepath.Join(tmpDir, "build"), } require.NoError(t, generator.parseSource()) assert.Len(t, generator.Constants, 2, "Expected 2 constants") expectedConstants := map[string]struct { Value string IsIota bool }{ "STATUS_OK": {"0", true}, "MAX_CONNECTIONS": {"100", false}, } for _, constant := range generator.Constants { expected, exists := expectedConstants[constant.Name] assert.True(t, exists, "Unexpected constant: %s", constant.Name) if !exists { continue } assert.Equal(t, expected.Value, constant.Value, "Constant %s: value mismatch", constant.Name) assert.Equal(t, expected.IsIota, constant.IsIota, "Constant %s: isIota mismatch", constant.Name) } require.NoError(t, generator.setupBuildDirectory()) require.NoError(t, generator.generateStubFile()) stubPath := filepath.Join(generator.BuildDir, generator.BaseName+".stub.php") stubContent, err := os.ReadFile(stubPath) require.NoError(t, err) stubStr := string(stubContent) assert.Contains(t, stubStr, "* @cvalue", "Stub does not contain @cvalue annotation for iota constant") assert.Contains(t, stubStr, "const STATUS_OK = UNKNOWN;", "Stub does not contain STATUS_OK constant with UNKNOWN value") assert.Contains(t, stubStr, "const MAX_CONNECTIONS = 100;", "Stub does not contain MAX_CONNECTIONS constant with explicit value") require.NoError(t, generator.generateCFile()) cPath := filepath.Join(generator.BuildDir, generator.BaseName+".c") cContent, err := os.ReadFile(cPath) require.NoError(t, err) cStr := string(cContent) assert.Contains(t, cStr, `REGISTER_LONG_CONSTANT("STATUS_OK", STATUS_OK, CONST_CS | CONST_PERSISTENT);`, "C file does not contain STATUS_OK registration") assert.Contains(t, cStr, `REGISTER_LONG_CONSTANT("MAX_CONNECTIONS", 100, CONST_CS | CONST_PERSISTENT);`, "C file does not contain MAX_CONNECTIONS registration") } func TestConstantsIntegrationOctal(t *testing.T) { tmpDir := t.TempDir() testFile := filepath.Join(tmpDir, "test.go") content := `package main //export_php:const const FILE_PERM = 0o755 //export_php:const const OTHER_PERM = 0o644 //export_php:const const REGULAR_INT = 42 func main() {} ` require.NoError(t, os.WriteFile(testFile, []byte(content), 0644)) generator := &Generator{ BaseName: "octalstest", SourceFile: testFile, BuildDir: filepath.Join(tmpDir, "build"), } require.NoError(t, generator.parseSource()) assert.Len(t, generator.Constants, 3, "Expected 3 constants") // Verify CValue conversion for _, constant := range generator.Constants { switch constant.Name { case "FILE_PERM": assert.Equal(t, "0o755", constant.Value, "FILE_PERM value mismatch") assert.Equal(t, "493", constant.CValue(), "FILE_PERM CValue mismatch") case "OTHER_PERM": assert.Equal(t, "0o644", constant.Value, "OTHER_PERM value mismatch") assert.Equal(t, "420", constant.CValue(), "OTHER_PERM CValue mismatch") case "REGULAR_INT": assert.Equal(t, "42", constant.Value, "REGULAR_INT value mismatch") assert.Equal(t, "42", constant.CValue(), "REGULAR_INT CValue mismatch") } } require.NoError(t, generator.setupBuildDirectory()) // Test C file generation require.NoError(t, generator.generateCFile()) cPath := filepath.Join(generator.BuildDir, generator.BaseName+".c") cContent, err := os.ReadFile(cPath) require.NoError(t, err) cStr := string(cContent) // Verify C file uses decimal values for octal constants assert.Contains(t, cStr, `REGISTER_LONG_CONSTANT("FILE_PERM", 493, CONST_CS | CONST_PERSISTENT);`, "C file does not contain FILE_PERM registration with decimal value 493") assert.Contains(t, cStr, `REGISTER_LONG_CONSTANT("OTHER_PERM", 420, CONST_CS | CONST_PERSISTENT);`, "C file does not contain OTHER_PERM registration with decimal value 420") assert.Contains(t, cStr, `REGISTER_LONG_CONSTANT("REGULAR_INT", 42, CONST_CS | CONST_PERSISTENT);`, "C file does not contain REGULAR_INT registration with value 42") // Test header file generation require.NoError(t, generator.generateHeaderFile()) hPath := filepath.Join(generator.BuildDir, generator.BaseName+".h") hContent, err := os.ReadFile(hPath) require.NoError(t, err) hStr := string(hContent) // Verify header file uses decimal values for octal constants in #define assert.Contains(t, hStr, "#define FILE_PERM 493", "Header file does not contain FILE_PERM #define with decimal value 493") assert.Contains(t, hStr, "#define OTHER_PERM 420", "Header file does not contain OTHER_PERM #define with decimal value 420") assert.Contains(t, hStr, "#define REGULAR_INT 42", "Header file does not contain REGULAR_INT #define with value 42") } ================================================ FILE: internal/extgen/constparser.go ================================================ package extgen import ( "bufio" "fmt" "os" "regexp" "strconv" "strings" ) var constRegex = regexp.MustCompile(`//\s*export_php:const$`) var classConstRegex = regexp.MustCompile(`//\s*export_php:classconst\s+(\w+)$`) var constDeclRegex = regexp.MustCompile(`const\s+(\w+)\s*=\s*(.+)`) type ConstantParser struct{} func (cp *ConstantParser) parse(filename string) (constants []phpConstant, err error) { file, err := os.Open(filename) if err != nil { return nil, err } defer func() { e := file.Close() if err == nil { err = e } }() scanner := bufio.NewScanner(file) lineNumber := 0 expectConstDecl := false expectClassConstDecl := false currentClassName := "" currentConstantValue := 0 inConstBlock := false exportAllInBlock := false lastConstValue := "" lastConstWasIota := false for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if constRegex.MatchString(line) { expectConstDecl = true expectClassConstDecl = false currentClassName = "" continue } if matches := classConstRegex.FindStringSubmatch(line); len(matches) == 2 { expectClassConstDecl = true expectConstDecl = false currentClassName = matches[1] continue } if strings.HasPrefix(line, "const (") { inConstBlock = true if expectConstDecl || expectClassConstDecl { exportAllInBlock = true } continue } if inConstBlock && line == ")" { inConstBlock = false exportAllInBlock = false expectConstDecl = false expectClassConstDecl = false currentClassName = "" lastConstValue = "" lastConstWasIota = false continue } if (expectConstDecl || expectClassConstDecl) && strings.HasPrefix(line, "const ") && !inConstBlock { matches := constDeclRegex.FindStringSubmatch(line) if len(matches) == 3 { name := matches[1] value := strings.TrimSpace(matches[2]) constant := phpConstant{ Name: name, Value: value, IsIota: value == "iota", lineNumber: lineNumber, ClassName: currentClassName, } constant.PhpType = determineConstantType(value) if constant.IsIota { constant.Value = fmt.Sprintf("%d", currentConstantValue) constant.PhpType = phpInt currentConstantValue++ lastConstWasIota = true lastConstValue = constant.Value } constants = append(constants, constant) } else { return nil, fmt.Errorf("invalid constant declaration at line %d: %s", lineNumber, line) } expectConstDecl = false expectClassConstDecl = false } else if inConstBlock && (expectConstDecl || expectClassConstDecl || exportAllInBlock) { constBlockDeclRegex := regexp.MustCompile(`^(\w+)\s*=\s*(.+)$`) if matches := constBlockDeclRegex.FindStringSubmatch(line); len(matches) == 3 { name := matches[1] value := strings.TrimSpace(matches[2]) constant := phpConstant{ Name: name, Value: value, IsIota: value == "iota", lineNumber: lineNumber, ClassName: currentClassName, } constant.PhpType = determineConstantType(value) if constant.IsIota { constant.Value = fmt.Sprintf("%d", currentConstantValue) constant.PhpType = phpInt currentConstantValue++ lastConstWasIota = true lastConstValue = constant.Value } else { lastConstWasIota = false lastConstValue = value } constants = append(constants, constant) expectConstDecl = false expectClassConstDecl = false } else { constNameRegex := regexp.MustCompile(`^(\w+)$`) if matches := constNameRegex.FindStringSubmatch(line); len(matches) == 2 { name := matches[1] constant := phpConstant{ Name: name, Value: "", IsIota: lastConstWasIota, lineNumber: lineNumber, ClassName: currentClassName, } if lastConstWasIota { constant.Value = fmt.Sprintf("%d", currentConstantValue) constant.PhpType = phpInt currentConstantValue++ lastConstValue = constant.Value } else { constant.Value = lastConstValue constant.PhpType = determineConstantType(lastConstValue) } constants = append(constants, constant) expectConstDecl = false expectClassConstDecl = false } } } else if (expectConstDecl || expectClassConstDecl) && !strings.HasPrefix(line, "//") && line != "" && !inConstBlock { // we expected a const declaration but found something else, reset expectConstDecl = false expectClassConstDecl = false currentClassName = "" } } return constants, scanner.Err() } // determineConstantType analyzes the value and determines its type func determineConstantType(value string) phpType { value = strings.TrimSpace(value) if (strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`)) || (strings.HasPrefix(value, "`") && strings.HasSuffix(value, "`")) { return phpString } if value == "true" || value == "false" { return phpBool } // check for integer literals, including hex, octal, binary if _, err := strconv.ParseInt(value, 0, 64); err == nil { return phpInt } if _, err := strconv.ParseFloat(value, 64); err == nil { return phpFloat } return phpInt } ================================================ FILE: internal/extgen/constparser_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConstantParser(t *testing.T) { tests := []struct { name string input string expected int }{ { name: "single constant", input: `package main //export_php:const const MyConstant = "test_value"`, expected: 1, }, { name: "multiple constants", input: `package main //export_php:const const FirstConstant = "first" //export_php:const const SecondConstant = 42 //export_php:const const ThirdConstant = true`, expected: 3, }, { name: "iota constant", input: `package main //export_php:const const IotaConstant = iota`, expected: 1, }, { name: "mixed constants and iota", input: `package main //export_php:const const StringConst = "hello" //export_php:const const IotaConst = iota //export_php:const const IntConst = 123`, expected: 3, }, { name: "no php constants", input: `package main const RegularConstant = "not exported" func someFunction() { // Just regular code }`, expected: 0, }, { name: "constant with complex value", input: `package main //export_php:const const ComplexConstant = "string with spaces and symbols !@#$%"`, expected: 1, }, { name: "directive without constant", input: `package main //export_php:const var notAConstant = "this is a variable"`, expected: 0, }, { name: "mixed export and non-export constants", input: `package main const RegularConst = "regular" //export_php:const const ExportedConst = "exported" const AnotherRegular = 456 //export_php:const const AnotherExported = 789`, expected: 2, }, { name: "numeric constants", input: `package main //export_php:const const IntConstant = 42 //export_php:const const FloatConstant = 3.14 //export_php:const const HexConstant = 0xFF`, expected: 3, }, { name: "boolean constants", input: `package main //export_php:const const TrueConstant = true //export_php:const const FalseConstant = false`, expected: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(tmpFile, []byte(tt.input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(tmpFile) assert.NoError(t, err, "parse() error") assert.Len(t, constants, tt.expected, "parse() got wrong number of constants") if tt.name == "single constant" && len(constants) > 0 { c := constants[0] assert.Equal(t, "MyConstant", c.Name, "Expected constant name 'MyConstant'") assert.Equal(t, `"test_value"`, c.Value, `Expected constant value '"test_value"'`) assert.Equal(t, phpString, c.PhpType, "Expected constant type 'string'") assert.False(t, c.IsIota, "Expected isIota to be false for string constant") } if tt.name == "iota constant" && len(constants) > 0 { c := constants[0] assert.Equal(t, "IotaConstant", c.Name, "Expected constant name 'IotaConstant'") assert.True(t, c.IsIota, "Expected isIota to be true") assert.Equal(t, "0", c.Value, "Expected iota constant value to be '0'") } if tt.name == "multiple constants" && len(constants) == 3 { expectedNames := []string{"FirstConstant", "SecondConstant", "ThirdConstant"} expectedValues := []string{`"first"`, "42", "true"} expectedTypes := []phpType{phpString, phpInt, phpBool} for i, c := range constants { assert.Equal(t, expectedNames[i], c.Name, "Expected constant name '%s'", expectedNames[i]) assert.Equal(t, expectedValues[i], c.Value, "Expected constant value '%s'", expectedValues[i]) assert.Equal(t, expectedTypes[i], c.PhpType, "Expected constant type '%s'", expectedTypes[i]) } } }) } } func TestConstantParserErrors(t *testing.T) { tests := []struct { name string input string expectError bool }{ { name: "invalid constant declaration", input: `package main //export_php:const const = "missing name"`, expectError: true, }, { name: "malformed constant", input: `package main //export_php:const const InvalidSyntax`, expectError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(tmpFile, []byte(tt.input), 0644)) parser := &ConstantParser{} _, err := parser.parse(tmpFile) require.NotNil(t, err) if tt.expectError { assert.Error(t, err, "Expected error but got none") return } assert.NoError(t, err) }) } } func TestConstantParserIotaSequence(t *testing.T) { input := `package main //export_php:const const FirstIota = iota //export_php:const const SecondIota = iota //export_php:const const ThirdIota = iota` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 3, "Expected 3 constants") expectedValues := []string{"0", "1", "2"} for i, c := range constants { assert.True(t, c.IsIota, "Expected constant %d to be iota", i) assert.Equal(t, expectedValues[i], c.Value, "Expected constant %d value to be '%s'", i, expectedValues[i]) } } func TestConstantParserConstBlock(t *testing.T) { input := `package main const ( // export_php:const STATUS_PENDING = iota // export_php:const STATUS_PROCESSING // export_php:const STATUS_COMPLETED )` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 3, "Expected 3 constants") expectedNames := []string{"STATUS_PENDING", "STATUS_PROCESSING", "STATUS_COMPLETED"} expectedValues := []string{"0", "1", "2"} for i, c := range constants { assert.Equal(t, expectedNames[i], c.Name, "Expected constant %d name to be '%s'", i, expectedNames[i]) assert.True(t, c.IsIota, "Expected constant %d to be iota", i) assert.Equal(t, expectedValues[i], c.Value, "Expected constant %d value to be '%s'", i, expectedValues[i]) assert.Equal(t, phpInt, c.PhpType, "Expected constant %d to be phpInt type", i) } } func TestConstantParserConstBlockWithBlockLevelDirective(t *testing.T) { input := `package main // export_php:const const ( STATUS_PENDING = iota STATUS_PROCESSING STATUS_COMPLETED )` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 3, "Expected 3 constants") expectedNames := []string{"STATUS_PENDING", "STATUS_PROCESSING", "STATUS_COMPLETED"} expectedValues := []string{"0", "1", "2"} for i, c := range constants { assert.Equal(t, expectedNames[i], c.Name, "Expected constant %d name to be '%s'", i, expectedNames[i]) assert.True(t, c.IsIota, "Expected constant %d to be iota", i) assert.Equal(t, expectedValues[i], c.Value, "Expected constant %d value to be '%s'", i, expectedValues[i]) assert.Equal(t, phpInt, c.PhpType, "Expected constant %d to be phpInt type", i) } } func TestConstantParserMixedConstBlockAndIndividual(t *testing.T) { input := `package main // export_php:const const INDIVIDUAL = 42 const ( // export_php:const BLOCK_ONE = iota // export_php:const BLOCK_TWO ) // export_php:const const ANOTHER_INDIVIDUAL = "test"` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 4, "Expected 4 constants") assert.Equal(t, "INDIVIDUAL", constants[0].Name) assert.Equal(t, "42", constants[0].Value) assert.Equal(t, phpInt, constants[0].PhpType) assert.Equal(t, "BLOCK_ONE", constants[1].Name) assert.Equal(t, "0", constants[1].Value) assert.True(t, constants[1].IsIota) assert.Equal(t, "BLOCK_TWO", constants[2].Name) assert.Equal(t, "1", constants[2].Value) assert.True(t, constants[2].IsIota) assert.Equal(t, "ANOTHER_INDIVIDUAL", constants[3].Name) assert.Equal(t, `"test"`, constants[3].Value) assert.Equal(t, phpString, constants[3].PhpType) } func TestConstantParserClassConstBlock(t *testing.T) { input := `package main // export_php:classconst Config const ( MODE_DEBUG = 1 MODE_PRODUCTION = 2 MODE_TEST = 3 )` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 3, "Expected 3 class constants") expectedNames := []string{"MODE_DEBUG", "MODE_PRODUCTION", "MODE_TEST"} expectedValues := []string{"1", "2", "3"} for i, c := range constants { assert.Equal(t, expectedNames[i], c.Name, "Expected constant %d name to be '%s'", i, expectedNames[i]) assert.Equal(t, "Config", c.ClassName, "Expected constant %d to belong to Config class", i) assert.Equal(t, expectedValues[i], c.Value, "Expected constant %d value to be '%s'", i, expectedValues[i]) assert.Equal(t, phpInt, c.PhpType, "Expected constant %d to be phpInt type", i) } } func TestConstantParserClassConstBlockWithIota(t *testing.T) { input := `package main // export_php:classconst Status const ( STATUS_PENDING = iota STATUS_ACTIVE STATUS_COMPLETED )` tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(fileName, []byte(input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(fileName) assert.NoError(t, err, "parse() error") assert.Len(t, constants, 3, "Expected 3 class constants") expectedNames := []string{"STATUS_PENDING", "STATUS_ACTIVE", "STATUS_COMPLETED"} expectedValues := []string{"0", "1", "2"} for i, c := range constants { assert.Equal(t, expectedNames[i], c.Name, "Expected constant %d name to be '%s'", i, expectedNames[i]) assert.Equal(t, "Status", c.ClassName, "Expected constant %d to belong to Status class", i) assert.True(t, c.IsIota, "Expected constant %d to be iota", i) assert.Equal(t, expectedValues[i], c.Value, "Expected constant %d value to be '%s'", i, expectedValues[i]) assert.Equal(t, phpInt, c.PhpType, "Expected constant %d to be phpInt type", i) } } func TestConstantParserTypeDetection(t *testing.T) { tests := []struct { name string value string expectedType phpType }{ {"string with double quotes", `"hello world"`, phpString}, {"string with backticks", "`hello world`", phpString}, {"boolean true", "true", phpBool}, {"boolean false", "false", phpBool}, {"integer", "42", phpInt}, {"negative integer", "-42", phpInt}, {"hex integer", "0xFF", phpInt}, {"octal integer", "0755", phpInt}, {"go octal integer", "0o755", phpInt}, {"binary integer", "0b1010", phpInt}, {"float", "3.14", phpFloat}, {"negative float", "-3.14", phpFloat}, {"scientific notation", "1e10", phpFloat}, {"unknown type", "someFunction()", phpInt}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := determineConstantType(tt.value) assert.Equal(t, tt.expectedType, result, "determineConstantType(%s) expected %s", tt.value, tt.expectedType) }) } } func TestConstantParserClassConstants(t *testing.T) { tests := []struct { name string input string expected int }{ { name: "single class constant", input: `package main //export_php:classconst MyClass const STATUS_ACTIVE = 1`, expected: 1, }, { name: "multiple class constants", input: `package main //export_php:classconst User const STATUS_ACTIVE = "active" //export_php:classconst User const STATUS_INACTIVE = "inactive" //export_php:classconst Order const STATE_PENDING = 0`, expected: 3, }, { name: "mixed global and class constants", input: `package main //export_php:const const GLOBAL_CONST = "global" //export_php:classconst MyClass const CLASS_CONST = 42 //export_php:const const ANOTHER_GLOBAL = true`, expected: 3, }, { name: "class constant with iota", input: `package main //export_php:classconst Status const FIRST = iota //export_php:classconst Status const SECOND = iota`, expected: 2, }, { name: "invalid class constant directive", input: `package main //export_php:classconst const INVALID = "missing class name"`, expected: 0, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(tmpFile, []byte(tt.input), 0644)) parser := &ConstantParser{} constants, err := parser.parse(tmpFile) assert.NoError(t, err, "parse() error") assert.Len(t, constants, tt.expected, "parse() got wrong number of constants") if tt.name == "single class constant" && len(constants) > 0 { c := constants[0] assert.Equal(t, "STATUS_ACTIVE", c.Name, "Expected constant name 'STATUS_ACTIVE'") assert.Equal(t, "MyClass", c.ClassName, "Expected class name 'MyClass'") assert.Equal(t, "1", c.Value, "Expected constant value '1'") assert.Equal(t, phpInt, c.PhpType, "Expected constant type 'int'") } if tt.name == "multiple class constants" && len(constants) == 3 { expectedClasses := []string{"User", "User", "Order"} expectedNames := []string{"STATUS_ACTIVE", "STATUS_INACTIVE", "STATE_PENDING"} expectedValues := []string{`"active"`, `"inactive"`, "0"} for i, c := range constants { assert.Equal(t, expectedClasses[i], c.ClassName, "Expected class name '%s'", expectedClasses[i]) assert.Equal(t, expectedNames[i], c.Name, "Expected constant name '%s'", expectedNames[i]) assert.Equal(t, expectedValues[i], c.Value, "Expected constant value '%s'", expectedValues[i]) } } if tt.name == "mixed global and class constants" && len(constants) == 3 { assert.Empty(t, constants[0].ClassName, "First constant should be global") assert.Equal(t, "MyClass", constants[1].ClassName, "Second constant should belong to MyClass") assert.Empty(t, constants[2].ClassName, "Third constant should be global") } }) } } func TestConstantParserRegexMatch(t *testing.T) { testCases := []struct { line string expected bool }{ {"//export_php:const", true}, {"// export_php:const", true}, {"// export_php:const", true}, {"//export_php:const ", false}, // should not match with trailing content {"//export_php", false}, {"//export_php:function", false}, {"//export_php:class", false}, {"// some other comment", false}, } for _, tc := range testCases { t.Run(tc.line, func(t *testing.T) { matches := constRegex.MatchString(tc.line) assert.Equal(t, tc.expected, matches, "Expected regex match for line '%s'", tc.line) }) } } func TestConstantParserClassConstRegex(t *testing.T) { testCases := []struct { line string shouldMatch bool className string }{ {"//export_php:classconst MyClass", true, "MyClass"}, {"// export_php:classconst User", true, "User"}, {"// export_php:classconst Status", true, "Status"}, {"//export_php:classconst Order123", true, "Order123"}, {"//export_php:classconst", false, ""}, {"//export_php:classconst ", false, ""}, {"//export_php:classconst MyClass extra", false, ""}, {"//export_php:const", false, ""}, {"//export_php:function", false, ""}, {"// some other comment", false, ""}, } for _, tc := range testCases { t.Run(tc.line, func(t *testing.T) { matches := classConstRegex.FindStringSubmatch(tc.line) if tc.shouldMatch { assert.Len(t, matches, 2, "Expected 2 matches for line '%s'", tc.line) if len(matches) != 2 { return } assert.Equal(t, tc.className, matches[1], "Expected class name '%s'", tc.className) } else { assert.Empty(t, matches, "Expected no matches for line '%s'", tc.line) } }) } } func TestConstantParserDeclRegex(t *testing.T) { testCases := []struct { line string shouldMatch bool name string value string }{ {`const MyConst = "value"`, true, "MyConst", `"value"`}, {"const IntConst = 42", true, "IntConst", "42"}, {"const BoolConst = true", true, "BoolConst", "true"}, {"const IotaConst = iota", true, "IotaConst", "iota"}, {"const ComplexValue = someFunction()", true, "ComplexValue", "someFunction()"}, {`const SpacedName = "with spaces"`, true, "SpacedName", `"with spaces"`}, {`var notAConst = "value"`, false, "", ""}, {"const", false, "", ""}, {"const =", false, "", ""}, } for _, tc := range testCases { t.Run(tc.line, func(t *testing.T) { matches := constDeclRegex.FindStringSubmatch(tc.line) if tc.shouldMatch { assert.Len(t, matches, 3, "Expected 3 matches for line '%s'", tc.line) if len(matches) != 3 { return } assert.Equal(t, tc.name, matches[1], "Expected name '%s'", tc.name) assert.Equal(t, tc.value, matches[2], "Expected value '%s'", tc.value) } else { assert.Empty(t, matches, "Expected no matches for line '%s'", tc.line) } }) } } func TestPHPConstantCValue(t *testing.T) { tests := []struct { name string constant phpConstant expected string }{ { name: "octal notation 0o35", constant: phpConstant{ Name: "OctalConst", Value: "0o35", PhpType: phpInt, }, expected: "29", // 0o35 = 29 in decimal }, { name: "octal notation 0o755", constant: phpConstant{ Name: "OctalPerm", Value: "0o755", PhpType: phpInt, }, expected: "493", // 0o755 = 493 in decimal }, { name: "regular integer", constant: phpConstant{ Name: "RegularInt", Value: "42", PhpType: phpInt, }, expected: "42", }, { name: "hex integer", constant: phpConstant{ Name: "HexInt", Value: "0xFF", PhpType: phpInt, }, expected: "0xFF", // hex should remain unchanged }, { name: "string constant", constant: phpConstant{ Name: "StringConst", Value: `"hello"`, PhpType: phpString, }, expected: `"hello"`, // strings should remain unchanged }, { name: "boolean constant", constant: phpConstant{ Name: "BoolConst", Value: "true", PhpType: phpBool, }, expected: "true", // booleans should remain unchanged }, { name: "float constant", constant: phpConstant{ Name: "FloatConst", Value: "3.14", PhpType: phpFloat, }, expected: "3.14", // floats should remain unchanged }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.constant.CValue() assert.Equal(t, tt.expected, result, "CValue() expected %s", tt.expected) }) } } ================================================ FILE: internal/extgen/docs.go ================================================ package extgen import ( "bytes" _ "embed" "path/filepath" "text/template" ) //go:embed templates/README.md.tpl var docFileContent string type DocumentationGenerator struct { generator *Generator } type DocTemplateData struct { BaseName string Functions []phpFunction Classes []phpClass } func (dg *DocumentationGenerator) generate() error { filename := filepath.Join(dg.generator.BuildDir, "README.md") content, err := dg.generateMarkdown() if err != nil { return err } return writeFile(filename, content) } func (dg *DocumentationGenerator) generateMarkdown() (string, error) { tmpl := template.Must(template.New("readme").Parse(docFileContent)) var buf bytes.Buffer if err := tmpl.Execute(&buf, DocTemplateData{ BaseName: dg.generator.BaseName, Functions: dg.generator.Functions, Classes: dg.generator.Classes, }); err != nil { return "", err } return buf.String(), nil } ================================================ FILE: internal/extgen/docs_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDocumentationGenerator_Generate(t *testing.T) { tests := []struct { name string generator *Generator expectError bool }{ { name: "simple extension with functions", generator: &Generator{ BaseName: "testextension", BuildDir: "", Functions: []phpFunction{ { Name: "greet", ReturnType: phpString, Params: []phpParameter{ {Name: "name", PhpType: phpString}, }, Signature: "greet(string $name): string", }, }, Classes: []phpClass{}, }, expectError: false, }, { name: "extension with classes", generator: &Generator{ BaseName: "classextension", BuildDir: "", Functions: []phpFunction{}, Classes: []phpClass{ { Name: "TestClass", Properties: []phpClassProperty{ {Name: "name", PhpType: phpString}, {Name: "count", PhpType: phpInt, IsNullable: true}, }, }, }, }, expectError: false, }, { name: "extension with both functions and classes", generator: &Generator{ BaseName: "fullextension", BuildDir: "", Functions: []phpFunction{ { Name: "calculate", ReturnType: phpInt, IsReturnNullable: true, Params: []phpParameter{ {Name: "base", PhpType: phpInt}, {Name: "multiplier", PhpType: phpInt, HasDefault: true, DefaultValue: "2", IsNullable: true}, }, Signature: "calculate(int $base, ?int $multiplier = 2): ?int", }, }, Classes: []phpClass{ { Name: "Calculator", Properties: []phpClassProperty{ {Name: "precision", PhpType: phpInt}, }, }, }, }, expectError: false, }, { name: "empty extension", generator: &Generator{ BaseName: "emptyextension", BuildDir: "", Functions: []phpFunction{}, Classes: []phpClass{}, }, expectError: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tempDir := t.TempDir() tt.generator.BuildDir = tempDir docGen := &DocumentationGenerator{ generator: tt.generator, } err := docGen.generate() if tt.expectError { assert.Error(t, err, "generate() expected error but got none") return } assert.NoError(t, err, "generate() unexpected error") readmePath := filepath.Join(tempDir, "README.md") require.FileExists(t, readmePath) content, err := os.ReadFile(readmePath) require.NoError(t, err, "Failed to read generated README.md") contentStr := string(content) assert.Contains(t, contentStr, "# "+tt.generator.BaseName+" Extension", "README should contain extension title") assert.Contains(t, contentStr, "Auto-generated PHP extension from Go code.", "README should contain description") if len(tt.generator.Functions) > 0 { assert.Contains(t, contentStr, "## Functions", "README should contain functions section when functions exist") for _, fn := range tt.generator.Functions { assert.Contains(t, contentStr, "### "+fn.Name, "README should contain function %s", fn.Name) assert.Contains(t, contentStr, fn.Signature, "README should contain function signature for %s", fn.Name) } } if len(tt.generator.Classes) > 0 { assert.Contains(t, contentStr, "## Classes", "README should contain classes section when classes exist") for _, class := range tt.generator.Classes { assert.Contains(t, contentStr, "### "+class.Name, "README should contain class %s", class.Name) } } }) } } func TestDocumentationGenerator_GenerateMarkdown(t *testing.T) { tests := []struct { name string generator *Generator contains []string notContains []string }{ { name: "function with parameters", generator: &Generator{ BaseName: "testextension", Functions: []phpFunction{ { Name: "processData", ReturnType: phpArray, Params: []phpParameter{ {Name: "data", PhpType: phpString}, {Name: "options", PhpType: phpArray, IsNullable: true}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, }, Signature: "processData(string $data, ?array $options, int $count = 10): array", }, }, Classes: []phpClass{}, }, contains: []string{ "# testextension Extension", "## Functions", "### processData", "**Parameters:**", "- `data` (string)", "- `options` (array) (nullable)", "- `count` (int) (default: 10)", "**Returns:** array", }, }, { name: "nullable return type", generator: &Generator{ BaseName: "nullableext", Functions: []phpFunction{ { Name: "maybeGetValue", ReturnType: phpString, IsReturnNullable: true, Params: []phpParameter{}, Signature: "maybeGetValue(): ?string", }, }, Classes: []phpClass{}, }, contains: []string{ "**Returns:** string (nullable)", }, }, { name: "class with properties", generator: &Generator{ BaseName: "classext", Functions: []phpFunction{}, Classes: []phpClass{ { Name: "DataProcessor", Properties: []phpClassProperty{ {Name: "name", PhpType: phpString}, {Name: "config", PhpType: phpArray, IsNullable: true}, {Name: "enabled", PhpType: phpBool}, }, }, }, }, contains: []string{ "## Classes", "### DataProcessor", "**Properties:**", "- `name`: string", "- `config`: array (nullable)", "- `enabled`: bool", }, }, { name: "extension with no functions or classes", generator: &Generator{ BaseName: "emptyext", Functions: []phpFunction{}, Classes: []phpClass{}, }, contains: []string{ "# emptyext Extension", "Auto-generated PHP extension from Go code.", }, notContains: []string{ "## Functions", "## Classes", }, }, { name: "function with no parameters", generator: &Generator{ BaseName: "noparamext", Functions: []phpFunction{ { Name: "getCurrentTime", ReturnType: phpInt, Params: []phpParameter{}, Signature: "getCurrentTime(): int", }, }, Classes: []phpClass{}, }, contains: []string{ "### getCurrentTime", "**Returns:** int", }, notContains: []string{ "**Parameters:**", }, }, { name: "class with no properties", generator: &Generator{ BaseName: "nopropsext", Functions: []phpFunction{}, Classes: []phpClass{ { Name: "EmptyClass", Properties: []phpClassProperty{}, }, }, }, contains: []string{ "### EmptyClass", }, notContains: []string{ "**Properties:**", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { docGen := &DocumentationGenerator{ generator: tt.generator, } result, err := docGen.generateMarkdown() if !assert.NoError(t, err, "generateMarkdown() unexpected error") { return } for _, expected := range tt.contains { assert.Contains(t, result, expected, "generateMarkdown() should contain '%s'", expected) } for _, notExpected := range tt.notContains { assert.NotContains(t, result, notExpected, "generateMarkdown() should NOT contain '%s'", notExpected) } }) } } func TestDocumentationGenerator_Generate_InvalidDirectory(t *testing.T) { generator := &Generator{ BaseName: "test", BuildDir: "/nonexistent/directory", Functions: []phpFunction{}, Classes: []phpClass{}, } docGen := &DocumentationGenerator{ generator: generator, } err := docGen.generate() assert.Error(t, err, "generate() expected error for invalid directory but got none") } func TestDocumentationGenerator_TemplateError(t *testing.T) { generator := &Generator{ BaseName: "test", Functions: []phpFunction{ { Name: "test", ReturnType: phpString, Signature: "test(): string", }, }, Classes: []phpClass{}, } docGen := &DocumentationGenerator{ generator: generator, } result, err := docGen.generateMarkdown() assert.NoError(t, err, "generateMarkdown() unexpected error") assert.NotEmpty(t, result, "generateMarkdown() returned empty result") } func BenchmarkDocumentationGenerator_GenerateMarkdown(b *testing.B) { generator := &Generator{ BaseName: "benchext", Functions: []phpFunction{ { Name: "function1", ReturnType: phpString, Params: []phpParameter{ {Name: "param1", PhpType: phpString}, {Name: "param2", PhpType: phpInt, HasDefault: true, DefaultValue: "0"}, }, Signature: "function1(string $param1, int $param2 = 0): string", }, { Name: "function2", ReturnType: phpArray, IsReturnNullable: true, Params: []phpParameter{ {Name: "data", PhpType: phpArray, IsNullable: true}, }, Signature: "function2(?array $data): ?array", }, }, Classes: []phpClass{ { Name: "TestClass", Properties: []phpClassProperty{ {Name: "prop1", PhpType: phpString}, {Name: "prop2", PhpType: phpInt, IsNullable: true}, }, }, }, } docGen := &DocumentationGenerator{ generator: generator, } for b.Loop() { _, err := docGen.generateMarkdown() assert.NoError(b, err) } } ================================================ FILE: internal/extgen/errors.go ================================================ package extgen import "fmt" type GeneratorError struct { Stage string Message string Err error } func (e *GeneratorError) Error() string { if e.Err == nil { return fmt.Sprintf("generator error at %s: %s", e.Stage, e.Message) } return fmt.Sprintf("generator error at %s: %s: %v", e.Stage, e.Message, e.Err) } ================================================ FILE: internal/extgen/funcparser.go ================================================ package extgen import ( "bufio" "fmt" "os" "regexp" "strings" ) var phpFuncRegex = regexp.MustCompile(`//\s*export_php:function\s+([^{}\n]+)(?:\s*{\s*})?`) var signatureRegex = regexp.MustCompile(`(\w+)\s*\(([^)]*)\)\s*:\s*(\??[\w|]+)`) var typeNameRegex = regexp.MustCompile(`(\??[\w|]+)\s+\$?(\w+)`) type FuncParser struct{} func (fp *FuncParser) parse(filename string) (functions []phpFunction, err error) { file, err := os.Open(filename) if err != nil { return nil, err } defer func() { e := file.Close() if err == nil { err = e } }() scanner := bufio.NewScanner(file) var currentPHPFunc *phpFunction validator := Validator{} lineNumber := 0 for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if matches := phpFuncRegex.FindStringSubmatch(line); matches != nil { signature := strings.TrimSpace(matches[1]) phpFunc, err := fp.parseSignature(signature) if err != nil { fmt.Printf("Warning: Error parsing signature '%s': %v\n", signature, err) continue } if err := validator.validateFunction(*phpFunc); err != nil { fmt.Printf("Warning: Invalid function '%s': %v\n", phpFunc.Name, err) continue } if err := validator.validateTypes(*phpFunc); err != nil { fmt.Printf("Warning: Function '%s' uses unsupported types: %v\n", phpFunc.Name, err) continue } phpFunc.lineNumber = lineNumber currentPHPFunc = phpFunc } if currentPHPFunc != nil && strings.HasPrefix(line, "func ") { goFunc, err := fp.extractGoFunction(scanner, line) if err != nil { return nil, fmt.Errorf("extracting Go function: %w", err) } currentPHPFunc.GoFunction = goFunc if err := validator.validateGoFunctionSignatureWithOptions(*currentPHPFunc, false); err != nil { fmt.Printf("Warning: Go function signature mismatch for %q: %v\n", currentPHPFunc.Name, err) currentPHPFunc = nil continue } functions = append(functions, *currentPHPFunc) currentPHPFunc = nil } } if currentPHPFunc != nil { return nil, fmt.Errorf("//export_php function directive at line %d is not followed by a function declaration", currentPHPFunc.lineNumber) } return functions, scanner.Err() } func (fp *FuncParser) extractGoFunction(scanner *bufio.Scanner, firstLine string) (string, error) { goFunc := firstLine + "\n" braceCount := 1 for scanner.Scan() { line := scanner.Text() goFunc += line + "\n" for _, char := range line { switch char { case '{': braceCount++ case '}': braceCount-- } } if braceCount == 0 { break } } return goFunc, nil } func (fp *FuncParser) parseSignature(signature string) (*phpFunction, error) { matches := signatureRegex.FindStringSubmatch(signature) if len(matches) != 4 { return nil, fmt.Errorf("invalid signature format") } name := matches[1] paramsStr := strings.TrimSpace(matches[2]) returnTypeStr := strings.TrimSpace(matches[3]) isReturnNullable := strings.HasPrefix(returnTypeStr, "?") returnType := strings.TrimPrefix(returnTypeStr, "?") var params []phpParameter if paramsStr != "" { paramParts := strings.SplitSeq(paramsStr, ",") for part := range paramParts { param, err := fp.parseParameter(strings.TrimSpace(part)) if err != nil { return nil, fmt.Errorf("parsing parameter '%s': %w", part, err) } params = append(params, param) } } return &phpFunction{ Name: name, Signature: signature, Params: params, ReturnType: phpType(returnType), IsReturnNullable: isReturnNullable, }, nil } func (fp *FuncParser) parseParameter(paramStr string) (phpParameter, error) { parts := strings.Split(paramStr, "=") typePart := strings.TrimSpace(parts[0]) param := phpParameter{HasDefault: len(parts) > 1} if param.HasDefault { param.DefaultValue = fp.sanitizeDefaultValue(strings.TrimSpace(parts[1])) } matches := typeNameRegex.FindStringSubmatch(typePart) if len(matches) < 3 { return phpParameter{}, fmt.Errorf("invalid parameter format: %s", paramStr) } typeStr := strings.TrimSpace(matches[1]) param.Name = strings.TrimSpace(matches[2]) param.IsNullable = strings.HasPrefix(typeStr, "?") param.PhpType = phpType(strings.TrimPrefix(typeStr, "?")) return param, nil } func (fp *FuncParser) sanitizeDefaultValue(value string) string { if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") { return value } if strings.ToLower(value) == "null" { return "null" } return strings.Trim(value, `'"`) } ================================================ FILE: internal/extgen/funcparser_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFunctionParser(t *testing.T) { tests := []struct { name string input string expected int }{ { name: "single function", input: `package main //export_php:function testFunc(string $name): string func testFunc(name *C.zend_string) unsafe.Pointer { return String("Hello " + CStringToGoString(name)) }`, expected: 1, }, { name: "multiple functions", input: `package main //export_php:function func1(int $a): int func func1(a int64) int64 { return a * 2 } //export_php:function func2(string $b): string func func2(b *C.zend_string) unsafe.Pointer { return String("processed: " + CStringToGoString(b)) }`, expected: 2, }, { name: "no php functions", input: `package main func regularFunc() { // Just a regular Go function }`, expected: 0, }, { name: "mixed functions", input: `package main //export_php:function phpFunc(string $data): string func phpFunc(data *C.zend_string) unsafe.Pointer { return String("PHP: " + CStringToGoString(data)) } func internalFunc() { // Internal function without export_php comment } //export_php:function anotherPhpFunc(int $num): int func anotherPhpFunc(num int64) int64 { return num * 10 }`, expected: 2, }, { name: "wrong args syntax", input: `package main //export_php function phpFunc(data string): string func phpFunc(data *C.zend_string) unsafe.Pointer { return String("PHP: " + CStringToGoString(data)) }`, expected: 0, }, { name: "decoupled function names", input: `package main //export_php:function my_php_function(string $name): string func myGoFunction(name *C.zend_string) unsafe.Pointer { return String("Hello " + CStringToGoString(name)) } //export_php:function another_php_func(int $num): int func someOtherGoName(num int64) int64 { return num * 5 }`, expected: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0644)) parser := &FuncParser{} functions, err := parser.parse(fileName) require.NoError(t, err) assert.Len(t, functions, tt.expected, "parse() got wrong number of functions") if tt.name == "single function" && len(functions) > 0 { fn := functions[0] assert.Equal(t, "testFunc", fn.Name, "Expected function name 'testFunc'") assert.Equal(t, phpString, fn.ReturnType, "Expected return type 'string'") assert.Len(t, fn.Params, 1, "Expected 1 parameter") if len(fn.Params) > 0 { assert.Equal(t, "name", fn.Params[0].Name, "Expected parameter name 'name'") } } if tt.name == "decoupled function names" && len(functions) >= 2 { fn1 := functions[0] assert.Equal(t, "my_php_function", fn1.Name, "Expected PHP function name 'my_php_function'") fn2 := functions[1] assert.Equal(t, "another_php_func", fn2.Name, "Expected PHP function name 'another_php_func'") } }) } } func TestSignatureParsing(t *testing.T) { tests := []struct { name string signature string expectError bool funcName string paramCount int returnType phpType nullable bool }{ { name: "simple function", signature: "test(name string): string", funcName: "test", paramCount: 1, returnType: phpString, nullable: false, }, { name: "nullable return", signature: "test(id int): ?string", funcName: "test", paramCount: 1, returnType: phpString, nullable: true, }, { name: "multiple params", signature: "calculate(a int, b float, name string): float", funcName: "calculate", paramCount: 3, returnType: phpFloat, nullable: false, }, { name: "no parameters", signature: "getValue(): int", funcName: "getValue", paramCount: 0, returnType: phpInt, nullable: false, }, { name: "nullable parameters", signature: "process(?string data, ?int count): bool", funcName: "process", paramCount: 2, returnType: phpBool, nullable: false, }, { name: "invalid signature", signature: "invalid syntax here", expectError: true, }, { name: "missing return type", signature: "test(name string)", expectError: true, }, } parser := &FuncParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fn, err := parser.parseSignature(tt.signature) if tt.expectError { assert.Error(t, err, "parseSignature() expected error but got none") return } assert.NoError(t, err, "parseSignature() unexpected error") assert.Equal(t, tt.funcName, fn.Name, "parseSignature() name mismatch") assert.Len(t, fn.Params, tt.paramCount, "parseSignature() param count mismatch") assert.Equal(t, tt.returnType, fn.ReturnType, "parseSignature() return type mismatch") assert.Equal(t, tt.nullable, fn.IsReturnNullable, "parseSignature() nullable mismatch") if tt.name == "nullable parameters" { if len(fn.Params) >= 2 { assert.True(t, fn.Params[0].IsNullable, "First parameter should be nullable") assert.True(t, fn.Params[1].IsNullable, "Second parameter should be nullable") } } }) } } func TestParameterParsing(t *testing.T) { tests := []struct { name string paramStr string expectedName string expectedType phpType expectedNullable bool expectedDefault string hasDefault bool expectError bool }{ { name: "simple string param", paramStr: "string name", expectedName: "name", expectedType: phpString, }, { name: "nullable int param", paramStr: "?int count", expectedName: "count", expectedType: phpInt, expectedNullable: true, }, { name: "param with default", paramStr: "string message = 'hello'", expectedName: "message", expectedType: phpString, expectedDefault: "hello", hasDefault: true, }, { name: "int with default", paramStr: "int limit = 10", expectedName: "limit", expectedType: phpInt, expectedDefault: "10", hasDefault: true, }, { name: "nullable with default", paramStr: "?string data = null", expectedName: "data", expectedType: phpString, expectedNullable: true, expectedDefault: "null", hasDefault: true, }, { name: "invalid format", paramStr: "invalid", expectError: true, }, } parser := &FuncParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { param, err := parser.parseParameter(tt.paramStr) if tt.expectError { assert.Error(t, err, "parseParameter() expected error but got none") return } assert.NoError(t, err, "parseParameter() unexpected error") assert.Equal(t, tt.expectedName, param.Name, "parseParameter() name mismatch") assert.Equal(t, tt.expectedType, param.PhpType, "parseParameter() type mismatch") assert.Equal(t, tt.expectedNullable, param.IsNullable, "parseParameter() nullable mismatch") assert.Equal(t, tt.hasDefault, param.HasDefault, "parseParameter() hasDefault mismatch") if tt.hasDefault { assert.Equal(t, tt.expectedDefault, param.DefaultValue, "parseParameter() defaultValue mismatch") } }) } } func TestFunctionParserUnsupportedTypes(t *testing.T) { tests := []struct { name string input string expected int hasWarning bool }{ { name: "function with array parameter should be rejected", input: `package main //export_php:function arrayFunc(array $data): string func arrayFunc(data any) unsafe.Pointer { return String("processed") }`, expected: 0, hasWarning: true, }, { name: "function with object parameter should be rejected", input: `package main //export_php:function objectFunc(object $obj): string func objectFunc(obj any) unsafe.Pointer { return String("processed") }`, expected: 0, hasWarning: true, }, { name: "function with mixed parameter should be rejected", input: `package main //export_php:function mixedFunc(mixed $value): string func mixedFunc(value any) unsafe.Pointer { return String("processed") }`, expected: 0, hasWarning: true, }, { name: "function with array return type should be rejected", input: `package main //export_php:function arrayReturnFunc(string $name): array func arrayReturnFunc(name *C.zend_string) any { return []string{"result"} }`, expected: 0, hasWarning: true, }, { name: "function with object return type should be rejected", input: `package main //export_php:function objectReturnFunc(string $name): object func objectReturnFunc(name *C.zend_string) any { return map[string]any{"key": "value"} }`, expected: 0, hasWarning: true, }, { name: "valid scalar types should pass", input: `package main //export_php:function validFunc(string $name, int $count, float $rate, bool $active): string func validFunc(name *C.zend_string, count int64, rate float64, active bool) unsafe.Pointer { return nil }`, expected: 1, hasWarning: false, }, { name: "valid void return should pass", input: `package main //export_php:function voidFunc(string $message): void func voidFunc(message *C.zend_string) { // Do something }`, expected: 1, hasWarning: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(tmpFile, []byte(tt.input), 0644)) parser := &FuncParser{} functions, err := parser.parse(tmpFile) require.NoError(t, err) assert.Len(t, functions, tt.expected, "parse() got wrong number of functions") }) } } func TestFunctionParserGoTypeMismatch(t *testing.T) { tests := []struct { name string input string expected int hasWarning bool }{ { name: "parameter count mismatch should be rejected", input: `package main //export_php:function countMismatch(string $name, int $count): string func countMismatch(name *C.zend_string) unsafe.Pointer { return nil }`, expected: 0, hasWarning: true, }, { name: "parameter type mismatch should be rejected", input: `package main //export_php:function typeMismatch(string $name, int $count): string func typeMismatch(name *C.zend_string, count string) unsafe.Pointer { return nil }`, expected: 0, hasWarning: true, }, { name: "return type mismatch should be rejected", input: `package main //export_php:function returnMismatch(string $name): int func returnMismatch(name *C.zend_string) string { return "" }`, expected: 0, hasWarning: true, }, { name: "valid matching types should pass", input: `package main //export_php:function validMatch(string $name, int $count): string func validMatch(name *C.zend_string, count int64) unsafe.Pointer { return nil }`, expected: 1, hasWarning: false, }, { name: "valid bool types should pass", input: `package main //export_php:function validBool(bool $flag): bool func validBool(flag bool) bool { return flag }`, expected: 1, hasWarning: false, }, { name: "valid float types should pass", input: `package main //export_php:function validFloat(float $value): float func validFloat(value float64) float64 { return value }`, expected: 1, hasWarning: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() fileName := filepath.Join(tmpDir, tt.name+".go") require.NoError(t, os.WriteFile(fileName, []byte(tt.input), 0644)) parser := &FuncParser{} functions, err := parser.parse(fileName) require.NoError(t, err) assert.Len(t, functions, tt.expected, "parse() got wrong number of functions") }) } } ================================================ FILE: internal/extgen/generator.go ================================================ package extgen import ( "fmt" "os" ) type Generator struct { BaseName string SourceFile string BuildDir string Functions []phpFunction Classes []phpClass Constants []phpConstant Namespace string } // EXPERIMENTAL func (g *Generator) Generate() error { if err := g.setupBuildDirectory(); err != nil { return fmt.Errorf("setup build directory: %w", err) } if err := g.parseSource(); err != nil { return fmt.Errorf("parse source: %w", err) } if len(g.Functions) == 0 && len(g.Classes) == 0 && len(g.Constants) == 0 { return fmt.Errorf("no PHP functions, classes, or constants found in source file") } generators := []struct { name string fn func() error }{ {"stub file", g.generateStubFile}, {"arginfo", g.generateArginfo}, {"header file", g.generateHeaderFile}, {"C file", g.generateCFile}, {"Go file", g.generateGoFile}, {"documentation", g.generateDocumentation}, } for _, gen := range generators { if err := gen.fn(); err != nil { return err } } return nil } func (g *Generator) setupBuildDirectory() error { return os.MkdirAll(g.BuildDir, 0755) } func (g *Generator) parseSource() error { parser := SourceParser{} functions, err := parser.ParseFunctions(g.SourceFile) if err != nil { return fmt.Errorf("parsing functions: %w", err) } g.Functions = functions classes, err := parser.ParseClasses(g.SourceFile) if err != nil { return fmt.Errorf("parsing classes: %w", err) } g.Classes = classes constants, err := parser.ParseConstants(g.SourceFile) if err != nil { return fmt.Errorf("parsing constants: %w", err) } g.Constants = constants ns, err := parser.ParseNamespace(g.SourceFile) if err != nil { return fmt.Errorf("parsing namespace: %w", err) } g.Namespace = ns return nil } func (g *Generator) generateStubFile() error { generator := StubGenerator{g} if err := generator.generate(); err != nil { return &GeneratorError{"stub generation", "failed to generate stub file", err} } return nil } func (g *Generator) generateArginfo() error { generator := arginfoGenerator{generator: g} if err := generator.generate(); err != nil { return &GeneratorError{"arginfo generation", "failed to generate arginfo", err} } return nil } func (g *Generator) generateHeaderFile() error { generator := HeaderGenerator{g} if err := generator.generate(); err != nil { return &GeneratorError{"header generation", "failed to generate header file", err} } return nil } func (g *Generator) generateCFile() error { generator := cFileGenerator{g} if err := generator.generate(); err != nil { return &GeneratorError{"C file generation", "failed to generate C file", err} } return nil } func (g *Generator) generateGoFile() error { generator := GoFileGenerator{g} if err := generator.generate(); err != nil { return &GeneratorError{"Go file generation", "failed to generate Go file", err} } return nil } func (g *Generator) generateDocumentation() error { docGen := DocumentationGenerator{g} if err := docGen.generate(); err != nil { return &GeneratorError{"documentation generation", "failed to generate documentation", err} } return nil } ================================================ FILE: internal/extgen/gofile.go ================================================ package extgen import ( "bytes" _ "embed" "fmt" "go/format" "path/filepath" "strings" "text/template" "github.com/Masterminds/sprig/v3" ) //go:embed templates/extension.go.tpl var goFileContent string type GoFileGenerator struct { generator *Generator } type goTemplateData struct { PackageName string BaseName string SanitizedBaseName string Constants []phpConstant Variables []string InternalFunctions []string Functions []phpFunction Classes []phpClass } func (gg *GoFileGenerator) generate() error { filename := filepath.Join(gg.generator.BuildDir, gg.generator.BaseName+"_generated.go") content, err := gg.buildContent() if err != nil { return fmt.Errorf("building Go file content: %w", err) } return writeFile(filename, content) } func (gg *GoFileGenerator) buildContent() (string, error) { sourceAnalyzer := SourceAnalyzer{} packageName, variables, internalFunctions, err := sourceAnalyzer.analyze(gg.generator.SourceFile) if err != nil { return "", fmt.Errorf("analyzing source file: %w", err) } classes := make([]phpClass, len(gg.generator.Classes)) copy(classes, gg.generator.Classes) templateContent, err := gg.getTemplateContent(goTemplateData{ PackageName: packageName, BaseName: gg.generator.BaseName, SanitizedBaseName: SanitizePackageName(gg.generator.BaseName), Constants: gg.generator.Constants, Variables: variables, InternalFunctions: internalFunctions, Functions: gg.generator.Functions, Classes: classes, }) if err != nil { return "", fmt.Errorf("executing template: %w", err) } fc, err := format.Source([]byte(templateContent)) if err != nil { return "", fmt.Errorf("formatting source: %w", err) } return string(fc), nil } func (gg *GoFileGenerator) getTemplateContent(data goTemplateData) (string, error) { funcMap := sprig.FuncMap() funcMap["phpTypeToGoType"] = gg.phpTypeToGoType funcMap["isStringOrArray"] = func(t phpType) bool { return t == phpString || t == phpArray } funcMap["isVoid"] = func(t phpType) bool { return t == phpVoid } funcMap["extractGoFunctionName"] = extractGoFunctionName funcMap["extractGoFunctionSignatureParams"] = extractGoFunctionSignatureParams funcMap["extractGoFunctionSignatureReturn"] = extractGoFunctionSignatureReturn funcMap["extractGoFunctionCallParams"] = extractGoFunctionCallParams tmpl := template.Must(template.New("gofile").Funcs(funcMap).Parse(goFileContent)) var buf bytes.Buffer if err := tmpl.Execute(&buf, data); err != nil { return "", err } return buf.String(), nil } type GoMethodSignature struct { MethodName string Params []GoParameter ReturnType string } type GoParameter struct { Name string Type string } var phpToGoTypeMap = map[phpType]string{ phpString: "string", phpInt: "int64", phpFloat: "float64", phpBool: "bool", phpArray: "*frankenphp.Array", phpMixed: "any", phpVoid: "", phpCallable: "*C.zval", } func (gg *GoFileGenerator) phpTypeToGoType(phpT phpType) string { if goType, exists := phpToGoTypeMap[phpT]; exists { return goType } return "any" } // extractGoFunctionName extracts the Go function name from a Go function signature string. func extractGoFunctionName(goFunction string) string { idx := strings.Index(goFunction, "func ") if idx == -1 { return "" } start := idx + len("func ") end := start for end < len(goFunction) && goFunction[end] != '(' { end++ } if end >= len(goFunction) { return "" } return strings.TrimSpace(goFunction[start:end]) } // extractGoFunctionSignatureParams extracts the parameters from a Go function signature. func extractGoFunctionSignatureParams(goFunction string) string { start := strings.IndexByte(goFunction, '(') if start == -1 { return "" } start++ depth := 1 end := start for end < len(goFunction) && depth > 0 { switch goFunction[end] { case '(': depth++ case ')': depth-- } if depth > 0 { end++ } } if end >= len(goFunction) { return "" } return strings.TrimSpace(goFunction[start:end]) } // extractGoFunctionSignatureReturn extracts the return type from a Go function signature. func extractGoFunctionSignatureReturn(goFunction string) string { start := strings.IndexByte(goFunction, '(') if start == -1 { return "" } depth := 1 pos := start + 1 for pos < len(goFunction) && depth > 0 { switch goFunction[pos] { case '(': depth++ case ')': depth-- } pos++ } if pos >= len(goFunction) { return "" } end := strings.IndexByte(goFunction[pos:], '{') if end == -1 { return "" } end += pos returnType := strings.TrimSpace(goFunction[pos:end]) return returnType } // extractGoFunctionCallParams extracts just the parameter names for calling a function. func extractGoFunctionCallParams(goFunction string) string { params := extractGoFunctionSignatureParams(goFunction) if params == "" { return "" } var names []string parts := strings.Split(params, ",") for _, part := range parts { part = strings.TrimSpace(part) if len(part) == 0 { continue } words := strings.Fields(part) if len(words) > 0 { names = append(names, words[0]) } } var result strings.Builder for i, name := range names { if i > 0 { result.WriteString(", ") } result.WriteString(name) } return result.String() } ================================================ FILE: internal/extgen/gofile_test.go ================================================ package extgen import ( "bytes" "crypto/sha256" "encoding/hex" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGoFileGenerator_Generate(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import ( "fmt" "strings" "github.com/dunglas/frankenphp/internal/extensions/types" ) //export_php: greet(name string): string func greet(name *go_string) *go_value { return types.String("Hello " + CStringToGoString(name)) } //export_php: calculate(a int, b int): int func calculate(a long, b long) *go_value { result := a + b return types.Int(result) } func internalHelper(data string) string { return strings.ToUpper(data) } func anotherHelper() { fmt.Println("Internal helper") }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) generator := &Generator{ BaseName: "test", SourceFile: sourceFile, BuildDir: tmpDir, Functions: []phpFunction{ { Name: "greet", ReturnType: phpString, GoFunction: `func greet(name *go_string) *go_value { return types.String("Hello " + CStringToGoString(name)) }`, }, { Name: "calculate", ReturnType: phpInt, GoFunction: `func calculate(a long, b long) *go_value { result := a + b return types.Int(result) }`, }, }, } goGen := GoFileGenerator{generator} require.NoError(t, goGen.generate()) sourceStillExists := filepath.Join(tmpDir, "test.go") require.FileExists(t, sourceStillExists) sourceStillContent, err := readFile(sourceStillExists) require.NoError(t, err) assert.Equal(t, sourceContent, sourceStillContent, "Source file should not be modified") generatedFile := filepath.Join(tmpDir, "test_generated.go") require.FileExists(t, generatedFile) generatedContent, err := readFile(generatedFile) require.NoError(t, err) testGeneratedFileBasicStructure(t, generatedContent, "main", "test") testGeneratedFileWrappers(t, generatedContent, generator.Functions) } func TestGoFileGenerator_BuildContent(t *testing.T) { tests := []struct { name string baseName string sourceFile string functions []phpFunction classes []phpClass contains []string notContains []string }{ { name: "simple extension", baseName: "simple", sourceFile: createTempSourceFile(t, `package main //export_php: test(): void func test() { // simple function }`), functions: []phpFunction{ { Name: "test", ReturnType: phpVoid, GoFunction: "func test() {\n\t// simple function\n}", }, }, contains: []string{ "package main", `#include "simple.h"`, `import "C"`, "func init()", "frankenphp.RegisterExtension(", "//export go_test", "func go_test()", "test()", // wrapper calls original function }, }, { name: "extension with complex imports", baseName: "complex", sourceFile: createTempSourceFile(t, `package main import ( "fmt" "strings" "encoding/json" "github.com/dunglas/frankenphp/internal/extensions/types" ) //export_php: process(data string): string func process(data *go_string) *go_value { return types.String(fmt.Sprintf("processed: %s", CStringToGoString(data))) }`), functions: []phpFunction{ { Name: "process", ReturnType: phpString, GoFunction: `func process(data *go_string) *go_value { return String(fmt.Sprintf("processed: %s", CStringToGoString(data))) }`, }, }, contains: []string{ "package main", "//export go_process", `"C"`, "process(", // wrapper calls original function }, }, { name: "extension with internal functions", baseName: "internal", sourceFile: createTempSourceFile(t, `package main //export_php: publicFunc(): void func publicFunc() {} func internalFunc1() string { return "internal" } func internalFunc2(data string) { // process data internally }`), functions: []phpFunction{ { Name: "publicFunc", ReturnType: phpVoid, GoFunction: "func publicFunc() {}", }, }, contains: []string{ "//export go_publicFunc", "func go_publicFunc()", "publicFunc()", // wrapper calls original function }, notContains: []string{ "func internalFunc1() string", "func internalFunc2(data string)", }, }, { name: "runtime/cgo blank import without classes", baseName: "no_classes", sourceFile: createTempSourceFile(t, `package main //export_php: getValue(): string func getValue() string { return "test" }`), functions: []phpFunction{ { Name: "getValue", ReturnType: phpString, GoFunction: `func getValue() string { return "test" }`, }, }, classes: nil, contains: []string{ `_ "runtime/cgo"`, "func init()", "frankenphp.RegisterExtension(", }, notContains: []string{ "cgo.NewHandle", "registerGoObject", "getGoObject", "removeGoObject", }, }, { name: "runtime/cgo normal import with classes", baseName: "with_classes", sourceFile: createTempSourceFile(t, `package main //export_php:class TestClass type TestStruct struct { value string } //export_php:method TestClass::getValue(): string func (ts *TestStruct) GetValue() string { return ts.value }`), functions: []phpFunction{}, classes: []phpClass{ { Name: "TestClass", GoStruct: "TestStruct", Methods: []phpClassMethod{ { Name: "GetValue", ReturnType: phpString, }, }, }, }, contains: []string{ `"runtime/cgo"`, "cgo.NewHandle", "func registerGoObject", "func getGoObject", }, notContains: []string{ `_ "runtime/cgo"`, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: tt.baseName, SourceFile: tt.sourceFile, Functions: tt.functions, Classes: tt.classes, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated Go content should contain %q", expected) } for _, notExpected := range tt.notContains { assert.NotContains(t, content, notExpected, "Generated Go content should NOT contain %q", notExpected) } }) } } func TestGoFileGenerator_PackageNameSanitization(t *testing.T) { tests := []struct { baseName string expectedPackage string }{ {"simple", "main"}, {"my-extension", "main"}, {"ext.with.dots", "main"}, {"123invalid", "main"}, {"valid_name", "main"}, } for _, tt := range tests { t.Run(tt.baseName, func(t *testing.T) { sourceFile := createTempSourceFile(t, "package main\n//export_php: test(): void\nfunc test() {}") generator := &Generator{ BaseName: tt.baseName, SourceFile: sourceFile, Functions: []phpFunction{ {Name: "test", ReturnType: phpVoid, GoFunction: "func test() {}"}, }, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) expectedPackage := "package " + tt.expectedPackage assert.Contains(t, content, expectedPackage, "Generated content should contain '%s'", expectedPackage) }) } } func TestGoFileGenerator_ErrorHandling(t *testing.T) { tests := []struct { name string sourceFile string expectErr bool }{ { name: "nonexistent file", sourceFile: "/nonexistent/file.go", expectErr: true, }, { name: "invalid Go syntax", sourceFile: createTempSourceFile(t, "invalid go syntax here"), expectErr: true, }, { name: "valid file", sourceFile: createTempSourceFile(t, "package main\nfunc test() {}"), expectErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{ BaseName: "test", SourceFile: tt.sourceFile, } goGen := GoFileGenerator{generator} _, err := goGen.buildContent() if tt.expectErr { assert.Error(t, err, "Expected error but got none") } else { assert.NoError(t, err, "Unexpected error") } }) } } func TestGoFileGenerator_ComplexScenario(t *testing.T) { sourceContent := `package example import ( "fmt" "strings" "encoding/json" "github.com/dunglas/frankenphp/internal/extensions/types" ) //export_php: processData(input string, options array): array func processData(input *go_string, options *go_nullable) *go_value { data := CStringToGoString(input) processed := internalProcess(data) return types.Array([]any{processed}) } //export_php: validateInput(data string): bool func validateInput(data *go_string) *go_value { input := CStringToGoString(data) isValid := len(input) > 0 && validateFormat(input) return types.Bool(isValid) } func internalProcess(data string) string { return strings.ToUpper(data) } func validateFormat(input string) bool { return !strings.Contains(input, "invalid") } func jsonHelper(data any) ([]byte, error) { return json.Marshal(data) } func debugPrint(msg string) { fmt.Printf("DEBUG: %s\n", msg) }` sourceFile := createTempSourceFile(t, sourceContent) functions := []phpFunction{ { Name: "processData", ReturnType: phpArray, GoFunction: `func processData(input *go_string, options *go_nullable) *go_value { data := CStringToGoString(input) processed := internalProcess(data) return Array([]any{processed}) }`, }, { Name: "validateInput", ReturnType: phpBool, GoFunction: `func validateInput(data *go_string) *go_value { input := CStringToGoString(data) isValid := len(input) > 0 && validateFormat(input) return Bool(isValid) }`, }, } generator := &Generator{ BaseName: "complex-example", SourceFile: sourceFile, Functions: functions, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) assert.Contains(t, content, "package example", "Package name should match source package") for _, fn := range functions { exportDirective := "//export go_" + fn.Name assert.Contains(t, content, exportDirective, "Generated content should contain export directive: %s", exportDirective) } } func TestGoFileGenerator_MethodWrapperWithNullableParams(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import "fmt" //export_php:class TestClass type TestStruct struct { name string } //export_php:method TestClass::processData(string $name, ?int $count, ?bool $enabled): string func (ts *TestStruct) ProcessData(name string, count *int64, enabled *bool) string { result := fmt.Sprintf("name=%s", name) if count != nil { result += fmt.Sprintf(", count=%d", *count) } if enabled != nil { result += fmt.Sprintf(", enabled=%t", *enabled) } return result }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) methods := []phpClassMethod{ { Name: "ProcessData", PhpName: "processData", ClassName: "TestClass", Signature: "processData(string $name, ?int $count, ?bool $enabled): string", ReturnType: phpString, Params: []phpParameter{ {Name: "name", PhpType: phpString, IsNullable: false}, {Name: "count", PhpType: phpInt, IsNullable: true}, {Name: "enabled", PhpType: phpBool, IsNullable: true}, }, GoFunction: `func (ts *TestStruct) ProcessData(name string, count *int64, enabled *bool) string { result := fmt.Sprintf("name=%s", name) if count != nil { result += fmt.Sprintf(", count=%d", *count) } if enabled != nil { result += fmt.Sprintf(", enabled=%t", *enabled) } return result }`, }, } classes := []phpClass{ { Name: "TestClass", GoStruct: "TestStruct", Methods: methods, }, } generator := &Generator{ BaseName: "nullable_test", SourceFile: sourceFile, Classes: classes, BuildDir: tmpDir, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) expectedWrapperSignature := "func ProcessData_wrapper(handle C.uintptr_t, name *C.zend_string, count *int64, enabled *bool)" assert.Contains(t, content, expectedWrapperSignature, "Generated content should contain wrapper with nullable pointer types: %s", expectedWrapperSignature) expectedCall := "structObj.ProcessData(name, count, enabled)" assert.Contains(t, content, expectedCall, "Generated content should contain correct method call: %s", expectedCall) exportDirective := "//export ProcessData_wrapper" assert.Contains(t, content, exportDirective, "Generated content should contain export directive: %s", exportDirective) } func TestGoFileGenerator_MethodWrapperWithArrayParams(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import "fmt" //export_php:class ArrayClass type ArrayStruct struct { data []any } //export_php:method ArrayClass::processArray(array $items): array func (as *ArrayStruct) ProcessArray(items frankenphp.AssociativeArray) frankenphp.AssociativeArray { result := frankenphp.AssociativeArray{} for key, value := range items.Map { result.Set("processed_"+key, value) } return result } //export_php:method ArrayClass::filterData(array $data, string $filter): array func (as *ArrayStruct) FilterData(data frankenphp.AssociativeArray, filter string) frankenphp.AssociativeArray { result := frankenphp.AssociativeArray{} // Filter logic here return result }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) methods := []phpClassMethod{ { Name: "ProcessArray", PhpName: "processArray", ClassName: "ArrayClass", Signature: "processArray(array $items): array", ReturnType: phpArray, Params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: false}, }, GoFunction: `func (as *ArrayStruct) ProcessArray(items frankenphp.AssociativeArray) frankenphp.AssociativeArray { result := frankenphp.AssociativeArray{} for key, value := range items.Entries() { result.Set("processed_"+key, value) } return result }`, }, { Name: "FilterData", PhpName: "filterData", ClassName: "ArrayClass", Signature: "filterData(array $data, string $filter): array", ReturnType: phpArray, Params: []phpParameter{ {Name: "data", PhpType: phpArray, IsNullable: false}, {Name: "filter", PhpType: phpString, IsNullable: false}, }, GoFunction: `func (as *ArrayStruct) FilterData(data frankenphp.AssociativeArray, filter string) frankenphp.AssociativeArray { result := frankenphp.AssociativeArray{} return result }`, }, } classes := []phpClass{ { Name: "ArrayClass", GoStruct: "ArrayStruct", Methods: methods, }, } generator := &Generator{ BaseName: "array_test", SourceFile: sourceFile, Classes: classes, BuildDir: tmpDir, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) expectedArrayWrapperSignature := "func ProcessArray_wrapper(handle C.uintptr_t, items *C.zval) unsafe.Pointer" assert.Contains(t, content, expectedArrayWrapperSignature, "Generated content should contain array wrapper signature: %s", expectedArrayWrapperSignature) expectedMixedWrapperSignature := "func FilterData_wrapper(handle C.uintptr_t, data *C.zval, filter *C.zend_string) unsafe.Pointer" assert.Contains(t, content, expectedMixedWrapperSignature, "Generated content should contain mixed wrapper signature: %s", expectedMixedWrapperSignature) expectedArrayCall := "structObj.ProcessArray(items)" assert.Contains(t, content, expectedArrayCall, "Generated content should contain array method call: %s", expectedArrayCall) expectedMixedCall := "structObj.FilterData(data, filter)" assert.Contains(t, content, expectedMixedCall, "Generated content should contain mixed method call: %s", expectedMixedCall) assert.Contains(t, content, "//export ProcessArray_wrapper", "Generated content should contain ProcessArray export directive") assert.Contains(t, content, "//export FilterData_wrapper", "Generated content should contain FilterData export directive") } func TestGoFileGenerator_Idempotency(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import ( "fmt" "strings" ) //export_php: greet(name string): string func greet(name *go_string) *go_value { return String("Hello " + CStringToGoString(name)) } func internalHelper(data string) string { return strings.ToUpper(data) }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) generator := &Generator{ BaseName: "test", SourceFile: sourceFile, BuildDir: tmpDir, Functions: []phpFunction{ { Name: "greet", ReturnType: phpString, GoFunction: `func greet(name *go_string) *go_value { return String("Hello " + CStringToGoString(name)) }`, }, }, } goGen := GoFileGenerator{generator} require.NoError(t, goGen.generate(), "First generation should succeed") generatedFile := filepath.Join(tmpDir, "test_generated.go") require.FileExists(t, generatedFile, "Generated file should exist after first run") firstRunContent, err := os.ReadFile(generatedFile) require.NoError(t, err) firstRunSourceContent, err := os.ReadFile(sourceFile) require.NoError(t, err) require.NoError(t, goGen.generate(), "Second generation should succeed") secondRunContent, err := os.ReadFile(generatedFile) require.NoError(t, err) secondRunSourceContent, err := os.ReadFile(sourceFile) require.NoError(t, err) assert.True(t, bytes.Equal(firstRunContent, secondRunContent), "Generated file content should be identical between runs") assert.True(t, bytes.Equal(firstRunSourceContent, secondRunSourceContent), "Source file should remain unchanged after both runs") assert.Equal(t, sourceContent, string(secondRunSourceContent), "Source file content should match original") } func TestGoFileGenerator_HeaderComments(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main //export_php: test(): void func test() { // simple function }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) generator := &Generator{ BaseName: "test", SourceFile: sourceFile, BuildDir: tmpDir, Functions: []phpFunction{ { Name: "test", ReturnType: phpVoid, GoFunction: "func test() {\n\t// simple function\n}", }, }, } goGen := GoFileGenerator{generator} require.NoError(t, goGen.generate()) generatedFile := filepath.Join(tmpDir, "test_generated.go") require.FileExists(t, generatedFile) assertContainsHeaderComment(t, generatedFile) } func TestExtractGoFunctionName(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "simple function", input: "func test() {}", expected: "test", }, { name: "function with params", input: "func calculate(a int, b int) int {}", expected: "calculate", }, { name: "function with complex params", input: "func process(data *go_string, opts *go_nullable) *go_value {}", expected: "process", }, { name: "function with whitespace", input: "func spacedName () {}", expected: "spacedName", }, { name: "no func keyword", input: "test() {}", expected: "", }, { name: "empty string", input: "", expected: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := extractGoFunctionName(tt.input) assert.Equal(t, tt.expected, result) }) } } func TestExtractGoFunctionSignatureParams(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "no parameters", input: "func test() {}", expected: "", }, { name: "single parameter", input: "func test(name string) {}", expected: "name string", }, { name: "multiple parameters", input: "func test(a int, b string, c bool) {}", expected: "a int, b string, c bool", }, { name: "pointer parameters", input: "func test(data *go_string) {}", expected: "data *go_string", }, { name: "nested parentheses", input: "func test(fn func(int) string) {}", expected: "fn func(int) string", }, { name: "variadic parameters", input: "func test(args ...string) {}", expected: "args ...string", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := extractGoFunctionSignatureParams(tt.input) assert.Equal(t, tt.expected, result) }) } } func TestExtractGoFunctionSignatureReturn(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "no return type", input: "func test() {}", expected: "", }, { name: "single return type", input: "func test() string {}", expected: "string", }, { name: "pointer return type", input: "func test() *go_value {}", expected: "*go_value", }, { name: "multiple return types", input: "func test() (string, error) {}", expected: "(string, error)", }, { name: "named return values", input: "func test() (result string, err error) {}", expected: "(result string, err error)", }, { name: "complex return type", input: "func test() unsafe.Pointer {}", expected: "unsafe.Pointer", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := extractGoFunctionSignatureReturn(tt.input) assert.Equal(t, tt.expected, result) }) } } func TestExtractGoFunctionCallParams(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "no parameters", input: "func test() {}", expected: "", }, { name: "single parameter", input: "func test(name string) {}", expected: "name", }, { name: "multiple parameters", input: "func test(a int, b string, c bool) {}", expected: "a, b, c", }, { name: "pointer parameters", input: "func test(data *go_string, opts *go_nullable) {}", expected: "data, opts", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := extractGoFunctionCallParams(tt.input) assert.Equal(t, tt.expected, result) }) } } func TestGoFileGenerator_SourceFilePreservation(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import "fmt" //export_php: greet(name string): string func greet(name *go_string) *go_value { return String(fmt.Sprintf("Hello, %s!", CStringToGoString(name))) } func internalHelper() { fmt.Println("internal") }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) hashBefore := computeFileHash(t, sourceFile) generator := &Generator{ BaseName: "test", SourceFile: sourceFile, BuildDir: tmpDir, Functions: []phpFunction{ { Name: "greet", ReturnType: phpString, GoFunction: `func greet(name *go_string) *go_value { return String(fmt.Sprintf("Hello, %s!", CStringToGoString(name))) }`, }, }, } goGen := GoFileGenerator{generator} require.NoError(t, goGen.generate()) hashAfter := computeFileHash(t, sourceFile) assert.Equal(t, hashBefore, hashAfter, "Source file hash should remain unchanged after generation") contentAfter, err := os.ReadFile(sourceFile) require.NoError(t, err) assert.Equal(t, sourceContent, string(contentAfter), "Source file content should be byte-for-byte identical") } func TestGoFileGenerator_WrapperParameterForwarding(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import "fmt" //export_php: process(name string, count int): string func process(name *go_string, count long) *go_value { n := CStringToGoString(name) return String(fmt.Sprintf("%s: %d", n, count)) } //export_php: simple(): void func simple() {}` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) functions := []phpFunction{ { Name: "process", ReturnType: phpString, GoFunction: `func process(name *go_string, count long) *go_value { n := CStringToGoString(name) return String(fmt.Sprintf("%s: %d", n, count)) }`, }, { Name: "simple", ReturnType: phpVoid, GoFunction: "func simple() {}", }, } generator := &Generator{ BaseName: "wrapper_test", SourceFile: sourceFile, BuildDir: tmpDir, Functions: functions, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) assert.Contains(t, content, "//export go_process", "Should have wrapper export directive") assert.Contains(t, content, "func go_process(", "Should have wrapper function") assert.Contains(t, content, "process(", "Wrapper should call original function") assert.Contains(t, content, "//export go_simple", "Should have simple wrapper export directive") assert.Contains(t, content, "func go_simple()", "Should have simple wrapper function") assert.Contains(t, content, "simple()", "Simple wrapper should call original function") } func TestGoFileGenerator_MalformedSource(t *testing.T) { tests := []struct { name string sourceContent string expectError bool }{ { name: "missing package declaration", sourceContent: "func test() {}", expectError: true, }, { name: "syntax error", sourceContent: "package main\nfunc test( {}", expectError: true, }, { name: "incomplete function", sourceContent: "package main\nfunc test() {", expectError: true, }, { name: "valid minimal source", sourceContent: "package main\nfunc test() {}", expectError: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpDir := t.TempDir() sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(tt.sourceContent), 0644)) generator := &Generator{ BaseName: "test", SourceFile: sourceFile, BuildDir: tmpDir, } goGen := GoFileGenerator{generator} _, err := goGen.buildContent() if tt.expectError { assert.Error(t, err, "Expected error for malformed source") } else { assert.NoError(t, err, "Should not error for valid source") } contentAfter, readErr := os.ReadFile(sourceFile) require.NoError(t, readErr) assert.Equal(t, tt.sourceContent, string(contentAfter), "Source file should remain unchanged even on error") }) } } func TestGoFileGenerator_MethodWrapperWithNullableArrayParams(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main //export_php:class NullableArrayClass type NullableArrayStruct struct{} //export_php:method NullableArrayClass::processOptionalArray(?array $items, string $name): string func (nas *NullableArrayStruct) ProcessOptionalArray(items frankenphp.AssociativeArray, name string) string { return fmt.Sprintf("Processing %d items for %s", len(items.Map), name) }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) methods := []phpClassMethod{ { Name: "ProcessOptionalArray", PhpName: "processOptionalArray", ClassName: "NullableArrayClass", Signature: "processOptionalArray(?array $items, string $name): string", ReturnType: phpString, Params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: true}, {Name: "name", PhpType: phpString, IsNullable: false}, }, GoFunction: `func (nas *NullableArrayStruct) ProcessOptionalArray(items frankenphp.AssociativeArray, name string) string { return fmt.Sprintf("Processing %d items for %s", len(items.Map), name) }`, }, } classes := []phpClass{ { Name: "NullableArrayClass", GoStruct: "NullableArrayStruct", Methods: methods, }, } generator := &Generator{ BaseName: "nullable_array_test", SourceFile: sourceFile, Classes: classes, BuildDir: tmpDir, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) expectedWrapperSignature := "func ProcessOptionalArray_wrapper(handle C.uintptr_t, items *C.zval, name *C.zend_string) unsafe.Pointer" assert.Contains(t, content, expectedWrapperSignature, "Generated content should contain nullable array wrapper signature: %s", expectedWrapperSignature) expectedCall := "structObj.ProcessOptionalArray(items, name)" assert.Contains(t, content, expectedCall, "Generated content should contain method call: %s", expectedCall) assert.Contains(t, content, "//export ProcessOptionalArray_wrapper", "Generated content should contain export directive") } func createTempSourceFile(t *testing.T, content string) string { tmpDir := t.TempDir() tmpFile := filepath.Join(tmpDir, "source.go") require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile } func TestGoFileGenerator_MethodWrapperWithCallableParams(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import "C" //export_php:class CallableClass type CallableStruct struct{} //export_php:method CallableClass::processCallback(callable $callback): string func (cs *CallableStruct) ProcessCallback(callback *C.zval) string { return "processed" } //export_php:method CallableClass::processOptionalCallback(?callable $callback): string func (cs *CallableStruct) ProcessOptionalCallback(callback *C.zval) string { return "processed_optional" }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) methods := []phpClassMethod{ { Name: "ProcessCallback", PhpName: "processCallback", ClassName: "CallableClass", Signature: "processCallback(callable $callback): string", ReturnType: phpString, Params: []phpParameter{ {Name: "callback", PhpType: phpCallable, IsNullable: false}, }, GoFunction: `func (cs *CallableStruct) ProcessCallback(callback *C.zval) string { return "processed" }`, }, { Name: "ProcessOptionalCallback", PhpName: "processOptionalCallback", ClassName: "CallableClass", Signature: "processOptionalCallback(?callable $callback): string", ReturnType: phpString, Params: []phpParameter{ {Name: "callback", PhpType: phpCallable, IsNullable: true}, }, GoFunction: `func (cs *CallableStruct) ProcessOptionalCallback(callback *C.zval) string { return "processed_optional" }`, }, } classes := []phpClass{ { Name: "CallableClass", GoStruct: "CallableStruct", Methods: methods, }, } generator := &Generator{ BaseName: "callable_test", SourceFile: sourceFile, Classes: classes, BuildDir: tmpDir, } goGen := GoFileGenerator{generator} content, err := goGen.buildContent() require.NoError(t, err) expectedCallableWrapperSignature := "func ProcessCallback_wrapper(handle C.uintptr_t, callback *C.zval) unsafe.Pointer" assert.Contains(t, content, expectedCallableWrapperSignature, "Generated content should contain callable wrapper signature: %s", expectedCallableWrapperSignature) expectedOptionalCallableWrapperSignature := "func ProcessOptionalCallback_wrapper(handle C.uintptr_t, callback *C.zval) unsafe.Pointer" assert.Contains(t, content, expectedOptionalCallableWrapperSignature, "Generated content should contain optional callable wrapper signature: %s", expectedOptionalCallableWrapperSignature) expectedCallableCall := "structObj.ProcessCallback(callback)" assert.Contains(t, content, expectedCallableCall, "Generated content should contain callable method call: %s", expectedCallableCall) expectedOptionalCallableCall := "structObj.ProcessOptionalCallback(callback)" assert.Contains(t, content, expectedOptionalCallableCall, "Generated content should contain optional callable method call: %s", expectedOptionalCallableCall) assert.Contains(t, content, "//export ProcessCallback_wrapper", "Generated content should contain ProcessCallback export directive") assert.Contains(t, content, "//export ProcessOptionalCallback_wrapper", "Generated content should contain ProcessOptionalCallback export directive") } func TestGoFileGenerator_phpTypeToGoType(t *testing.T) { generator := &Generator{} goGen := GoFileGenerator{generator} tests := []struct { phpType phpType expected string }{ {phpString, "string"}, {phpInt, "int64"}, {phpFloat, "float64"}, {phpBool, "bool"}, {phpArray, "*frankenphp.Array"}, {phpMixed, "any"}, {phpVoid, ""}, {phpCallable, "*C.zval"}, } for _, tt := range tests { t.Run(string(tt.phpType), func(t *testing.T) { result := goGen.phpTypeToGoType(tt.phpType) assert.Equal(t, tt.expected, result, "phpTypeToGoType(%s) should return %s", tt.phpType, tt.expected) }) } t.Run("unknown_type", func(t *testing.T) { unknownType := phpType("unknown") result := goGen.phpTypeToGoType(unknownType) assert.Equal(t, "any", result, "phpTypeToGoType should fallback to interface{} for unknown types") }) } func testGeneratedFileBasicStructure(t *testing.T, content, expectedPackage, baseName string) { requiredElements := []string{ "package " + expectedPackage, "// #include ", `// #include "` + baseName + `.h"`, `import "C"`, "func init() {", "frankenphp.RegisterExtension(", "}", } for _, element := range requiredElements { assert.Contains(t, content, element, "Generated file should contain: %s", element) } assert.NotContains(t, content, "func internalHelper", "Generated file should not contain internal functions from source") assert.NotContains(t, content, "func anotherHelper", "Generated file should not contain internal functions from source") } func testGeneratedFileWrappers(t *testing.T, content string, functions []phpFunction) { for _, fn := range functions { exportDirective := "//export go_" + fn.Name assert.Contains(t, content, exportDirective, "Generated file should contain export directive: %s", exportDirective) wrapperFunc := "func go_" + fn.Name + "(" assert.Contains(t, content, wrapperFunc, "Generated file should contain wrapper function: %s", wrapperFunc) funcName := extractGoFunctionName(fn.GoFunction) if funcName != "" { assert.Contains(t, content, funcName+"(", "Generated wrapper should call original function: %s", funcName) } } } // computeFileHash returns SHA256 hash of file func computeFileHash(t *testing.T, filename string) string { content, err := os.ReadFile(filename) require.NoError(t, err) hash := sha256.Sum256(content) return hex.EncodeToString(hash[:]) } // assertContainsHeaderComment verifies file has autogenerated header func assertContainsHeaderComment(t *testing.T, filename string) { content, err := os.ReadFile(filename) require.NoError(t, err) headerSection := string(content[:min(len(content), 500)]) assert.Contains(t, headerSection, "AUTOGENERATED FILE - DO NOT EDIT", "File should contain autogenerated header comment") assert.Contains(t, headerSection, "FrankenPHP extension generator", "File should mention FrankenPHP extension generator") } ================================================ FILE: internal/extgen/hfile.go ================================================ // header.go package extgen import ( "bytes" _ "embed" "path/filepath" "strings" "text/template" ) //go:embed templates/extension.h.tpl var hFileContent string type HeaderGenerator struct { generator *Generator } type TemplateData struct { BaseName string HeaderGuard string Constants []phpConstant Classes []phpClass } func (hg *HeaderGenerator) generate() error { filename := filepath.Join(hg.generator.BuildDir, hg.generator.BaseName+".h") content, err := hg.buildContent() if err != nil { return err } return writeFile(filename, content) } func (hg *HeaderGenerator) buildContent() (string, error) { headerGuard := strings.Map(func(r rune) rune { if r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { return r } return '_' }, hg.generator.BaseName) headerGuard = strings.ToUpper(headerGuard) + "_H" tmpl, err := template.New("header").Parse(hFileContent) if err != nil { return "", err } var buf bytes.Buffer err = tmpl.Execute(&buf, TemplateData{ BaseName: hg.generator.BaseName, HeaderGuard: headerGuard, Constants: hg.generator.Constants, Classes: hg.generator.Classes, }) if err != nil { return "", err } return buf.String(), nil } ================================================ FILE: internal/extgen/hfile_test.go ================================================ package extgen import ( "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHeaderGenerator_Generate(t *testing.T) { tmpDir := t.TempDir() generator := &Generator{ BaseName: "test_extension", BuildDir: tmpDir, } headerGen := HeaderGenerator{generator} require.NoError(t, headerGen.generate()) expectedFile := filepath.Join(tmpDir, "test_extension.h") require.FileExists(t, expectedFile) content, err := readFile(expectedFile) require.NoError(t, err) testHeaderBasicStructure(t, content, "test_extension") testHeaderIncludeGuards(t, content, "TEST_EXTENSION_H") } func TestHeaderGenerator_BuildContent(t *testing.T) { tests := []struct { name string baseName string contains []string }{ { name: "simple extension", baseName: "simple", contains: []string{ "#ifndef _SIMPLE_H", "#define _SIMPLE_H", "#include ", "extern zend_module_entry simple_module_entry;", "#endif", }, }, { name: "extension with hyphens", baseName: "my-extension", contains: []string{ "#ifndef _MY_EXTENSION_H", "#define _MY_EXTENSION_H", "#endif", }, }, { name: "extension with underscores", baseName: "my_extension_name", contains: []string{ "#ifndef _MY_EXTENSION_NAME_H", "#define _MY_EXTENSION_NAME_H", "#endif", }, }, { name: "complex extension name", baseName: "complex.name-with_symbols", contains: []string{ "#ifndef _COMPLEX_NAME_WITH_SYMBOLS_H", "#define _COMPLEX_NAME_WITH_SYMBOLS_H", "#endif", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := &Generator{BaseName: tt.baseName} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) for _, expected := range tt.contains { assert.Contains(t, content, expected, "Generated header content should contain '%s'", expected) } }) } } func TestHeaderGenerator_HeaderGuardGeneration(t *testing.T) { tests := []struct { baseName string expectedGuard string }{ {"simple", "_SIMPLE_H"}, {"my-extension", "_MY_EXTENSION_H"}, {"complex.name", "_COMPLEX_NAME_H"}, {"under_score", "_UNDER_SCORE_H"}, {"MixedCase", "_MIXEDCASE_H"}, {"123numeric", "_123NUMERIC_H"}, {"special!@#chars", "_SPECIAL___CHARS_H"}, } for _, tt := range tests { t.Run(tt.baseName, func(t *testing.T) { generator := &Generator{BaseName: tt.baseName} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) expectedIfndef := "#ifndef " + tt.expectedGuard expectedDefine := "#define " + tt.expectedGuard assert.Contains(t, content, expectedIfndef, "Expected #ifndef %s, but not found in content", tt.expectedGuard) assert.Contains(t, content, expectedDefine, "Expected #define %s, but not found in content", tt.expectedGuard) }) } } func TestHeaderGenerator_BasicStructure(t *testing.T) { generator := &Generator{BaseName: "structtest"} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) expectedElements := []string{ "#include ", "extern zend_module_entry structtest_module_entry;", } for _, element := range expectedElements { assert.Contains(t, content, element, "Header should contain: %s", element) } } func TestHeaderGenerator_CompleteStructure(t *testing.T) { generator := &Generator{BaseName: "complete_test"} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) lines := strings.Split(content, "\n") assert.GreaterOrEqual(t, len(lines), 5, "Header file should have multiple lines") var foundIfndef, foundDefine, foundEndif bool for _, line := range lines { line = strings.TrimSpace(line) if line == "" { continue } if strings.HasPrefix(line, "#ifndef") && !foundIfndef { foundIfndef = true } else if strings.HasPrefix(line, "#define") && foundIfndef && !foundDefine { foundDefine = true } else if line == "#endif" { foundEndif = true } } assert.True(t, foundIfndef, "Header should start with #ifndef guard") assert.True(t, foundDefine, "Header should have #define after #ifndef") assert.True(t, foundEndif, "Header should end with #endif") } func TestHeaderGenerator_ErrorHandling(t *testing.T) { generator := &Generator{ BaseName: "test", BuildDir: "/invalid/readonly/path", } headerGen := HeaderGenerator{generator} err := headerGen.generate() assert.Error(t, err, "Expected error when writing to invalid directory") } func TestHeaderGenerator_EmptyBaseName(t *testing.T) { generator := &Generator{BaseName: ""} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) assert.Contains(t, content, "#ifndef __H", "Header with empty basename should have __H guard") assert.Contains(t, content, "#define __H", "Header with empty basename should have __H define") } func TestHeaderGenerator_ContentValidation(t *testing.T) { generator := &Generator{BaseName: "validation_test"} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) assert.Equal(t, 1, strings.Count(content, "#ifndef"), "Header should have exactly one #ifndef") assert.Equal(t, 1, strings.Count(content, "#define"), "Header should have exactly one #define") assert.Equal(t, 1, strings.Count(content, "#endif"), "Header should have exactly one #endif") assert.False(t, strings.Contains(content, "{{") || strings.Contains(content, "}}"), "Generated header contains unresolved template syntax") } func TestHeaderGenerator_SpecialCharacterHandling(t *testing.T) { tests := []struct { input string expected string }{ {"normal", "NORMAL"}, {"with-hyphens", "WITH_HYPHENS"}, {"with.dots", "WITH_DOTS"}, {"with_underscores", "WITH_UNDERSCORES"}, {"MixedCASE", "MIXEDCASE"}, {"123numbers", "123NUMBERS"}, {"special!@#$%", "SPECIAL_____"}, } for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { generator := &Generator{BaseName: tt.input} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) expectedGuard := "_" + tt.expected + "_H" expectedIfndef := "#ifndef " + expectedGuard expectedDefine := "#define " + expectedGuard assert.Contains(t, content, expectedIfndef, "Expected #ifndef %s for input %s", expectedGuard, tt.input) assert.Contains(t, content, expectedDefine, "Expected #define %s for input %s", expectedGuard, tt.input) }) } } func TestHeaderGenerator_TemplateErrorHandling(t *testing.T) { generator := &Generator{BaseName: "error_test"} headerGen := HeaderGenerator{generator} _, err := headerGen.buildContent() assert.NoError(t, err, "buildContent() should not fail with valid template") } func TestHeaderGenerator_GuardConsistency(t *testing.T) { baseName := "test_consistency" generator := &Generator{BaseName: baseName} headerGen := HeaderGenerator{generator} content1, err := headerGen.buildContent() require.NoError(t, err, "First buildContent() failed: %v", err) content2, err := headerGen.buildContent() require.NoError(t, err, "Second buildContent() failed: %v", err) assert.Equal(t, content1, content2, "Multiple calls to buildContent() should produce identical results") } func TestHeaderGenerator_MinimalContent(t *testing.T) { generator := &Generator{BaseName: "minimal"} headerGen := HeaderGenerator{generator} content, err := headerGen.buildContent() require.NoError(t, err) essentialElements := []string{ "#ifndef _MINIMAL_H", "#define _MINIMAL_H", "#include ", "extern zend_module_entry minimal_module_entry;", "#endif", } for _, element := range essentialElements { assert.Contains(t, content, element, "Minimal header should contain: %s", element) } } func testHeaderBasicStructure(t *testing.T, content, baseName string) { headerGuard := strings.Map(func(r rune) rune { if r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { return r } return '_' }, baseName) headerGuard = strings.ToUpper(headerGuard) + "_H" requiredElements := []string{ "#ifndef _" + headerGuard, "#define _" + headerGuard, "#include ", "extern zend_module_entry test_extension_module_entry;", "#endif", } for _, element := range requiredElements { assert.Contains(t, content, element, "Header file should contain: %s", element) } } func testHeaderIncludeGuards(t *testing.T, content, expectedGuard string) { expectedIfndef := "#ifndef _" + expectedGuard expectedDefine := "#define _" + expectedGuard assert.Contains(t, content, expectedIfndef, "Header should contain: %s", expectedIfndef) assert.Contains(t, content, expectedDefine, "Header should contain: %s", expectedDefine) assert.Contains(t, content, "#endif", "Header should end with #endif") ifndefPos := strings.Index(content, expectedIfndef) definePos := strings.Index(content, expectedDefine) assert.Less(t, ifndefPos, definePos, "#ifndef should come before #define") endifPos := strings.LastIndex(content, "#endif") assert.NotEqual(t, -1, endifPos, "Header should end with #endif") assert.Greater(t, endifPos, definePos, "#endif should come after #define") } ================================================ FILE: internal/extgen/integration_test.go ================================================ //go:build integration package extgen import ( "fmt" "os" "os/exec" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const ( testModuleName = "github.com/frankenphp/test-extension" ) type IntegrationTestSuite struct { tempDir string genStubScript string xcaddyPath string frankenphpPath string phpConfigPath string t *testing.T } func setupTest(t *testing.T) *IntegrationTestSuite { t.Helper() suite := &IntegrationTestSuite{t: t} suite.genStubScript = os.Getenv("GEN_STUB_SCRIPT") if suite.genStubScript == "" { suite.genStubScript = "/usr/local/src/php/build/gen_stub.php" } if _, err := os.Stat(suite.genStubScript); os.IsNotExist(err) { t.Error("GEN_STUB_SCRIPT not found. Integration tests require PHP sources. Set GEN_STUB_SCRIPT environment variable.") } xcaddyPath, err := exec.LookPath("xcaddy") if err != nil { t.Error("xcaddy not found in PATH. Integration tests require xcaddy to build FrankenPHP.") } suite.xcaddyPath = xcaddyPath phpConfigPath, err := exec.LookPath("php-config") if err != nil { t.Error("php-config not found in PATH. Integration tests require PHP development headers.") } suite.phpConfigPath = phpConfigPath tempDir := t.TempDir() suite.tempDir = tempDir return suite } func (s *IntegrationTestSuite) createGoModule(sourceFile string) (string, error) { s.t.Helper() moduleDir := filepath.Join(s.tempDir, "module") if err := os.MkdirAll(moduleDir, 0o755); err != nil { return "", fmt.Errorf("failed to create module directory: %w", err) } // Get project root for replace directive projectRoot, err := filepath.Abs(filepath.Join("..", "..")) if err != nil { return "", fmt.Errorf("failed to get project root: %w", err) } goModContent := fmt.Sprintf(`module %s go 1.26 require github.com/dunglas/frankenphp v0.0.0 replace github.com/dunglas/frankenphp => %s `, testModuleName, projectRoot) if err := os.WriteFile(filepath.Join(moduleDir, "go.mod"), []byte(goModContent), 0o644); err != nil { return "", fmt.Errorf("failed to create go.mod: %w", err) } sourceContent, err := os.ReadFile(sourceFile) if err != nil { return "", fmt.Errorf("failed to read source file: %w", err) } targetFile := filepath.Join(moduleDir, filepath.Base(sourceFile)) if err := os.WriteFile(targetFile, sourceContent, 0o644); err != nil { return "", fmt.Errorf("failed to write source file: %w", err) } return targetFile, nil } func (s *IntegrationTestSuite) runExtensionInit(sourceFile string) error { s.t.Helper() os.Setenv("GEN_STUB_SCRIPT", s.genStubScript) baseName := SanitizePackageName(strings.TrimSuffix(filepath.Base(sourceFile), ".go")) generator := Generator{ BaseName: baseName, SourceFile: sourceFile, BuildDir: filepath.Dir(sourceFile), } if err := generator.Generate(); err != nil { return fmt.Errorf("generation failed: %w", err) } return nil } // cleanupGeneratedFiles removes generated files from the original source directory func (s *IntegrationTestSuite) cleanupGeneratedFiles(originalSourceFile string) { s.t.Helper() sourceDir := filepath.Dir(originalSourceFile) baseName := SanitizePackageName(strings.TrimSuffix(filepath.Base(originalSourceFile), ".go")) generatedFiles := []string{ baseName + ".stub.php", baseName + "_arginfo.h", baseName + ".h", baseName + ".c", baseName + ".go", "README.md", } for _, file := range generatedFiles { fullPath := filepath.Join(sourceDir, file) if _, err := os.Stat(fullPath); err == nil { os.Remove(fullPath) } } } // compileFrankenPHP compiles FrankenPHP with the generated extension func (s *IntegrationTestSuite) compileFrankenPHP(moduleDir string) (string, error) { s.t.Helper() projectRoot, err := filepath.Abs(filepath.Join("..", "..")) if err != nil { return "", fmt.Errorf("failed to get project root: %w", err) } cflags, err := exec.Command(s.phpConfigPath, "--includes").Output() if err != nil { return "", fmt.Errorf("failed to get PHP includes: %w", err) } ldflags, err := exec.Command(s.phpConfigPath, "--ldflags").Output() if err != nil { return "", fmt.Errorf("failed to get PHP ldflags: %w", err) } libs, err := exec.Command(s.phpConfigPath, "--libs").Output() if err != nil { return "", fmt.Errorf("failed to get PHP libs: %w", err) } cgoCflags := strings.TrimSpace(string(cflags)) cgoLdflags := strings.TrimSpace(string(ldflags)) + " " + strings.TrimSpace(string(libs)) outputBinary := filepath.Join(s.tempDir, "frankenphp") cmd := exec.Command( s.xcaddyPath, "build", "--output", outputBinary, "--with", "github.com/dunglas/frankenphp="+projectRoot, "--with", "github.com/dunglas/frankenphp/caddy="+projectRoot+"/caddy", "--with", testModuleName+"="+moduleDir, ) cmd.Env = append(os.Environ(), "CGO_ENABLED=1", "CGO_CFLAGS="+cgoCflags, "CGO_LDFLAGS="+cgoLdflags, fmt.Sprintf("XCADDY_GO_BUILD_FLAGS=-ldflags='-w -s' -tags=nobadger,nomysql,nopgx,nowatcher"), ) cmd.Dir = s.tempDir output, err := cmd.CombinedOutput() if err != nil { return "", fmt.Errorf("xcaddy build failed: %w\nOutput: %s", err, string(output)) } s.frankenphpPath = outputBinary return outputBinary, nil } func (s *IntegrationTestSuite) runPHPCode(phpCode string) (string, error) { s.t.Helper() if s.frankenphpPath == "" { return "", fmt.Errorf("FrankenPHP not compiled yet") } phpFile := filepath.Join(s.tempDir, "test.php") if err := os.WriteFile(phpFile, []byte(phpCode), 0o644); err != nil { return "", fmt.Errorf("failed to create PHP file: %w", err) } cmd := exec.Command(s.frankenphpPath, "php-cli", phpFile) output, err := cmd.CombinedOutput() if err != nil { return "", fmt.Errorf("PHP execution failed: %w\nOutput: %s", err, string(output)) } return string(output), nil } // verifyPHPSymbols checks if PHP can find the exposed functions, classes, and constants func (s *IntegrationTestSuite) verifyPHPSymbols(functions []string, classes []string, constants []string) error { s.t.Helper() var checks []string for _, fn := range functions { checks = append(checks, fmt.Sprintf("if (!function_exists('%s')) { echo 'MISSING_FUNCTION: %s'; exit(1); }", fn, fn)) } for _, cls := range classes { checks = append(checks, fmt.Sprintf("if (!class_exists('%s')) { echo 'MISSING_CLASS: %s'; exit(1); }", cls, cls)) } for _, cnst := range constants { checks = append(checks, fmt.Sprintf("if (!defined('%s')) { echo 'MISSING_CONSTANT: %s'; exit(1); }", cnst, cnst)) } checks = append(checks, "echo 'OK';") phpCode := "getValue() !== 0) { echo "FAIL: Counter initial value expected 0, got " . $counter->getValue(); exit(1); } $counter->increment(); if ($counter->getValue() !== 1) { echo "FAIL: Counter after increment expected 1, got " . $counter->getValue(); exit(1); } $counter->decrement(); if ($counter->getValue() !== 0) { echo "FAIL: Counter after decrement expected 0, got " . $counter->getValue(); exit(1); } $counter->setValue(10); if ($counter->getValue() !== 10) { echo "FAIL: Counter after setValue(10) expected 10, got " . $counter->getValue(); exit(1); } $newValue = $counter->addValue(5); if ($newValue !== 15) { echo "FAIL: Counter addValue(5) expected to return 15, got $newValue"; exit(1); } if ($counter->getValue() !== 15) { echo "FAIL: Counter value after addValue(5) expected 15, got " . $counter->getValue(); exit(1); } $counter->updateWithNullable(50); if ($counter->getValue() !== 50) { echo "FAIL: Counter after updateWithNullable(50) expected 50, got " . $counter->getValue(); exit(1); } $counter->updateWithNullable(null); if ($counter->getValue() !== 50) { echo "FAIL: Counter after updateWithNullable(null) expected 50 (unchanged), got " . $counter->getValue(); exit(1); } $counter->reset(); if ($counter->getValue() !== 0) { echo "FAIL: Counter after reset expected 0, got " . $counter->getValue(); exit(1); } $counter1 = new Counter(); $counter2 = new Counter(); $counter1->setValue(100); $counter2->setValue(200); if ($counter1->getValue() !== 100 || $counter2->getValue() !== 200) { echo "FAIL: Multiple Counter instances should be independent"; exit(1); } $holder = new StringHolder(); $holder->setData("test string"); if ($holder->getData() !== "test string") { echo "FAIL: StringHolder getData expected 'test string', got '" . $holder->getData() . "'"; exit(1); } if ($holder->getLength() !== 11) { echo "FAIL: StringHolder getLength expected 11, got " . $holder->getLength(); exit(1); } $holder->setData(""); if ($holder->getData() !== "") { echo "FAIL: StringHolder empty string expected '', got '" . $holder->getData() . "'"; exit(1); } if ($holder->getLength() !== 0) { echo "FAIL: StringHolder empty string length expected 0, got " . $holder->getLength(); exit(1); } echo "OK"; `, "OK") require.NoError(t, err, "all class methods should work correctly") } func TestConstants(t *testing.T) { suite := setupTest(t) sourceFile := filepath.Join("..", "..", "testdata", "integration", "constants.go") sourceFile, err := filepath.Abs(sourceFile) require.NoError(t, err) defer suite.cleanupGeneratedFiles(sourceFile) targetFile, err := suite.createGoModule(sourceFile) require.NoError(t, err) err = suite.runExtensionInit(targetFile) require.NoError(t, err) _, err = suite.compileFrankenPHP(filepath.Dir(targetFile)) require.NoError(t, err) err = suite.verifyPHPSymbols( []string{"test_with_constants"}, []string{"Config"}, []string{ "TEST_MAX_RETRIES", "TEST_API_VERSION", "TEST_ENABLED", "TEST_PI", "STATUS_PENDING", "STATUS_PROCESSING", "STATUS_COMPLETED", "ONE", "TWO", }, ) require.NoError(t, err, "all constants, functions, and classes should be accessible from PHP") err = suite.verifyFunctionBehavior(` 0.00001) { echo "FAIL: TEST_PI expected 3.14159, got " . TEST_PI; exit(1); } if (Config::MODE_DEBUG !== 1) { echo "FAIL: Config::MODE_DEBUG expected 1, got " . Config::MODE_DEBUG; exit(1); } if (Config::MODE_PRODUCTION !== 2) { echo "FAIL: Config::MODE_PRODUCTION expected 2, got " . Config::MODE_PRODUCTION; exit(1); } if (Config::DEFAULT_TIMEOUT !== 30) { echo "FAIL: Config::DEFAULT_TIMEOUT expected 30, got " . Config::DEFAULT_TIMEOUT; exit(1); } $config = new Config(); $config->setMode(Config::MODE_DEBUG); if ($config->getMode() !== Config::MODE_DEBUG) { echo "FAIL: Config getMode expected MODE_DEBUG, got " . $config->getMode(); exit(1); } $result = test_with_constants(STATUS_PENDING); if ($result !== "pending") { echo "FAIL: test_with_constants(STATUS_PENDING) expected 'pending', got '$result'"; exit(1); } $result = test_with_constants(STATUS_PROCESSING); if ($result !== "processing") { echo "FAIL: test_with_constants(STATUS_PROCESSING) expected 'processing', got '$result'"; exit(1); } $result = test_with_constants(STATUS_COMPLETED); if ($result !== "completed") { echo "FAIL: test_with_constants(STATUS_COMPLETED) expected 'completed', got '$result'"; exit(1); } $result = test_with_constants(999); if ($result !== "unknown") { echo "FAIL: test_with_constants(999) expected 'unknown', got '$result'"; exit(1); } echo "OK"; `, "OK") require.NoError(t, err, "all constants should have correct values and functions should work") } func TestNamespace(t *testing.T) { suite := setupTest(t) sourceFile := filepath.Join("..", "..", "testdata", "integration", "namespace.go") sourceFile, err := filepath.Abs(sourceFile) require.NoError(t, err) defer suite.cleanupGeneratedFiles(sourceFile) targetFile, err := suite.createGoModule(sourceFile) require.NoError(t, err) err = suite.runExtensionInit(targetFile) require.NoError(t, err) _, err = suite.compileFrankenPHP(filepath.Dir(targetFile)) require.NoError(t, err) err = suite.verifyPHPSymbols( []string{`\\TestIntegration\\Extension\\greet`}, []string{`\\TestIntegration\\Extension\\Person`}, []string{`\\TestIntegration\\Extension\\NAMESPACE_VERSION`}, ) require.NoError(t, err, "all namespaced symbols should be accessible from PHP") err = suite.verifyFunctionBehavior(`setName("Bob"); $person->setAge(25); if ($person->getName() !== "Bob") { echo "FAIL: Person getName expected 'Bob', got '" . $person->getName() . "'"; exit(1); } if ($person->getAge() !== 25) { echo "FAIL: Person getAge expected 25, got " . $person->getAge(); exit(1); } $person->setAge(Extension\Person::DEFAULT_AGE); if ($person->getAge() !== 18) { echo "FAIL: Person setAge(DEFAULT_AGE) expected 18, got " . $person->getAge(); exit(1); } $person1 = new Extension\Person(); $person2 = new Extension\Person(); $person1->setName("Alice"); $person1->setAge(30); $person2->setName("Charlie"); $person2->setAge(40); if ($person1->getName() !== "Alice" || $person1->getAge() !== 30) { echo "FAIL: person1 should have independent state"; exit(1); } if ($person2->getName() !== "Charlie" || $person2->getAge() !== 40) { echo "FAIL: person2 should have independent state"; exit(1); } echo "OK"; `, "OK") require.NoError(t, err, "all namespaced symbols should work correctly") } func TestInvalidSignature(t *testing.T) { suite := setupTest(t) sourceFile := filepath.Join("..", "..", "testdata", "integration", "invalid_signature.go") sourceFile, err := filepath.Abs(sourceFile) require.NoError(t, err) defer suite.cleanupGeneratedFiles(sourceFile) targetFile, err := suite.createGoModule(sourceFile) require.NoError(t, err) err = suite.runExtensionInit(targetFile) assert.Error(t, err, "extension-init should fail for invalid return type") assert.Contains(t, err.Error(), "no PHP functions, classes, or constants found", "invalid functions should be ignored, resulting in no valid exports") } func TestTypeMismatch(t *testing.T) { suite := setupTest(t) sourceFile := filepath.Join("..", "..", "testdata", "integration", "type_mismatch.go") sourceFile, err := filepath.Abs(sourceFile) require.NoError(t, err) defer suite.cleanupGeneratedFiles(sourceFile) targetFile, err := suite.createGoModule(sourceFile) require.NoError(t, err) err = suite.runExtensionInit(targetFile) assert.NoError(t, err, "generation should succeed - class is valid even though function/method have type mismatches") baseDir := filepath.Dir(targetFile) baseName := strings.TrimSuffix(filepath.Base(targetFile), ".go") stubFile := filepath.Join(baseDir, baseName+".stub.php") assert.FileExists(t, stubFile, "stub file should be generated for valid class") } func TestMissingGenStub(t *testing.T) { // temp override of GEN_STUB_SCRIPT originalValue := os.Getenv("GEN_STUB_SCRIPT") defer os.Setenv("GEN_STUB_SCRIPT", originalValue) os.Setenv("GEN_STUB_SCRIPT", "/nonexistent/gen_stub.php") tempDir := t.TempDir() sourceFile := filepath.Join(tempDir, "test.go") err := os.WriteFile(sourceFile, []byte(`package test //export_php:function dummy(): void func dummy() {} `), 0o644) require.NoError(t, err) baseName := SanitizePackageName(strings.TrimSuffix(filepath.Base(sourceFile), ".go")) gen := Generator{ BaseName: baseName, SourceFile: sourceFile, BuildDir: filepath.Dir(sourceFile), } err = gen.Generate() assert.Error(t, err, "should fail when gen_stub.php is missing") assert.Contains(t, err.Error(), "gen_stub.php", "error should mention missing script") } func TestCallable(t *testing.T) { suite := setupTest(t) sourceFile := filepath.Join("..", "..", "testdata", "integration", "callable.go") sourceFile, err := filepath.Abs(sourceFile) require.NoError(t, err) defer suite.cleanupGeneratedFiles(sourceFile) targetFile, err := suite.createGoModule(sourceFile) require.NoError(t, err) err = suite.runExtensionInit(targetFile) require.NoError(t, err) _, err = suite.compileFrankenPHP(filepath.Dir(targetFile)) require.NoError(t, err) err = suite.verifyPHPSymbols( []string{"my_array_map", "my_filter"}, []string{"Processor"}, []string{}, ) require.NoError(t, err, "all functions and classes should be accessible from PHP") err = suite.verifyFunctionBehavior(`transform('hello', function($s) { return strtoupper($s); }); if ($result !== 'HELLO') { echo "FAIL: Processor::transform with closure expected 'HELLO', got '$result'"; exit(1); } $result = $processor->transform('world', 'strtoupper'); if ($result !== 'WORLD') { echo "FAIL: Processor::transform with function name expected 'WORLD', got '$result'"; exit(1); } $result = $processor->transform(' test ', 'trim'); if ($result !== 'test') { echo "FAIL: Processor::transform with trim expected 'test', got '$result'"; exit(1); } echo "OK"; `, "OK") require.NoError(t, err, "all callable tests should pass") } ================================================ FILE: internal/extgen/namespace_test.go ================================================ package extgen import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNamespaceParser(t *testing.T) { tests := []struct { name string content string expected string shouldError bool }{ { name: "basic namespace", content: `package main //export_php:namespace My\Test\Namespace func main() {}`, expected: `My\Test\Namespace`, }, { name: "namespace with spaces", content: `package main //export_php:namespace My\Test\Namespace func main() {}`, expected: `My\Test\Namespace`, }, { name: "no namespace", content: `package main func main() {}`, expected: "", }, { name: "multiple namespaces should error", content: `package main //export_php:namespace First\Namespace //export_php:namespace Second\Namespace func main() {}`, expected: "", shouldError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tmpfile, err := os.CreateTemp("", "test_namespace_*.go") require.NoError(t, err, "Failed to create temp file") defer func() { err := os.Remove(tmpfile.Name()) assert.NoError(t, err, "Failed to remove temp file: %v", err) }() _, err = tmpfile.Write([]byte(tt.content)) require.NoError(t, err, "Failed to write to temp file") err = tmpfile.Close() require.NoError(t, err, "Failed to close temp file") parser := NamespaceParser{} result, err := parser.parse(tmpfile.Name()) if tt.shouldError { require.Error(t, err, "expected error but got none") return } require.NoError(t, err, "unexpected error") require.Equal(t, tt.expected, result, "expected %q, got %q", tt.expected, result) }) } } func TestGeneratorWithNamespace(t *testing.T) { content := `package main //export_php:namespace My\Test\Namespace //export_php:function hello(): string func hello() string { return "Hello from namespace!" } //export_php:constant TEST_CONSTANT = "test_value" const TEST_CONSTANT = "test_value" ` tmpfile, err := os.CreateTemp("", "test_generator_namespace_*.go") require.NoError(t, err, "Failed to create temp file") defer func() { if err := os.Remove(tmpfile.Name()); err != nil { t.Logf("Failed to remove temp file: %v", err) } }() _, err = tmpfile.Write([]byte(content)) require.NoError(t, err, "Failed to write to temp file") err = tmpfile.Close() require.NoError(t, err, "Failed to close temp file") parser := SourceParser{} namespace, err := parser.ParseNamespace(tmpfile.Name()) require.NoErrorf(t, err, "Failed to parse namespace from %s: %v", tmpfile.Name(), err) require.Equal(t, `My\Test\Namespace`, namespace, "Namespace should match the parsed namespace") generator := &Generator{ SourceFile: tmpfile.Name(), Namespace: namespace, } require.Equal(t, `My\Test\Namespace`, generator.Namespace, "Namespace should match the parsed namespace") } ================================================ FILE: internal/extgen/nodes.go ================================================ package extgen import ( "strconv" "strings" ) // phpType represents a PHP type type phpType string const ( phpString phpType = "string" phpInt phpType = "int" phpFloat phpType = "float" phpBool phpType = "bool" phpArray phpType = "array" phpObject phpType = "object" phpMixed phpType = "mixed" phpVoid phpType = "void" phpNull phpType = "null" phpTrue phpType = "true" phpFalse phpType = "false" phpCallable phpType = "callable" ) type phpFunction struct { Name string Signature string GoFunction string Params []phpParameter ReturnType phpType IsReturnNullable bool lineNumber int } type phpParameter struct { Name string PhpType phpType IsNullable bool DefaultValue string HasDefault bool } type phpClass struct { Name string GoStruct string Properties []phpClassProperty Methods []phpClassMethod } type phpClassMethod struct { Name string PhpName string Signature string GoFunction string Wrapper string Params []phpParameter ReturnType phpType isReturnNullable bool lineNumber int ClassName string // used by the "//export_php:method" directive } type phpClassProperty struct { Name string PhpType phpType GoType string IsNullable bool } type phpConstant struct { Name string Value string PhpType phpType IsIota bool lineNumber int ClassName string // empty for global constants, set for class constants } // CValue returns the constant value in C-compatible format func (c phpConstant) CValue() string { if c.PhpType != phpInt { return c.Value } if strings.HasPrefix(c.Value, "0o") { if val, err := strconv.ParseInt(c.Value, 0, 64); err == nil { return strconv.FormatInt(val, 10) } } return c.Value } ================================================ FILE: internal/extgen/nsparser.go ================================================ package extgen import ( "bufio" "fmt" "os" "regexp" "strings" ) type NamespaceParser struct{} var namespaceRegex = regexp.MustCompile(`//\s*export_php:namespace\s+(.+)`) func (np *NamespaceParser) parse(filename string) (string, error) { file, err := os.Open(filename) if err != nil { return "", err } defer func() { if err := file.Close(); err != nil { fmt.Printf("Error closing file %s: %v\n", filename, err) } }() var foundNamespace string var lineNumber int var foundLineNumber int scanner := bufio.NewScanner(file) for scanner.Scan() { lineNumber++ line := strings.TrimSpace(scanner.Text()) if matches := namespaceRegex.FindStringSubmatch(line); matches != nil { namespace := strings.TrimSpace(matches[1]) if foundNamespace != "" { return "", fmt.Errorf("multiple namespace declarations found: first at line %d, second at line %d", foundLineNumber, lineNumber) } foundNamespace = namespace foundLineNumber = lineNumber } } return foundNamespace, scanner.Err() } ================================================ FILE: internal/extgen/paramparser.go ================================================ package extgen import ( "fmt" "strings" ) type ParameterParser struct{} type ParameterInfo struct { RequiredCount int TotalCount int } func (pp *ParameterParser) analyzeParameters(params []phpParameter) ParameterInfo { info := ParameterInfo{TotalCount: len(params)} for _, param := range params { if !param.HasDefault { info.RequiredCount++ } } return info } func (pp *ParameterParser) generateParamDeclarations(params []phpParameter) string { if len(params) == 0 { return "" } var declarations []string for _, param := range params { declarations = append(declarations, pp.generateSingleParamDeclaration(param)...) } return " " + strings.Join(declarations, "\n ") } func (pp *ParameterParser) generateSingleParamDeclaration(param phpParameter) []string { var decls []string switch param.PhpType { case phpString: decls = append(decls, fmt.Sprintf("zend_string *%s = NULL;", param.Name)) if param.IsNullable { decls = append(decls, fmt.Sprintf("zend_bool %s_is_null = 0;", param.Name)) } case phpInt: defaultVal := pp.getDefaultValue(param, "0") decls = append(decls, fmt.Sprintf("zend_long %s = %s;", param.Name, defaultVal)) if param.IsNullable { decls = append(decls, fmt.Sprintf("zend_bool %s_is_null = 0;", param.Name)) } case phpFloat: defaultVal := pp.getDefaultValue(param, "0.0") decls = append(decls, fmt.Sprintf("double %s = %s;", param.Name, defaultVal)) if param.IsNullable { decls = append(decls, fmt.Sprintf("zend_bool %s_is_null = 0;", param.Name)) } case phpBool: defaultVal := pp.getDefaultValue(param, "0") if param.HasDefault && param.DefaultValue == "true" { defaultVal = "1" } decls = append(decls, fmt.Sprintf("zend_bool %s = %s;", param.Name, defaultVal)) if param.IsNullable { decls = append(decls, fmt.Sprintf("zend_bool %s_is_null = 0;", param.Name)) } case phpArray: decls = append(decls, fmt.Sprintf("zend_array *%s = NULL;", param.Name)) case phpMixed: decls = append(decls, fmt.Sprintf("zval *%s = NULL;", param.Name)) case "callable": decls = append(decls, fmt.Sprintf("zval *%s_callback;", param.Name)) } return decls } func (pp *ParameterParser) getDefaultValue(param phpParameter, fallback string) string { if !param.HasDefault || param.DefaultValue == "" { return fallback } return param.DefaultValue } func (pp *ParameterParser) generateParamParsing(params []phpParameter, requiredCount int) string { if len(params) == 0 { return ` ZEND_PARSE_PARAMETERS_NONE();` } var builder strings.Builder _, _ = fmt.Fprintf(&builder, " ZEND_PARSE_PARAMETERS_START(%d, %d)", requiredCount, len(params)) optionalStarted := false for _, param := range params { if param.HasDefault && !optionalStarted { builder.WriteString("\n Z_PARAM_OPTIONAL") optionalStarted = true } builder.WriteString(pp.generateParamParsingMacro(param)) } builder.WriteString("\n ZEND_PARSE_PARAMETERS_END();") return builder.String() } func (pp *ParameterParser) generateParamParsingMacro(param phpParameter) string { if param.IsNullable { switch param.PhpType { case phpString: return fmt.Sprintf("\n Z_PARAM_STR_OR_NULL(%s, %s_is_null)", param.Name, param.Name) case phpInt: return fmt.Sprintf("\n Z_PARAM_LONG_OR_NULL(%s, %s_is_null)", param.Name, param.Name) case phpFloat: return fmt.Sprintf("\n Z_PARAM_DOUBLE_OR_NULL(%s, %s_is_null)", param.Name, param.Name) case phpBool: return fmt.Sprintf("\n Z_PARAM_BOOL_OR_NULL(%s, %s_is_null)", param.Name, param.Name) case phpArray: return fmt.Sprintf("\n Z_PARAM_ARRAY_HT_OR_NULL(%s)", param.Name) case phpMixed: return fmt.Sprintf("\n Z_PARAM_ZVAL_OR_NULL(%s)", param.Name) case phpCallable: return fmt.Sprintf("\n Z_PARAM_ZVAL_OR_NULL(%s_callback)", param.Name) default: return "" } } else { switch param.PhpType { case phpString: return fmt.Sprintf("\n Z_PARAM_STR(%s)", param.Name) case phpInt: return fmt.Sprintf("\n Z_PARAM_LONG(%s)", param.Name) case phpFloat: return fmt.Sprintf("\n Z_PARAM_DOUBLE(%s)", param.Name) case phpBool: return fmt.Sprintf("\n Z_PARAM_BOOL(%s)", param.Name) case phpArray: return fmt.Sprintf("\n Z_PARAM_ARRAY_HT(%s)", param.Name) case phpMixed: return fmt.Sprintf("\n Z_PARAM_ZVAL(%s)", param.Name) case phpCallable: return fmt.Sprintf("\n Z_PARAM_ZVAL(%s_callback)", param.Name) default: return "" } } } func (pp *ParameterParser) generateGoCallParams(params []phpParameter) string { if len(params) == 0 { return "" } var goParams []string for _, param := range params { goParams = append(goParams, pp.generateSingleGoCallParam(param)) } return strings.Join(goParams, ", ") } func (pp *ParameterParser) generateSingleGoCallParam(param phpParameter) string { if param.IsNullable { switch param.PhpType { case phpString: return fmt.Sprintf("%s_is_null ? NULL : %s", param.Name, param.Name) case phpInt: return fmt.Sprintf("%s_is_null ? NULL : &%s", param.Name, param.Name) case phpFloat: return fmt.Sprintf("%s_is_null ? NULL : &%s", param.Name, param.Name) case phpBool: return fmt.Sprintf("%s_is_null ? NULL : &%s", param.Name, param.Name) case phpCallable: return fmt.Sprintf("%s_callback", param.Name) default: return param.Name } } switch param.PhpType { case phpInt: return fmt.Sprintf("(long) %s", param.Name) case phpFloat: return fmt.Sprintf("(double) %s", param.Name) case phpBool: return fmt.Sprintf("(int) %s", param.Name) case phpCallable: return fmt.Sprintf("%s_callback", param.Name) default: return param.Name } } ================================================ FILE: internal/extgen/paramparser_test.go ================================================ package extgen import ( "testing" "github.com/stretchr/testify/assert" ) func TestParameterParser_AnalyzeParameters(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string params []phpParameter expected ParameterInfo }{ { name: "no parameters", params: []phpParameter{}, expected: ParameterInfo{ RequiredCount: 0, TotalCount: 0, }, }, { name: "all required parameters", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: false}, }, expected: ParameterInfo{ RequiredCount: 2, TotalCount: 2, }, }, { name: "mixed required and optional parameters", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, {Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, }, expected: ParameterInfo{ RequiredCount: 1, TotalCount: 3, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.analyzeParameters(tt.params) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateParamDeclarations(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string params []phpParameter expected string }{ { name: "no parameters", params: []phpParameter{}, expected: "", }, { name: "string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString, HasDefault: false}, }, expected: " zend_string *message = NULL;", }, { name: "nullable string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString, HasDefault: false, IsNullable: true}, }, expected: " zend_string *message = NULL;\n zend_bool message_is_null = 0;", }, { name: "int parameter with default", params: []phpParameter{ {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "42"}, }, expected: " zend_long count = 42;", }, { name: "nullable int parameter", params: []phpParameter{ {Name: "count", PhpType: phpInt, HasDefault: false, IsNullable: true}, }, expected: " zend_long count = 0;\n zend_bool count_is_null = 0;", }, { name: "bool parameter with true default", params: []phpParameter{ {Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, }, expected: " zend_bool enabled = 1;", }, { name: "nullable bool parameter", params: []phpParameter{ {Name: "enabled", PhpType: phpBool, HasDefault: false, IsNullable: true}, }, expected: " zend_bool enabled = 0;\n zend_bool enabled_is_null = 0;", }, { name: "float parameter", params: []phpParameter{ {Name: "ratio", PhpType: phpFloat, HasDefault: false}, }, expected: " double ratio = 0.0;", }, { name: "nullable float parameter", params: []phpParameter{ {Name: "ratio", PhpType: phpFloat, HasDefault: false, IsNullable: true}, }, expected: " double ratio = 0.0;\n zend_bool ratio_is_null = 0;", }, { name: "multiple parameters", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, }, expected: " zend_string *name = NULL;\n zend_long count = 10;", }, { name: "mixed nullable and non-nullable parameters", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false, IsNullable: false}, {Name: "count", PhpType: phpInt, HasDefault: false, IsNullable: true}, }, expected: " zend_string *name = NULL;\n zend_long count = 0;\n zend_bool count_is_null = 0;", }, { name: "array parameter", params: []phpParameter{ {Name: "items", PhpType: phpArray, HasDefault: false}, }, expected: " zend_array *items = NULL;", }, { name: "nullable array parameter", params: []phpParameter{ {Name: "items", PhpType: phpArray, HasDefault: false, IsNullable: true}, }, expected: " zend_array *items = NULL;", }, { name: "mixed types with array", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "items", PhpType: phpArray, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "5"}, }, expected: " zend_string *name = NULL;\n zend_array *items = NULL;\n zend_long count = 5;", }, { name: "mixed parameter", params: []phpParameter{ {Name: "m", PhpType: phpMixed, HasDefault: false}, }, expected: " zval *m = NULL;", }, { name: "nullable mixed parameter", params: []phpParameter{ {Name: "m", PhpType: phpMixed, HasDefault: false, IsNullable: true}, }, expected: " zval *m = NULL;", }, { name: "callable parameter", params: []phpParameter{ {Name: "callback", PhpType: phpCallable, HasDefault: false}, }, expected: " zval *callback_callback;", }, { name: "nullable callable parameter", params: []phpParameter{ {Name: "callback", PhpType: phpCallable, HasDefault: false, IsNullable: true}, }, expected: " zval *callback_callback;", }, { name: "mixed types with callable", params: []phpParameter{ {Name: "data", PhpType: phpArray, HasDefault: false}, {Name: "callback", PhpType: phpCallable, HasDefault: false}, {Name: "options", PhpType: phpInt, HasDefault: true, DefaultValue: "0"}, }, expected: " zend_array *data = NULL;\n zval *callback_callback;\n zend_long options = 0;", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateParamDeclarations(tt.params) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateParamParsing(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string params []phpParameter requiredCount int expected string }{ { name: "no parameters", params: []phpParameter{}, requiredCount: 0, expected: ` ZEND_PARSE_PARAMETERS_NONE();`, }, { name: "single required string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString, HasDefault: false}, }, requiredCount: 1, expected: ` ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(message) ZEND_PARSE_PARAMETERS_END();`, }, { name: "mixed required and optional parameters", params: []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, {Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, }, requiredCount: 1, expected: ` ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_STR(name) Z_PARAM_OPTIONAL Z_PARAM_LONG(count) Z_PARAM_BOOL(enabled) ZEND_PARSE_PARAMETERS_END();`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateParamParsing(tt.params, tt.requiredCount) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateGoCallParams(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string params []phpParameter expected string }{ { name: "no parameters", params: []phpParameter{}, expected: "", }, { name: "single string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString}, }, expected: "message", }, { name: "multiple parameters of different types", params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "count", PhpType: phpInt}, {Name: "ratio", PhpType: phpFloat}, {Name: "enabled", PhpType: phpBool}, }, expected: "name, (long) count, (double) ratio, (int) enabled", }, { name: "array parameter", params: []phpParameter{ {Name: "items", PhpType: phpArray}, }, expected: "items", }, { name: "nullable array parameter", params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: true}, }, expected: "items", }, { name: "mixed parameters with array", params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "items", PhpType: phpArray}, {Name: "count", PhpType: phpInt}, }, expected: "name, items, (long) count", }, { name: "callable parameter", params: []phpParameter{ {Name: "callback", PhpType: "callable"}, }, expected: "callback_callback", }, { name: "nullable callable parameter", params: []phpParameter{ {Name: "callback", PhpType: "callable", IsNullable: true}, }, expected: "callback_callback", }, { name: "mixed parameters with callable", params: []phpParameter{ {Name: "data", PhpType: "array"}, {Name: "callback", PhpType: "callable"}, {Name: "limit", PhpType: "int"}, }, expected: "data, callback_callback, (long) limit", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateGoCallParams(tt.params) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateParamParsingMacro(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string param phpParameter expected string }{ { name: "string parameter", param: phpParameter{Name: "message", PhpType: phpString}, expected: "\n Z_PARAM_STR(message)", }, { name: "nullable string parameter", param: phpParameter{Name: "message", PhpType: phpString, IsNullable: true}, expected: "\n Z_PARAM_STR_OR_NULL(message, message_is_null)", }, { name: "int parameter", param: phpParameter{Name: "count", PhpType: phpInt}, expected: "\n Z_PARAM_LONG(count)", }, { name: "nullable int parameter", param: phpParameter{Name: "count", PhpType: phpInt, IsNullable: true}, expected: "\n Z_PARAM_LONG_OR_NULL(count, count_is_null)", }, { name: "float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat}, expected: "\n Z_PARAM_DOUBLE(ratio)", }, { name: "nullable float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat, IsNullable: true}, expected: "\n Z_PARAM_DOUBLE_OR_NULL(ratio, ratio_is_null)", }, { name: "bool parameter", param: phpParameter{Name: "enabled", PhpType: phpBool}, expected: "\n Z_PARAM_BOOL(enabled)", }, { name: "nullable bool parameter", param: phpParameter{Name: "enabled", PhpType: phpBool, IsNullable: true}, expected: "\n Z_PARAM_BOOL_OR_NULL(enabled, enabled_is_null)", }, { name: "array parameter", param: phpParameter{Name: "items", PhpType: phpArray}, expected: "\n Z_PARAM_ARRAY_HT(items)", }, { name: "nullable array parameter", param: phpParameter{Name: "items", PhpType: phpArray, IsNullable: true}, expected: "\n Z_PARAM_ARRAY_HT_OR_NULL(items)", }, { name: "mixed parameter", param: phpParameter{Name: "m", PhpType: phpMixed}, expected: "\n Z_PARAM_ZVAL(m)", }, { name: "nullable mixed parameter", param: phpParameter{Name: "m", PhpType: phpMixed, IsNullable: true}, expected: "\n Z_PARAM_ZVAL_OR_NULL(m)", }, { name: "callable parameter", param: phpParameter{Name: "callback", PhpType: phpCallable}, expected: "\n Z_PARAM_ZVAL(callback_callback)", }, { name: "nullable callable parameter", param: phpParameter{Name: "callback", PhpType: phpCallable, IsNullable: true}, expected: "\n Z_PARAM_ZVAL_OR_NULL(callback_callback)", }, { name: "unknown type", param: phpParameter{Name: "unknown", PhpType: phpType("unknown")}, expected: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateParamParsingMacro(tt.param) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GetDefaultValue(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string param phpParameter fallback string expected string }{ { name: "parameter without default", param: phpParameter{Name: "count", PhpType: phpInt, HasDefault: false}, fallback: "0", expected: "0", }, { name: "parameter with default value", param: phpParameter{Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "42"}, fallback: "0", expected: "42", }, { name: "parameter with empty default value", param: phpParameter{Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: ""}, fallback: "0", expected: "0", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.getDefaultValue(tt.param, tt.fallback) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateSingleGoCallParam(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string param phpParameter expected string }{ { name: "string parameter", param: phpParameter{Name: "message", PhpType: phpString}, expected: "message", }, { name: "nullable string parameter", param: phpParameter{Name: "message", PhpType: phpString, IsNullable: true}, expected: "message_is_null ? NULL : message", }, { name: "int parameter", param: phpParameter{Name: "count", PhpType: phpInt}, expected: "(long) count", }, { name: "nullable int parameter", param: phpParameter{Name: "count", PhpType: phpInt, IsNullable: true}, expected: "count_is_null ? NULL : &count", }, { name: "float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat}, expected: "(double) ratio", }, { name: "nullable float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat, IsNullable: true}, expected: "ratio_is_null ? NULL : &ratio", }, { name: "bool parameter", param: phpParameter{Name: "enabled", PhpType: phpBool}, expected: "(int) enabled", }, { name: "nullable bool parameter", param: phpParameter{Name: "enabled", PhpType: phpBool, IsNullable: true}, expected: "enabled_is_null ? NULL : &enabled", }, { name: "array parameter", param: phpParameter{Name: "items", PhpType: phpArray}, expected: "items", }, { name: "nullable array parameter", param: phpParameter{Name: "items", PhpType: phpArray, IsNullable: true}, expected: "items", }, { name: "callable parameter", param: phpParameter{Name: "callback", PhpType: "callable"}, expected: "callback_callback", }, { name: "nullable callable parameter", param: phpParameter{Name: "callback", PhpType: "callable", IsNullable: true}, expected: "callback_callback", }, { name: "unknown type", param: phpParameter{Name: "unknown", PhpType: phpType("unknown")}, expected: "unknown", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateSingleGoCallParam(tt.param) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_GenerateSingleParamDeclaration(t *testing.T) { pp := &ParameterParser{} tests := []struct { name string param phpParameter expected []string }{ { name: "string parameter", param: phpParameter{Name: "message", PhpType: phpString, HasDefault: false}, expected: []string{"zend_string *message = NULL;"}, }, { name: "nullable string parameter", param: phpParameter{Name: "message", PhpType: phpString, HasDefault: false, IsNullable: true}, expected: []string{"zend_string *message = NULL;", "zend_bool message_is_null = 0;"}, }, { name: "int parameter with default", param: phpParameter{Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "42"}, expected: []string{"zend_long count = 42;"}, }, { name: "nullable int parameter", param: phpParameter{Name: "count", PhpType: phpInt, HasDefault: false, IsNullable: true}, expected: []string{"zend_long count = 0;", "zend_bool count_is_null = 0;"}, }, { name: "bool parameter with true default", param: phpParameter{Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, expected: []string{"zend_bool enabled = 1;"}, }, { name: "nullable bool parameter", param: phpParameter{Name: "enabled", PhpType: phpBool, HasDefault: false, IsNullable: true}, expected: []string{"zend_bool enabled = 0;", "zend_bool enabled_is_null = 0;"}, }, { name: "bool parameter with false default", param: phpParameter{Name: "disabled", PhpType: phpBool, HasDefault: true, DefaultValue: "false"}, expected: []string{"zend_bool disabled = false;"}, }, { name: "float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat, HasDefault: false}, expected: []string{"double ratio = 0.0;"}, }, { name: "nullable float parameter", param: phpParameter{Name: "ratio", PhpType: phpFloat, HasDefault: false, IsNullable: true}, expected: []string{"double ratio = 0.0;", "zend_bool ratio_is_null = 0;"}, }, { name: "array parameter", param: phpParameter{Name: "items", PhpType: phpArray, HasDefault: false}, expected: []string{"zend_array *items = NULL;"}, }, { name: "nullable array parameter", param: phpParameter{Name: "items", PhpType: phpArray, HasDefault: false, IsNullable: true}, expected: []string{"zend_array *items = NULL;"}, }, { name: "callable parameter", param: phpParameter{Name: "callback", PhpType: "callable", HasDefault: false}, expected: []string{"zval *callback_callback;"}, }, { name: "nullable callable parameter", param: phpParameter{Name: "callback", PhpType: "callable", HasDefault: false, IsNullable: true}, expected: []string{"zval *callback_callback;"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := pp.generateSingleParamDeclaration(tt.param) assert.Equal(t, tt.expected, result) }) } } func TestParameterParser_Integration(t *testing.T) { pp := &ParameterParser{} params := []phpParameter{ {Name: "name", PhpType: phpString, HasDefault: false}, {Name: "count", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, {Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, } info := pp.analyzeParameters(params) assert.Equal(t, 1, info.RequiredCount) assert.Equal(t, 3, info.TotalCount) declarations := pp.generateParamDeclarations(params) expectedDeclarations := []string{ "zend_string *name = NULL;", "zend_long count = 10;", "zend_bool enabled = 1;", } for _, expected := range expectedDeclarations { assert.Contains(t, declarations, expected) } parsing := pp.generateParamParsing(params, info.RequiredCount) assert.Contains(t, parsing, "ZEND_PARSE_PARAMETERS_START(1, 3)") assert.Contains(t, parsing, "Z_PARAM_OPTIONAL") goCallParams := pp.generateGoCallParams(params) assert.Equal(t, "name, (long) count, (int) enabled", goCallParams) } ================================================ FILE: internal/extgen/parser.go ================================================ package extgen type SourceParser struct{} // EXPERIMENTAL func (p *SourceParser) ParseFunctions(filename string) ([]phpFunction, error) { functionParser := &FuncParser{} return functionParser.parse(filename) } // EXPERIMENTAL func (p *SourceParser) ParseClasses(filename string) ([]phpClass, error) { classParser := classParser{} return classParser.parse(filename) } // EXPERIMENTAL func (p *SourceParser) ParseConstants(filename string) ([]phpConstant, error) { constantParser := &ConstantParser{} return constantParser.parse(filename) } // EXPERIMENTAL func (p *SourceParser) ParseNamespace(filename string) (string, error) { namespaceParser := NamespaceParser{} return namespaceParser.parse(filename) } ================================================ FILE: internal/extgen/phpfunc.go ================================================ package extgen import ( "fmt" "strings" ) type PHPFuncGenerator struct { paramParser *ParameterParser namespace string } func (pfg *PHPFuncGenerator) generate(fn phpFunction) string { var builder strings.Builder paramInfo := pfg.paramParser.analyzeParameters(fn.Params) funcName := NamespacedName(pfg.namespace, fn.Name) _, _ = fmt.Fprintf(&builder, "PHP_FUNCTION(%s)\n{\n", funcName) if decl := pfg.paramParser.generateParamDeclarations(fn.Params); decl != "" { builder.WriteString(decl + "\n") } builder.WriteString(pfg.paramParser.generateParamParsing(fn.Params, paramInfo.RequiredCount) + "\n") builder.WriteString(pfg.generateGoCall(fn) + "\n") if returnCode := pfg.generateReturnCode(fn.ReturnType); returnCode != "" { builder.WriteString(returnCode + "\n") } builder.WriteString("}\n\n") return builder.String() } func (pfg *PHPFuncGenerator) generateGoCall(fn phpFunction) string { callParams := pfg.paramParser.generateGoCallParams(fn.Params) goFuncName := "go_" + fn.Name if fn.ReturnType == phpVoid { return fmt.Sprintf(" %s(%s);", goFuncName, callParams) } if fn.ReturnType == phpString { return fmt.Sprintf(" zend_string *result = %s(%s);", goFuncName, callParams) } if fn.ReturnType == phpArray { return fmt.Sprintf(" zend_array *result = %s(%s);", goFuncName, callParams) } if fn.ReturnType == phpMixed { return fmt.Sprintf(" zval *result = %s(%s);", goFuncName, callParams) } return fmt.Sprintf(" %s result = %s(%s);", pfg.getCReturnType(fn.ReturnType), goFuncName, callParams) } func (pfg *PHPFuncGenerator) getCReturnType(returnType phpType) string { switch returnType { case phpInt: return "long" case phpFloat: return "double" case phpBool: return "int" default: return "void" } } func (pfg *PHPFuncGenerator) generateReturnCode(returnType phpType) string { switch returnType { case phpString: return ` if (result) { RETURN_STR(result); } RETURN_EMPTY_STRING();` case phpInt: return ` RETURN_LONG(result);` case phpFloat: return ` RETURN_DOUBLE(result);` case phpBool: return ` RETURN_BOOL(result);` case phpArray: return ` if (result) { RETURN_ARR(result); } RETURN_EMPTY_ARRAY();` default: return "" } } ================================================ FILE: internal/extgen/phpfunc_namespace_test.go ================================================ package extgen import ( "testing" "github.com/stretchr/testify/require" ) func TestPHPFuncGenerator_NamespacedFunctions(t *testing.T) { tests := []struct { name string namespace string function phpFunction expected string }{ { name: "no namespace", namespace: "", function: phpFunction{Name: "test_func", ReturnType: "int"}, expected: "PHP_FUNCTION(test_func)", }, { name: "single level namespace", namespace: "MyNamespace", function: phpFunction{Name: "test_func", ReturnType: "int"}, expected: "PHP_FUNCTION(MyNamespace_test_func)", }, { name: "multi level namespace", namespace: `Go\Extension`, function: phpFunction{Name: "multiply", ReturnType: "int"}, expected: "PHP_FUNCTION(Go_Extension_multiply)", }, { name: "deep namespace", namespace: `My\Deep\Nested\Namespace`, function: phpFunction{Name: "is_even", ReturnType: "bool"}, expected: "PHP_FUNCTION(My_Deep_Nested_Namespace_is_even)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { generator := PHPFuncGenerator{ paramParser: &ParameterParser{}, namespace: tt.namespace, } result := generator.generate(tt.function) require.Contains(t, result, tt.expected, "Expected to find %q in generated PHP code, but didn't.\nGenerated:\n%s", tt.expected, result) }) } } func TestGetNamespacedFunctionName(t *testing.T) { tests := []struct { name string namespace string functionName string expected string }{ { name: "no namespace", namespace: "", functionName: "test_func", expected: "test_func", }, { name: "single level namespace", namespace: "MyNamespace", functionName: "test_func", expected: "MyNamespace_test_func", }, { name: "multi level namespace", namespace: `Go\Extension`, functionName: "multiply", expected: "Go_Extension_multiply", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := NamespacedName(tt.namespace, tt.functionName) require.Equal(t, tt.expected, result, "Expected %q, got %q", tt.expected, result) }) } } func TestCFileWithNamespacedPHPFunctions(t *testing.T) { generator := &Generator{ BaseName: "test_extension", Namespace: `Go\Extension`, Functions: []phpFunction{ { Name: "multiply", ReturnType: "int", Params: []phpParameter{ {Name: "a", PhpType: "int"}, {Name: "b", PhpType: "int"}, }, }, { Name: "is_even", ReturnType: "bool", Params: []phpParameter{ {Name: "num", PhpType: "int"}, }, }, }, Classes: []phpClass{ { Name: "MySuperClass", GoStruct: "MySuperClass", Methods: []phpClassMethod{ { Name: "getName", PhpName: "getName", ReturnType: "string", ClassName: "MySuperClass", }, }, }, }, BuildDir: t.TempDir(), } cFileGen := cFileGenerator{generator: generator} content, err := cFileGen.buildContent() require.NoError(t, err, "error generating C file") expectedFunctions := []string{ "PHP_FUNCTION(Go_Extension_multiply)", "PHP_FUNCTION(Go_Extension_is_even)", } for _, expected := range expectedFunctions { require.Contains(t, content, expected, "Expected to find %q in C file content", expected) } expectedMethods := []string{ "PHP_METHOD(Go_Extension_MySuperClass, __construct)", "PHP_METHOD(Go_Extension_MySuperClass, getName)", } for _, expected := range expectedMethods { require.Contains(t, content, expected, "Expected to find %q in C file content", expected) } oldDeclarations := []string{ "PHP_FUNCTION(multiply)", "PHP_FUNCTION(is_even)", "PHP_METHOD(MySuperClass, __construct)", "PHP_METHOD(MySuperClass, getName)", } for _, old := range oldDeclarations { require.NotContains(t, content, old, "Did not expect to find old declaration %q in C file content", old) } } ================================================ FILE: internal/extgen/phpfunc_test.go ================================================ package extgen import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestPHPFunctionGenerator_Generate(t *testing.T) { tests := []struct { name string function phpFunction contains []string // Strings that should be present in the output }{ { name: "simple string function", function: phpFunction{ Name: "greet", ReturnType: phpString, Params: []phpParameter{ {Name: "name", PhpType: phpString}, }, }, contains: []string{ "PHP_FUNCTION(greet)", "zend_string *name = NULL;", "Z_PARAM_STR(name)", "zend_string *result = go_greet(name);", "RETURN_STR(result)", }, }, { name: "function with default parameter", function: phpFunction{ Name: "calculate", ReturnType: phpInt, Params: []phpParameter{ {Name: "base", PhpType: phpInt}, {Name: "multiplier", PhpType: phpInt, HasDefault: true, DefaultValue: "2"}, }, }, contains: []string{ "PHP_FUNCTION(calculate)", "zend_long base = 0;", "zend_long multiplier = 2;", "ZEND_PARSE_PARAMETERS_START(1, 2)", "Z_PARAM_OPTIONAL", "Z_PARAM_LONG(base)", "Z_PARAM_LONG(multiplier)", }, }, { name: "void function", function: phpFunction{ Name: "doSomething", ReturnType: phpVoid, Params: []phpParameter{ {Name: "action", PhpType: phpString}, }, }, contains: []string{ "PHP_FUNCTION(doSomething)", "go_doSomething(action);", }, }, { name: "bool function with default", function: phpFunction{ Name: "isEnabled", ReturnType: phpBool, Params: []phpParameter{ {Name: "flag", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, }, }, contains: []string{ "PHP_FUNCTION(isEnabled)", "zend_bool flag = 1;", "Z_PARAM_BOOL(flag)", "RETURN_BOOL(result)", }, }, { name: "float function", function: phpFunction{ Name: "calculate", ReturnType: phpFloat, Params: []phpParameter{ {Name: "value", PhpType: phpFloat}, }, }, contains: []string{ "PHP_FUNCTION(calculate)", "double value = 0.0;", "Z_PARAM_DOUBLE(value)", "RETURN_DOUBLE(result)", }, }, { name: "array function with array parameter", function: phpFunction{ Name: "process_array", ReturnType: phpArray, Params: []phpParameter{ {Name: "input", PhpType: phpArray}, }, }, contains: []string{ "PHP_FUNCTION(process_array)", "zend_array *input = NULL;", "Z_PARAM_ARRAY_HT(input)", "zend_array *result = go_process_array(input);", "RETURN_ARR(result)", }, }, { name: "array function with mixed parameters", function: phpFunction{ Name: "filter_array", ReturnType: phpArray, Params: []phpParameter{ {Name: "data", PhpType: phpArray}, {Name: "key", PhpType: phpString}, {Name: "limit", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, }, }, contains: []string{ "PHP_FUNCTION(filter_array)", "zend_array *data = NULL;", "zend_string *key = NULL;", "zend_long limit = 10;", "Z_PARAM_ARRAY_HT(data)", "Z_PARAM_STR(key)", "Z_PARAM_LONG(limit)", "ZEND_PARSE_PARAMETERS_START(2, 3)", "Z_PARAM_OPTIONAL", }, }, } generator := PHPFuncGenerator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := generator.generate(tt.function) for _, expected := range tt.contains { assert.Contains(t, result, expected, "Generated code should contain '%s'", expected) } assert.True(t, strings.HasPrefix(result, "PHP_FUNCTION("), "Generated code should start with PHP_FUNCTION") assert.True(t, strings.HasSuffix(strings.TrimSpace(result), "}"), "Generated code should end with closing brace") }) } } func TestPHPFunctionGenerator_GenerateParamDeclarations(t *testing.T) { tests := []struct { name string params []phpParameter contains []string }{ { name: "string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString}, }, contains: []string{ "zend_string *message = NULL;", }, }, { name: "int parameter", params: []phpParameter{ {Name: "count", PhpType: phpInt}, }, contains: []string{ "zend_long count = 0;", }, }, { name: "bool with default", params: []phpParameter{ {Name: "enabled", PhpType: phpBool, HasDefault: true, DefaultValue: "true"}, }, contains: []string{ "zend_bool enabled = 1;", }, }, { name: "float parameter with default", params: []phpParameter{ {Name: "rate", PhpType: phpFloat, HasDefault: true, DefaultValue: "1.5"}, }, contains: []string{ "double rate = 1.5;", }, }, { name: "array parameter", params: []phpParameter{ {Name: "items", PhpType: phpArray}, }, contains: []string{ "zend_array *items = NULL;", }, }, { name: "mixed types with array", params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "data", PhpType: phpArray}, {Name: "count", PhpType: phpInt}, }, contains: []string{ "zend_string *name = NULL;", "zend_array *data = NULL;", "zend_long count = 0;", }, }, } parser := ParameterParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := parser.generateParamDeclarations(tt.params) for _, expected := range tt.contains { assert.Contains(t, result, expected, "phpParameter declarations should contain '%s'", expected) } }) } } func TestPHPFunctionGenerator_GenerateReturnCode(t *testing.T) { tests := []struct { name string returnType phpType contains []string }{ { name: "string return", returnType: phpString, contains: []string{ "RETURN_STR(result)", "RETURN_EMPTY_STRING()", }, }, { name: "int return", returnType: phpInt, contains: []string{ "RETURN_LONG(result)", }, }, { name: "bool return", returnType: phpBool, contains: []string{ "RETURN_BOOL(result)", }, }, { name: "float return", returnType: phpFloat, contains: []string{ "RETURN_DOUBLE(result)", }, }, { name: "array return", returnType: phpArray, contains: []string{ "RETURN_ARR(result)", "RETURN_EMPTY_ARRAY()", }, }, { name: "void return", returnType: phpVoid, contains: []string{}, }, } generator := PHPFuncGenerator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := generator.generateReturnCode(phpType(tt.returnType)) if len(tt.contains) == 0 { assert.Empty(t, result, "Return code should be empty for void") return } for _, expected := range tt.contains { assert.Contains(t, result, expected, "Return code should contain '%s'", expected) } }) } } func TestPHPFunctionGenerator_GenerateGoCallParams(t *testing.T) { tests := []struct { name string params []phpParameter expected string }{ { name: "no parameters", params: []phpParameter{}, expected: "", }, { name: "simple string parameter", params: []phpParameter{ {Name: "message", PhpType: phpString}, }, expected: "message", }, { name: "int parameter", params: []phpParameter{ {Name: "count", PhpType: phpInt}, }, expected: "(long) count", }, { name: "multiple parameters", params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "age", PhpType: phpInt}, }, expected: "name, (long) age", }, { name: "bool and float parameters", params: []phpParameter{ {Name: "enabled", PhpType: phpBool}, {Name: "rate", PhpType: phpFloat}, }, expected: "(int) enabled, (double) rate", }, { name: "array parameter", params: []phpParameter{ {Name: "data", PhpType: phpArray}, }, expected: "data", }, { name: "mixed parameters with array", params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "items", PhpType: phpArray}, {Name: "count", PhpType: phpInt}, }, expected: "name, items, (long) count", }, } parser := ParameterParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := parser.generateGoCallParams(tt.params) assert.Equal(t, tt.expected, result, "generateGoCallParams() mismatch") }) } } func TestPHPFunctionGenerator_AnalyzeParameters(t *testing.T) { tests := []struct { name string params []phpParameter expectedReq int expectedTotal int }{ { name: "no parameters", params: []phpParameter{}, expectedReq: 0, expectedTotal: 0, }, { name: "all required", params: []phpParameter{ {Name: "a", PhpType: phpString}, {Name: "b", PhpType: phpInt}, }, expectedReq: 2, expectedTotal: 2, }, { name: "mixed required and optional", params: []phpParameter{ {Name: "required", PhpType: phpString}, {Name: "optional", PhpType: phpInt, HasDefault: true, DefaultValue: "10"}, }, expectedReq: 1, expectedTotal: 2, }, { name: "all optional", params: []phpParameter{ {Name: "opt1", PhpType: phpString, HasDefault: true, DefaultValue: "hello"}, {Name: "opt2", PhpType: phpInt, HasDefault: true, DefaultValue: "0"}, }, expectedReq: 0, expectedTotal: 2, }, } parser := ParameterParser{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { info := parser.analyzeParameters(tt.params) assert.Equal(t, tt.expectedReq, info.RequiredCount, "analyzeParameters() RequiredCount mismatch") assert.Equal(t, tt.expectedTotal, info.TotalCount, "analyzeParameters() TotalCount mismatch") }) } } ================================================ FILE: internal/extgen/srcanalyzer.go ================================================ package extgen import ( "fmt" "go/parser" "go/token" "os" "strings" ) type SourceAnalyzer struct{} func (sa *SourceAnalyzer) analyze(filename string) (packageName string, variables []string, internalFunctions []string, err error) { fset := token.NewFileSet() node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) if err != nil { return "", nil, nil, fmt.Errorf("parsing file: %w", err) } packageName = node.Name.Name sourceContent, err := os.ReadFile(filename) if err != nil { return "", nil, nil, fmt.Errorf("reading source file: %w", err) } variables = sa.extractVariables(string(sourceContent)) internalFunctions = sa.extractInternalFunctions(string(sourceContent)) return packageName, variables, internalFunctions, nil } func (sa *SourceAnalyzer) extractVariables(content string) []string { lines := strings.Split(content, "\n") var ( variables []string currentVar strings.Builder inVarBlock bool parenCount int ) for _, line := range lines { trimmedLine := strings.TrimSpace(line) if strings.HasPrefix(trimmedLine, "var ") && !inVarBlock { if strings.Contains(trimmedLine, "(") { inVarBlock = true parenCount = 1 currentVar.Reset() currentVar.WriteString(line + "\n") } else { variables = append(variables, strings.TrimSpace(line)) } } else if inVarBlock { currentVar.WriteString(line + "\n") for _, char := range line { switch char { case '(': parenCount++ case ')': parenCount-- } } if parenCount == 0 { varContent := currentVar.String() variables = append(variables, strings.TrimSpace(varContent)) inVarBlock = false currentVar.Reset() } } } return variables } func (sa *SourceAnalyzer) extractInternalFunctions(content string) []string { lines := strings.Split(content, "\n") var ( functions []string currentFunc strings.Builder inFunction, hasPHPFunc bool braceCount int ) for i, line := range lines { trimmedLine := strings.TrimSpace(line) if strings.HasPrefix(trimmedLine, "func ") && !inFunction { inFunction = true braceCount = 0 hasPHPFunc = false currentFunc.Reset() // look backwards for export_php comment for j := i - 1; j >= 0 && j >= i-5; j-- { prevLine := strings.TrimSpace(lines[j]) if prevLine == "" { continue } if strings.Contains(prevLine, "export_php:") { hasPHPFunc = true break } if !strings.HasPrefix(prevLine, "//") { break } } } if inFunction { currentFunc.WriteString(line + "\n") for _, char := range line { switch char { case '{': braceCount++ case '}': braceCount-- } } if braceCount == 0 && strings.Contains(line, "}") { funcContent := currentFunc.String() if !hasPHPFunc { functions = append(functions, strings.TrimSpace(funcContent)) } inFunction = false currentFunc.Reset() } } } return functions } ================================================ FILE: internal/extgen/srcanalyzer_test.go ================================================ package extgen import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "github.com/stretchr/testify/assert" ) func TestSourceAnalyzer_Analyze(t *testing.T) { tests := []struct { name string sourceContent string expectedImports []string expectedVariables []string expectedFunctions []string expectError bool }{ { name: "simple file with imports and functions", sourceContent: `package main import ( "fmt" "strings" ) func regularFunction() { fmt.Println("hello") } //export_php:function func exportedFunction() string { return "exported" }`, expectedImports: []string{`"fmt"`, `"strings"`}, expectedVariables: nil, expectedFunctions: []string{ `func regularFunction() { fmt.Println("hello") }`, }, expectError: false, }, { name: "file with named imports", sourceContent: `package main import ( custom "fmt" . "strings" _ "os" ) func test() {}`, expectedImports: []string{`custom "fmt"`, `. "strings"`, `_ "os"`}, expectedVariables: nil, expectedFunctions: []string{ `func test() {}`, }, expectError: false, }, { name: "file with multiple functions and export comments", sourceContent: `package main func internalOne() { // some code } // This function is exported to PHP //export_php:function func exportedOne() int { return 42 } func internalTwo() string { return "internal" } // Another exported function //export_php:function func exportedTwo() bool { return true }`, expectedImports: []string{}, expectedVariables: nil, expectedFunctions: []string{ `func internalOne() { // some code }`, `func internalTwo() string { return "internal" }`, }, expectError: false, }, { name: "file with nested braces", sourceContent: `package main func complexFunction() { if true { for i := 0; i < 10; i++ { if i%2 == 0 { fmt.Println(i) } } } } //export_php:function func exportedComplex() { obj := struct{ field string }{ field: "value", } fmt.Println(obj) }`, expectedImports: []string{}, expectedVariables: nil, expectedFunctions: []string{ `func complexFunction() { if true { for i := 0; i < 10; i++ { if i%2 == 0 { fmt.Println(i) } } } }`, }, expectError: false, }, { name: "empty file", sourceContent: `package main`, expectedImports: []string{}, expectedFunctions: []string{}, expectError: false, }, { name: "file with only exported functions", sourceContent: `package main //export_php:function func onlyExported() {} //export_php:function func anotherExported() string { return "test" }`, expectedImports: []string{}, expectedFunctions: []string{}, expectError: false, }, { name: "file with export comment not immediately before function", sourceContent: `package main //export_php:function // Some other comment func shouldNotBeExported() {} func normalFunction() { //export_php:function inside function should not count }`, expectedImports: []string{}, expectedVariables: nil, expectedFunctions: []string{ `func normalFunction() { //export_php:function inside function should not count }`, }, expectError: false, }, { name: "file with variable blocks", sourceContent: `package main import ( "sync" ) var ( mu sync.RWMutex store = map[string]struct { val string expires int64 }{} ) var singleVar = "test" func testFunction() { // test function }`, expectedImports: []string{`"sync"`}, expectedVariables: []string{ `var ( mu sync.RWMutex store = map[string]struct { val string expires int64 }{} )`, `var singleVar = "test"`, }, expectedFunctions: []string{ `func testFunction() { // test function }`, }, expectError: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tempDir := t.TempDir() filename := filepath.Join(tempDir, "test.go") require.NoError(t, os.WriteFile(filename, []byte(tt.sourceContent), 0644)) analyzer := &SourceAnalyzer{} _, variables, functions, err := analyzer.analyze(filename) if tt.expectError { assert.Error(t, err, "expected error") return } assert.NoError(t, err, "unexpected error") assert.Equal(t, tt.expectedVariables, variables, "variables mismatch") assert.Len(t, functions, len(tt.expectedFunctions), "function count mismatch") for i, expected := range tt.expectedFunctions { assert.Equal(t, expected, functions[i], "function %d mismatch", i) } }) } } func TestSourceAnalyzer_Analyze_InvalidFile(t *testing.T) { analyzer := &SourceAnalyzer{} t.Run("nonexistent file", func(t *testing.T) { _, _, _, err := analyzer.analyze("/nonexistent/file.go") assert.Error(t, err, "expected error for nonexistent file") }) t.Run("invalid Go syntax", func(t *testing.T) { tempDir := t.TempDir() filename := filepath.Join(tempDir, "invalid.go") invalidContent := `package main func incomplete( { // invalid syntax ` require.NoError(t, os.WriteFile(filename, []byte(invalidContent), 0644)) _, _, _, err := analyzer.analyze(filename) assert.Error(t, err, "expected error for invalid syntax") }) } func TestSourceAnalyzer_ExtractInternalFunctions(t *testing.T) { tests := []struct { name string content string expected []string }{ { name: "single function without export", content: `func test() { fmt.Println("test") }`, expected: []string{ `func test() { fmt.Println("test") }`, }, }, { name: "function with export comment", content: `//export_php:function func exported() {}`, expected: []string{}, }, { name: "mixed functions", content: `func internal() {} //export_php:function func exported() {} func anotherInternal() { return "test" }`, expected: []string{ "func internal() {}", `func anotherInternal() { return "test" }`, }, }, { name: "export comment with spacing", content: `//export_php:function func exported1() {} //export_php:function func exported2() {} // export_php:function func exported3() {}`, expected: []string{}, }, { name: "complex function with nested braces", content: `func complex() { if true { for { switch x { case 1: { // nested block } } } } }`, expected: []string{ `func complex() { if true { for { switch x { case 1: { // nested block } } } } }`, }, }, { name: "empty content", content: "", expected: []string{}, }, { name: "no functions", content: `package main import "fmt" var x = 10`, expected: []string{}, }, } analyzer := &SourceAnalyzer{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := analyzer.extractInternalFunctions(tt.content) assert.Len(t, result, len(tt.expected), "function count mismatch") for i, expected := range tt.expected { assert.Equal(t, expected, result[i], "function %d mismatch", i) } }) } } func TestSourceAnalyzer_InternalFunctionPreservation(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import ( "fmt" "strings" ) //export_php: exported1(): string func exported1() *go_value { return String(internal1()) } func internal1() string { return "helper1" } //export_php: exported2(): void func exported2() { internal2() } func internal2() { fmt.Println("helper2") } func internal3(data string) string { return strings.ToUpper(data) }` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) analyzer := &SourceAnalyzer{} packageName, variables, internalFuncs, err := analyzer.analyze(sourceFile) require.NoError(t, err) assert.Equal(t, "main", packageName) assert.Len(t, internalFuncs, 3, "Should extract exactly 3 internal functions") expectedInternalFuncs := []string{ `func internal1() string { return "helper1" }`, `func internal2() { fmt.Println("helper2") }`, `func internal3(data string) string { return strings.ToUpper(data) }`, } for i, expected := range expectedInternalFuncs { assert.Equal(t, expected, internalFuncs[i], "Internal function %d should match", i) } assert.Empty(t, variables, "Should not have variables") } func TestSourceAnalyzer_VariableBlockPreservation(t *testing.T) { tmpDir := t.TempDir() sourceContent := `package main import ( "sync" ) var ( mu sync.RWMutex cache = make(map[string]string) ) var globalCounter int = 0 //export_php: test(): void func test() {}` sourceFile := filepath.Join(tmpDir, "test.go") require.NoError(t, os.WriteFile(sourceFile, []byte(sourceContent), 0644)) analyzer := &SourceAnalyzer{} packageName, variables, internalFuncs, err := analyzer.analyze(sourceFile) require.NoError(t, err) assert.Equal(t, "main", packageName) assert.Len(t, variables, 2, "Should extract exactly 2 variable declarations") expectedVar1 := `var ( mu sync.RWMutex cache = make(map[string]string) )` expectedVar2 := `var globalCounter int = 0` assert.Equal(t, expectedVar1, variables[0], "First variable block should match") assert.Equal(t, expectedVar2, variables[1], "Second variable declaration should match") assert.Empty(t, internalFuncs, "Should not have internal functions (only exported function)") } func BenchmarkSourceAnalyzer_Analyze(b *testing.B) { content := `package main import ( "fmt" "strings" "os" ) func internalOne() { fmt.Println("test") } //export_php:function func exported() string { return "exported" } func internalTwo() { for i := 0; i < 100; i++ { if i%2 == 0 { fmt.Println(i) } } }` tempDir := b.TempDir() filename := filepath.Join(tempDir, "bench.go") require.NoError(b, os.WriteFile(filename, []byte(content), 0644)) analyzer := &SourceAnalyzer{} for b.Loop() { _, _, _, err := analyzer.analyze(filename) require.NoError(b, err) } } func BenchmarkSourceAnalyzer_ExtractInternalFunctions(b *testing.B) { content := `func test1() { fmt.Println("1") } func test2() { fmt.Println("2") } //export_php:function func exported() {} func test3() { for i := 0; i < 10; i++ { fmt.Println(i) } }` analyzer := &SourceAnalyzer{} for b.Loop() { analyzer.extractInternalFunctions(content) } } ================================================ FILE: internal/extgen/stub.go ================================================ package extgen import ( _ "embed" "path/filepath" "strings" "text/template" ) //go:embed templates/stub.php.tpl var templateContent string type StubGenerator struct { Generator *Generator } func (sg *StubGenerator) generate() error { filename := filepath.Join(sg.Generator.BuildDir, sg.Generator.BaseName+".stub.php") content, err := sg.buildContent() if err != nil { return err } return writeFile(filename, content) } func (sg *StubGenerator) buildContent() (string, error) { tmpl, err := template.New("stub.php.tpl").Funcs(template.FuncMap{ "phpType": getPhpTypeAnnotation, }).Parse(templateContent) if err != nil { return "", err } var buf strings.Builder if err := tmpl.Execute(&buf, sg.Generator); err != nil { return "", err } return buf.String(), nil } // getPhpTypeAnnotation converts phpType to PHP type annotation func getPhpTypeAnnotation(t phpType) string { switch t { case phpString: return "string" case phpBool: return "bool" case phpFloat: return "float" case phpInt: return "int" case phpArray: return "array" default: return "int" } } ================================================ FILE: internal/extgen/stub_test.go ================================================ package extgen import ( "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestStubGenerator_Generate(t *testing.T) { tmpDir := t.TempDir() generator := &Generator{ BaseName: "test_extension", BuildDir: tmpDir, Functions: []phpFunction{ { Name: "greet", Signature: "greet(string $name): string", Params: []phpParameter{ {Name: "name", PhpType: phpString}, }, ReturnType: phpString, }, { Name: "calculate", Signature: "calculate(int $a, int $b): int", Params: []phpParameter{ {Name: "a", PhpType: phpInt}, {Name: "b", PhpType: phpInt}, }, ReturnType: phpInt, }, }, Classes: []phpClass{ { Name: "User", GoStruct: "UserStruct", }, }, Constants: []phpConstant{ { Name: "GLOBAL_CONST", Value: "42", PhpType: phpInt, }, { Name: "USER_STATUS_ACTIVE", Value: "1", PhpType: phpInt, ClassName: "User", }, }, } stubGen := StubGenerator{generator} assert.NoError(t, stubGen.generate(), "generate() failed") expectedFile := filepath.Join(tmpDir, "test_extension.stub.php") assert.FileExists(t, expectedFile, "Expected stub file was not created: %s", expectedFile) content, err := readFile(expectedFile) assert.NoError(t, err, "Failed to read generated stub file") testStubBasicStructure(t, content) testStubFunctions(t, content, generator.Functions) testStubClasses(t, content, generator.Classes) testStubConstants(t, content, generator.Constants) } func TestStubGenerator_BuildContent(t *testing.T) { tests := []struct { name string functions []phpFunction classes []phpClass constants []phpConstant contains []string }{ { name: "empty extension", functions: []phpFunction{}, classes: []phpClass{}, constants: []phpConstant{}, contains: []string{ " 0 { assert.Equal(t, " #include #include #include #include #include "{{.BaseName}}.h" #include "{{.BaseName}}_arginfo.h" #include "_cgo_export.h" {{- if .Classes}} #define VALIDATE_GO_HANDLE(intern) \ do { \ if ((intern)->go_handle == 0) { \ zend_throw_error(NULL, "Go object not found in registry"); \ RETURN_THROWS(); \ } \ } while (0) static zend_object_handlers object_handlers_{{.BaseName}}; typedef struct { uintptr_t go_handle; zend_object std; /* This must be the last field in the structure: the property store starts at this offset */ } {{.BaseName}}_object; static inline {{.BaseName}}_object *{{.BaseName}}_object_from_obj(zend_object *obj) { return ({{.BaseName}}_object*)((char*)(obj) - offsetof({{.BaseName}}_object, std)); } static zend_object *{{.BaseName}}_create_object(zend_class_entry *ce) { {{.BaseName}}_object *intern = ecalloc(1, sizeof({{.BaseName}}_object) + zend_object_properties_size(ce)); zend_object_std_init(&intern->std, ce); object_properties_init(&intern->std, ce); intern->std.handlers = &object_handlers_{{.BaseName}}; intern->go_handle = 0; /* will be set in __construct */ return &intern->std; } static void {{.BaseName}}_free_object(zend_object *object) { {{.BaseName}}_object *intern = {{.BaseName}}_object_from_obj(object); if (intern->go_handle != 0) { removeGoObject(intern->go_handle); } zend_object_std_dtor(&intern->std); } void init_object_handlers() { memcpy(&object_handlers_{{.BaseName}}, &std_object_handlers, sizeof(zend_object_handlers)); object_handlers_{{.BaseName}}.free_obj = {{.BaseName}}_free_object; object_handlers_{{.BaseName}}.clone_obj = NULL; object_handlers_{{.BaseName}}.offset = offsetof({{.BaseName}}_object, std); } {{- end}} {{ range .Classes}} static zend_class_entry *{{.Name}}_ce = NULL; PHP_METHOD({{namespacedClassName $.Namespace .Name}}, __construct) { ZEND_PARSE_PARAMETERS_NONE(); {{$.BaseName}}_object *intern = {{$.BaseName}}_object_from_obj(Z_OBJ_P(ZEND_THIS)); /* Constructor is called more than once, make it no-op */ if (intern->go_handle != 0) { return; } intern->go_handle = create_{{.GoStruct}}_object(); } {{ range .Methods}} PHP_METHOD({{namespacedClassName $.Namespace .ClassName}}, {{.PhpName}}) { {{$.BaseName}}_object *intern = {{$.BaseName}}_object_from_obj(Z_OBJ_P(ZEND_THIS)); VALIDATE_GO_HANDLE(intern); {{- if .Params -}} {{range $i, $param := .Params -}} {{- if eq $param.PhpType "string"}} zend_string *{{$param.Name}} = NULL;{{if $param.IsNullable}} zend_bool {{$param.Name}}_is_null = 0;{{end}} {{- else if eq $param.PhpType "int"}} zend_long {{$param.Name}} = {{if $param.HasDefault}}{{$param.DefaultValue}}{{else}}0{{end}};{{if $param.IsNullable}} zend_bool {{$param.Name}}_is_null = 0;{{end}} {{- else if eq $param.PhpType "float"}} double {{$param.Name}} = {{if $param.HasDefault}}{{$param.DefaultValue}}{{else}}0.0{{end}};{{if $param.IsNullable}} zend_bool {{$param.Name}}_is_null = 0;{{end}} {{- else if eq $param.PhpType "bool"}} zend_bool {{$param.Name}} = {{if $param.HasDefault}}{{if eq $param.DefaultValue "true"}}1{{else}}0{{end}}{{else}}0{{end}};{{if $param.IsNullable}} zend_bool {{$param.Name}}_is_null = 0;{{end}} {{- else if eq $param.PhpType "array"}} zend_array *{{$param.Name}} = NULL; {{- else if eq $param.PhpType "callable"}} zval *{{$param.Name}}_callback; {{- end}} {{- end}} {{$requiredCount := 0}}{{range .Params}}{{if not .HasDefault}}{{$requiredCount = add1 $requiredCount}}{{end}}{{end -}} ZEND_PARSE_PARAMETERS_START({{$requiredCount}}, {{len .Params}}) {{$optionalStarted := false}}{{range .Params}}{{if .HasDefault}}{{if not $optionalStarted -}} Z_PARAM_OPTIONAL {{$optionalStarted = true}}{{end}}{{end -}} {{if .IsNullable}}{{if eq .PhpType "string"}}Z_PARAM_STR_OR_NULL({{.Name}}, {{.Name}}_is_null){{else if eq .PhpType "int"}}Z_PARAM_LONG_OR_NULL({{.Name}}, {{.Name}}_is_null){{else if eq .PhpType "float"}}Z_PARAM_DOUBLE_OR_NULL({{.Name}}, {{.Name}}_is_null){{else if eq .PhpType "bool"}}Z_PARAM_BOOL_OR_NULL({{.Name}}, {{.Name}}_is_null){{else if eq .PhpType "array"}}Z_PARAM_ARRAY_HT_OR_NULL({{.Name}}){{else if eq .PhpType "callable"}}Z_PARAM_ZVAL_OR_NULL({{.Name}}_callback){{end}}{{else}}{{if eq .PhpType "string"}}Z_PARAM_STR({{.Name}}){{else if eq .PhpType "int"}}Z_PARAM_LONG({{.Name}}){{else if eq .PhpType "float"}}Z_PARAM_DOUBLE({{.Name}}){{else if eq .PhpType "bool"}}Z_PARAM_BOOL({{.Name}}){{else if eq .PhpType "array"}}Z_PARAM_ARRAY_HT({{.Name}}){{else if eq .PhpType "callable"}}Z_PARAM_ZVAL({{.Name}}_callback){{end}}{{end}} {{end -}} ZEND_PARSE_PARAMETERS_END(); {{else}} ZEND_PARSE_PARAMETERS_NONE(); {{end}} {{- if ne .ReturnType "void"}} {{- if eq .ReturnType "string"}} zend_string* result = {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{else}}{{.Name}}{{end}}{{end}}{{end}}{{end}}); if (result) { RETURN_STR(result); } RETURN_EMPTY_STRING(); {{- else if eq .ReturnType "int"}} zend_long result = {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{else}}(long){{.Name}}{{end}}{{end}}{{end}}{{end}}); RETURN_LONG(result); {{- else if eq .ReturnType "float"}} double result = {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{else}}(double){{.Name}}{{end}}{{end}}{{end}}{{end}}); RETURN_DOUBLE(result); {{- else if eq .ReturnType "bool"}} int result = {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{else}}(int){{.Name}}{{end}}{{end}}{{end}}{{end}}); RETURN_BOOL(result); {{- else if eq .ReturnType "array"}} void* result = {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{else}}{{.Name}}{{end}}{{end}}{{end}}{{end}}); if (result != NULL) { HashTable *ht = (HashTable*)result; RETURN_ARR(ht); } else { RETURN_NULL(); } {{- end}} {{- else}} {{.Name}}_wrapper(intern->go_handle{{if .Params}}{{range .Params}}, {{if .IsNullable}}{{if eq .PhpType "string"}}{{.Name}}_is_null ? NULL : {{.Name}}{{else if eq .PhpType "int"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "float"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "bool"}}{{.Name}}_is_null ? NULL : &{{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{else}}{{if eq .PhpType "string"}}{{.Name}}{{else if eq .PhpType "int"}}(long){{.Name}}{{else if eq .PhpType "float"}}(double){{.Name}}{{else if eq .PhpType "bool"}}(int){{.Name}}{{else if eq .PhpType "array"}}{{.Name}}{{else if eq .PhpType "callable"}}{{.Name}}_callback{{end}}{{end}}{{end}}{{end}}); {{- end}} } {{end}}{{end}} {{- if .Classes}} void register_all_classes() { init_object_handlers(); {{- range .Classes}} {{.Name}}_ce = register_class_{{namespacedClassName $.Namespace .Name}}(); if (!{{.Name}}_ce) { php_error_docref(NULL, E_ERROR, "Failed to register class {{.Name}}"); return; } {{.Name}}_ce->create_object = {{$.BaseName}}_create_object; {{- end}} } {{- end}} PHP_MINIT_FUNCTION({{.BaseName}}) { {{ if .Classes}}register_all_classes();{{end}} {{- range .Constants}} {{- if eq .ClassName ""}} {{- if $.Namespace}} {{if .IsIota}}REGISTER_NS_LONG_CONSTANT("{{cString $.Namespace}}", "{{.Name}}", {{.Name}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "string"}}REGISTER_NS_STRING_CONSTANT("{{cString $.Namespace}}", "{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "bool"}}REGISTER_NS_BOOL_CONSTANT("{{cString $.Namespace}}", "{{.Name}}", {{if eq .Value "true"}}true{{else}}false{{end}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "float"}}REGISTER_NS_DOUBLE_CONSTANT("{{cString $.Namespace}}", "{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{else}}REGISTER_NS_LONG_CONSTANT("{{cString $.Namespace}}", "{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{- end}} {{- else}} {{if .IsIota}}REGISTER_LONG_CONSTANT("{{.Name}}", {{.Name}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "string"}}REGISTER_STRING_CONSTANT("{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "bool"}}REGISTER_BOOL_CONSTANT("{{.Name}}", {{if eq .Value "true"}}true{{else}}false{{end}}, CONST_CS | CONST_PERSISTENT); {{else if eq .PhpType "float"}}REGISTER_DOUBLE_CONSTANT("{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{else}}REGISTER_LONG_CONSTANT("{{.Name}}", {{.CValue}}, CONST_CS | CONST_PERSISTENT); {{- end}} {{- end}} {{- end}} {{- end}} return SUCCESS; } zend_module_entry {{.BaseName}}_module_entry = {STANDARD_MODULE_HEADER, "{{.BaseName}}", {{if .Functions}}ext_functions{{else}}NULL{{end}}, /* Functions */ PHP_MINIT({{.BaseName}}), /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "1.0.0", /* Version */ STANDARD_MODULE_PROPERTIES}; ================================================ FILE: internal/extgen/templates/extension.go.tpl ================================================ package {{.PackageName}} // AUTOGENERATED FILE - DO NOT EDIT. // // This file has been automatically generated by FrankenPHP extension generator // and should not be edited as it will be overwritten when running the // extension generator again. // // You may edit the file and remove this comment if you plan to manually maintain // this file going forward. // #include // #include "{{.BaseName}}.h" import "C" import ( {{if not .Classes}}_ {{end}}"runtime/cgo" "unsafe" "github.com/dunglas/frankenphp" ) func init() { frankenphp.RegisterExtension(unsafe.Pointer(&C.{{.SanitizedBaseName}}_module_entry)) } {{- range .Functions}} //export go_{{.Name}} func go_{{.Name}}({{extractGoFunctionSignatureParams .GoFunction}}) {{extractGoFunctionSignatureReturn .GoFunction}} { {{if not (isVoid .ReturnType)}}return {{end}}{{extractGoFunctionName .GoFunction}}({{extractGoFunctionCallParams .GoFunction}}) } {{- end}} {{- if .Classes}} //export registerGoObject func registerGoObject(obj interface{}) C.uintptr_t { handle := cgo.NewHandle(obj) return C.uintptr_t(handle) } //export getGoObject func getGoObject(handle C.uintptr_t) interface{} { h := cgo.Handle(handle) return h.Value() } //export removeGoObject func removeGoObject(handle C.uintptr_t) { h := cgo.Handle(handle) h.Delete() } {{- end}} {{- range $class := .Classes}} //export create_{{.GoStruct}}_object func create_{{.GoStruct}}_object() C.uintptr_t { obj := &{{.GoStruct}}{} return registerGoObject(obj) } {{- range .Methods}} //export {{.Name}}_wrapper func {{.Name}}_wrapper(handle C.uintptr_t{{range .Params}}{{if eq .PhpType "string"}}, {{.Name}} *C.zend_string{{else if eq .PhpType "array"}}, {{.Name}} *C.zval{{else if eq .PhpType "callable"}}, {{.Name}} *C.zval{{else}}, {{.Name}} {{if .IsNullable}}*{{end}}{{phpTypeToGoType .PhpType}}{{end}}{{end}}){{if not (isVoid .ReturnType)}}{{if isStringOrArray .ReturnType}} unsafe.Pointer{{else}} {{phpTypeToGoType .ReturnType}}{{end}}{{end}} { obj := getGoObject(handle) if obj == nil { {{- if not (isVoid .ReturnType)}} {{- if isStringOrArray .ReturnType}} return nil {{- else}} var zero {{phpTypeToGoType .ReturnType}} return zero {{- end}} {{- else}} return {{- end}} } structObj := obj.(*{{$class.GoStruct}}) {{if not (isVoid .ReturnType)}}return {{end}}structObj.{{.Name | title}}({{range $i, $param := .Params}}{{if $i}}, {{end}}{{$param.Name}}{{end}}) } {{end}} {{- end}} ================================================ FILE: internal/extgen/templates/extension.h.tpl ================================================ // AUTOGENERATED FILE - DO NOT EDIT. // // This file has been automatically generated by FrankenPHP extension generator // and should not be edited as it will be overwritten when running the // extension generator again. // // You may edit the file and remove this comment if you plan to manually maintain // this file going forward. #ifndef _{{.HeaderGuard}} #define _{{.HeaderGuard}} #include #include extern zend_module_entry {{.BaseName}}_module_entry; {{if .Constants}} /* User defined constants */{{end}} {{range .Constants}}#define {{.Name}} {{.CValue}} {{end}} #endif ================================================ FILE: internal/extgen/templates/stub.php.tpl ================================================ 0 && !unicode.IsLetter(rune(sanitized[0])) && sanitized[0] != '_' { sanitized = "_" + sanitized } return sanitized } ================================================ FILE: internal/extgen/utils_namespace_test.go ================================================ package extgen import ( "testing" "github.com/stretchr/testify/require" ) func TestNamespacedName(t *testing.T) { tests := []struct { name string namespace string itemName string expected string }{ { name: "no namespace", namespace: "", itemName: "TestItem", expected: "TestItem", }, { name: "single level namespace", namespace: "MyNamespace", itemName: "TestItem", expected: "MyNamespace_TestItem", }, { name: "multi level namespace", namespace: `Go\Extension`, itemName: "TestItem", expected: "Go_Extension_TestItem", }, { name: "deep namespace", namespace: `Very\Deep\Nested\Namespace`, itemName: "MyItem", expected: "Very_Deep_Nested_Namespace_MyItem", }, { name: "function name", namespace: `Go\Extension`, itemName: "multiply", expected: "Go_Extension_multiply", }, { name: "class name", namespace: `Go\Extension`, itemName: "MySuperClass", expected: "Go_Extension_MySuperClass", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := NamespacedName(tt.namespace, tt.itemName) require.Equal(t, tt.expected, result, "NamespacedName(%q, %q) = %q, expected %q", tt.namespace, tt.itemName, result, tt.expected) }) } } ================================================ FILE: internal/extgen/utils_test.go ================================================ package extgen import ( "os" "path/filepath" "runtime" "testing" "github.com/stretchr/testify/assert" ) func TestWriteFile(t *testing.T) { tests := []struct { name string filename string content string expectError bool }{ { name: "write simple file", filename: "test.txt", content: "hello world", expectError: false, }, { name: "write empty file", filename: "empty.txt", content: "", expectError: false, }, { name: "write file with special characters", filename: "special.txt", content: "hello\nworld\t!@#$%^&*()", expectError: false, }, { name: "write to invalid directory", filename: "/nonexistent/directory/file.txt", content: "test", expectError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var filename string if !tt.expectError { tempDir := t.TempDir() filename = filepath.Join(tempDir, tt.filename) } else { filename = tt.filename } err := writeFile(filename, tt.content) if tt.expectError { assert.Error(t, err, "writeFile() should return an error") return } assert.NoError(t, err, "writeFile() should not return an error") content, err := os.ReadFile(filename) assert.NoError(t, err, "Failed to read written file") assert.Equal(t, tt.content, string(content), "writeFile() content mismatch") info, err := os.Stat(filename) assert.NoError(t, err, "Failed to stat file") expectedMode := os.FileMode(0644) if runtime.GOOS == "windows" { expectedMode = os.FileMode(0666) } assert.Equal(t, expectedMode, info.Mode().Perm(), "writeFile() wrong permissions") }) } } func TestReadFile(t *testing.T) { tests := []struct { name string content string expectError bool }{ { name: "read simple file", content: "hello world", expectError: false, }, { name: "read empty file", content: "", expectError: false, }, { name: "read file with special characters", content: "hello\nworld\t!@#$%^&*()", expectError: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tempDir := t.TempDir() filename := filepath.Join(tempDir, "test.txt") err := os.WriteFile(filename, []byte(tt.content), 0644) assert.NoError(t, err, "Failed to create test file") content, err := readFile(filename) if tt.expectError { assert.Error(t, err, "readFile() should return an error") return } assert.NoError(t, err, "readFile() should not return an error") assert.Equal(t, tt.content, content, "readFile() content mismatch") }) } t.Run("read nonexistent file", func(t *testing.T) { _, err := readFile("/nonexistent/file.txt") assert.Error(t, err, "readFile() should return an error for nonexistent file") }) } func TestSanitizePackageName(t *testing.T) { tests := []struct { name string input string expected string }{ { name: "simple valid name", input: "mypackage", expected: "mypackage", }, { name: "name with hyphens", input: "my-package", expected: "my_package", }, { name: "name with dots", input: "my.package", expected: "my_package", }, { name: "name with both hyphens and dots", input: "my-package.name", expected: "my_package_name", }, { name: "name starting with number", input: "123package", expected: "_123package", }, { name: "name starting with underscore", input: "_package", expected: "_package", }, { name: "name starting with letter", input: "Package", expected: "Package", }, { name: "name starting with special character", input: "@package", expected: "_@package", }, { name: "complex name", input: "123my-complex.package@name", expected: "_123my_complex_package@name", }, { name: "empty string", input: "", expected: "", }, { name: "single character letter", input: "a", expected: "a", }, { name: "single character number", input: "1", expected: "_1", }, { name: "single character underscore", input: "_", expected: "_", }, { name: "single character special", input: "@", expected: "_@", }, { name: "multiple consecutive hyphens", input: "my--package", expected: "my__package", }, { name: "multiple consecutive dots", input: "my..package", expected: "my__package", }, { name: "mixed case with special chars", input: "MyPackage-name.version", expected: "MyPackage_name_version", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := SanitizePackageName(tt.input) assert.Equal(t, tt.expected, result, "SanitizePackageName(%q)", tt.input) }) } } func BenchmarkSanitizePackageName(b *testing.B) { testCases := []string{ "simple", "my-package", "my.package.name", "123complex-package.name@version", "very-long-package-name-with-many-special-characters.and.dots", } for _, tc := range testCases { b.Run(tc, func(b *testing.B) { for b.Loop() { SanitizePackageName(tc) } }) } } ================================================ FILE: internal/extgen/validator.go ================================================ package extgen import ( "fmt" "go/ast" "go/parser" "go/token" "regexp" "slices" "strings" ) var ( paramTypes = []phpType{phpString, phpInt, phpFloat, phpBool, phpArray, phpObject, phpMixed, phpCallable} returnTypes = []phpType{phpVoid, phpString, phpInt, phpFloat, phpBool, phpArray, phpObject, phpMixed, phpNull, phpTrue, phpFalse} propTypes = []phpType{phpString, phpInt, phpFloat, phpBool, phpArray, phpObject, phpMixed} supportedTypes = []phpType{phpString, phpInt, phpFloat, phpBool, phpArray, phpMixed, phpCallable} functionNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) parameterNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) classNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) propNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) ) type Validator struct{} func (v *Validator) validateFunction(fn phpFunction) error { if fn.Name == "" { return fmt.Errorf("function name cannot be empty") } if !functionNameRegex.MatchString(fn.Name) { return fmt.Errorf("invalid function name: %s", fn.Name) } for i, param := range fn.Params { if err := v.validateParameter(param); err != nil { return fmt.Errorf("parameter %d (%s): %w", i, param.Name, err) } } if err := v.validateReturnType(fn.ReturnType); err != nil { return fmt.Errorf("return type: %w", err) } return nil } func (v *Validator) validateParameter(param phpParameter) error { if param.Name == "" { return fmt.Errorf("parameter name cannot be empty") } if !parameterNameRegex.MatchString(param.Name) { return fmt.Errorf("invalid parameter name: %s", param.Name) } if !slices.Contains(paramTypes, param.PhpType) { return fmt.Errorf("invalid parameter type: %s", param.PhpType) } return nil } func (v *Validator) validateReturnType(returnType phpType) error { if !slices.Contains(returnTypes, returnType) { return fmt.Errorf("invalid return type: %s", returnType) } return nil } func (v *Validator) validateClass(class phpClass) error { if class.Name == "" { return fmt.Errorf("class name cannot be empty") } if !classNameRegex.MatchString(class.Name) { return fmt.Errorf("invalid class name: %s", class.Name) } for i, prop := range class.Properties { if err := v.validateClassProperty(prop); err != nil { return fmt.Errorf("property %d (%s): %w", i, prop.Name, err) } } return nil } func (v *Validator) validateClassProperty(prop phpClassProperty) error { if prop.Name == "" { return fmt.Errorf("property name cannot be empty") } if !propNameRegex.MatchString(prop.Name) { return fmt.Errorf("invalid property name: %s", prop.Name) } if !slices.Contains(propTypes, prop.PhpType) { return fmt.Errorf("invalid property type: %s", prop.PhpType) } return nil } // validateTypes checks if PHP signature contains only supported types func (v *Validator) validateTypes(fn phpFunction) error { for i, param := range fn.Params { if !slices.Contains(supportedTypes, param.PhpType) { return fmt.Errorf("parameter %d %q has unsupported type %q, supported typed: string, int, float, bool, array and mixed, can be nullable", i+1, param.Name, param.PhpType) } } if fn.ReturnType != phpVoid && !slices.Contains(supportedTypes, fn.ReturnType) { return fmt.Errorf("return type %q is not supported, supported typed: string, int, float, bool, array and mixed, can be nullable", fn.ReturnType) } return nil } // validateGoFunctionSignatureWithOptions validates with option for method vs function func (v *Validator) validateGoFunctionSignatureWithOptions(phpFunc phpFunction, isMethod bool) error { if phpFunc.GoFunction == "" { return fmt.Errorf("no Go function found for PHP function %q", phpFunc.Name) } fset := token.NewFileSet() file, err := parser.ParseFile(fset, "", "package main\n"+phpFunc.GoFunction, 0) if err != nil { return fmt.Errorf("failed to parse Go function: %w", err) } var goFunc *ast.FuncDecl for _, decl := range file.Decls { if funcDecl, ok := decl.(*ast.FuncDecl); ok { goFunc = funcDecl break } } if goFunc == nil { return fmt.Errorf("no function declaration found in Go function") } goParamCount := 0 if goFunc.Type.Params != nil { goParamCount = len(goFunc.Type.Params.List) } hasReceiver := goFunc.Recv != nil && len(goFunc.Recv.List) > 0 paramOffset := 0 effectiveGoParamCount := goParamCount if hasReceiver { paramOffset = 0 effectiveGoParamCount = goParamCount } else if isMethod && goParamCount > 0 { // this is a method-like function, first parameter should be the struct paramOffset = 1 effectiveGoParamCount = goParamCount - 1 } expectedGoParams := len(phpFunc.Params) if expectedGoParams != effectiveGoParamCount { return fmt.Errorf("parameter count mismatch: PHP function has %d parameters (expecting %d Go parameters) but Go function has %d", len(phpFunc.Params), expectedGoParams, effectiveGoParamCount) } if goFunc.Type.Params != nil && len(phpFunc.Params) > 0 { for i, phpParam := range phpFunc.Params { goParamIndex := i + paramOffset if goParamIndex >= len(goFunc.Type.Params.List) { break } goParam := goFunc.Type.Params.List[goParamIndex] expectedGoType := v.phpTypeToGoType(phpParam.PhpType, phpParam.IsNullable) actualGoType := v.goTypeToString(goParam.Type) if !v.isCompatibleGoType(expectedGoType, actualGoType) { return fmt.Errorf("parameter %d type mismatch: PHP %q requires Go type %q but found %q", i+1, phpParam.PhpType, expectedGoType, actualGoType) } } } expectedGoReturnType := v.phpReturnTypeToGoType(phpFunc.ReturnType) actualGoReturnType := v.goReturnTypeToString(goFunc.Type.Results) if !v.isCompatibleGoType(expectedGoReturnType, actualGoReturnType) { return fmt.Errorf("return type mismatch: PHP %q requires Go return type %q but found %q", phpFunc.ReturnType, expectedGoReturnType, actualGoReturnType) } return nil } func (v *Validator) phpTypeToGoType(t phpType, isNullable bool) string { var baseType string switch t { case phpString: baseType = "*C.zend_string" case phpInt: baseType = "int64" case phpFloat: baseType = "float64" case phpBool: baseType = "bool" case phpArray: baseType = "*C.zend_array" case phpMixed: baseType = "*C.zval" case phpCallable: baseType = "*C.zval" default: baseType = "any" } if isNullable && t != phpString && t != phpArray && t != phpCallable { return "*" + baseType } return baseType } // isCompatibleGoType checks if the actual Go type is compatible with the expected type. func (v *Validator) isCompatibleGoType(expectedType, actualType string) bool { if expectedType == actualType { return true } switch expectedType { case "int64": return actualType == "int" case "*int64": return actualType == "*int" case "*float64": return actualType == "*float32" } return false } func (v *Validator) phpReturnTypeToGoType(phpReturnType phpType) string { switch phpReturnType { case phpVoid: return "" case phpString: return "unsafe.Pointer" case phpInt: return "int64" case phpFloat: return "float64" case phpBool: return "bool" case phpArray: return "unsafe.Pointer" default: return "any" } } func (v *Validator) goTypeToString(expr ast.Expr) string { switch t := expr.(type) { case *ast.Ident: return t.Name case *ast.StarExpr: return "*" + v.goTypeToString(t.X) case *ast.SelectorExpr: return v.goTypeToString(t.X) + "." + t.Sel.Name default: return "unknown" } } func (v *Validator) goReturnTypeToString(results *ast.FieldList) string { if results == nil || len(results.List) == 0 { return "" } if len(results.List) == 1 { return v.goTypeToString(results.List[0].Type) } var types []string for _, field := range results.List { types = append(types, v.goTypeToString(field.Type)) } return "(" + strings.Join(types, ", ") + ")" } ================================================ FILE: internal/extgen/validator_test.go ================================================ package extgen import ( "testing" "github.com/stretchr/testify/assert" ) func TestValidateFunction(t *testing.T) { tests := []struct { name string function phpFunction expectError bool }{ { name: "valid function", function: phpFunction{ Name: "validFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "param1", PhpType: phpString}, {Name: "param2", PhpType: phpInt}, }, }, expectError: false, }, { name: "valid function with nullable return", function: phpFunction{ Name: "nullableReturn", ReturnType: phpString, IsReturnNullable: true, Params: []phpParameter{ {Name: "data", PhpType: phpArray}, }, }, expectError: false, }, { name: "valid function with array parameter", function: phpFunction{ Name: "arrayFunction", ReturnType: phpArray, Params: []phpParameter{ {Name: "items", PhpType: phpArray}, {Name: "filter", PhpType: phpString}, }, }, expectError: false, }, { name: "valid function with nullable array parameter", function: phpFunction{ Name: "nullableArrayFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: true}, {Name: "name", PhpType: phpString}, }, }, expectError: false, }, { name: "valid function with array parameter", function: phpFunction{ Name: "arrayFunction", ReturnType: "array", Params: []phpParameter{ {Name: "items", PhpType: phpArray}, {Name: "filter", PhpType: phpString}, }, }, expectError: false, }, { name: "valid function with nullable array parameter", function: phpFunction{ Name: "nullableArrayFunction", ReturnType: "string", Params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: true}, {Name: "name", PhpType: phpString}, }, }, expectError: false, }, { name: "valid function with callable parameter", function: phpFunction{ Name: "callableFunction", ReturnType: "array", Params: []phpParameter{ {Name: "data", PhpType: phpArray}, {Name: "callback", PhpType: phpCallable}, }, }, expectError: false, }, { name: "valid function with nullable callable parameter", function: phpFunction{ Name: "nullableCallableFunction", ReturnType: "string", Params: []phpParameter{ {Name: "callback", PhpType: phpCallable, IsNullable: true}, }, }, expectError: false, }, { name: "empty function name", function: phpFunction{ Name: "", ReturnType: phpString, }, expectError: true, }, { name: "invalid function name - starts with number", function: phpFunction{ Name: "123invalid", ReturnType: phpString, }, expectError: true, }, { name: "invalid function name - contains special chars", function: phpFunction{ Name: "invalid-name", ReturnType: phpString, }, expectError: true, }, { name: "invalid parameter name", function: phpFunction{ Name: "validName", ReturnType: phpString, Params: []phpParameter{ {Name: "123invalid", PhpType: phpString}, }, }, expectError: true, }, { name: "empty parameter name", function: phpFunction{ Name: "validName", ReturnType: phpString, Params: []phpParameter{ {Name: "", PhpType: phpString}, }, }, expectError: true, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateFunction(tt.function) if tt.expectError { assert.Error(t, err, "validateFunction() should return an error for function %s", tt.function.Name) } else { assert.NoError(t, err, "validateFunction() should not return an error for function %s", tt.function.Name) } }) } } func TestValidateReturnType(t *testing.T) { tests := []struct { name string returnType string expectError bool }{ { name: "valid string type", returnType: "string", expectError: false, }, { name: "valid int type", returnType: "int", expectError: false, }, { name: "valid array type", returnType: "array", expectError: false, }, { name: "valid bool type", returnType: "bool", expectError: false, }, { name: "valid float type", returnType: "float", expectError: false, }, { name: "valid void type", returnType: "void", expectError: false, }, { name: "invalid return type", returnType: "invalidType", expectError: true, }, { name: "empty return type", returnType: "", expectError: true, }, { name: "case sensitive - String should be invalid", returnType: "String", expectError: true, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateReturnType(phpType(tt.returnType)) if tt.expectError { assert.Error(t, err, "validateReturnType(%s) should return an error", tt.returnType) } else { assert.NoError(t, err, "validateReturnType(%s) should not return an error", tt.returnType) } }) } } func TestValidateClassProperty(t *testing.T) { tests := []struct { name string prop phpClassProperty expectError bool }{ { name: "valid property", prop: phpClassProperty{ Name: "validProperty", PhpType: phpString, GoType: "string", }, expectError: false, }, { name: "valid nullable property", prop: phpClassProperty{ Name: "nullableProperty", PhpType: phpInt, GoType: "*int", IsNullable: true, }, expectError: false, }, { name: "empty property name", prop: phpClassProperty{ Name: "", PhpType: phpString, }, expectError: true, }, { name: "invalid property name", prop: phpClassProperty{ Name: "123invalid", PhpType: phpString, }, expectError: true, }, { name: "invalid property type", prop: phpClassProperty{ Name: "validName", PhpType: phpType("invalidType"), }, expectError: true, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateClassProperty(tt.prop) if tt.expectError { assert.Error(t, err, "validateClassProperty() should return an error") } else { assert.NoError(t, err, "validateClassProperty() should not return an error") } }) } } func TestValidateParameter(t *testing.T) { tests := []struct { name string param phpParameter expectError bool }{ { name: "valid string parameter", param: phpParameter{ Name: "validParam", PhpType: phpString, }, expectError: false, }, { name: "valid nullable parameter", param: phpParameter{ Name: "nullableParam", PhpType: phpInt, IsNullable: true, }, expectError: false, }, { name: "valid parameter with default", param: phpParameter{ Name: "defaultParam", PhpType: phpString, HasDefault: true, DefaultValue: "hello", }, expectError: false, }, { name: "valid array parameter", param: phpParameter{ Name: "arrayParam", PhpType: phpArray, }, expectError: false, }, { name: "valid nullable array parameter", param: phpParameter{ Name: "nullableArrayParam", PhpType: phpArray, IsNullable: true, }, expectError: false, }, { name: "valid callable parameter", param: phpParameter{ Name: "callbackParam", PhpType: phpCallable, }, expectError: false, }, { name: "valid nullable callable parameter", param: phpParameter{ Name: "nullableCallbackParam", PhpType: "callable", IsNullable: true, }, expectError: false, }, { name: "empty parameter name", param: phpParameter{ Name: "", PhpType: phpString, }, expectError: true, }, { name: "invalid parameter name", param: phpParameter{ Name: "123invalid", PhpType: phpString, }, expectError: true, }, { name: "invalid parameter type", param: phpParameter{ Name: "validName", PhpType: phpType("invalidType"), }, expectError: true, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateParameter(tt.param) if tt.expectError { assert.Error(t, err, "validateParameter() should return an error") } else { assert.NoError(t, err, "validateParameter() should not return an error") } }) } } func TestValidateClass(t *testing.T) { tests := []struct { name string class phpClass expectError bool }{ { name: "valid class", class: phpClass{ Name: "ValidClass", GoStruct: "ValidStruct", Properties: []phpClassProperty{ {Name: "name", PhpType: phpString}, {Name: "age", PhpType: phpInt}, }, }, expectError: false, }, { name: "valid class with nullable properties", class: phpClass{ Name: "NullableClass", GoStruct: "NullableStruct", Properties: []phpClassProperty{ {Name: "required", PhpType: phpString, IsNullable: false}, {Name: "optional", PhpType: phpString, IsNullable: true}, }, }, expectError: false, }, { name: "empty class name", class: phpClass{ Name: "", GoStruct: "ValidStruct", }, expectError: true, }, { name: "invalid class name", class: phpClass{ Name: "123InvalidClass", GoStruct: "ValidStruct", }, expectError: true, }, { name: "invalid property", class: phpClass{ Name: "ValidClass", GoStruct: "ValidStruct", Properties: []phpClassProperty{ {Name: "123invalid", PhpType: phpString}, }, }, expectError: true, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateClass(tt.class) if tt.expectError { assert.Error(t, err, "validateClass() should return an error") } else { assert.NoError(t, err, "validateClass() should not return an error") } }) } } func TestValidateTypes(t *testing.T) { tests := []struct { name string function phpFunction expectError bool errorMsg string }{ { name: "valid scalar parameters only", function: phpFunction{ Name: "validFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "stringParam", PhpType: phpString}, {Name: "intParam", PhpType: phpInt}, {Name: "floatParam", PhpType: phpFloat}, {Name: "boolParam", PhpType: phpBool}, }, }, expectError: false, }, { name: "valid nullable scalar parameters", function: phpFunction{ Name: "nullableFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "stringParam", PhpType: phpString, IsNullable: true}, {Name: "intParam", PhpType: phpInt, IsNullable: true}, }, }, expectError: false, }, { name: "valid void return type", function: phpFunction{ Name: "voidFunction", ReturnType: phpVoid, Params: []phpParameter{ {Name: "stringParam", PhpType: phpString}, }, }, expectError: false, }, { name: "valid array parameter and return", function: phpFunction{ Name: "arrayFunction", ReturnType: phpArray, Params: []phpParameter{ {Name: "arrayParam", PhpType: phpArray}, {Name: "stringParam", PhpType: phpString}, }, }, expectError: false, }, { name: "valid nullable array parameter", function: phpFunction{ Name: "nullableArrayFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "arrayParam", PhpType: phpArray, IsNullable: true}, }, }, expectError: false, }, { name: "valid callable parameter", function: phpFunction{ Name: "callableFunction", ReturnType: "array", Params: []phpParameter{ {Name: "callbackParam", PhpType: phpCallable}, }, }, expectError: false, }, { name: "valid nullable callable parameter", function: phpFunction{ Name: "nullableCallableFunction", ReturnType: "string", Params: []phpParameter{ {Name: "callbackParam", PhpType: phpCallable, IsNullable: true}, }, }, expectError: false, }, { name: "invalid object parameter", function: phpFunction{ Name: "objectFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "objectParam", PhpType: phpObject}, }, }, expectError: true, errorMsg: `parameter 1 "objectParam" has unsupported type "object"`, }, { name: "invalid object return type", function: phpFunction{ Name: "objectReturnFunction", ReturnType: phpObject, Params: []phpParameter{ {Name: "stringParam", PhpType: phpString}, }, }, expectError: true, errorMsg: `return type "object" is not supported`, }, { name: "mixed scalar and invalid parameters", function: phpFunction{ Name: "mixedFunction", ReturnType: phpString, Params: []phpParameter{ {Name: "validParam", PhpType: phpString}, {Name: "invalidParam", PhpType: phpObject}, {Name: "anotherValidParam", PhpType: phpInt}, }, }, expectError: true, errorMsg: `parameter 2 "invalidParam" has unsupported type "object"`, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateTypes(tt.function) if tt.expectError { assert.Error(t, err, "validateTypes() should return an error for function %s", tt.function.Name) assert.Contains(t, err.Error(), tt.errorMsg, "Error message should contain expected text") } else { assert.NoError(t, err, "validateTypes() should not return an error for function %s", tt.function.Name) } }) } } func TestValidateGoFunctionSignature(t *testing.T) { tests := []struct { name string phpFunc phpFunction expectError bool errorMsg string }{ { name: "valid Go function signature", phpFunc: phpFunction{ Name: "testFunc", ReturnType: phpString, Params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "count", PhpType: phpInt}, }, GoFunction: `func testFunc(name *C.zend_string, count int64) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "valid void return type", phpFunc: phpFunction{ Name: "voidFunc", ReturnType: phpVoid, Params: []phpParameter{ {Name: "message", PhpType: phpString}, }, GoFunction: `func voidFunc(message *C.zend_string) { // Do something }`, }, expectError: false, }, { name: "no Go function provided", phpFunc: phpFunction{ Name: "noGoFunc", ReturnType: phpString, Params: []phpParameter{}, GoFunction: "", }, expectError: true, errorMsg: "no Go function found", }, { name: "parameter count mismatch", phpFunc: phpFunction{ Name: "countMismatch", ReturnType: phpString, Params: []phpParameter{ {Name: "param1", PhpType: phpString}, {Name: "param2", PhpType: phpInt}, }, GoFunction: `func countMismatch(param1 *C.zend_string) unsafe.Pointer { return nil }`, }, expectError: true, errorMsg: "parameter count mismatch: PHP function has 2 parameters (expecting 2 Go parameters) but Go function has 1", }, { name: "parameter type mismatch", phpFunc: phpFunction{ Name: "typeMismatch", ReturnType: phpString, Params: []phpParameter{ {Name: "name", PhpType: phpString}, {Name: "count", PhpType: phpInt}, }, GoFunction: `func typeMismatch(name *C.zend_string, count string) unsafe.Pointer { return nil }`, }, expectError: true, errorMsg: `parameter 2 type mismatch: PHP "int" requires Go type "int64" but found "string"`, }, { name: "return type mismatch", phpFunc: phpFunction{ Name: "returnMismatch", ReturnType: phpInt, Params: []phpParameter{ {Name: "value", PhpType: phpString}, }, GoFunction: `func returnMismatch(value *C.zend_string) string { return "" }`, }, expectError: true, errorMsg: `return type mismatch: PHP "int" requires Go return type "int64" but found "string"`, }, { name: "valid bool parameter and return", phpFunc: phpFunction{ Name: "boolFunc", ReturnType: phpBool, Params: []phpParameter{ {Name: "flag", PhpType: phpBool}, }, GoFunction: `func boolFunc(flag bool) bool { return flag }`, }, expectError: false, }, { name: "valid float parameter and return", phpFunc: phpFunction{ Name: "floatFunc", ReturnType: phpFloat, Params: []phpParameter{ {Name: "value", PhpType: phpFloat}, }, GoFunction: `func floatFunc(value float64) float64 { return value * 2.0 }`, }, expectError: false, }, { name: "valid array parameter and return", phpFunc: phpFunction{ Name: "arrayFunc", ReturnType: phpArray, Params: []phpParameter{ {Name: "items", PhpType: phpArray}, }, GoFunction: `func arrayFunc(items *C.zend_array) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "valid nullable array parameter", phpFunc: phpFunction{ Name: "nullableArrayFunc", ReturnType: phpString, Params: []phpParameter{ {Name: "items", PhpType: phpArray, IsNullable: true}, {Name: "name", PhpType: phpString}, }, GoFunction: `func nullableArrayFunc(items *C.zend_array, name *C.zend_string) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "mixed array and scalar parameters", phpFunc: phpFunction{ Name: "mixedFunc", ReturnType: phpArray, Params: []phpParameter{ {Name: "data", PhpType: phpArray}, {Name: "filter", PhpType: phpString}, {Name: "limit", PhpType: phpInt}, }, GoFunction: `func mixedFunc(data *C.zend_array, filter *C.zend_string, limit int64) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "valid callable parameter", phpFunc: phpFunction{ Name: "callableFunc", ReturnType: "array", Params: []phpParameter{ {Name: "callback", PhpType: phpCallable}, }, GoFunction: `func callableFunc(callback *C.zval) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "valid nullable callable parameter", phpFunc: phpFunction{ Name: "nullableCallableFunc", ReturnType: "string", Params: []phpParameter{ {Name: "callback", PhpType: phpCallable, IsNullable: true}, }, GoFunction: `func nullableCallableFunc(callback *C.zval) unsafe.Pointer { return nil }`, }, expectError: false, }, { name: "mixed callable and other parameters", phpFunc: phpFunction{ Name: "mixedCallableFunc", ReturnType: "array", Params: []phpParameter{ {Name: "data", PhpType: phpArray}, {Name: "callback", PhpType: phpCallable}, {Name: "options", PhpType: "int"}, }, GoFunction: `func mixedCallableFunc(data *C.zend_array, callback *C.zval, options int64) unsafe.Pointer { return nil }`, }, expectError: false, }, } validator := Validator{} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := validator.validateGoFunctionSignatureWithOptions(tt.phpFunc, false) if tt.expectError { assert.Error(t, err, "validateGoFunctionSignature() should return an error for function %s", tt.phpFunc.Name) assert.Contains(t, err.Error(), tt.errorMsg, "Error message should contain expected text") } else { assert.NoError(t, err, "validateGoFunctionSignature() should not return an error for function %s", tt.phpFunc.Name) } }) } } func TestPhpTypeToGoType(t *testing.T) { tests := []struct { phpType string isNullable bool expected string }{ {"string", false, "*C.zend_string"}, {"string", true, "*C.zend_string"}, {"int", false, "int64"}, {"int", true, "*int64"}, {"float", false, "float64"}, {"float", true, "*float64"}, {"bool", false, "bool"}, {"bool", true, "*bool"}, {"array", false, "*C.zend_array"}, {"array", true, "*C.zend_array"}, {"callable", false, "*C.zval"}, {"callable", true, "*C.zval"}, {"unknown", false, "any"}, } validator := Validator{} for _, tt := range tests { t.Run(tt.phpType, func(t *testing.T) { result := validator.phpTypeToGoType(phpType(tt.phpType), tt.isNullable) assert.Equal(t, tt.expected, result, "phpTypeToGoType(%s, %v) should return %s", tt.phpType, tt.isNullable, tt.expected) }) } } func TestPhpReturnTypeToGoType(t *testing.T) { tests := []struct { phpReturnType string expected string }{ {"void", ""}, {"void", ""}, {"string", "unsafe.Pointer"}, {"string", "unsafe.Pointer"}, {"int", "int64"}, {"int", "int64"}, {"float", "float64"}, {"float", "float64"}, {"bool", "bool"}, {"bool", "bool"}, {"array", "unsafe.Pointer"}, {"array", "unsafe.Pointer"}, {"unknown", "any"}, } validator := Validator{} for _, tt := range tests { t.Run(tt.phpReturnType, func(t *testing.T) { result := validator.phpReturnTypeToGoType(phpType(tt.phpReturnType)) assert.Equal(t, tt.expected, result, "phpReturnTypeToGoType(%s) should return %s", tt.phpReturnType, tt.expected) }) } } ================================================ FILE: internal/fastabs/filepath.go ================================================ //go:build !unix package fastabs import ( "path/filepath" ) // FastAbs can't be optimized on Windows because the // syscall.FullPath function takes an input. func FastAbs(path string) (string, error) { // Normalize forward slashes to backslashes for Windows compatibility return filepath.Abs(filepath.FromSlash(path)) } ================================================ FILE: internal/fastabs/filepath_unix.go ================================================ //go:build unix package fastabs import ( "os" "path/filepath" ) var ( wd string wderr error ) func init() { wd, wderr = os.Getwd() if wderr != nil { return } canonicalWD, err := filepath.EvalSymlinks(wd) if err == nil { wd = canonicalWD } } // FastAbs is an optimized version of filepath.Abs for Unix systems, // since we don't expect the working directory to ever change once // Caddy is running. Avoid the os.Getwd syscall overhead. func FastAbs(path string) (string, error) { if filepath.IsAbs(path) { return filepath.Clean(path), nil } if wderr != nil { return "", wderr } return filepath.Join(wd, path), nil } ================================================ FILE: internal/memory/memory_linux.go ================================================ package memory import "syscall" func TotalSysMemory() uint64 { sysInfo := &syscall.Sysinfo_t{} err := syscall.Sysinfo(sysInfo) if err != nil { return 0 } return uint64(sysInfo.Totalram) * uint64(sysInfo.Unit) } ================================================ FILE: internal/memory/memory_others.go ================================================ //go:build !linux package memory // TotalSysMemory returns 0 if the total system memory cannot be determined func TotalSysMemory() uint64 { return 0 } ================================================ FILE: internal/phpheaders/phpheaders.go ================================================ package phpheaders import "C" import ( "context" "strings" "github.com/maypok86/otter/v2" ) // Translate header names to PHP header names // All headers in 'commonHeaders' can be cached and registered safely // All other headers must be sanitized // Note: net/http will capitalize lowercase headers, so we don't need to worry about case sensitivity var CommonRequestHeaders = map[string]string{ "Accept": "HTTP_ACCEPT", "Accept-Charset": "HTTP_ACCEPT_CHARSET", "Accept-Encoding": "HTTP_ACCEPT_ENCODING", "Accept-Language": "HTTP_ACCEPT_LANGUAGE", "Access-Control-Request-Headers": "HTTP_ACCESS_CONTROL_REQUEST_HEADERS", "Access-Control-Request-Method": "HTTP_ACCESS_CONTROL_REQUEST_METHOD", "Authorization": "HTTP_AUTHORIZATION", "Cache-Control": "HTTP_CACHE_CONTROL", "Connection": "HTTP_CONNECTION", "Content-Disposition": "HTTP_CONTENT_DISPOSITION", "Content-Encoding": "HTTP_CONTENT_ENCODING", "Content-Length": "HTTP_CONTENT_LENGTH", "Content-Type": "HTTP_CONTENT_TYPE", "Cookie": "HTTP_COOKIE", "Date": "HTTP_DATE", "Device-Memory": "HTTP_DEVICE_MEMORY", "Dnt": "HTTP_DNT", "Downlink": "HTTP_DOWNLINK", "Dpr": "HTTP_DPR", "Early-Data": "HTTP_EARLY_DATA", "Ect": "HTTP_ECT", "Am-I": "HTTP_AM_I", "Expect": "HTTP_EXPECT", "Forwarded": "HTTP_FORWARDED", "From": "HTTP_FROM", "Host": "HTTP_HOST", "If-Match": "HTTP_IF_MATCH", "If-Modified-Since": "HTTP_IF_MODIFIED_SINCE", "If-None-Match": "HTTP_IF_NONE_MATCH", "If-Range": "HTTP_IF_RANGE", "If-Unmodified-Since": "HTTP_IF_UNMODIFIED_SINCE", "Keep-Alive": "HTTP_KEEP_ALIVE", "Max-Forwards": "HTTP_MAX_FORWARDS", "Origin": "HTTP_ORIGIN", "Pragma": "HTTP_PRAGMA", "Proxy-Authorization": "HTTP_PROXY_AUTHORIZATION", "Range": "HTTP_RANGE", "Referer": "HTTP_REFERER", "Rtt": "HTTP_RTT", "Save-Data": "HTTP_SAVE_DATA", "Sec-Ch-Ua": "HTTP_SEC_CH_UA", "Sec-Ch-Ua-Arch": "HTTP_SEC_CH_UA_ARCH", "Sec-Ch-Ua-Bitness": "HTTP_SEC_CH_UA_BITNESS", "Sec-Ch-Ua-Full-Version": "HTTP_SEC_CH_UA_FULL_VERSION", "Sec-Ch-Ua-Full-Version-List": "HTTP_SEC_CH_UA_FULL_VERSION_LIST", "Sec-Ch-Ua-Mobile": "HTTP_SEC_CH_UA_MOBILE", "Sec-Ch-Ua-Model": "HTTP_SEC_CH_UA_MODEL", "Sec-Ch-Ua-Platform": "HTTP_SEC_CH_UA_PLATFORM", "Sec-Ch-Ua-Platform-Version": "HTTP_SEC_CH_UA_PLATFORM_VERSION", "Sec-Fetch-Dest": "HTTP_SEC_FETCH_DEST", "Sec-Fetch-Mode": "HTTP_SEC_FETCH_MODE", "Sec-Fetch-Site": "HTTP_SEC_FETCH_SITE", "Sec-Fetch-User": "HTTP_SEC_FETCH_USER", "Sec-Gpc": "HTTP_SEC_GPC", "Service-Worker-Navigation-Preload": "HTTP_SERVICE_WORKER_NAVIGATION_PRELOAD", "Te": "HTTP_TE", "Priority": "HTTP_PRIORITY", "Trailer": "HTTP_TRAILER", "Transfer-Encoding": "HTTP_TRANSFER_ENCODING", "Upgrade": "HTTP_UPGRADE", "Upgrade-Insecure-Requests": "HTTP_UPGRADE_INSECURE_REQUESTS", "User-Agent": "HTTP_USER_AGENT", "Via": "HTTP_VIA", "Viewport-Width": "HTTP_VIEWPORT_WIDTH", "Want-Digest": "HTTP_WANT_DIGEST", "Warning": "HTTP_WARNING", "Width": "HTTP_WIDTH", "X-Forwarded-For": "HTTP_X_FORWARDED_FOR", "X-Forwarded-Host": "HTTP_X_FORWARDED_HOST", "X-Forwarded-Path": "HTTP_X_FORWARDED_PATH", "X-Forwarded-Prefix": "HTTP_X_FORWARDED_PREFIX", "X-Forwarded-Proto": "HTTP_X_FORWARDED_PROTO", "A-Im": "HTTP_A_IM", "Accept-Datetime": "HTTP_ACCEPT_DATETIME", "Content-Md5": "HTTP_CONTENT_MD5", "Http2-Settings": "HTTP_HTTP2_SETTINGS", "Prefer": "HTTP_PREFER", "X-Requested-With": "HTTP_X_REQUESTED_WITH", "Front-End-Https": "HTTP_FRONT_END_HTTPS", "X-Http-Method-Override": "HTTP_X_HTTP_METHOD_OVERRIDE", "X-Att-Deviceid": "HTTP_X_ATT_DEVICEID", "X-Wap-Profile": "HTTP_X_WAP_PROFILE", "Proxy-Connection": "HTTP_PROXY_CONNECTION", "X-Uidh": "HTTP_X_UIDH", "X-Csrf-Token": "HTTP_X_CSRF_TOKEN", "X-Request-Id": "HTTP_X_REQUEST_ID", "X-Correlation-Id": "HTTP_X_CORRELATION_ID", // Additional CDN/Framework headers "Cloudflare-Visitor": "HTTP_CLOUDFLARE_VISITOR", "Cloudfront-Viewer-Address": "HTTP_CLOUDFRONT_VIEWER_ADDRESS", "Cloudfront-Viewer-Country": "HTTP_CLOUDFRONT_VIEWER_COUNTRY", "X-Amzn-Trace-Id": "HTTP_X_AMZN_TRACE_ID", "X-Cloud-Trace-Context": "HTTP_X_CLOUD_TRACE_CONTEXT", "Cf-Ray": "HTTP_CF_RAY", "Cf-Visitor": "HTTP_CF_VISITOR", "Cf-Request-Id": "HTTP_CF_REQUEST_ID", "Cf-Ipcountry": "HTTP_CF_IPCOUNTRY", "X-Device-Type": "HTTP_X_DEVICE_TYPE", "X-Network-Info": "HTTP_X_NETWORK_INFO", "X-Client-Id": "HTTP_X_CLIENT_ID", "X-Livewire": "HTTP_X_LIVEWIRE", "X-Real-Ip": "HTTP_X_REAL_IP", } // Cache up to 256 uncommon headers // This is ~2.5x faster than converting the header each time var ( headerKeyCache = otter.Must[string, string](&otter.Options[string, string]{MaximumSize: 256}) headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_") loader = otter.LoaderFunc[string, string](func(_ context.Context, key string) (string, error) { return "HTTP_" + headerNameReplacer.Replace(strings.ToUpper(key)) + "\x00", nil }) ) func GetUnCommonHeader(ctx context.Context, key string) string { phpHeaderKey, err := headerKeyCache.Get(ctx, key, loader) if err != nil { panic(err) } return phpHeaderKey } ================================================ FILE: internal/phpheaders/phpheaders_test.go ================================================ package phpheaders import ( "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestAllCommonHeadersAreCorrect(t *testing.T) { fakeRequest := httptest.NewRequest("GET", "http://localhost", nil) for header, phpHeader := range CommonRequestHeaders { // verify that common and uncommon headers return the same result expectedPHPHeader := GetUnCommonHeader(t.Context(), header) assert.Equal(t, phpHeader+"\x00", expectedPHPHeader, "header is not well formed: "+phpHeader) // net/http will capitalize lowercase headers, verify that headers are capitalized fakeRequest.Header.Add(header, "foo") assert.Contains(t, fakeRequest.Header, header, "header is not correctly capitalized: "+header) } } ================================================ FILE: internal/state/state.go ================================================ package state import "C" import ( "slices" "sync" "sync/atomic" "time" ) type State int const ( // lifecycle States of a thread Reserved State = iota Booting BootRequested ShuttingDown Done // these States are 'stable' and safe to transition from at any time Inactive Ready // States necessary for restarting workers Restarting Yielding // States necessary for transitioning between different handlers TransitionRequested TransitionInProgress TransitionComplete ) func (s State) String() string { switch s { case Reserved: return "reserved" case Booting: return "booting" case BootRequested: return "boot requested" case ShuttingDown: return "shutting down" case Done: return "done" case Inactive: return "inactive" case Ready: return "ready" case Restarting: return "restarting" case Yielding: return "yielding" case TransitionRequested: return "transition requested" case TransitionInProgress: return "transition in progress" case TransitionComplete: return "transition complete" default: return "unknown" } } type ThreadState struct { currentState State mu sync.RWMutex subscribers []stateSubscriber // how long threads have been waiting in stable states (unix ms, 0 = not waiting) waitingSince atomic.Int64 } type stateSubscriber struct { states []State ch chan struct{} } func NewThreadState() *ThreadState { return &ThreadState{ currentState: Reserved, subscribers: []stateSubscriber{}, mu: sync.RWMutex{}, } } func (ts *ThreadState) Is(state State) bool { ts.mu.RLock() ok := ts.currentState == state ts.mu.RUnlock() return ok } func (ts *ThreadState) CompareAndSwap(compareTo State, swapTo State) bool { ts.mu.Lock() ok := ts.currentState == compareTo if ok { ts.currentState = swapTo ts.notifySubscribers(swapTo) } ts.mu.Unlock() return ok } func (ts *ThreadState) Name() string { return ts.Get().String() } func (ts *ThreadState) Get() State { ts.mu.RLock() id := ts.currentState ts.mu.RUnlock() return id } func (ts *ThreadState) Set(nextState State) { ts.mu.Lock() ts.currentState = nextState ts.notifySubscribers(nextState) ts.mu.Unlock() } func (ts *ThreadState) notifySubscribers(nextState State) { if len(ts.subscribers) == 0 { return } n := 0 for _, sub := range ts.subscribers { if !slices.Contains(sub.states, nextState) { ts.subscribers[n] = sub n++ continue } close(sub.ch) } ts.subscribers = ts.subscribers[:n] } // WaitFor blocks until the thread reaches a certain state func (ts *ThreadState) WaitFor(states ...State) { ts.mu.Lock() if slices.Contains(states, ts.currentState) { ts.mu.Unlock() return } sub := stateSubscriber{ states: states, ch: make(chan struct{}), } ts.subscribers = append(ts.subscribers, sub) ts.mu.Unlock() <-sub.ch } // RequestSafeStateChange safely requests a state change from a different goroutine func (ts *ThreadState) RequestSafeStateChange(nextState State) bool { ts.mu.Lock() switch ts.currentState { // disallow state changes if shutting down or done case ShuttingDown, Done, Reserved: ts.mu.Unlock() return false // ready and inactive are safe states to transition from case Ready, Inactive: ts.currentState = nextState ts.notifySubscribers(nextState) ts.mu.Unlock() return true } ts.mu.Unlock() // wait for the state to change to a safe state ts.WaitFor(Ready, Inactive, ShuttingDown) return ts.RequestSafeStateChange(nextState) } // MarkAsWaiting hints that the thread reached a stable state and is waiting for requests or shutdown func (ts *ThreadState) MarkAsWaiting(isWaiting bool) { if isWaiting { ts.waitingSince.Store(time.Now().UnixMilli()) } else { ts.waitingSince.Store(0) } } // IsInWaitingState returns true if a thread is waiting for a request or shutdown func (ts *ThreadState) IsInWaitingState() bool { return ts.waitingSince.Load() != 0 } // WaitTime returns the time since the thread is waiting in a stable state in ms func (ts *ThreadState) WaitTime() int64 { since := ts.waitingSince.Load() if since == 0 { return 0 } return time.Now().UnixMilli() - since } func (ts *ThreadState) SetWaitTime(t time.Time) { ts.waitingSince.Store(t.UnixMilli()) } ================================================ FILE: internal/state/state_test.go ================================================ package state import ( "testing" "time" "github.com/stretchr/testify/assert" ) func Test2GoroutinesYieldToEachOtherViaStates(t *testing.T) { threadState := &ThreadState{currentState: Booting} go func() { threadState.WaitFor(Inactive) assert.True(t, threadState.Is(Inactive)) threadState.Set(Ready) }() threadState.Set(Inactive) threadState.WaitFor(Ready) assert.True(t, threadState.Is(Ready)) } func TestStateShouldHaveCorrectAmountOfSubscribers(t *testing.T) { threadState := &ThreadState{currentState: Booting} // 3 subscribers waiting for different states go threadState.WaitFor(Inactive) go threadState.WaitFor(Inactive, ShuttingDown) go threadState.WaitFor(ShuttingDown) assertNumberOfSubscribers(t, threadState, 3) threadState.Set(Inactive) assertNumberOfSubscribers(t, threadState, 1) assert.True(t, threadState.CompareAndSwap(Inactive, ShuttingDown)) assertNumberOfSubscribers(t, threadState, 0) } func assertNumberOfSubscribers(t *testing.T, threadState *ThreadState, expected int) { t.Helper() for range 10_000 { // wait for 1 second max time.Sleep(100 * time.Microsecond) threadState.mu.RLock() if len(threadState.subscribers) == expected { threadState.mu.RUnlock() break } threadState.mu.RUnlock() } threadState.mu.RLock() assert.Len(t, threadState.subscribers, expected) threadState.mu.RUnlock() } ================================================ FILE: internal/testcli/main.go ================================================ package main import ( "log" "os" "github.com/dunglas/frankenphp" ) func main() { if len(os.Args) <= 1 { log.Println("Usage: testcli script.php") os.Exit(1) } if len(os.Args) == 3 && os.Args[1] == "-r" { os.Exit(frankenphp.ExecutePHPCode(os.Args[2])) } os.Exit(frankenphp.ExecuteScriptCLI(os.Args[1], os.Args)) } ================================================ FILE: internal/testext/ext_test.go ================================================ package testext import "testing" func TestRegisterExtension(t *testing.T) { testRegisterExtension(t) } ================================================ FILE: internal/testext/extension.h ================================================ #ifndef _EXTENSIONS_H #define _EXTENSIONS_H #include "../../frankenphp.h" #include extern zend_module_entry module1_entry; extern zend_module_entry module2_entry; #endif ================================================ FILE: internal/testext/extensions.c ================================================ #include "extension.h" #include #include #include "_cgo_export.h" zend_module_entry module1_entry = {STANDARD_MODULE_HEADER, "ext1", NULL, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.0", STANDARD_MODULE_PROPERTIES}; zend_module_entry module2_entry = {STANDARD_MODULE_HEADER, "ext2", NULL, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ "0.1.0", STANDARD_MODULE_PROPERTIES}; ================================================ FILE: internal/testext/exttest.go ================================================ package testext // #cgo darwin pkg-config: libxml-2.0 // #cgo unix CFLAGS: -Wall -Werror // #cgo unix CFLAGS: -I/usr/local/include -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib // #cgo linux CFLAGS: -D_GNU_SOURCE // #cgo darwin CFLAGS: -I/opt/homebrew/include // #cgo unix LDFLAGS: -L/usr/local/lib -L/usr/lib -lphp -lm -lutil // #cgo linux LDFLAGS: -ldl -lresolv // #cgo darwin LDFLAGS: -Wl,-rpath,/usr/local/lib -L/opt/homebrew/lib -L/opt/homebrew/opt/libiconv/lib -liconv -ldl // #cgo windows CFLAGS: -D_WINDOWS -DWINDOWS=1 -DZEND_WIN32=1 -DPHP_WIN32=1 -DWIN32 -D_MBCS -D_USE_MATH_DEFINES -DNDebug -DNDEBUG -DZEND_DEBUG=0 -DZTS=1 -DFD_SETSIZE=256 // #include "extension.h" import "C" import ( "io" "net/http/httptest" "testing" "unsafe" "github.com/dunglas/frankenphp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func testRegisterExtension(t *testing.T) { frankenphp.RegisterExtension(unsafe.Pointer(&C.module1_entry)) frankenphp.RegisterExtension(unsafe.Pointer(&C.module2_entry)) err := frankenphp.Init() require.Nil(t, err) defer frankenphp.Shutdown() req := httptest.NewRequest("GET", "http://example.com/index.php", nil) w := httptest.NewRecorder() req, err = frankenphp.NewRequestWithContext(req, frankenphp.WithRequestDocumentRoot("./testdata", false)) assert.NoError(t, err) err = frankenphp.ServeHTTP(w, req) assert.NoError(t, err) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), "ext1") assert.Contains(t, string(body), "ext2") } ================================================ FILE: internal/testext/testdata/index.php ================================================ len(partsToMatch) { return false } cursor = j subPattern := strings.Join(partsToMatch[j:j+patternSize], sep) if matchCurlyBracePattern(pattern, subPattern) { cursor = j + patternSize - 1 break } if cursor > len(partsToMatch)-patternSize-1 { return false } } } return true } // we also check for the following syntax: /path/*.{php,twig,yaml} func matchCurlyBracePattern(pattern string, fileName string) bool { for _, subPattern := range expandCurlyBraces(pattern) { if matchPattern(subPattern, fileName) { return true } } return false } // {dir1,dir2}/path -> []string{"dir1/path", "dir2/path"} func expandCurlyBraces(s string) []string { before, rest, found := strings.Cut(s, "{") if !found { return []string{s} } inside, after, found := strings.Cut(rest, "}") if !found { return []string{s} // no closing brace } var out []string for _, subPattern := range strings.Split(inside, ",") { out = append(out, expandCurlyBraces(before+subPattern+after)...) } return out } func matchPattern(pattern string, fileName string) bool { if pattern == "" { return true } patternMatches, err := filepath.Match(pattern, fileName) if err != nil { if globalLogger.Enabled(globalCtx, slog.LevelError) { globalLogger.LogAttrs(globalCtx, slog.LevelError, "failed to match filename", slog.String("file", fileName), slog.Any("error", err)) } return false } return patternMatches } ================================================ FILE: internal/watcher/pattern_test.go ================================================ //go:build !nowatcher package watcher import ( "path/filepath" "strings" "testing" "github.com/e-dant/watcher/watcher-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func normalizePath(t *testing.T, path string) string { t.Helper() if filepath.Separator == '/' { return path } path = filepath.FromSlash(path) if strings.HasPrefix(path, "\\") { path = "C:\\" + path[1:] } return path } func newPattern(t *testing.T, value string) pattern { t.Helper() p := pattern{value: normalizePath(t, value)} require.NoError(t, p.parse()) return p } func TestDisallowOnEventTypeBiggerThan3(t *testing.T) { t.Parallel() w := newPattern(t, "/some/path") assert.False(t, w.allowReload(&watcher.Event{PathName: "/some/path/watch-me.php", EffectType: watcher.EffectTypeOwner})) } func TestDisallowOnPathTypeBiggerThan2(t *testing.T) { t.Parallel() w := newPattern(t, "/some/path") assert.False(t, w.allowReload(&watcher.Event{PathName: "/some/path/watch-me.php", PathType: watcher.PathTypeSymLink})) } func TestWatchesCorrectDir(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path", "/path"}, {"/path/", "/path"}, {"/path/**/*.php", "/path"}, {"/path/*.php", "/path"}, {"/path/*/*.php", "/path"}, {"/path/?path/*.php", "/path"}, {"/path/{dir1,dir2}/**/*.php", "/path"}, {".", relativeDir(t, "")}, {"./", relativeDir(t, "")}, {"./**", relativeDir(t, "")}, {"..", relativeDir(t, "/..")}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() hasDir(t, d.pattern, d.dir) }) } } func TestValidRecursiveDirectories(t *testing.T) { t.Parallel() data := []struct { pattern string file string }{ {"/path", "/path/file.php"}, {"/path", "/path/subpath/file.php"}, {"/path/", "/path/subpath/file.php"}, {"/path**", "/path/subpath/file.php"}, {"/path/**", "/path/subpath/file.php"}, {"/path/**/", "/path/subpath/file.php"}, {".", relativeDir(t, "file.php")}, {".", relativeDir(t, "subpath/file.php")}, {"./**", relativeDir(t, "subpath/file.php")}, {"..", relativeDir(t, "subpath/file.php")}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternMatch(t, d.pattern, d.file) }) } } func TestInvalidRecursiveDirectories(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path", "/other/file.php"}, {"/path/**", "/other/file.php"}, {".", "/other/file.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternNotMatch(t, d.pattern, d.dir) }) } } func TestValidNonRecursiveFilePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/*.php", "/file.php"}, {"/path/*.php", "/path/file.php"}, {"/path/?ile.php", "/path/file.php"}, {"/path/file.php", "/path/file.php"}, {"*.php", relativeDir(t, "file.php")}, {"./*.php", relativeDir(t, "file.php")}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternMatch(t, d.pattern, d.dir) }) } } func TestInValidNonRecursiveFilePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/*.txt", "/path/file.php"}, {"/path/*.php", "/path/subpath/file.php"}, {"/*.php", "/path/file.php"}, {"*.txt", relativeDir(t, "file.php")}, {"*.php", relativeDir(t, "subpath/file.php")}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternNotMatch(t, d.pattern, d.dir) }) } } func TestValidRecursiveFilePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/**/*.php", "/path/file.php"}, {"/path/**/*.php", "/path/subpath/file.php"}, {"/path/**/?ile.php", "/path/subpath/file.php"}, {"/path/**/file.php", "/path/subpath/file.php"}, {"**/*.php", relativeDir(t, "file.php")}, {"**/*.php", relativeDir(t, "subpath/file.php")}, {"./**/*.php", relativeDir(t, "subpath/file.php")}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternMatch(t, d.pattern, d.dir) }) } } func TestInvalidRecursiveFilePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/**/*.txt", "/path/file.php"}, {"/path/**/*.txt", "/other/file.php"}, {"/path/**/*.txt", "/path/subpath/file.php"}, {"/path/**/?ilm.php", "/path/subpath/file.php"}, {"**/*.php", "/other/file.php"}, {".**/*.php", "/other/file.php"}, {"./**/*.php", "/other/file.php"}, {"/a/**/very/long/path.php", "/a/short.php"}, {"", ""}, {"/a/**/b/c/d/**/e.php", "/a/x/e.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternNotMatch(t, d.pattern, d.dir) }) } } func TestValidDirectoryPatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/*/*.php", "/path/subpath/file.php"}, {"/path/*/*/*.php", "/path/subpath/subpath/file.php"}, {"/path/?/*.php", "/path/1/file.php"}, {"/path/**/vendor/*.php", "/path/vendor/file.php"}, {"/path/**/vendor/*.php", "/path/subpath/vendor/file.php"}, {"/path/**/vendor/**/*.php", "/path/vendor/file.php"}, {"/path/**/vendor/**/*.php", "/path/subpath/subpath/vendor/subpath/subpath/file.php"}, {"/path/**/vendor/*/*.php", "/path/subpath/subpath/vendor/subpath/file.php"}, {"/path*/path*/*", "/path1/path2/file.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternMatch(t, d.pattern, d.dir) }) } } func TestInvalidDirectoryPatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/subpath/*.php", "/path/other/file.php"}, {"/path/*/*.php", "/path/subpath/subpath/file.php"}, {"/path/?/*.php", "/path/subpath/file.php"}, {"/path/*/*/*.php", "/path/subpath/file.php"}, {"/path/*/*/*.php", "/path/subpath/subpath/subpath/file.php"}, {"/path/**/vendor/*.php", "/path/subpath/vendor/subpath/file.php"}, {"/path/**/vendor/*.php", "/path/subpath/file.php"}, {"/path/**/vendor/**/*.php", "/path/subpath/file.php"}, {"/path/**/vendor/**/*.txt", "/path/subpath/vendor/subpath/file.php"}, {"/path/**/vendor/**/*.php", "/path/subpath/subpath/subpath/file.php"}, {"/path/**/vendor/*/*.php", "/path/subpath/vendor/subpath/subpath/file.php"}, {"/path*/path*", "/path1/path1/file.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternNotMatch(t, d.pattern, d.dir) }) } } func TestValidCurlyBracePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string file string }{ {"/path/*.{php}", "/path/file.php"}, {"/path/*.{php,twig}", "/path/file.php"}, {"/path/*.{php,twig}", "/path/file.twig"}, {"/path/**/{file.php,file.twig}", "/path/subpath/file.twig"}, {"/path/{dir1,dir2}/file.php", "/path/dir1/file.php"}, {"/path/{dir1,dir2}/file.php", "/path/dir2/file.php"}, {"/app/{app,config,resources}/**/*.php", "/app/app/subpath/file.php"}, {"/app/{app,config,resources}/**/*.php", "/app/config/subpath/file.php"}, {"/path/{dir1,dir2}/{a,b}{a,b}.php", "/path/dir1/ab.php"}, {"/path/{dir1,dir2}/{a,b}{a,b}.php", "/path/dir2/aa.php"}, {"/path/{dir1,dir2}/{a,b}{a,b}.php", "/path/dir2/bb.php"}, {"/path/{dir1/test.php,dir2/test.php}", "/path/dir1/test.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternMatch(t, d.pattern, d.file) }) } } func TestInvalidCurlyBracePatterns(t *testing.T) { t.Parallel() data := []struct { pattern string dir string }{ {"/path/*.{php}", "/path/file.txt"}, {"/path/*.{php,twig}", "/path/file.txt"}, {"/path/{file.php,file.twig}", "/path/file.txt"}, {"/path/{dir1,dir2}/file.php", "/path/dir3/file.php"}, {"/path/{dir1,dir2}/**/*.php", "/path/dir1/subpath/file.txt"}, {"/path/{dir1,dir2}/{a,b}{a,b}.php", "/path/dir1/ac.php"}, {"/path/{}/{a,b}{a,b}.php", "/path/dir1/ac.php"}, {"/path/}dir{/{a,b}{a,b}.php", "/path/dir1/aa.php"}, } for _, d := range data { t.Run(d.pattern, func(t *testing.T) { t.Parallel() assertPatternNotMatch(t, d.pattern, d.dir) }) } } func TestAnAssociatedEventTriggersTheWatcher(t *testing.T) { t.Parallel() w := newPattern(t, "/**/*.php") w.events = make(chan eventHolder) e := &watcher.Event{PathName: normalizePath(t, "/path/temporary_file"), AssociatedPathName: normalizePath(t, "/path/file.php")} go w.handle(e) assert.Equal(t, e, (<-w.events).event) } func relativeDir(t *testing.T, relativePath string) string { t.Helper() dir, err := filepath.Abs("./" + relativePath) assert.NoError(t, err) return dir } func hasDir(t *testing.T, p string, dir string) { t.Helper() w := newPattern(t, p) assert.Equal(t, normalizePath(t, dir), w.value) } func assertPatternMatch(t *testing.T, p, fileName string) { t.Helper() w := newPattern(t, p) assert.True(t, w.allowReload(&watcher.Event{PathName: normalizePath(t, fileName)})) } func assertPatternNotMatch(t *testing.T, p, fileName string) { t.Helper() w := newPattern(t, p) assert.False(t, w.allowReload(&watcher.Event{PathName: normalizePath(t, fileName)})) } ================================================ FILE: internal/watcher/watcher.go ================================================ //go:build !nowatcher package watcher import ( "context" "errors" "log/slog" "sync" "sync/atomic" "time" "github.com/e-dant/watcher/watcher-go" ) const ( // duration to wait before triggering a reload after a file change debounceDuration = 150 * time.Millisecond // times to retry watching if the watcher was closed prematurely maxFailureCount = 5 failureResetDuration = 5 * time.Second ) var ( ErrAlreadyStarted = errors.New("watcher is already running") failureMu sync.Mutex watcherIsActive atomic.Bool // the currently active file watcher activeWatcher *globalWatcher // after stopping the watcher we will wait for eventual reloads to finish reloadWaitGroup sync.WaitGroup // we are passing the context from the main package to the watcher globalCtx context.Context // we are passing the globalLogger from the main package to the watcher globalLogger *slog.Logger ) type PatternGroup struct { Patterns []string Callback func([]*watcher.Event) } type eventHolder struct { patternGroup *PatternGroup event *watcher.Event } type globalWatcher struct { groups []*PatternGroup watchers []*pattern events chan eventHolder stop chan struct{} } func InitWatcher(ct context.Context, slogger *slog.Logger, groups []*PatternGroup) error { if len(groups) == 0 { return nil } if watcherIsActive.Load() { return ErrAlreadyStarted } watcherIsActive.Store(true) globalCtx = ct globalLogger = slogger activeWatcher = &globalWatcher{groups: groups} for _, g := range groups { if len(g.Patterns) == 0 { continue } for _, p := range g.Patterns { activeWatcher.watchers = append(activeWatcher.watchers, &pattern{patternGroup: g, value: p}) } } if err := activeWatcher.startWatching(); err != nil { return err } return nil } func DrainWatcher() { if !watcherIsActive.Load() { return } watcherIsActive.Store(false) if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "stopping watcher") } activeWatcher.stopWatching() reloadWaitGroup.Wait() activeWatcher = nil } // TODO: how to test this? func (p *pattern) retryWatching() { failureMu.Lock() defer failureMu.Unlock() if p.failureCount >= maxFailureCount { if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, "giving up watching", slog.String("pattern", p.value)) } return } if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "watcher was closed prematurely, retrying...", slog.String("pattern", p.value)) } p.failureCount++ p.startSession() // reset the failure-count if the watcher hasn't reached max failures after 5 seconds go func() { time.Sleep(failureResetDuration) failureMu.Lock() if p.failureCount < maxFailureCount { p.failureCount = 0 } failureMu.Unlock() }() } func (g *globalWatcher) startWatching() error { g.events = make(chan eventHolder) g.stop = make(chan struct{}) if err := g.parseFilePatterns(); err != nil { return err } for _, w := range g.watchers { w.events = g.events w.startSession() } go g.listenForFileEvents() return nil } func (g *globalWatcher) parseFilePatterns() error { for _, w := range g.watchers { if err := w.parse(); err != nil { return err } } return nil } func (g *globalWatcher) stopWatching() { close(g.stop) for _, w := range g.watchers { w.stop() } } func (g *globalWatcher) listenForFileEvents() { timer := time.NewTimer(debounceDuration) timer.Stop() eventsPerGroup := make(map[*PatternGroup][]*watcher.Event, len(g.groups)) defer timer.Stop() for { select { case <-g.stop: return case eh := <-g.events: timer.Reset(debounceDuration) eventsPerGroup[eh.patternGroup] = append(eventsPerGroup[eh.patternGroup], eh.event) case <-timer.C: timer.Stop() if globalLogger.Enabled(globalCtx, slog.LevelInfo) { var events []*watcher.Event for _, eventList := range eventsPerGroup { events = append(events, eventList...) } globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "filesystem changes detected", slog.Any("events", events)) } g.scheduleReload(eventsPerGroup) eventsPerGroup = make(map[*PatternGroup][]*watcher.Event, len(g.groups)) } } } func (g *globalWatcher) scheduleReload(eventsPerGroup map[*PatternGroup][]*watcher.Event) { reloadWaitGroup.Add(1) // Call callbacks in order for _, g := range g.groups { if len(g.Patterns) == 0 { g.Callback(nil) } if e, ok := eventsPerGroup[g]; ok { g.Callback(e) } } reloadWaitGroup.Done() } ================================================ FILE: log_test.go ================================================ package frankenphp_test import ( "bytes" "fmt" "log/slog" "sync" "testing" ) func newTestLogger(t *testing.T) (*slog.Logger, fmt.Stringer) { t.Helper() var buf syncBuffer return slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})), &buf } // SyncBuffer is a thread-safe buffer for capturing logs in tests. type syncBuffer struct { b bytes.Buffer mu sync.RWMutex } func (s *syncBuffer) Write(p []byte) (n int, err error) { s.mu.Lock() defer s.mu.Unlock() return s.b.Write(p) } func (s *syncBuffer) String() string { s.mu.RLock() defer s.mu.RUnlock() return s.b.String() } ================================================ FILE: mercure-skip.go ================================================ //go:build nomercure package frankenphp // #include // #include import "C" type mercureContext struct { } //export go_mercure_publish func go_mercure_publish(threadIndex C.uintptr_t, topics *C.struct__zval_struct, data *C.zend_string, private bool, id, typ *C.zend_string, retry uint64) (generatedID *C.zend_string, error C.short) { return nil, 3 } func (w *worker) configureMercure(_ *workerOpt) { } ================================================ FILE: mercure.go ================================================ //go:build !nomercure package frankenphp // #include // #include "frankenphp.h" // #include import "C" import ( "log/slog" "unsafe" "github.com/dunglas/mercure" ) type mercureContext struct { mercureHub *mercure.Hub } //export go_mercure_publish func go_mercure_publish(threadIndex C.uintptr_t, topics *C.struct__zval_struct, data *C.zend_string, private bool, id, typ *C.zend_string, retry uint64) (generatedID *C.zend_string, error C.short) { thread := phpThreads[threadIndex] ctx := thread.context() fc := thread.frankenPHPContext() if fc.mercureHub == nil { if fc.logger.Enabled(ctx, slog.LevelError) { fc.logger.LogAttrs(ctx, slog.LevelError, "No Mercure hub configured") } return nil, 1 } u := &mercure.Update{ Event: mercure.Event{ Data: GoString(unsafe.Pointer(data)), ID: GoString(unsafe.Pointer(id)), Retry: retry, Type: GoString(unsafe.Pointer(typ)), }, Private: private, Debug: fc.logger.Enabled(ctx, slog.LevelDebug), } zvalType := C.zval_get_type(topics) switch zvalType { case C.IS_STRING: u.Topics = []string{GoString(unsafe.Pointer(*(**C.zend_string)(unsafe.Pointer(&topics.value[0]))))} case C.IS_ARRAY: ts, err := GoPackedArray[string](unsafe.Pointer(*(**C.zend_array)(unsafe.Pointer(&topics.value[0])))) if err != nil { if fc.logger.Enabled(ctx, slog.LevelError) { fc.logger.LogAttrs(ctx, slog.LevelError, "invalid topics type", slog.Any("error", err)) } return nil, 1 } u.Topics = ts default: // Never happens as the function is called from C with proper types panic("invalid topics type") } if err := fc.mercureHub.Publish(ctx, u); err != nil { if fc.logger.Enabled(ctx, slog.LevelError) { fc.logger.LogAttrs(ctx, slog.LevelError, "Unable to publish Mercure update", slog.Any("error", err)) } return nil, 2 } return (*C.zend_string)(PHPString(u.ID, false)), 0 } func (w *worker) configureMercure(o *workerOpt) { if o.mercureHub == nil { return } w.mercureHub = o.mercureHub } // WithMercureHub sets the mercure.Hub to use to publish updates func WithMercureHub(hub *mercure.Hub) RequestOption { return func(o *frankenPHPContext) error { o.mercureHub = hub return nil } } // WithWorkerMercureHub sets the mercure.Hub in the worker script and used to dispatch hot reloading-related mercure.Update. func WithWorkerMercureHub(hub *mercure.Hub) WorkerOption { return func(w *workerOpt) error { w.mercureHub = hub w.requestOptions = append(w.requestOptions, WithMercureHub(hub)) return nil } } ================================================ FILE: mercure_test.go ================================================ //go:build !nomercure package frankenphp_test import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/dunglas/frankenphp" "github.com/dunglas/mercure" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMercurePublish_module(t *testing.T) { testMercurePublish(t, &testOptions{}) } func TestMercurePublish_worker(t *testing.T) { testMercurePublish(t, &testOptions{workerScript: "index.php"}) } func testMercurePublish(t *testing.T, opts *testOptions) { h, err := mercure.NewHub(t.Context(), mercure.WithTransport(mercure.NewLocalTransport(mercure.NewSubscriberList(0)))) require.NoError(t, err) opts.requestOpts = []frankenphp.RequestOption{frankenphp.WithMercureHub(h)} runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { body, _ := testGet(fmt.Sprintf("https://example.com/mercure-publish.php?i=%d", i), handler, t) assert.Contains(t, body, "update 1: ") assert.Contains(t, body, "update 2: ") }, opts) } ================================================ FILE: metrics.go ================================================ package frankenphp import ( "errors" "sync" "time" "github.com/prometheus/client_golang/prometheus" ) const ( StopReasonCrash = iota StopReasonRestart StopReasonBootFailure // worker crashed before reaching frankenphp_handle_request ) type StopReason int type Metrics interface { // StartWorker collects started workers StartWorker(name string) // ReadyWorker collects ready workers ReadyWorker(name string) // StopWorker collects stopped workers StopWorker(name string, reason StopReason) // TotalWorkers collects expected workers TotalWorkers(name string, num int) // TotalThreads collects total threads TotalThreads(num int) // StartRequest collects started requests StartRequest() // StopRequest collects stopped requests StopRequest() // StopWorkerRequest collects stopped worker requests StopWorkerRequest(name string, duration time.Duration) // StartWorkerRequest collects started worker requests StartWorkerRequest(name string) Shutdown() QueuedWorkerRequest(name string) DequeuedWorkerRequest(name string) QueuedRequest() DequeuedRequest() } type nullMetrics struct{} func (n nullMetrics) StartWorker(string) { } func (n nullMetrics) ReadyWorker(string) { } func (n nullMetrics) StopWorker(string, StopReason) { } func (n nullMetrics) TotalWorkers(string, int) { } func (n nullMetrics) TotalThreads(int) { } func (n nullMetrics) StartRequest() { } func (n nullMetrics) StopRequest() { } func (n nullMetrics) StopWorkerRequest(string, time.Duration) { } func (n nullMetrics) StartWorkerRequest(string) { } func (n nullMetrics) Shutdown() { } func (n nullMetrics) QueuedWorkerRequest(string) {} func (n nullMetrics) DequeuedWorkerRequest(string) {} func (n nullMetrics) QueuedRequest() {} func (n nullMetrics) DequeuedRequest() {} type PrometheusMetrics struct { registry prometheus.Registerer totalThreads prometheus.Counter busyThreads prometheus.Gauge totalWorkers *prometheus.GaugeVec busyWorkers *prometheus.GaugeVec readyWorkers *prometheus.GaugeVec workerCrashes *prometheus.CounterVec workerRestarts *prometheus.CounterVec workerRequestTime *prometheus.CounterVec workerRequestCount *prometheus.CounterVec workerQueueDepth *prometheus.GaugeVec queueDepth prometheus.Gauge mu sync.Mutex } func (m *PrometheusMetrics) StartWorker(name string) { m.busyThreads.Inc() // tests do not register workers before starting them if m.totalWorkers == nil { return } m.totalWorkers.WithLabelValues(name).Inc() } func (m *PrometheusMetrics) ReadyWorker(name string) { if m.totalWorkers == nil { return } m.readyWorkers.WithLabelValues(name).Inc() } func (m *PrometheusMetrics) StopWorker(name string, reason StopReason) { m.busyThreads.Dec() // tests do not register workers before starting them if m.totalWorkers == nil { return } m.totalWorkers.WithLabelValues(name).Dec() // only decrement readyWorkers if the worker actually reached frankenphp_handle_request if reason != StopReasonBootFailure { m.readyWorkers.WithLabelValues(name).Dec() } switch reason { case StopReasonCrash, StopReasonBootFailure: m.workerCrashes.WithLabelValues(name).Inc() case StopReasonRestart: m.workerRestarts.WithLabelValues(name).Inc() } } func (m *PrometheusMetrics) TotalWorkers(string, int) { m.mu.Lock() defer m.mu.Unlock() const ns, sub = "frankenphp", "worker" basicLabels := []string{"worker"} if m.totalWorkers == nil { m.totalWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Name: "total_workers", Help: "Total number of PHP workers for this worker", }, basicLabels) if err := m.registry.Register(m.totalWorkers); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.readyWorkers == nil { m.readyWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Name: "ready_workers", Help: "Running workers that have successfully called frankenphp_handle_request at least once", }, basicLabels) if err := m.registry.Register(m.readyWorkers); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.busyWorkers == nil { m.busyWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: ns, Name: "busy_workers", Help: "Number of busy PHP workers for this worker", }, basicLabels) if err := m.registry.Register(m.busyWorkers); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.workerCrashes == nil { m.workerCrashes = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "crashes", Help: "Number of PHP worker crashes for this worker", }, basicLabels) if err := m.registry.Register(m.workerCrashes); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.workerRestarts == nil { m.workerRestarts = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "restarts", Help: "Number of PHP worker restarts for this worker", }, basicLabels) if err := m.registry.Register(m.workerRestarts); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.workerRequestTime == nil { m.workerRequestTime = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "request_time", }, basicLabels) if err := m.registry.Register(m.workerRequestTime); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.workerRequestCount == nil { m.workerRequestCount = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: ns, Subsystem: sub, Name: "request_count", }, basicLabels) if err := m.registry.Register(m.workerRequestCount); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } if m.workerQueueDepth == nil { m.workerQueueDepth = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "frankenphp", Subsystem: sub, Name: "queue_depth", }, basicLabels) if err := m.registry.Register(m.workerQueueDepth); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } } func (m *PrometheusMetrics) TotalThreads(num int) { m.totalThreads.Add(float64(num)) } func (m *PrometheusMetrics) StartRequest() { m.busyThreads.Inc() } func (m *PrometheusMetrics) StopRequest() { m.busyThreads.Dec() } func (m *PrometheusMetrics) StopWorkerRequest(name string, duration time.Duration) { if m.workerRequestTime == nil { return } m.workerRequestCount.WithLabelValues(name).Inc() m.busyWorkers.WithLabelValues(name).Dec() m.workerRequestTime.WithLabelValues(name).Add(duration.Seconds()) } func (m *PrometheusMetrics) StartWorkerRequest(name string) { if m.busyWorkers == nil { return } m.busyWorkers.WithLabelValues(name).Inc() } func (m *PrometheusMetrics) QueuedWorkerRequest(name string) { if m.workerQueueDepth == nil { return } m.workerQueueDepth.WithLabelValues(name).Inc() } func (m *PrometheusMetrics) DequeuedWorkerRequest(name string) { if m.workerQueueDepth == nil { return } m.workerQueueDepth.WithLabelValues(name).Dec() } func (m *PrometheusMetrics) QueuedRequest() { m.queueDepth.Inc() } func (m *PrometheusMetrics) DequeuedRequest() { m.queueDepth.Dec() } func (m *PrometheusMetrics) Shutdown() { m.registry.Unregister(m.totalThreads) m.registry.Unregister(m.busyThreads) m.registry.Unregister(m.queueDepth) if m.totalWorkers != nil { m.registry.Unregister(m.totalWorkers) m.totalWorkers = nil } if m.busyWorkers != nil { m.registry.Unregister(m.busyWorkers) m.busyWorkers = nil } if m.workerRequestTime != nil { m.registry.Unregister(m.workerRequestTime) m.workerRequestTime = nil } if m.workerRequestCount != nil { m.registry.Unregister(m.workerRequestCount) m.workerRequestCount = nil } if m.workerCrashes != nil { m.registry.Unregister(m.workerCrashes) m.workerCrashes = nil } if m.workerRestarts != nil { m.registry.Unregister(m.workerRestarts) m.workerRestarts = nil } if m.readyWorkers != nil { m.registry.Unregister(m.readyWorkers) m.readyWorkers = nil } if m.workerQueueDepth != nil { m.registry.Unregister(m.workerQueueDepth) m.workerQueueDepth = nil } m.totalThreads = prometheus.NewCounter(prometheus.CounterOpts{ Name: "frankenphp_total_threads", Help: "Total number of PHP threads", }) m.busyThreads = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "frankenphp_busy_threads", Help: "Number of busy PHP threads", }) m.queueDepth = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "frankenphp_queue_depth", Help: "Number of regular queued requests", }) if err := m.registry.Register(m.totalThreads); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } if err := m.registry.Register(m.busyThreads); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } if err := m.registry.Register(m.queueDepth); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } } func NewPrometheusMetrics(registry prometheus.Registerer) *PrometheusMetrics { if registry == nil { registry = prometheus.NewRegistry() } m := &PrometheusMetrics{ registry: registry, totalThreads: prometheus.NewCounter(prometheus.CounterOpts{ Name: "frankenphp_total_threads", Help: "Total number of PHP threads", }), busyThreads: prometheus.NewGauge(prometheus.GaugeOpts{ Name: "frankenphp_busy_threads", Help: "Number of busy PHP threads", }), queueDepth: prometheus.NewGauge(prometheus.GaugeOpts{ Name: "frankenphp_queue_depth", Help: "Number of regular queued requests", }), totalWorkers: nil, busyWorkers: nil, workerRequestTime: nil, workerRequestCount: nil, workerRestarts: nil, workerCrashes: nil, readyWorkers: nil, workerQueueDepth: nil, } if err := m.registry.Register(m.totalThreads); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } if err := m.registry.Register(m.busyThreads); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } if err := m.registry.Register(m.queueDepth); err != nil && !errors.As(err, &prometheus.AlreadyRegisteredError{}) { panic(err) } return m } ================================================ FILE: metrics_test.go ================================================ package frankenphp import ( "strings" "sync" "testing" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" ) func createPrometheusMetrics() *PrometheusMetrics { return &PrometheusMetrics{ registry: prometheus.NewRegistry(), totalThreads: prometheus.NewCounter(prometheus.CounterOpts{Name: "frankenphp_total_threads"}), busyThreads: prometheus.NewGauge(prometheus.GaugeOpts{Name: "frankenphp_busy_threads"}), queueDepth: prometheus.NewGauge(prometheus.GaugeOpts{Name: "frankenphp_queue_depth"}), mu: sync.Mutex{}, } } func TestPrometheusMetrics_TotalWorkers(t *testing.T) { m := createPrometheusMetrics() require.Nil(t, m.totalWorkers) require.Nil(t, m.busyWorkers) require.Nil(t, m.readyWorkers) require.Nil(t, m.workerCrashes) require.Nil(t, m.workerRestarts) require.Nil(t, m.workerRequestTime) require.Nil(t, m.workerRequestCount) m.TotalWorkers("test_worker", 2) require.NotNil(t, m.totalWorkers) require.NotNil(t, m.busyWorkers) require.NotNil(t, m.readyWorkers) require.NotNil(t, m.workerCrashes) require.NotNil(t, m.workerRestarts) require.NotNil(t, m.workerRequestTime) require.NotNil(t, m.workerRequestCount) } func TestPrometheusMetrics_StopWorkerRequest(t *testing.T) { m := createPrometheusMetrics() m.TotalWorkers("test_worker", 2) m.StopWorkerRequest("test_worker", 2*time.Second) inputs := []struct { name string c prometheus.Collector metadata string expect string }{ { name: "Testing WorkerRequestCount", c: m.workerRequestCount, metadata: ` # HELP frankenphp_worker_request_count # TYPE frankenphp_worker_request_count counter `, expect: ` frankenphp_worker_request_count{worker="test_worker"} 1 `, }, { name: "Testing BusyWorkers", c: m.busyWorkers, metadata: ` # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge `, expect: ` frankenphp_busy_workers{worker="test_worker"} -1 `, }, { name: "Testing WorkerRequestTime", c: m.workerRequestTime, metadata: ` # HELP frankenphp_worker_request_time # TYPE frankenphp_worker_request_time counter `, expect: ` frankenphp_worker_request_time{worker="test_worker"} 2 `, }, } for _, input := range inputs { t.Run(input.name, func(t *testing.T) { require.NoError(t, testutil.CollectAndCompare(input.c, strings.NewReader(input.metadata+input.expect))) }) } } func TestPrometheusMetrics_StartWorkerRequest(t *testing.T) { m := createPrometheusMetrics() m.TotalWorkers("test_worker", 2) m.StartWorkerRequest("test_worker") inputs := []struct { name string c prometheus.Collector metadata string expect string }{ { name: "Testing BusyWorkers", c: m.busyWorkers, metadata: ` # HELP frankenphp_busy_workers Number of busy PHP workers for this worker # TYPE frankenphp_busy_workers gauge `, expect: ` frankenphp_busy_workers{worker="test_worker"} 1 `, }, } for _, input := range inputs { t.Run(input.name, func(t *testing.T) { require.NoError(t, testutil.CollectAndCompare(input.c, strings.NewReader(input.metadata+input.expect))) }) } } func TestPrometheusMetrics_TestStopReasonCrash(t *testing.T) { m := createPrometheusMetrics() m.TotalWorkers("test_worker", 2) m.StopWorker("test_worker", StopReasonCrash) inputs := []struct { name string c prometheus.Collector metadata string expect string }{ { name: "Testing BusyThreads", c: m.busyThreads, metadata: ` # HELP frankenphp_busy_threads # TYPE frankenphp_busy_threads gauge `, expect: ` frankenphp_busy_threads -1 `, }, { name: "Testing TotalWorkers", c: m.totalWorkers, metadata: ` # HELP frankenphp_total_workers Total number of PHP workers for this worker # TYPE frankenphp_total_workers gauge `, expect: ` frankenphp_total_workers{worker="test_worker"} -1 `, }, { name: "Testing ReadyWorkers", c: m.readyWorkers, metadata: ` # HELP frankenphp_ready_workers Running workers that have successfully called frankenphp_handle_request at least once # TYPE frankenphp_ready_workers gauge `, expect: ` frankenphp_ready_workers{worker="test_worker"} -1 `, }, { name: "Testing WorkerCrashes", c: m.workerCrashes, metadata: ` # HELP frankenphp_worker_crashes Number of PHP worker crashes for this worker # TYPE frankenphp_worker_crashes counter `, expect: ` frankenphp_worker_crashes{worker="test_worker"} 1 `, }, } for _, input := range inputs { t.Run(input.name, func(t *testing.T) { require.NoError(t, testutil.CollectAndCompare(input.c, strings.NewReader(input.metadata+input.expect))) }) } } ================================================ FILE: options.go ================================================ package frankenphp import ( "context" "fmt" "log/slog" "time" ) // defaultMaxConsecutiveFailures is the default maximum number of consecutive failures before panicking const defaultMaxConsecutiveFailures = 6 // Option instances allow to configure FrankenPHP. type Option func(h *opt) error // WorkerOption instances allow configuring FrankenPHP worker. type WorkerOption func(*workerOpt) error // opt contains the available options. // // If you change this, also update the Caddy module and the documentation. type opt struct { hotReloadOpt ctx context.Context numThreads int maxThreads int workers []workerOpt logger *slog.Logger metrics Metrics phpIni map[string]string maxWaitTime time.Duration maxIdleTime time.Duration } type workerOpt struct { mercureContext name string fileName string num int maxThreads int env PreparedEnv requestOptions []RequestOption watch []string maxConsecutiveFailures int extensionWorkers *extensionWorkers onThreadReady func(int) onThreadShutdown func(int) onServerStartup func() onServerShutdown func() } // WithContext sets the main context to use. func WithContext(ctx context.Context) Option { return func(h *opt) error { h.ctx = ctx return nil } } // WithNumThreads configures the number of PHP threads to start. func WithNumThreads(numThreads int) Option { return func(o *opt) error { o.numThreads = numThreads return nil } } func WithMaxThreads(maxThreads int) Option { return func(o *opt) error { o.maxThreads = maxThreads return nil } } func WithMetrics(m Metrics) Option { return func(o *opt) error { o.metrics = m return nil } } // WithWorkers configures the PHP workers to start func WithWorkers(name, fileName string, num int, options ...WorkerOption) Option { return func(o *opt) error { worker := workerOpt{ name: name, fileName: fileName, num: num, env: PrepareEnv(nil), watch: []string{}, maxConsecutiveFailures: defaultMaxConsecutiveFailures, } for _, option := range options { if err := option(&worker); err != nil { return err } } o.workers = append(o.workers, worker) return nil } } // EXPERIMENTAL: WithExtensionWorkers allow extensions to create workers. // // A worker script with the provided name, fileName and thread count will be registered, along with additional // configuration through WorkerOptions. // // Workers are designed to run indefinitely and will be gracefully shut down when FrankenPHP shuts down. // // Extension workers receive the lowest priority when determining thread allocations. If the requested number of threads // cannot be allocated, then FrankenPHP will panic and provide this information to the user (who will need to allocate // more total threads). Don't be greedy. func WithExtensionWorkers(name, fileName string, numThreads int, options ...WorkerOption) (Workers, Option) { w := &extensionWorkers{ name: name, fileName: fileName, num: numThreads, } w.options = append(options, withExtensionWorkers(w)) return w, WithWorkers(w.name, w.fileName, w.num, w.options...) } // WithLogger configures the global logger to use. func WithLogger(l *slog.Logger) Option { return func(o *opt) error { o.logger = l return nil } } // WithPhpIni configures user defined PHP ini settings. func WithPhpIni(overrides map[string]string) Option { return func(o *opt) error { o.phpIni = overrides return nil } } // WithMaxWaitTime configures the max time a request may be stalled waiting for a thread. func WithMaxWaitTime(maxWaitTime time.Duration) Option { return func(o *opt) error { o.maxWaitTime = maxWaitTime return nil } } // WithMaxIdleTime configures the max time an autoscaled thread may be idle before being deactivated. func WithMaxIdleTime(maxIdleTime time.Duration) Option { return func(o *opt) error { o.maxIdleTime = maxIdleTime return nil } } // WithWorkerEnv sets environment variables for the worker func WithWorkerEnv(env map[string]string) WorkerOption { return func(w *workerOpt) error { w.env = PrepareEnv(env) return nil } } // WithWorkerRequestOptions sets options for the main dummy request created for the worker func WithWorkerRequestOptions(options ...RequestOption) WorkerOption { return func(w *workerOpt) error { w.requestOptions = append(w.requestOptions, options...) return nil } } // WithWorkerMaxThreads sets the max number of threads for this specific worker func WithWorkerMaxThreads(num int) WorkerOption { return func(w *workerOpt) error { w.maxThreads = num return nil } } // WithWorkerWatchMode sets directories to watch for file changes func WithWorkerWatchMode(watch []string) WorkerOption { return func(w *workerOpt) error { w.watch = watch return nil } } // WithWorkerMaxFailures sets the maximum number of consecutive failures before panicking func WithWorkerMaxFailures(maxFailures int) WorkerOption { return func(w *workerOpt) error { if maxFailures < -1 { return fmt.Errorf("max consecutive failures must be >= -1, got %d", maxFailures) } w.maxConsecutiveFailures = maxFailures return nil } } func WithWorkerOnReady(f func(int)) WorkerOption { return func(w *workerOpt) error { w.onThreadReady = f return nil } } func WithWorkerOnShutdown(f func(int)) WorkerOption { return func(w *workerOpt) error { w.onThreadShutdown = f return nil } } // WithWorkerOnServerStartup adds a function to be called right after server startup. Useful for extensions. func WithWorkerOnServerStartup(f func()) WorkerOption { return func(w *workerOpt) error { w.onServerStartup = f return nil } } // WithWorkerOnServerShutdown adds a function to be called right before server shutdown. Useful for extensions. func WithWorkerOnServerShutdown(f func()) WorkerOption { return func(w *workerOpt) error { w.onServerShutdown = f return nil } } func withExtensionWorkers(w *extensionWorkers) WorkerOption { return func(wo *workerOpt) error { wo.extensionWorkers = w return nil } } ================================================ FILE: package/Caddyfile ================================================ # The Caddyfile is an easy way to configure FrankenPHP and the Caddy web server. # # https://frankenphp.dev/docs/config # https://caddyserver.com/docs/caddyfile { frankenphp } http:// { root /usr/share/frankenphp/ encode zstd br gzip php_server } # As an alternative to editing the above site block, you can add your own site # block files in the Caddyfile.d directory, and they will be included as long # as they use the .caddyfile extension. import Caddyfile.d/*.caddyfile ================================================ FILE: package/alpine/frankenphp.openrc ================================================ #!/sbin/openrc-run name="FrankenPHP" description="The modern PHP app server" command="/usr/bin/frankenphp" command_args="run --environ --config /etc/frankenphp/Caddyfile" command_user="frankenphp:frankenphp" command_background="yes" capabilities="^cap_net_bind_service" pidfile="/run/frankenphp/frankenphp.pid" start_stop_daemon_args="--chdir /var/lib/frankenphp" respawn_delay=3 respawn_max=10 depend() { need net after firewall } start_pre() { checkpath --directory --owner frankenphp:frankenphp --mode 0755 /run/frankenphp $command validate --config /etc/frankenphp/Caddyfile } reload() { ebegin "Reloading $name configuration" $command reload --config /etc/frankenphp/Caddyfile --force eend $? } ================================================ FILE: package/alpine/post-deinstall.sh ================================================ #!/bin/sh if getent passwd frankenphp >/dev/null; then deluser frankenphp fi if getent group frankenphp >/dev/null; then delgroup frankenphp fi rmdir /var/lib/frankenphp 2>/dev/null || true exit 0 ================================================ FILE: package/alpine/post-install.sh ================================================ #!/bin/sh if ! getent group frankenphp >/dev/null; then addgroup -S frankenphp fi if ! getent passwd frankenphp >/dev/null; then adduser -S -h /var/lib/frankenphp -s /sbin/nologin -G frankenphp -g "FrankenPHP web server" frankenphp fi chown -R frankenphp:frankenphp /var/lib/frankenphp chmod 755 /var/lib/frankenphp # allow binding to privileged ports if command -v setcap >/dev/null 2>&1; then setcap cap_net_bind_service=+ep /usr/bin/frankenphp || true fi # check if 0.0.0.0:2019 or 127.0.0.1:2019 are in use port_in_use() { port_hex=$(printf '%04X' "$1") grep -qE "(00000000|0100007F):${port_hex}" /proc/net/tcp 2>/dev/null } # trust frankenphp certificates if the admin api can start if [ -x /usr/bin/frankenphp ]; then if ! port_in_use 2019; then HOME=/var/lib/frankenphp /usr/bin/frankenphp run >/dev/null 2>&1 & FRANKENPHP_PID=$! sleep 2 HOME=/var/lib/frankenphp /usr/bin/frankenphp trust || true kill -TERM $FRANKENPHP_PID 2>/dev/null || true chown -R frankenphp:frankenphp /var/lib/frankenphp fi fi if command -v rc-update >/dev/null 2>&1; then rc-update add frankenphp default rc-service frankenphp start fi exit 0 ================================================ FILE: package/alpine/pre-deinstall.sh ================================================ #!/bin/sh if command -v rc-service >/dev/null 2>&1; then rc-service frankenphp stop || true fi if command -v rc-update >/dev/null 2>&1; then rc-update del frankenphp default || true fi exit 0 ================================================ FILE: package/content/index.php ================================================ Test Page for FrankenPHP

Test page

If you are a member of the general public:

The fact that you are seeing this page indicates that the website you just visited is either experiencing problems, or is undergoing routine maintenance.

If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person.

For example, try contacting webmaster@.

Learn more about FrankenPHP at the official website.

If you are the website administrator:

Your server is running and serving requests using FrankenPHP

To replace this page, deploy your application files to .

Configuration is handled in your Caddyfile.

Served by PHP SAPI:
================================================ FILE: package/debian/frankenphp.service ================================================ [Unit] Description=FrankenPHP - The modern PHP app server Documentation=https://frankenphp.dev/docs/ After=network.target network-online.target Requires=network-online.target [Service] Type=notify User=frankenphp Group=frankenphp ExecStartPre=/usr/bin/frankenphp validate --config /etc/frankenphp/Caddyfile ExecStart=/usr/bin/frankenphp run --environ --config /etc/frankenphp/Caddyfile ExecReload=/usr/bin/frankenphp reload --config /etc/frankenphp/Caddyfile WorkingDirectory=/var/lib/frankenphp Restart=on-failure RestartSec=3s TimeoutStopSec=5s LimitNOFILE=1048576 LimitNPROC=512 PrivateTmp=true ProtectHome=true ProtectSystem=full AmbientCapabilities=CAP_NET_BIND_SERVICE [Install] WantedBy=multi-user.target ================================================ FILE: package/debian/postinst.sh ================================================ #!/bin/sh set -e if [ "$1" = "configure" ]; then # Add user and group if ! getent group frankenphp >/dev/null; then groupadd --system frankenphp fi if ! getent passwd frankenphp >/dev/null; then useradd --system \ --gid frankenphp \ --create-home \ --home-dir /var/lib/frankenphp \ --shell /usr/sbin/nologin \ --comment "FrankenPHP web server" \ frankenphp fi if getent group www-data >/dev/null; then usermod -aG www-data frankenphp fi # trust frankenphp certificates before starting the systemd service if [ -z "$2" ] && [ -x /usr/bin/frankenphp ]; then HOME=/var/lib/frankenphp /usr/bin/frankenphp run --config /dev/null & FRANKENPHP_PID=$! sleep 2 HOME=/var/lib/frankenphp /usr/bin/frankenphp trust || true kill "$FRANKENPHP_PID" || true wait "$FRANKENPHP_PID" 2>/dev/null || true chown -R frankenphp:frankenphp /var/lib/frankenphp fi # Handle cases where package was installed and then purged; # user and group will still exist but with no home dir if [ ! -d /var/lib/frankenphp ]; then mkdir -p /var/lib/frankenphp chown -R frankenphp:frankenphp /var/lib/frankenphp fi # Add log directory with correct permissions if [ ! -d /var/log/frankenphp ]; then mkdir -p /var/log/frankenphp chown -R frankenphp:frankenphp /var/log/frankenphp fi fi if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ]; then # This will only remove masks created by d-s-h on package removal. deb-systemd-helper unmask frankenphp.service >/dev/null || true # was-enabled defaults to true, so new installations run enable. if deb-systemd-helper --quiet was-enabled frankenphp.service; then # Enables the unit on first installation, creates new # symlinks on upgrades if the unit file has changed. deb-systemd-helper enable frankenphp.service >/dev/null || true deb-systemd-invoke start frankenphp.service >/dev/null || true else # Update the statefile to add new symlinks (if any), which need to be # cleaned up on purge. Also remove old symlinks. deb-systemd-helper update-state frankenphp.service >/dev/null || true fi # Restart only if it was already started if [ -d /run/systemd/system ]; then systemctl --system daemon-reload >/dev/null || true if [ -n "$2" ]; then deb-systemd-invoke try-restart frankenphp.service >/dev/null || true fi fi fi if command -v setcap >/dev/null 2>&1; then setcap cap_net_bind_service=+ep /usr/bin/frankenphp || true fi ================================================ FILE: package/debian/postrm.sh ================================================ #!/bin/sh set -e if [ -d /run/systemd/system ]; then systemctl --system daemon-reload >/dev/null || true fi if [ "$1" = "remove" ]; then if [ -x "/usr/bin/deb-systemd-helper" ]; then deb-systemd-helper mask frankenphp.service >/dev/null || true fi fi if [ "$1" = "purge" ]; then if [ -x "/usr/bin/deb-systemd-helper" ]; then deb-systemd-helper purge frankenphp.service >/dev/null || true deb-systemd-helper unmask frankenphp.service >/dev/null || true fi rm -rf /var/lib/frankenphp /var/log/frankenphp /etc/frankenphp fi ================================================ FILE: package/debian/prerm.sh ================================================ #!/bin/sh set -e if [ -d /run/systemd/system ] && [ "$1" = remove ]; then deb-systemd-invoke stop frankenphp.service >/dev/null || true fi ================================================ FILE: package/rhel/frankenphp.service ================================================ [Unit] Description=FrankenPHP - The modern PHP app server Documentation=https://frankenphp.dev/docs/ After=network.target network-online.target Requires=network-online.target [Service] Type=notify User=frankenphp Group=frankenphp ExecStartPre=/usr/bin/frankenphp validate --config /etc/frankenphp/Caddyfile ExecStart=/usr/bin/frankenphp run --environ --config /etc/frankenphp/Caddyfile ExecReload=/usr/bin/frankenphp reload --config /etc/frankenphp/Caddyfile WorkingDirectory=/var/lib/frankenphp Restart=on-failure RestartSec=3s TimeoutStopSec=5s LimitNOFILE=1048576 LimitNPROC=512 PrivateTmp=true ProtectHome=true ProtectSystem=full AmbientCapabilities=CAP_NET_BIND_SERVICE [Install] WantedBy=multi-user.target ================================================ FILE: package/rhel/postinstall.sh ================================================ #!/bin/bash if [ "$1" -eq 1 ] && [ -x "/usr/lib/systemd/systemd-update-helper" ]; then # Initial installation /usr/lib/systemd/systemd-update-helper install-system-units frankenphp.service || : fi if [ -x /usr/sbin/getsebool ]; then # Connect to ACME endpoint to request certificates setsebool -P httpd_can_network_connect on fi if [ -x /usr/sbin/semanage ] && [ -x /usr/sbin/restorecon ]; then # file contexts semanage fcontext --add --type httpd_exec_t '/usr/bin/frankenphp' 2>/dev/null || : semanage fcontext --add --type httpd_sys_content_t '/usr/share/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --add --type httpd_config_t '/etc/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --add --type httpd_var_lib_t '/var/lib/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --add --type httpd_sys_rw_content_t "/var/lib/frankenphp(/.*\.db)" 2>/dev/null || : restorecon -r /usr/bin/frankenphp /usr/share/frankenphp /etc/frankenphp /var/lib/frankenphp || : fi if [ -x /usr/sbin/semanage ]; then # QUIC semanage port --add --type http_port_t --proto udp 80 2>/dev/null || : semanage port --add --type http_port_t --proto udp 443 2>/dev/null || : # admin endpoint semanage port --add --type http_port_t --proto tcp 2019 2>/dev/null || : fi if command -v setcap >/dev/null 2>&1; then setcap cap_net_bind_service=+ep /usr/bin/frankenphp || : fi # check if 0.0.0.0:2019 or 127.0.0.1:2019 are in use port_in_use() { port_hex=$(printf '%04X' "$1") grep -qE "(00000000|0100007F):${port_hex}" /proc/net/tcp 2>/dev/null } # trust frankenphp certificates if the admin api can start if [ "$1" -eq 1 ] && [ -x /usr/bin/frankenphp ]; then if ! port_in_use 2019; then HOME=/var/lib/frankenphp /usr/bin/frankenphp run --config /dev/null & FRANKENPHP_PID=$! sleep 2 HOME=/var/lib/frankenphp /usr/bin/frankenphp trust || : kill "$FRANKENPHP_PID" || : wait "$FRANKENPHP_PID" 2>/dev/null || : chown -R frankenphp:frankenphp /var/lib/frankenphp fi fi ================================================ FILE: package/rhel/postuninstall.sh ================================================ #!/bin/bash if [ "$1" -ge 1 ] && [ -x "/usr/lib/systemd/systemd-update-helper" ]; then # Package upgrade, not uninstall /usr/lib/systemd/systemd-update-helper mark-restart-system-units frankenphp.service || : fi if [ "$1" -eq 0 ]; then if [ -x /usr/sbin/getsebool ]; then # connect to ACME endpoint to request certificates setsebool -P httpd_can_network_connect off fi if [ -x /usr/sbin/semanage ]; then # file contexts semanage fcontext --delete --type httpd_exec_t '/usr/bin/frankenphp' 2>/dev/null || : semanage fcontext --delete --type httpd_sys_content_t '/usr/share/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --delete --type httpd_config_t '/etc/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --delete --type httpd_var_lib_t '/var/lib/frankenphp(/.*)?' 2>/dev/null || : semanage fcontext --delete --type httpd_sys_rw_content_t '/var/lib/frankenphp(/.*\.db)' 2>/dev/null || : # QUIC semanage port --delete --type http_port_t --proto udp 80 2>/dev/null || : semanage port --delete --type http_port_t --proto udp 443 2>/dev/null || : # admin endpoint semanage port --delete --type http_port_t --proto tcp 2019 2>/dev/null || : fi fi ================================================ FILE: package/rhel/preinstall.sh ================================================ #!/bin/bash getent group frankenphp &>/dev/null || groupadd -r frankenphp &>/dev/null getent passwd frankenphp &>/dev/null || useradd -r -g frankenphp -d /var/lib/frankenphp -s /sbin/nologin -c 'FrankenPHP web server' frankenphp &>/dev/null exit 0 ================================================ FILE: package/rhel/preuninstall.sh ================================================ #!/bin/bash if [ "$1" -eq 0 ] && [ -x "/usr/lib/systemd/systemd-update-helper" ]; then # Package removal, not upgrade /usr/lib/systemd/systemd-update-helper remove-system-units frankenphp.service || : fi ================================================ FILE: phpmainthread.go ================================================ package frankenphp // #cgo nocallback frankenphp_new_main_thread // #cgo noescape frankenphp_new_main_thread // #include "frankenphp.h" // #include import "C" import ( "log/slog" "strings" "sync" "github.com/dunglas/frankenphp/internal/memory" "github.com/dunglas/frankenphp/internal/phpheaders" "github.com/dunglas/frankenphp/internal/state" ) // represents the main PHP thread // the thread needs to keep running as long as all other threads are running type phpMainThread struct { state *state.ThreadState done chan struct{} numThreads int maxThreads int phpIni map[string]string } var ( phpThreads []*phpThread mainThread *phpMainThread commonHeaders map[string]*C.zend_string ) // initPHPThreads starts the main PHP thread, // a fixed number of inactive PHP threads // and reserves a fixed number of possible PHP threads func initPHPThreads(numThreads int, numMaxThreads int, phpIni map[string]string) (*phpMainThread, error) { mainThread = &phpMainThread{ state: state.NewThreadState(), done: make(chan struct{}), numThreads: numThreads, maxThreads: numMaxThreads, phpIni: phpIni, } // initialize the first thread // this needs to happen before starting the main thread // since some extensions access environment variables on startup // the threadIndex on the main thread defaults to 0 -> phpThreads[0].Pin(...) initialThread := newPHPThread(0) phpThreads = []*phpThread{initialThread} if err := mainThread.start(); err != nil { return nil, err } // initialize all other threads phpThreads = make([]*phpThread, mainThread.maxThreads) phpThreads[0] = initialThread for i := 1; i < mainThread.maxThreads; i++ { phpThreads[i] = newPHPThread(i) } // start the underlying C threads var ready sync.WaitGroup for i := 0; i < numThreads; i++ { ready.Go(phpThreads[i].boot) } ready.Wait() return mainThread, nil } func drainPHPThreads() { if mainThread == nil { return // mainThread was never initialized } doneWG := sync.WaitGroup{} doneWG.Add(len(phpThreads)) mainThread.state.Set(state.ShuttingDown) close(mainThread.done) for _, thread := range phpThreads { // shut down all reserved threads if thread.state.CompareAndSwap(state.Reserved, state.Done) { doneWG.Done() continue } // shut down all active threads go func(thread *phpThread) { thread.shutdown() doneWG.Done() }(thread) } doneWG.Wait() mainThread.state.Set(state.Done) mainThread.state.WaitFor(state.Reserved) phpThreads = nil } func (mainThread *phpMainThread) start() error { if C.frankenphp_new_main_thread(C.int(mainThread.numThreads)) != 0 { return ErrMainThreadCreation } mainThread.state.WaitFor(state.Ready) // cache common request headers as zend_strings (HTTP_ACCEPT, HTTP_USER_AGENT, etc.) if commonHeaders == nil { commonHeaders = make(map[string]*C.zend_string, len(phpheaders.CommonRequestHeaders)) for key, phpKey := range phpheaders.CommonRequestHeaders { commonHeaders[key] = newPersistentZendString(phpKey) } } return nil } func getInactivePHPThread() *phpThread { for _, thread := range phpThreads { if thread.state.Is(state.Inactive) { return thread } } for _, thread := range phpThreads { if thread.state.CompareAndSwap(state.Reserved, state.BootRequested) { thread.boot() return thread } } return nil } //export go_frankenphp_main_thread_is_ready func go_frankenphp_main_thread_is_ready() { mainThread.setAutomaticMaxThreads() if mainThread.maxThreads < mainThread.numThreads { mainThread.maxThreads = mainThread.numThreads } mainThread.state.Set(state.Ready) mainThread.state.WaitFor(state.Done) } // max_threads = auto // setAutomaticMaxThreads estimates the amount of threads based on php.ini and system memory_limit // If unable to get the system's memory limit, simply double num_threads func (mainThread *phpMainThread) setAutomaticMaxThreads() { if mainThread.maxThreads >= 0 { return } perThreadMemoryLimit := int64(C.frankenphp_get_current_memory_limit()) totalSysMemory := memory.TotalSysMemory() if perThreadMemoryLimit <= 0 || totalSysMemory == 0 { mainThread.maxThreads = mainThread.numThreads * 2 return } maxAllowedThreads := totalSysMemory / uint64(perThreadMemoryLimit) mainThread.maxThreads = int(maxAllowedThreads) if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "Automatic thread limit", slog.Int("perThreadMemoryLimitMB", int(perThreadMemoryLimit/1024/1024)), slog.Int("maxThreads", mainThread.maxThreads)) } } //export go_frankenphp_shutdown_main_thread func go_frankenphp_shutdown_main_thread() { mainThread.state.Set(state.Reserved) } //export go_get_custom_php_ini func go_get_custom_php_ini(disableTimeouts C.bool) *C.char { if mainThread.phpIni == nil { mainThread.phpIni = make(map[string]string) } // Timeouts are currently fundamentally broken // with ZTS except on Linux and FreeBSD: https://bugs.php.net/bug.php?id=79464 // Disable timeouts if ZEND_MAX_EXECUTION_TIMERS is not supported if disableTimeouts { mainThread.phpIni["max_execution_time"] = "0" mainThread.phpIni["max_input_time"] = "-1" } // Pass the php.ini overrides to PHP before startup // TODO: if needed this would also be possible on a per-thread basis var overrides strings.Builder // 32 is an over-estimate for php.ini settings overrides.Grow(len(mainThread.phpIni) * 32) for k, v := range mainThread.phpIni { overrides.WriteString(k) overrides.WriteByte('=') overrides.WriteString(v) overrides.WriteByte('\n') } return C.CString(overrides.String()) } ================================================ FILE: phpmainthread_test.go ================================================ package frankenphp import ( "io" "math/rand/v2" "net/http/httptest" "path/filepath" "runtime" "sync" "sync/atomic" "testing" "time" "github.com/dunglas/frankenphp/internal/state" "github.com/stretchr/testify/assert" ) var testDataPath, _ = filepath.Abs("./testdata") func setupGlobals(t *testing.T) { t.Helper() t.Cleanup(Shutdown) resetGlobals() } func TestStartAndStopTheMainThreadWithOneInactiveThread(t *testing.T) { _, err := initPHPThreads(1, 1, nil) // boot 1 thread assert.NoError(t, err) assert.Len(t, phpThreads, 1) assert.Equal(t, 0, phpThreads[0].threadIndex) assert.True(t, phpThreads[0].state.Is(state.Inactive)) drainPHPThreads() assert.Nil(t, phpThreads) } func TestTransitionRegularThreadToWorkerThread(t *testing.T) { setupGlobals(t) _, err := initPHPThreads(1, 1, nil) assert.NoError(t, err) // transition to regular thread convertToRegularThread(phpThreads[0]) assert.IsType(t, ®ularThread{}, phpThreads[0].handler) // transition to worker thread worker := getDummyWorker(t, "transition-worker-1.php") convertToWorkerThread(phpThreads[0], worker) assert.IsType(t, &workerThread{}, phpThreads[0].handler) assert.Len(t, worker.threads, 1) // transition back to inactive thread convertToInactiveThread(phpThreads[0]) assert.IsType(t, &inactiveThread{}, phpThreads[0].handler) assert.Len(t, worker.threads, 0) drainPHPThreads() assert.Nil(t, phpThreads) } func TestTransitionAThreadBetween2DifferentWorkers(t *testing.T) { setupGlobals(t) _, err := initPHPThreads(1, 1, nil) assert.NoError(t, err) firstWorker := getDummyWorker(t, "transition-worker-1.php") secondWorker := getDummyWorker(t, "transition-worker-2.php") // convert to first worker thread convertToWorkerThread(phpThreads[0], firstWorker) firstHandler := phpThreads[0].handler.(*workerThread) assert.Same(t, firstWorker, firstHandler.worker) assert.Len(t, firstWorker.threads, 1) assert.Len(t, secondWorker.threads, 0) // convert to second worker thread convertToWorkerThread(phpThreads[0], secondWorker) secondHandler := phpThreads[0].handler.(*workerThread) assert.Same(t, secondWorker, secondHandler.worker) assert.Len(t, firstWorker.threads, 0) assert.Len(t, secondWorker.threads, 1) drainPHPThreads() assert.Nil(t, phpThreads) } // try all possible handler transitions // takes around 200ms and is supposed to force race conditions func TestTransitionThreadsWhileDoingRequests(t *testing.T) { t.Cleanup(Shutdown) var ( isDone atomic.Bool wg sync.WaitGroup ) numThreads := 10 numRequestsPerThread := 100 worker1Path := filepath.Join(testDataPath, "transition-worker-1.php") worker1Name := "worker-1" worker2Path := filepath.Join(testDataPath, "transition-worker-2.php") worker2Name := "worker-2" assert.NoError(t, Init( WithNumThreads(numThreads), WithWorkers(worker1Name, worker1Path, 1, WithWorkerEnv(map[string]string{"ENV1": "foo"}), WithWorkerWatchMode([]string{}), WithWorkerMaxFailures(0), ), WithWorkers(worker2Name, worker2Path, 1, WithWorkerEnv(map[string]string{"ENV1": "foo"}), WithWorkerWatchMode([]string{}), WithWorkerMaxFailures(0), ), )) // try all possible permutations of transition, transition every ms transitions := allPossibleTransitions(worker1Path, worker2Path) for i := range numThreads { go func(thread *phpThread, start int) { for { for j := start; j < len(transitions); j++ { if isDone.Load() { return } transitions[j](thread) time.Sleep(time.Millisecond) } start = 0 } }(phpThreads[i], i) } // randomly do requests to the 3 endpoints wg.Add(numThreads) for i := range numThreads { go func(i int) { for range numRequestsPerThread { switch rand.IntN(3) { case 0: assertRequestBody(t, "http://localhost/transition-worker-1.php", "Hello from worker 1") case 1: assertRequestBody(t, "http://localhost/transition-worker-2.php", "Hello from worker 2") case 2: assertRequestBody(t, "http://localhost/transition-regular.php", "Hello from regular thread") } } wg.Done() }(i) } // we are finished as soon as all 1000 requests are done wg.Wait() isDone.Store(true) } func TestFinishBootingAWorkerScript(t *testing.T) { setupGlobals(t) _, err := initPHPThreads(1, 1, nil) assert.NoError(t, err) // boot the worker worker := getDummyWorker(t, "transition-worker-1.php") convertToWorkerThread(phpThreads[0], worker) phpThreads[0].state.WaitFor(state.Ready) assert.NotNil(t, phpThreads[0].handler.(*workerThread).dummyContext) assert.Nil(t, phpThreads[0].handler.(*workerThread).workerContext) assert.False( t, phpThreads[0].handler.(*workerThread).isBootingScript, "isBootingScript should be false after the worker thread is ready", ) drainPHPThreads() assert.Nil(t, phpThreads) } func TestReturnAnErrorIf2WorkersHaveTheSameFileName(t *testing.T) { workers = []*worker{} workersByName = map[string]*worker{} workersByPath = map[string]*worker{} w, err1 := newWorker(workerOpt{fileName: testDataPath + "/index.php"}) assert.NoError(t, err1) workers = append(workers, w) workersByName[w.name] = w workersByPath[w.fileName] = w _, err2 := newWorker(workerOpt{fileName: testDataPath + "/index.php"}) assert.Error(t, err2, "two workers cannot have the same filename") } func TestReturnAnErrorIf2ModuleWorkersHaveTheSameName(t *testing.T) { workers = []*worker{} workersByName = map[string]*worker{} workersByPath = map[string]*worker{} w, err1 := newWorker(workerOpt{fileName: testDataPath + "/index.php", name: "workername"}) assert.NoError(t, err1) workers = append(workers, w) workersByName[w.name] = w workersByPath[w.fileName] = w _, err2 := newWorker(workerOpt{fileName: testDataPath + "/hello.php", name: "workername"}) assert.Error(t, err2, "two workers cannot have the same name") } func getDummyWorker(t *testing.T, fileName string) *worker { t.Helper() if workers == nil { workers = []*worker{} } worker, _ := newWorker(workerOpt{ fileName: testDataPath + "/" + fileName, num: 1, }) workers = append(workers, worker) return worker } func assertRequestBody(t *testing.T, url string, expected string) { r := httptest.NewRequest("GET", url, nil) w := httptest.NewRecorder() req, err := NewRequestWithContext(r, WithRequestDocumentRoot(testDataPath, false)) assert.NoError(t, err) err = ServeHTTP(w, req) assert.NoError(t, err) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Equal(t, expected, string(body)) } // create a mix of possible transitions of workers and regular threads func allPossibleTransitions(worker1Path string, worker2Path string) []func(*phpThread) { return []func(*phpThread){ convertToRegularThread, func(thread *phpThread) { thread.shutdown() }, func(thread *phpThread) { if thread.state.Is(state.Reserved) { thread.boot() } }, func(thread *phpThread) { convertToWorkerThread(thread, workersByPath[worker1Path]) }, convertToInactiveThread, func(thread *phpThread) { convertToWorkerThread(thread, workersByPath[worker2Path]) }, convertToInactiveThread, } } func TestCorrectThreadCalculation(t *testing.T) { maxProcs := runtime.GOMAXPROCS(0) * 2 oneWorkerThread := []workerOpt{{num: 1}} // default values testThreadCalculation(t, maxProcs, maxProcs, &opt{}) testThreadCalculation(t, maxProcs, maxProcs, &opt{workers: oneWorkerThread}) // num_threads is set testThreadCalculation(t, 1, 1, &opt{numThreads: 1}) testThreadCalculation(t, 2, 2, &opt{numThreads: 2, workers: oneWorkerThread}) // max_threads is set testThreadCalculation(t, 1, 10, &opt{maxThreads: 10}) testThreadCalculation(t, 2, 10, &opt{maxThreads: 10, workers: oneWorkerThread}) testThreadCalculation(t, 5, 10, &opt{numThreads: 5, maxThreads: 10, workers: oneWorkerThread}) // automatic max_threads testThreadCalculation(t, 1, -1, &opt{maxThreads: -1}) testThreadCalculation(t, 2, -1, &opt{maxThreads: -1, workers: oneWorkerThread}) testThreadCalculation(t, 2, -1, &opt{numThreads: 2, maxThreads: -1}) // max_threads should be thread minimum + sum of worker max_threads testThreadCalculation(t, 2, 6, &opt{workers: []workerOpt{{num: 1, maxThreads: 5}}}) testThreadCalculation(t, 6, 9, &opt{workers: []workerOpt{{num: 1, maxThreads: 4}, {num: 4, maxThreads: 4}}}) testThreadCalculation(t, 10, 14, &opt{numThreads: 10, workers: []workerOpt{{num: 1, maxThreads: 4}, {num: 3, maxThreads: 4}}}) // max_threads should remain equal to overall max_threads testThreadCalculation(t, 2, 5, &opt{maxThreads: 5, workers: []workerOpt{{num: 1, maxThreads: 3}}}) testThreadCalculation(t, 3, 5, &opt{maxThreads: 5, workers: []workerOpt{{num: 1, maxThreads: 4}, {num: 1, maxThreads: 4}}}) // not enough num threads testThreadCalculationError(t, &opt{numThreads: 1, workers: oneWorkerThread}) testThreadCalculationError(t, &opt{numThreads: 1, maxThreads: 1, workers: oneWorkerThread}) // not enough max_threads testThreadCalculationError(t, &opt{numThreads: 2, maxThreads: 1}) testThreadCalculationError(t, &opt{maxThreads: 1, workers: oneWorkerThread}) // worker max_threads is bigger than overall max_threads testThreadCalculationError(t, &opt{maxThreads: 5, workers: []workerOpt{{num: 1, maxThreads: 10}}}) // worker max_threads is smaller than num_threads testThreadCalculationError(t, &opt{workers: []workerOpt{{num: 3, maxThreads: 2}}}) } func testThreadCalculation(t *testing.T, expectedNumThreads int, expectedMaxThreads int, o *opt) { t.Helper() _, err := calculateMaxThreads(o) assert.NoError(t, err, "no error should be returned") assert.Equal(t, expectedNumThreads, o.numThreads, "num_threads must be correct") assert.Equal(t, expectedMaxThreads, o.maxThreads, "max_threads must be correct") } func testThreadCalculationError(t *testing.T, o *opt) { t.Helper() _, err := calculateMaxThreads(o) assert.Error(t, err, "configuration must error") } ================================================ FILE: phpthread.go ================================================ package frankenphp // #cgo nocallback frankenphp_new_php_thread // #include "frankenphp.h" import "C" import ( "context" "runtime" "sync" "unsafe" "github.com/dunglas/frankenphp/internal/state" ) // representation of the actual underlying PHP thread // identified by the index in the phpThreads slice type phpThread struct { runtime.Pinner threadIndex int requestChan chan contextHolder drainChan chan struct{} handlerMu sync.RWMutex handler threadHandler state *state.ThreadState } // threadHandler defines how the callbacks from the C thread should be handled type threadHandler interface { name() string beforeScriptExecution() string afterScriptExecution(exitStatus int) context() context.Context frankenPHPContext() *frankenPHPContext } func newPHPThread(threadIndex int) *phpThread { return &phpThread{ threadIndex: threadIndex, requestChan: make(chan contextHolder), state: state.NewThreadState(), } } // boot starts the underlying PHP thread func (thread *phpThread) boot() { // thread must be in reserved state to boot if !thread.state.CompareAndSwap(state.Reserved, state.Booting) && !thread.state.CompareAndSwap(state.BootRequested, state.Booting) { panic("thread is not in reserved state: " + thread.state.Name()) } // boot threads as inactive thread.handlerMu.Lock() thread.handler = &inactiveThread{thread: thread} thread.drainChan = make(chan struct{}) thread.handlerMu.Unlock() // start the actual posix thread - TODO: try this with go threads instead if !C.frankenphp_new_php_thread(C.uintptr_t(thread.threadIndex)) { panic("unable to create thread") } thread.state.WaitFor(state.Inactive) } // shutdown the underlying PHP thread func (thread *phpThread) shutdown() { if !thread.state.RequestSafeStateChange(state.ShuttingDown) { // already shutting down or done, wait for the C thread to finish thread.state.WaitFor(state.Done, state.Reserved) return } close(thread.drainChan) thread.state.WaitFor(state.Done) thread.drainChan = make(chan struct{}) // threads go back to the reserved state from which they can be booted again if mainThread.state.Is(state.Ready) { thread.state.Set(state.Reserved) } } // setHandler changes the thread handler safely // must be called from outside the PHP thread func (thread *phpThread) setHandler(handler threadHandler) { thread.handlerMu.Lock() defer thread.handlerMu.Unlock() if !thread.state.RequestSafeStateChange(state.TransitionRequested) { // no state change allowed == shutdown or done return } close(thread.drainChan) thread.state.WaitFor(state.TransitionInProgress) thread.handler = handler thread.drainChan = make(chan struct{}) thread.state.Set(state.TransitionComplete) } // transition to a new handler safely // is triggered by setHandler and executed on the PHP thread func (thread *phpThread) transitionToNewHandler() string { thread.state.Set(state.TransitionInProgress) thread.state.WaitFor(state.TransitionComplete) // execute beforeScriptExecution of the new handler return thread.handler.beforeScriptExecution() } func (thread *phpThread) frankenPHPContext() *frankenPHPContext { return thread.handler.frankenPHPContext() } func (thread *phpThread) context() context.Context { if thread.handler == nil { // handler can be nil when using opcache.preload return globalCtx } return thread.handler.context() } func (thread *phpThread) name() string { thread.handlerMu.RLock() name := thread.handler.name() thread.handlerMu.RUnlock() return name } // Pin a string that is not null-terminated // PHP's zend_string may contain null-bytes func (thread *phpThread) pinString(s string) *C.char { sData := unsafe.StringData(s) if sData == nil { return nil } thread.Pin(sData) return (*C.char)(unsafe.Pointer(sData)) } // C strings must be null-terminated func (thread *phpThread) pinCString(s string) *C.char { return thread.pinString(s + "\x00") } func (*phpThread) updateContext(isWorker bool) { C.frankenphp_update_local_thread_context(C.bool(isWorker)) } //export go_frankenphp_before_script_execution func go_frankenphp_before_script_execution(threadIndex C.uintptr_t) *C.char { thread := phpThreads[threadIndex] scriptName := thread.handler.beforeScriptExecution() // if no scriptName is passed, shut down if scriptName == "" { return nil } // return the name of the PHP script that should be executed return thread.pinCString(scriptName) } //export go_frankenphp_after_script_execution func go_frankenphp_after_script_execution(threadIndex C.uintptr_t, exitStatus C.int) { thread := phpThreads[threadIndex] if exitStatus < 0 { panic(ErrScriptExecution) } thread.handler.afterScriptExecution(int(exitStatus)) // unpin all memory used during script execution thread.Unpin() } //export go_frankenphp_on_thread_shutdown func go_frankenphp_on_thread_shutdown(threadIndex C.uintptr_t) { thread := phpThreads[threadIndex] thread.Unpin() thread.state.Set(state.Done) } ================================================ FILE: recorder_test.go ================================================ // Remove me when https://github.com/golang/go/pull/56151 will be merged // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package frankenphp_test import ( "bytes" "fmt" "io" "net/http" "net/http/httptrace" "net/textproto" "strconv" "strings" "golang.org/x/net/http/httpguts" ) // ResponseRecorder is an implementation of http.ResponseWriter that // records its mutations for later inspection in tests. type ResponseRecorder struct { // Code is the HTTP response code set by WriteHeader. // // Note that if a Handler never calls WriteHeader or Write, // this might end up being 0, rather than the implicit // http.StatusOK. To get the implicit value, use the Result // method. Code int // HeaderMap contains the headers explicitly set by the Handler. // It is an internal detail. // // Deprecated: HeaderMap exists for historical compatibility // and should not be used. To access the headers returned by a handler, // use the Response.Header map as returned by the Result method. HeaderMap http.Header // Body is the buffer to which the Handler's Write calls are sent. // If nil, the Writes are silently discarded. Body *bytes.Buffer // Flushed is whether the Handler called Flush. Flushed bool // ClientTrace is used to trace 1XX responses ClientTrace *httptrace.ClientTrace result *http.Response // cache of Result's return value snapHeader http.Header // snapshot of HeaderMap at first Write wroteHeader bool } // NewRecorder returns an initialized ResponseRecorder. func NewRecorder() *ResponseRecorder { return &ResponseRecorder{ HeaderMap: make(http.Header), Body: new(bytes.Buffer), Code: 200, } } // DefaultRemoteAddr is the default remote address to return in RemoteAddr if // an explicit DefaultRemoteAddr isn't set on ResponseRecorder. const DefaultRemoteAddr = "1.2.3.4" // Header implements http.ResponseWriter. It returns the response // headers to mutate within a handler. To test the headers that were // written after a handler completes, use the Result method and see // the returned Response value's Header. func (rw *ResponseRecorder) Header() http.Header { m := rw.HeaderMap if m == nil { m = make(http.Header) rw.HeaderMap = m } return m } // writeHeader writes a header if it was not written yet and // detects Content-Type if needed. // // bytes or str are the beginning of the response body. // We pass both to avoid unnecessarily generate garbage // in rw.WriteString which was created for performance reasons. // Non-nil bytes win. func (rw *ResponseRecorder) writeHeader(b []byte, str string) { if rw.wroteHeader { return } if len(str) > 512 { str = str[:512] } m := rw.Header() _, hasType := m["Content-Type"] hasTE := m.Get("Transfer-Encoding") != "" if !hasType && !hasTE { if b == nil { b = []byte(str) } m.Set("Content-Type", http.DetectContentType(b)) } rw.WriteHeader(200) } // Write implements http.ResponseWriter. The data in buf is written to // rw.Body, if not nil. func (rw *ResponseRecorder) Write(buf []byte) (int, error) { rw.writeHeader(buf, "") if rw.Body != nil { rw.Body.Write(buf) } return len(buf), nil } // WriteString implements io.StringWriter. The data in str is written // to rw.Body, if not nil. func (rw *ResponseRecorder) WriteString(str string) (int, error) { rw.writeHeader(nil, str) if rw.Body != nil { rw.Body.WriteString(str) } return len(str), nil } func checkWriteHeaderCode(code int) { // Issue 22880: require valid WriteHeader status codes. // For now, we only enforce that it's three digits. // In the future we might block things over 599 (600 and above aren't defined // at https://httpwg.org/specs/rfc7231.html#status.codes) // and we might block under 200 (once we have more mature 1xx support). // But for now any three digits. // // We used to send "HTTP/1.1 000 0" on the wire in responses but there's // no equivalent bogus thing we can realistically send in HTTP/2, // so we'll consistently panic instead and help people find their bugs // early. (We can't return an error from WriteHeader even if we wanted to.) if code < 100 || code > 999 { panic(fmt.Sprintf("invalid WriteHeader code %v", code)) } } // WriteHeader implements http.ResponseWriter. func (rw *ResponseRecorder) WriteHeader(code int) { if rw.wroteHeader { return } checkWriteHeaderCode(code) if rw.ClientTrace != nil && code >= 100 && code < 200 { if code == 100 { rw.ClientTrace.Got100Continue() } // treat 101 as a terminal status, see issue 26161 if code != http.StatusSwitchingProtocols { if err := rw.ClientTrace.Got1xxResponse(code, textproto.MIMEHeader(rw.HeaderMap)); err != nil { panic(err) } return } } rw.Code = code rw.wroteHeader = true if rw.HeaderMap == nil { rw.HeaderMap = make(http.Header) } rw.snapHeader = rw.HeaderMap.Clone() } // Flush implements http.Flusher. To test whether Flush was // called, see rw.Flushed. func (rw *ResponseRecorder) Flush() { if !rw.wroteHeader { rw.WriteHeader(200) } rw.Flushed = true } // Result returns the response generated by the handler. // // The returned Response will have at least its StatusCode, // Header, Body, and optionally Trailer populated. // More fields may be populated in the future, so callers should // not DeepEqual the result in tests. // // The Response.Header is a snapshot of the headers at the time of the // first write call, or at the time of this call, if the handler never // did a write. // // The Response.Body is guaranteed to be non-nil and Body.Read call is // guaranteed to not return any error other than io.EOF. // // Result must only be called after the handler has finished running. func (rw *ResponseRecorder) Result() *http.Response { if rw.result != nil { return rw.result } if rw.snapHeader == nil { rw.snapHeader = rw.HeaderMap.Clone() } res := &http.Response{ Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, StatusCode: rw.Code, Header: rw.snapHeader, } rw.result = res if res.StatusCode == 0 { res.StatusCode = 200 } res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) if rw.Body != nil { res.Body = io.NopCloser(bytes.NewReader(rw.Body.Bytes())) } else { res.Body = http.NoBody } res.ContentLength = parseContentLength(res.Header.Get("Content-Length")) if trailers, ok := rw.snapHeader["Trailer"]; ok { res.Trailer = make(http.Header, len(trailers)) for _, k := range trailers { for k := range strings.SplitSeq(k, ",") { k = http.CanonicalHeaderKey(textproto.TrimString(k)) if !httpguts.ValidTrailerHeader(k) { // Ignore since forbidden by RFC 7230, section 4.1.2. continue } vv, ok := rw.HeaderMap[k] if !ok { continue } vv2 := make([]string, len(vv)) copy(vv2, vv) res.Trailer[k] = vv2 } } } for k, vv := range rw.HeaderMap { if !strings.HasPrefix(k, http.TrailerPrefix) { continue } if res.Trailer == nil { res.Trailer = make(http.Header) } for _, v := range vv { res.Trailer.Add(strings.TrimPrefix(k, http.TrailerPrefix), v) } } return res } // parseContentLength trims whitespace from s and returns -1 if no value // is set, or the value if it's >= 0. // // This a modified version of same function found in net/http/transfer.go. This // one just ignores an invalid header. func parseContentLength(cl string) int64 { cl = textproto.TrimString(cl) if cl == "" { return -1 } n, err := strconv.ParseUint(cl, 10, 63) if err != nil { return -1 } return int64(n) } ================================================ FILE: release.sh ================================================ #!/usr/bin/env bash # Creates the tags for the library and the Caddy module. set -o nounset set -o errexit trap 'echo "Aborting due to errexit on line $LINENO. Exit code: $?" >&2' ERR set -o errtrace set -o pipefail set -o xtrace if ! type "git" >/dev/null; then echo "The \"git\" command must be installed." exit 1 fi if ! type "gh" >/dev/null; then echo "The \"gh\" command must be installed." exit 1 fi if ! type "brew" >/dev/null; then echo "The \"brew\" command must be installed." exit 1 fi if [[ $# -ne 1 ]]; then echo "Usage: ./release.sh version" >&2 exit 1 fi # Adapted from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string if [[ ! $1 =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?$ ]]; then echo "Invalid version number: $1" >&2 exit 1 fi git checkout main git pull cd caddy/ go get "github.com/dunglas/frankenphp@v$1" cd - git commit -S -a -m "chore: prepare release $1" || echo "skip" git tag -s -m "Version $1" "v$1" git tag -s -m "Version $1" "caddy/v$1" git push --follow-tags tags=$(git tag --list --sort=-version:refname 'v*') previous_tag=$(awk 'NR==2 {print;exit}' <<<"${tags}") gh release create --draft --generate-notes --latest --notes-start-tag "${previous_tag}" --verify-tag "v$1" brew bump-formula-pr dunglas/frankenphp/frankenphp --version "$1" ================================================ FILE: reload_test.sh ================================================ #!/bin/bash for ((i = 0; i < 100; i++)); do curl --no-progress-meter -o /dev/null http://localhost:2019/config/apps/frankenphp -: --no-progress-meter -o /dev/null -H 'Cache-Control: must-revalidate' -H 'Content-Type: application/json' --data-binary '{"workers":[{"file_name":"./index.php"}]}' -X PATCH http://localhost:2019/config/apps/frankenphp done ================================================ FILE: requestoptions.go ================================================ package frankenphp import ( "errors" "log/slog" "net/http" "path/filepath" "strings" "sync" "sync/atomic" "unicode/utf8" "github.com/dunglas/frankenphp/internal/fastabs" ) // RequestOption instances allow to configure a FrankenPHP Request. type RequestOption func(h *frankenPHPContext) error var ( ErrInvalidSplitPath = errors.New("split path contains non-ASCII characters") documentRootCache sync.Map documentRootCacheLen atomic.Uint32 ) // WithRequestDocumentRoot sets the root directory of the PHP application. // if resolveSymlink is true, oath declared as root directory will be resolved // to its absolute value after the evaluation of any symbolic links. // Due to the nature of PHP opcache, root directory path is cached: when // using a symlinked directory as root this could generate errors when // symlink is changed without PHP being restarted; enabling this // directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path. func WithRequestDocumentRoot(documentRoot string, resolveSymlink bool) RequestOption { return func(o *frankenPHPContext) (err error) { v, ok := documentRootCache.Load(documentRoot) if !ok { // make sure file root is absolute v, err = fastabs.FastAbs(documentRoot) if err != nil { return err } // prevent the cache to grow forever, this is a totally arbitrary value if documentRootCacheLen.Load() < 1024 { documentRootCache.LoadOrStore(documentRoot, v) documentRootCacheLen.Add(1) } } if resolveSymlink { if v, err = filepath.EvalSymlinks(v.(string)); err != nil { return err } } o.documentRoot = v.(string) return nil } } // WithRequestResolvedDocumentRoot is similar to WithRequestDocumentRoot // but doesn't do any checks or resolving on the path to improve performance. func WithRequestResolvedDocumentRoot(documentRoot string) RequestOption { return func(o *frankenPHPContext) error { o.documentRoot = documentRoot return nil } } // WithRequestSplitPath contains a list of split path strings. // // The path in the URL will be split into two, with the first piece ending // with the value of splitPath. The first piece will be assumed as the // actual resource (CGI script) name, and the second piece will be set to // PATH_INFO for the CGI script to use. // // Split paths can only contain ASCII characters. // Comparison is case-insensitive. // // Future enhancements should be careful to avoid CVE-2019-11043, // which can be mitigated with use of a try_files-like behavior // that 404s if the FastCGI path info is not found. func WithRequestSplitPath(splitPath []string) (RequestOption, error) { var b strings.Builder for i, split := range splitPath { b.Grow(len(split)) for j := 0; j < len(split); j++ { c := split[j] if c >= utf8.RuneSelf { return nil, ErrInvalidSplitPath } if 'A' <= c && c <= 'Z' { b.WriteByte(c + 'a' - 'A') } else { b.WriteByte(c) } } splitPath[i] = b.String() b.Reset() } return func(o *frankenPHPContext) error { o.splitPath = splitPath return nil }, nil } type PreparedEnv = map[string]string func PrepareEnv(env map[string]string) PreparedEnv { preparedEnv := make(PreparedEnv, len(env)) for k, v := range env { preparedEnv[k+"\x00"] = v } return preparedEnv } // WithRequestEnv set CGI-like environment variables that will be available in $_SERVER. // Values set with WithEnv always have priority over automatically populated values. func WithRequestEnv(env map[string]string) RequestOption { return WithRequestPreparedEnv(PrepareEnv(env)) } func WithRequestPreparedEnv(env PreparedEnv) RequestOption { return func(o *frankenPHPContext) error { o.env = env return nil } } func WithOriginalRequest(r *http.Request) RequestOption { return func(o *frankenPHPContext) error { o.originalRequest = r return nil } } // WithRequestLogger sets the logger associated with the current request func WithRequestLogger(logger *slog.Logger) RequestOption { return func(o *frankenPHPContext) error { o.logger = logger return nil } } // WithWorkerName sets the worker that should handle the request func WithWorkerName(name string) RequestOption { return func(o *frankenPHPContext) error { if name != "" { o.worker = workersByName[name] } return nil } } ================================================ FILE: requestoptions_test.go ================================================ package frankenphp import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestWithRequestSplitPath(t *testing.T) { t.Parallel() tests := []struct { name string splitPath []string wantErr error wantSplitPath []string }{ { name: "valid lowercase split path", splitPath: []string{".php"}, wantErr: nil, wantSplitPath: []string{".php"}, }, { name: "valid uppercase split path normalized", splitPath: []string{".PHP"}, wantErr: nil, wantSplitPath: []string{".php"}, }, { name: "valid mixed case split path normalized", splitPath: []string{".PhP", ".PHTML"}, wantErr: nil, wantSplitPath: []string{".php", ".phtml"}, }, { name: "empty split path", splitPath: []string{}, wantErr: nil, wantSplitPath: []string{}, }, { name: "non-ASCII character in split path rejected", splitPath: []string{".php", ".Ⱥphp"}, wantErr: ErrInvalidSplitPath, }, { name: "unicode character in split path rejected", splitPath: []string{".phpⱥ"}, wantErr: ErrInvalidSplitPath, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() ctx := &frankenPHPContext{} opt, err := WithRequestSplitPath(tt.splitPath) if tt.wantErr != nil { require.ErrorIs(t, err, tt.wantErr) return } require.NoError(t, err) require.NoError(t, opt(ctx)) assert.Equal(t, tt.wantSplitPath, ctx.splitPath) }) } } ================================================ FILE: scaling.go ================================================ package frankenphp import ( "errors" "log/slog" "sync" "time" "github.com/dunglas/frankenphp/internal/cpu" "github.com/dunglas/frankenphp/internal/state" ) const ( // requests have to be stalled for at least this amount of time before scaling minStallTime = 5 * time.Millisecond // time to check for CPU usage before scaling a single thread cpuProbeTime = 120 * time.Millisecond // do not scale over this amount of CPU usage maxCpuUsageForScaling = 0.8 // downscale idle threads every x seconds downScaleCheckTime = 5 * time.Second // max amount of threads stopped in one iteration of downScaleCheckTime maxTerminationCount = 10 // default time an autoscaled thread may be idle before being deactivated defaultMaxIdleTime = 5 * time.Second ) var ( ErrMaxThreadsReached = errors.New("max amount of overall threads reached") maxIdleTime = defaultMaxIdleTime scaleChan chan *frankenPHPContext autoScaledThreads = []*phpThread{} scalingMu = new(sync.RWMutex) ) func initAutoScaling(mainThread *phpMainThread) { if mainThread.maxThreads <= mainThread.numThreads { scaleChan = nil return } scalingMu.Lock() scaleChan = make(chan *frankenPHPContext) maxScaledThreads := mainThread.maxThreads - mainThread.numThreads autoScaledThreads = make([]*phpThread, 0, maxScaledThreads) scalingMu.Unlock() go startUpscalingThreads(maxScaledThreads, scaleChan, mainThread.done) go startDownScalingThreads(mainThread.done) } func drainAutoScaling() { scalingMu.Lock() if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "shutting down autoscaling", slog.Int("autoScaledThreads", len(autoScaledThreads))) } scalingMu.Unlock() } func addRegularThread() (*phpThread, error) { thread := getInactivePHPThread() if thread == nil { return nil, ErrMaxThreadsReached } convertToRegularThread(thread) thread.state.WaitFor(state.Ready, state.ShuttingDown, state.Reserved) return thread, nil } func addWorkerThread(worker *worker) (*phpThread, error) { thread := getInactivePHPThread() if thread == nil { return nil, ErrMaxThreadsReached } convertToWorkerThread(thread, worker) thread.state.WaitFor(state.Ready, state.ShuttingDown, state.Reserved) return thread, nil } // scaleWorkerThread adds a worker PHP thread automatically func scaleWorkerThread(worker *worker) { // probe CPU usage before acquiring the lock (avoids holding lock during 120ms sleep) if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) { return } scalingMu.Lock() defer scalingMu.Unlock() if !mainThread.state.Is(state.Ready) { return } thread, err := addWorkerThread(worker) if err != nil { if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, "could not increase max_threads, consider raising this limit", slog.String("worker", worker.name), slog.Any("error", err)) } return } autoScaledThreads = append(autoScaledThreads, thread) if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "upscaling worker thread", slog.String("worker", worker.name), slog.Int("thread", thread.threadIndex), slog.Int("num_threads", len(autoScaledThreads))) } } // scaleRegularThread adds a regular PHP thread automatically func scaleRegularThread() { // probe CPU usage before acquiring the lock (avoids holding lock during 120ms sleep) if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) { return } scalingMu.Lock() defer scalingMu.Unlock() if !mainThread.state.Is(state.Ready) { return } thread, err := addRegularThread() if err != nil { if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, "could not increase max_threads, consider raising this limit", slog.Any("error", err)) } return } autoScaledThreads = append(autoScaledThreads, thread) if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "upscaling regular thread", slog.Int("thread", thread.threadIndex), slog.Int("num_threads", len(autoScaledThreads))) } } func startUpscalingThreads(maxScaledThreads int, scale chan *frankenPHPContext, done chan struct{}) { for { scalingMu.Lock() scaledThreadCount := len(autoScaledThreads) scalingMu.Unlock() if scaledThreadCount >= maxScaledThreads { // we have reached max_threads, check again later select { case <-done: return case <-time.After(downScaleCheckTime): continue } } select { case fc := <-scale: timeSinceStalled := time.Since(fc.startedAt) // if the request has not been stalled long enough, wait and repeat if timeSinceStalled < minStallTime { select { case <-done: return case <-time.After(minStallTime - timeSinceStalled): continue } } // if the request has been stalled long enough, scale if fc.worker == nil { scaleRegularThread() continue } // check for max worker threads here again in case requests overflowed while waiting if fc.worker.isAtThreadLimit() { if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "cannot scale worker thread, max threads reached for worker", slog.String("worker", fc.worker.name)) } continue } scaleWorkerThread(fc.worker) case <-done: return } } } func startDownScalingThreads(done chan struct{}) { for { select { case <-done: return case <-time.After(downScaleCheckTime): deactivateThreads() } } } // deactivateThreads checks all threads and removes those that have been inactive for too long func deactivateThreads() { stoppedThreadCount := 0 scalingMu.Lock() defer scalingMu.Unlock() for i := len(autoScaledThreads) - 1; i >= 0; i-- { thread := autoScaledThreads[i] // the thread might have been stopped otherwise, remove it if thread.state.Is(state.Reserved) { autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...) continue } waitTime := thread.state.WaitTime() if stoppedThreadCount > maxTerminationCount || waitTime == 0 { continue } // convert threads to inactive if they have been idle for too long if thread.state.Is(state.Ready) && waitTime > maxIdleTime.Milliseconds() { convertToInactiveThread(thread) stoppedThreadCount++ autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...) if globalLogger.Enabled(globalCtx, slog.LevelInfo) { globalLogger.LogAttrs(globalCtx, slog.LevelInfo, "downscaling thread", slog.Int("thread", thread.threadIndex), slog.Int64("wait_time", waitTime), slog.Int("num_threads", len(autoScaledThreads))) } continue } // TODO: Completely stopping threads is more memory efficient // Some PECL extensions like #1296 will prevent threads from fully stopping (they leak memory) // Reactivate this if there is a better solution or workaround // if thread.state.Is(state.Inactive) && waitTime > maxThreadIdleTime.Milliseconds() { // logger.LogAttrs(nil, slog.LevelDebug, "auto-stopping thread", slog.Int("thread", thread.threadIndex)) // thread.shutdown() // stoppedThreadCount++ // autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...) // continue // } } } ================================================ FILE: scaling_test.go ================================================ package frankenphp import ( "path/filepath" "testing" "time" "github.com/dunglas/frankenphp/internal/state" "github.com/stretchr/testify/assert" ) func TestScaleARegularThreadUpAndDown(t *testing.T) { t.Cleanup(Shutdown) assert.NoError(t, Init( WithNumThreads(1), WithMaxThreads(2), )) autoScaledThread := phpThreads[1] // scale up scaleRegularThread() assert.Equal(t, state.Ready, autoScaledThread.state.Get()) assert.IsType(t, ®ularThread{}, autoScaledThread.handler) // on down-scale, the thread will be marked as inactive setLongWaitTime(t, autoScaledThread) deactivateThreads() assert.IsType(t, &inactiveThread{}, autoScaledThread.handler) } func TestScaleAWorkerThreadUpAndDown(t *testing.T) { t.Cleanup(Shutdown) workerName := "worker1" workerPath := filepath.Join(testDataPath, "transition-worker-1.php") assert.NoError(t, Init( WithNumThreads(2), WithMaxThreads(3), WithWorkers(workerName, workerPath, 1, WithWorkerEnv(map[string]string{}), WithWorkerWatchMode([]string{}), WithWorkerMaxFailures(0), ), )) autoScaledThread := phpThreads[2] // scale up scaleWorkerThread(workersByPath[workerPath]) assert.Equal(t, state.Ready, autoScaledThread.state.Get()) // on down-scale, the thread will be marked as inactive setLongWaitTime(t, autoScaledThread) deactivateThreads() assert.IsType(t, &inactiveThread{}, autoScaledThread.handler) } func TestMaxIdleTimePreventsEarlyDeactivation(t *testing.T) { t.Cleanup(Shutdown) assert.NoError(t, Init( WithNumThreads(1), WithMaxThreads(2), WithMaxIdleTime(time.Hour), )) autoScaledThread := phpThreads[1] // scale up scaleRegularThread() assert.Equal(t, state.Ready, autoScaledThread.state.Get()) // set wait time to 30 minutes (less than 1 hour max idle time) autoScaledThread.state.SetWaitTime(time.Now().Add(-30 * time.Minute)) deactivateThreads() assert.IsType(t, ®ularThread{}, autoScaledThread.handler, "thread should still be active after 30min with 1h max idle time") // set wait time to over 1 hour (exceeds max idle time) autoScaledThread.state.SetWaitTime(time.Now().Add(-time.Hour - time.Minute)) deactivateThreads() assert.IsType(t, &inactiveThread{}, autoScaledThread.handler, "thread should be deactivated after exceeding max idle time") } func setLongWaitTime(t *testing.T, thread *phpThread) { t.Helper() thread.state.SetWaitTime(time.Now().Add(-time.Hour)) } ================================================ FILE: static-builder-gnu.Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 FROM centos:7 ARG FRANKENPHP_VERSION='' ENV FRANKENPHP_VERSION=${FRANKENPHP_VERSION} ARG PHP_VERSION='' ENV PHP_VERSION=${PHP_VERSION} # args passed to static-php-cli ARG PHP_EXTENSIONS='' ARG PHP_EXTENSION_LIBS='' ARG SPC_OPT_BUILD_ARGS # args passed to xcaddy ARG XCADDY_ARGS='--with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy' ENV SPC_CMD_VAR_FRANKENPHP_XCADDY_MODULES="${XCADDY_ARGS}" ARG CLEAN='' ARG EMBED='' ARG DEBUG_SYMBOLS='' ARG MIMALLOC='' ARG NO_COMPRESS='' # Go ARG GO_VERSION ENV GOTOOLCHAIN=local SHELL ["/bin/bash", "-o", "pipefail", "-c"] # Pass through CI environment flag so build-static.sh can detect CI context ARG CI ENV CI=${CI} # labels, same as static-builder.Dockerfile LABEL org.opencontainers.image.title=FrankenPHP LABEL org.opencontainers.image.description="The modern PHP app server" LABEL org.opencontainers.image.url=https://frankenphp.dev LABEL org.opencontainers.image.source=https://github.com/php/frankenphp LABEL org.opencontainers.image.licenses=MIT LABEL org.opencontainers.image.vendor="Kévin Dunglas" # yum update RUN sed -i 's/mirror.centos.org/vault.centos.org/g' /etc/yum.repos.d/*.repo && \ sed -i 's/^#.*baseurl=http/baseurl=http/g' /etc/yum.repos.d/*.repo && \ sed -i 's/^mirrorlist=http/#mirrorlist=http/g' /etc/yum.repos.d/*.repo && \ yum clean all && \ yum makecache && \ yum update -y && \ yum install -y centos-release-scl # different arch for different scl repo RUN if [ "$(uname -m)" = "aarch64" ]; then \ sed -i 's|mirror.centos.org/centos|vault.centos.org/altarch|g' /etc/yum.repos.d/CentOS-SCLo-scl-rh.repo ; \ sed -i 's|mirror.centos.org/centos|vault.centos.org/altarch|g' /etc/yum.repos.d/CentOS-SCLo-scl.repo ; \ sed -i 's/^#.*baseurl=http/baseurl=http/g' /etc/yum.repos.d/*.repo ; \ sed -i 's/^mirrorlist=http/#mirrorlist=http/g' /etc/yum.repos.d/*.repo ; \ else \ sed -i 's/mirror.centos.org/vault.centos.org/g' /etc/yum.repos.d/*.repo ; \ sed -i 's/^#.*baseurl=http/baseurl=http/g' /etc/yum.repos.d/*.repo ; \ sed -i 's/^mirrorlist=http/#mirrorlist=http/g' /etc/yum.repos.d/*.repo ; \ fi; \ yum update -y && \ yum install -y devtoolset-10-gcc-* && \ echo "source scl_source enable devtoolset-10" >> /etc/bashrc && \ source /etc/bashrc # install build essentials RUN yum install -y \ perl \ make \ bison \ flex \ git \ autoconf \ automake \ tar \ unzip \ gzip \ gcc \ bzip2 \ patch \ xz \ libtool \ perl-IPC-Cmd ; \ curl -o make.tar.gz -fsSL https://ftp.gnu.org/gnu/make/make-4.4.tar.gz && \ tar -zxvf make.tar.gz && \ cd make-* && \ ./configure && \ make && \ make install && \ ln -sf /usr/local/bin/make /usr/bin/make && \ cd .. && \ rm -Rf make* && \ curl -o cmake.tar.gz -fsSL https://github.com/Kitware/CMake/releases/download/v4.1.2/cmake-4.1.2-linux-$(uname -m).tar.gz && \ mkdir /cmake && \ tar -xzf cmake.tar.gz -C /cmake --strip-components 1 && \ rm cmake.tar.gz && \ curl -fsSL -o patchelf.tar.gz https://github.com/NixOS/patchelf/releases/download/0.18.0/patchelf-0.18.0-$(uname -m).tar.gz && \ mkdir -p /patchelf && \ tar -xzf patchelf.tar.gz -C /patchelf --strip-components=1 && \ cp /patchelf/bin/patchelf /usr/bin/ && \ rm patchelf.tar.gz && \ if [ "$(uname -m)" = "aarch64" ]; then \ GO_ARCH="arm64" ; \ else \ GO_ARCH="amd64" ; \ fi; \ curl -o /usr/local/bin/jq -fsSL https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux-${GO_ARCH} && \ chmod +x /usr/local/bin/jq && \ curl -o go.tar.gz -fsSL https://go.dev/dl/$(curl -fsS https://go.dev/dl/?mode=json | jq -r "first(first(.[] | select(.stable and (.version | startswith(\"go${GO_VERSION}\")))).files[] | select(.os == \"linux\" and (.kind == \"archive\") and (.arch == \"${GO_ARCH}\"))).filename") && \ rm -rf /usr/local/go && \ tar -C /usr/local -xzf go.tar.gz && \ rm go.tar.gz && \ /usr/local/go/bin/go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest ENV PATH="/opt/rh/devtoolset-10/root/usr/bin:/cmake/bin:/usr/local/go/bin:$PATH" # Apply GNU mode ENV SPC_DEFAULT_C_FLAGS='-fPIE -fPIC -O3' ENV SPC_LIBC='glibc' ENV SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM='-Wl,-O3 -pie' ENV SPC_CMD_VAR_PHP_MAKE_EXTRA_LIBS='-ldl -lpthread -lm -lresolv -lutil -lrt' # Keep default config paths and append any externally provided SPC_OPT_BUILD_ARGS (e.g., from CI) ENV SPC_OPT_BUILD_ARGS="--with-config-file-path=/etc/frankenphp --with-config-file-scan-dir=/etc/frankenphp/php.d ${SPC_OPT_BUILD_ARGS}" ENV SPC_REL_TYPE='binary' ENV EXTENSION_DIR='/usr/lib/frankenphp/modules' # not sure if this is needed ENV COMPOSER_ALLOW_SUPERUSER=1 WORKDIR /go/src/app COPY go.mod go.sum ./ RUN go mod download WORKDIR /go/src/app/caddy COPY caddy/go.mod caddy/go.sum ./ RUN go mod download WORKDIR /go/src/app COPY --link *.* ./ COPY --link caddy caddy COPY --link internal internal COPY --link package package RUN --mount=type=secret,id=github-token GITHUB_TOKEN=$(cat /run/secrets/github-token) ./build-static.sh ================================================ FILE: static-builder-musl.Dockerfile ================================================ # syntax=docker/dockerfile:1 #checkov:skip=CKV_DOCKER_2 #checkov:skip=CKV_DOCKER_3 #checkov:skip=CKV_DOCKER_7 FROM golang-base ARG TARGETARCH ARG FRANKENPHP_VERSION='' ENV FRANKENPHP_VERSION=${FRANKENPHP_VERSION} ARG PHP_VERSION='' ENV PHP_VERSION=${PHP_VERSION} # args passed to static-php-cli ARG PHP_EXTENSIONS='' ARG PHP_EXTENSION_LIBS='' ARG SPC_OPT_BUILD_ARGS # args passed to xcaddy ARG XCADDY_ARGS='--with github.com/dunglas/caddy-cbrotli --with github.com/dunglas/mercure/caddy --with github.com/dunglas/vulcain/caddy' ENV SPC_CMD_VAR_FRANKENPHP_XCADDY_MODULES="${XCADDY_ARGS}" ARG CLEAN='' ARG EMBED='' ARG DEBUG_SYMBOLS='' ARG MIMALLOC='' ARG NO_COMPRESS='' ENV GOTOOLCHAIN=local SHELL ["/bin/ash", "-eo", "pipefail", "-c"] ARG CI ENV CI=${CI} LABEL org.opencontainers.image.title=FrankenPHP LABEL org.opencontainers.image.description="The modern PHP app server" LABEL org.opencontainers.image.url=https://frankenphp.dev LABEL org.opencontainers.image.source=https://github.com/php/frankenphp LABEL org.opencontainers.image.licenses=MIT LABEL org.opencontainers.image.vendor="Kévin Dunglas" RUN apk update; \ apk add --no-cache \ alpine-sdk \ autoconf \ automake \ bash \ binutils \ bison \ build-base \ cmake \ curl \ file \ flex \ g++ \ gcc \ git \ jq \ libgcc \ libstdc++ \ libtool \ linux-headers \ m4 \ make \ pkgconfig \ php84 \ php84-common \ php84-ctype \ php84-curl \ php84-dom \ php84-iconv \ php84-mbstring \ php84-openssl \ php84-pcntl \ php84-phar \ php84-posix \ php84-session \ php84-sodium \ php84-tokenizer \ php84-xml \ php84-xmlwriter \ upx \ wget \ xz ; \ ln -sf /usr/bin/php84 /usr/bin/php && \ go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest # https://getcomposer.org/doc/03-cli.md#composer-allow-superuser ENV COMPOSER_ALLOW_SUPERUSER=1 COPY --from=composer/composer:2-bin /composer /usr/bin/composer WORKDIR /go/src/app COPY go.mod go.sum ./ RUN go mod download WORKDIR /go/src/app/caddy COPY caddy/go.mod caddy/go.sum ./ RUN go mod download WORKDIR /go/src/app COPY --link . ./ ENV SPC_DEFAULT_C_FLAGS='-fPIE -fPIC -O3' ENV SPC_LIBC='musl' ENV SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM='-Wl,-O3 -pie' # Keep default config paths and append any externally provided SPC_OPT_BUILD_ARGS (e.g., from CI) ENV SPC_OPT_BUILD_ARGS="--with-config-file-path=/etc/frankenphp --with-config-file-scan-dir=/etc/frankenphp/php.d ${SPC_OPT_BUILD_ARGS}" ENV SPC_REL_TYPE='binary' ENV EXTENSION_DIR='/usr/lib/frankenphp/modules' RUN --mount=type=secret,id=github-token GITHUB_TOKEN=$(cat /run/secrets/github-token) ./build-static.sh ================================================ FILE: testdata/Caddyfile ================================================ { debug frankenphp { #worker ./index.php } } http:// { log route { root . # Add trailing slash for directory requests @canonicalPath { file {path}/index.php not path */ } redir @canonicalPath {path}/ 308 # If the requested file does not exist, try index files @indexFiles file { try_files {path} {path}/index.php index.php split_path .php } rewrite @indexFiles {http.matchers.file.relative} encode zstd br gzip # FrankenPHP! @phpFiles path *.php php @phpFiles file_server respond 404 } } ================================================ FILE: testdata/_executor.php ================================================ message = $message; } public function __destruct() { if (isset($this->message)) { echo $this->message; } } } $dumper = new Dumper(); while (frankenphp_handle_request(function () use ($dumper) { $dumper->dump($_GET['output'] ?? ''); exit(1); })) { // keep handling requests } echo "we should never reach here\n"; ================================================ FILE: testdata/die.php ================================================ ; rel=preload; as=style'); header("Request: {$_GET['i']}"); headers_send(103); header_remove('Link'); echo 'Hello'; }; ================================================ FILE: testdata/echo.php ================================================ "$key=" . $_ENV[$key], $keys)); }; ================================================ FILE: testdata/env/import-env.php ================================================ start(); }; ================================================ FILE: testdata/fiber-no-cgo.php ================================================ start(); $fiber->resume(); }; ================================================ FILE: testdata/file-stream.php ================================================ HTML; }; ================================================ FILE: testdata/files/.gitignore ================================================ test.txt ================================================ FILE: testdata/files/static.txt ================================================ Hello from file ================================================ FILE: testdata/finish-request.php ================================================ import "C" import ( "strings" "unsafe" "github.com/dunglas/frankenphp" ) // export_php:function test_uppercase(string $str): string func test_uppercase(s *C.zend_string) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(s)) upper := strings.ToUpper(str) return frankenphp.PHPString(upper, false) } // export_php:function test_add_numbers(int $a, int $b): int func test_add_numbers(a int64, b int64) int64 { return a + b } // export_php:function test_multiply(float $a, float $b): float func test_multiply(a float64, b float64) float64 { return a * b } // export_php:function test_is_enabled(bool $flag): bool func test_is_enabled(flag bool) bool { return !flag } ================================================ FILE: testdata/integration/callable.go ================================================ package testintegration // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:function my_array_map(array $data, callable $callback): array func my_array_map(arr *C.zend_array, callback *C.zval) unsafe.Pointer { goArray, err := frankenphp.GoPackedArray[any](unsafe.Pointer(arr)) if err != nil { return nil } result := make([]any, len(goArray)) for i, item := range goArray { callResult := frankenphp.CallPHPCallable(unsafe.Pointer(callback), []any{item}) result[i] = callResult } return frankenphp.PHPPackedArray[any](result) } // export_php:function my_filter(array $data, ?callable $callback): array func my_filter(arr *C.zend_array, callback *C.zval) unsafe.Pointer { goArray, err := frankenphp.GoPackedArray[any](unsafe.Pointer(arr)) if err != nil { return nil } if callback == nil { return unsafe.Pointer(arr) } result := make([]any, 0) for _, item := range goArray { callResult := frankenphp.CallPHPCallable(unsafe.Pointer(callback), []any{item}) if boolResult, ok := callResult.(bool); ok && boolResult { result = append(result, item) } } return frankenphp.PHPPackedArray[any](result) } // export_php:class Processor type Processor struct{} // export_php:method Processor::transform(string $input, callable $transformer): string func (p *Processor) Transform(input *C.zend_string, callback *C.zval) unsafe.Pointer { goInput := frankenphp.GoString(unsafe.Pointer(input)) callResult := frankenphp.CallPHPCallable(unsafe.Pointer(callback), []any{goInput}) resultStr, ok := callResult.(string) if !ok { return unsafe.Pointer(input) } return frankenphp.PHPString(resultStr, false) } ================================================ FILE: testdata/integration/class_methods.go ================================================ package testintegration // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:class Counter type CounterStruct struct { Value int } // export_php:method Counter::increment(): void func (c *CounterStruct) Increment() { c.Value++ } // export_php:method Counter::decrement(): void func (c *CounterStruct) Decrement() { c.Value-- } // export_php:method Counter::getValue(): int func (c *CounterStruct) GetValue() int64 { return int64(c.Value) } // export_php:method Counter::setValue(int $value): void func (c *CounterStruct) SetValue(value int64) { c.Value = int(value) } // export_php:method Counter::reset(): void func (c *CounterStruct) Reset() { c.Value = 0 } // export_php:method Counter::addValue(int $amount): int func (c *CounterStruct) AddValue(amount int64) int64 { c.Value += int(amount) return int64(c.Value) } // export_php:method Counter::updateWithNullable(?int $newValue): void func (c *CounterStruct) UpdateWithNullable(newValue *int64) { if newValue != nil { c.Value = int(*newValue) } } // export_php:class StringHolder type StringHolderStruct struct { Data string } // export_php:method StringHolder::setData(string $data): void func (sh *StringHolderStruct) SetData(data *C.zend_string) { sh.Data = frankenphp.GoString(unsafe.Pointer(data)) } // export_php:method StringHolder::getData(): string func (sh *StringHolderStruct) GetData() unsafe.Pointer { return frankenphp.PHPString(sh.Data, false) } // export_php:method StringHolder::getLength(): int func (sh *StringHolderStruct) GetLength() int64 { return int64(len(sh.Data)) } ================================================ FILE: testdata/integration/constants.go ================================================ package testintegration // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:const const TEST_MAX_RETRIES = 100 // export_php:const const TEST_API_VERSION = "2.0.0" // export_php:const const TEST_ENABLED = true // export_php:const const TEST_PI = 3.14159 // export_php:const const ( STATUS_PENDING = iota STATUS_PROCESSING STATUS_COMPLETED ) const ( // export_php:const ONE = 1 // export_php:const TWO = 2 ) // export_php:class Config type ConfigStruct struct { Mode int } // export_php:classconst Config const MODE_DEBUG = 1 // export_php:classconst Config const MODE_PRODUCTION = 2 // export_php:classconst Config const DEFAULT_TIMEOUT = 30 // export_php:method Config::setMode(int $mode): void func (c *ConfigStruct) SetMode(mode int64) { c.Mode = int(mode) } // export_php:method Config::getMode(): int func (c *ConfigStruct) GetMode() int64 { return int64(c.Mode) } // export_php:function test_with_constants(int $status): string func test_with_constants(status int64) unsafe.Pointer { var result string switch status { case STATUS_PENDING: result = "pending" case STATUS_PROCESSING: result = "processing" case STATUS_COMPLETED: result = "completed" default: result = "unknown" } return frankenphp.PHPString(result, false) } ================================================ FILE: testdata/integration/invalid_signature.go ================================================ package testintegration // #include import "C" // export_php:function invalid_return_type(string $str): unsupported_type func invalid_return_type(s *C.zend_string) int { return 42 } ================================================ FILE: testdata/integration/namespace.go ================================================ package testintegration // export_php:namespace TestIntegration\Extension // #include import "C" import ( "unsafe" "github.com/dunglas/frankenphp" ) // export_php:const const NAMESPACE_VERSION = "1.0.0" // export_php:function greet(string $name): string func greet(name *C.zend_string) unsafe.Pointer { str := frankenphp.GoString(unsafe.Pointer(name)) result := "Hello, " + str + "!" return frankenphp.PHPString(result, false) } // export_php:class Person type PersonStruct struct { Name string Age int } // export_php:method Person::setName(string $name): void func (p *PersonStruct) SetName(name *C.zend_string) { p.Name = frankenphp.GoString(unsafe.Pointer(name)) } // export_php:method Person::getName(): string func (p *PersonStruct) GetName() unsafe.Pointer { return frankenphp.PHPString(p.Name, false) } // export_php:method Person::setAge(int $age): void func (p *PersonStruct) SetAge(age int64) { p.Age = int(age) } // export_php:method Person::getAge(): int func (p *PersonStruct) GetAge() int64 { return int64(p.Age) } // export_php:classconst Person const DEFAULT_AGE = 18 ================================================ FILE: testdata/integration/type_mismatch.go ================================================ package testintegration // #include import "C" // export_php:function mismatched_param_type(int $value): int func mismatched_param_type(value string) int64 { return 0 } // export_php:class BadClass type BadClassStruct struct { Value int } // export_php:method BadClass::wrongReturnType(): string func (bc *BadClassStruct) WrongReturnType() int { return bc.Value } ================================================ FILE: testdata/large-request.php ================================================ r.status === 200, "is echoed": (r) => r.body === payload, }); } ================================================ FILE: testdata/log-error_log.php ================================================ 1, ]); frankenphp_log("some info message {$_GET['i']}", FRANKENPHP_LOG_LEVEL_INFO, [ "key string" => "string", ]); frankenphp_log("some warn message {$_GET['i']}", FRANKENPHP_LOG_LEVEL_WARN); frankenphp_log("some error message {$_GET['i']}", FRANKENPHP_LOG_LEVEL_ERROR, [ "err" => ["a", "v"], ]); }; ================================================ FILE: testdata/mercure-publish.php ================================================ /go/src/app/testdata/performance/flamegraph.svg ================================================ FILE: testdata/performance/hanging-requests.js ================================================ import http from "k6/http"; /** * It is not uncommon for external services to hang for a long time. * Make sure the server is resilient in such cases and doesn't hang as well. */ export const options = { stages: [ { duration: "20s", target: 100 }, { duration: "20s", target: 500 }, { duration: "20s", target: 0 }, ], thresholds: { http_req_failed: ["rate<0.01"], }, }; /* global __ENV */ export default function () { // 2% chance for a request that hangs for 15s if (Math.random() < 0.02) { http.get( `${__ENV.CADDY_HOSTNAME}/sleep.php?sleep=15000&work=10000&output=100`, ); return; } // a regular request http.get(`${__ENV.CADDY_HOSTNAME}/sleep.php?sleep=5&work=10000&output=100`); } ================================================ FILE: testdata/performance/hello-world.js ================================================ import http from "k6/http"; /** * 'Hello world' tests the raw server performance. */ export const options = { stages: [ { duration: "5s", target: 100 }, { duration: "20s", target: 400 }, { duration: "5s", target: 0 }, ], thresholds: { http_req_failed: ["rate<0.01"], }, }; /* global __ENV */ export default function () { http.get(`${__ENV.CADDY_HOSTNAME}/sleep.php`); } ================================================ FILE: testdata/performance/k6.Caddyfile ================================================ { frankenphp { max_threads {$MAX_THREADS} num_threads {$NUM_THREADS} worker { file /go/src/app/testdata/{$WORKER_FILE:sleep.php} num {$WORKER_THREADS} } } } :80 { route { root /go/src/app/testdata php { root /go/src/app/testdata } } } ================================================ FILE: testdata/performance/perf-test.sh ================================================ #!/bin/bash # install the dev.Dockerfile, build the app and run k6 tests docker build -t frankenphp-dev -f dev.Dockerfile . export "CADDY_HOSTNAME=http://host.docker.internal" select filename in ./testdata/performance/*.js; do read -r -p "How many worker threads? " workerThreads read -r -p "How many max threads? " maxThreads numThreads=$((workerThreads + 1)) docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ -p 8125:80 \ -v "$PWD:/go/src/app" \ --name load-test-container \ -e "MAX_THREADS=$maxThreads" \ -e "WORKER_THREADS=$workerThreads" \ -e "NUM_THREADS=$numThreads" \ -itd \ frankenphp-dev \ sh /go/src/app/testdata/performance/start-server.sh docker exec -d load-test-container sh /go/src/app/testdata/performance/flamegraph.sh sleep 10 docker run --entrypoint "" -it --rm -v .:/app -w /app \ --add-host "host.docker.internal:host-gateway" \ grafana/k6:latest \ k6 run -e "CADDY_HOSTNAME=$CADDY_HOSTNAME:8125" "./$filename" docker exec load-test-container curl "http://localhost:2019/frankenphp/threads" docker stop load-test-container docker rm load-test-container done ================================================ FILE: testdata/performance/performance-testing.md ================================================ # Running Load tests To run load tests with k6 you need to have Docker and Bash installed. Go the root of this repository and run: ```sh bash testdata/performance/perf-test.sh ``` This will build the `frankenphp-dev` Docker image and run it under the name 'load-test-container' in the background. Additionally, it will run the `grafana/k6` container, and you'll be able to choose the load test you want to run. A `flamegraph.svg` will be created in the `testdata/performance` directory. If the load test has stopped prematurely, you might have to remove the container manually: ```sh docker stop load-test-container docker rm load-test-container ``` ================================================ FILE: testdata/performance/start-server.sh ================================================ #!/bin/bash # build and run FrankenPHP with the k6.Caddyfile cd /go/src/app/caddy/frankenphp && go build --buildvcs=false && cd ../../testdata/performance && /go/src/app/caddy/frankenphp/frankenphp run -c k6.Caddyfile ================================================ FILE: testdata/performance/timeouts.js ================================================ import http from "k6/http"; /** * Databases or external resources can sometimes become unavailable for short periods of time. * Make sure the server can recover quickly from periods of unavailability. * This simulation swaps between a hanging and a working server every 10 seconds. */ export const options = { stages: [ { duration: "20s", target: 100 }, { duration: "20s", target: 500 }, { duration: "20s", target: 0 }, ], thresholds: { http_req_failed: ["rate<0.01"], }, }; /* global __ENV */ export default function () { const tenSecondInterval = Math.floor(new Date().getSeconds() / 10); const shouldHang = tenSecondInterval % 2 === 0; // every 10 seconds requests lead to a max_execution-timeout if (shouldHang) { http.get(`${__ENV.CADDY_HOSTNAME}/sleep.php?sleep=50000`); return; } // every other 10 seconds the resource is back http.get(`${__ENV.CADDY_HOSTNAME}/sleep.php?sleep=5&work=30000&output=100`); } ================================================ FILE: testdata/persistent-object-require.php ================================================ id . "\n"; echo 'object id: '. spl_object_id($foo); }; ================================================ FILE: testdata/phpinfo.php ================================================ \n"; foreach ([ 'CONTENT_LENGTH', 'HTTP_CONTENT_LENGTH', 'CONTENT_TYPE', 'HTTP_CONTENT_TYPE', 'HTTP_SPECIAL_CHARS', 'DOCUMENT_ROOT', 'DOCUMENT_URI', 'GATEWAY_INTERFACE', 'HTTP_HOST', 'HTTPS', 'PATH_INFO', 'DOCUMENT_ROOT', 'REMOTE_ADDR', 'PHP_SELF', 'REMOTE_HOST', 'REQUEST_SCHEME', 'SCRIPT_FILENAME', 'SCRIPT_NAME', 'SERVER_NAME', 'SERVER_PORT', 'SERVER_PROTOCOL', 'SERVER_SOFTWARE', 'SSL_PROTOCOL', 'AUTH_TYPE', 'REMOTE_IDENT', 'PATH_TRANSLATED', 'QUERY_STRING', 'REMOTE_USER', 'REQUEST_METHOD', 'REQUEST_URI', 'HTTP_X_EMPTY_HEADER', ] as $name) { echo "$name:" . $_SERVER[$name] . "\n"; } echo "\n"; ================================================ FILE: testdata/server-all-vars-ordered.txt ================================================
CONTENT_LENGTH:7
HTTP_CONTENT_LENGTH:7
CONTENT_TYPE:application/x-www-form-urlencoded
HTTP_CONTENT_TYPE:application/x-www-form-urlencoded
HTTP_SPECIAL_CHARS:<%00>
DOCUMENT_ROOT:{documentRoot}
DOCUMENT_URI:/server-all-vars-ordered.php
GATEWAY_INTERFACE:CGI/1.1
HTTP_HOST:localhost:{testPort}
HTTPS:
PATH_INFO:/path
DOCUMENT_ROOT:{documentRoot}
REMOTE_ADDR:127.0.0.1
PHP_SELF:/server-all-vars-ordered.php/path
REMOTE_HOST:127.0.0.1
REQUEST_SCHEME:http
SCRIPT_FILENAME:{documentRoot}/server-all-vars-ordered.php
SCRIPT_NAME:/server-all-vars-ordered.php
SERVER_NAME:localhost
SERVER_PORT:{testPort}
SERVER_PROTOCOL:HTTP/1.1
SERVER_SOFTWARE:FrankenPHP
SSL_PROTOCOL:
AUTH_TYPE:
REMOTE_IDENT:
PATH_TRANSLATED:{documentRoot}/path
QUERY_STRING:specialChars=%3E\x00%00
REMOTE_USER:user
REQUEST_METHOD:POST
REQUEST_URI:/original-path?specialChars=%3E\x00%00
HTTP_X_EMPTY_HEADER:
================================================ FILE: testdata/server-variable.php ================================================ getMessage(); } restore_error_handler(); // Now output everything $output[] = "save_handler_before=" . $saveHandlerBefore; $output[] = "SESSION_START_RESULT=" . ($result ? "true" : "false"); if ($error) { $output[] = "ERROR:" . $error; } if ($exception) { $output[] = "EXCEPTION:" . $exception; } break; case 'just_start': // Simple session start without any custom handler // This should always work session_id('test-session-id-3'); session_start(); $_SESSION['test'] = 'value'; session_write_close(); $output[] = "SESSION_STARTED_OK"; break; default: $output[] = "UNKNOWN_ACTION"; } echo implode("\n", $output); }; ================================================ FILE: testdata/session-leak.php ================================================ 0) { usleep($sleep * 1000); } // simulate output for ($k = 0; $k < $output; $k++) { echo "slept for $sleep ms and worked for $work iterations"; } } }; ================================================ FILE: testdata/super-globals.php ================================================ getMessage(); } restore_error_handler(); if ($error) { $output[] = "ERROR:" . $error; } break; case 'check': default: $saveHandler = ini_get('session.save_handler'); $output[] = "save_handler=$saveHandler"; if ($saveHandler === 'user') { $output[] = "HANDLER_PRESERVED"; } else { $output[] = "HANDLER_LOST"; } } echo implode("\n", $output); }); } while ($ok); ================================================ FILE: testdata/worker.php ================================================ = 0 && startupFailChan != nil && !watcherIsEnabled && handler.failureCount >= worker.maxConsecutiveFailures { startupFailChan <- fmt.Errorf("too many consecutive failures: worker %s has not reached frankenphp_handle_request()", worker.fileName) handler.thread.state.Set(state.ShuttingDown) return } if watcherIsEnabled { // worker script has probably failed due to script changes while watcher is enabled if globalLogger.Enabled(globalCtx, slog.LevelError) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, "(watcher enabled) worker script has not reached frankenphp_handle_request()", slog.String("worker", worker.name), slog.Int("thread", handler.thread.threadIndex)) } } else { // rare case where worker script has failed on a restart during normal operation // this can happen if startup success depends on external resources if globalLogger.Enabled(globalCtx, slog.LevelWarn) { globalLogger.LogAttrs(globalCtx, slog.LevelWarn, "worker script has failed on restart", slog.String("worker", worker.name), slog.Int("thread", handler.thread.threadIndex), slog.Int("failures", handler.failureCount)) } } // wait a bit and try again (exponential backoff) backoffDuration := time.Duration(handler.failureCount*handler.failureCount*100) * time.Millisecond if backoffDuration > time.Second { backoffDuration = time.Second } handler.failureCount++ time.Sleep(backoffDuration) } // waitForWorkerRequest is called during frankenphp_handle_request in the php worker script. func (handler *workerThread) waitForWorkerRequest() (bool, any) { // unpin any memory left over from previous requests handler.thread.Unpin() if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "waiting for request", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } // Clear the first dummy request created to initialize the worker if handler.isBootingScript { handler.isBootingScript = false handler.failureCount = 0 if !C.frankenphp_shutdown_dummy_request() { panic("Not in CGI context") } // worker is truly ready only after reaching frankenphp_handle_request() metrics.ReadyWorker(handler.worker.name) } if handler.state.Is(state.TransitionComplete) { handler.state.Set(state.Ready) } handler.state.MarkAsWaiting(true) var requestCH contextHolder select { case <-handler.thread.drainChan: if globalLogger.Enabled(globalCtx, slog.LevelDebug) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "shutting down", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } // flush the opcache when restarting due to watcher or admin api // note: this is done right before frankenphp_handle_request() returns 'false' if handler.state.Is(state.Restarting) { C.frankenphp_reset_opcache() } return false, nil case requestCH = <-handler.thread.requestChan: case requestCH = <-handler.worker.requestChan: } handler.workerContext = requestCH.ctx handler.workerFrankenPHPContext = requestCH.frankenPHPContext handler.state.MarkAsWaiting(false) if globalLogger.Enabled(requestCH.ctx, slog.LevelDebug) { if handler.workerFrankenPHPContext.request == nil { globalLogger.LogAttrs(requestCH.ctx, slog.LevelDebug, "request handling started", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } else { globalLogger.LogAttrs(requestCH.ctx, slog.LevelDebug, "request handling started", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex), slog.String("url", handler.workerFrankenPHPContext.request.RequestURI)) } } return true, handler.workerFrankenPHPContext.handlerParameters } // go_frankenphp_worker_handle_request_start is called at the start of every php request served. // //export go_frankenphp_worker_handle_request_start func go_frankenphp_worker_handle_request_start(threadIndex C.uintptr_t) (C.bool, unsafe.Pointer) { handler := phpThreads[threadIndex].handler.(*workerThread) hasRequest, parameters := handler.waitForWorkerRequest() if parameters != nil { var ptr unsafe.Pointer switch p := parameters.(type) { case unsafe.Pointer: ptr = p default: ptr = PHPValue(p) } handler.thread.Pin(ptr) return C.bool(hasRequest), ptr } return C.bool(hasRequest), nil } // go_frankenphp_finish_worker_request is called at the end of every php request served. // //export go_frankenphp_finish_worker_request func go_frankenphp_finish_worker_request(threadIndex C.uintptr_t, retval *C.zval) { thread := phpThreads[threadIndex] ctx := thread.context() fc := ctx.Value(contextKey).(*frankenPHPContext) if retval != nil { r, err := GoValue[any](unsafe.Pointer(retval)) if err != nil && globalLogger.Enabled(ctx, slog.LevelError) { globalLogger.LogAttrs(ctx, slog.LevelError, "cannot convert return value", slog.Any("error", err), slog.Int("thread", thread.threadIndex)) } fc.handlerReturn = r } fc.closeContext() thread.handler.(*workerThread).workerFrankenPHPContext = nil thread.handler.(*workerThread).workerContext = nil if globalLogger.Enabled(ctx, slog.LevelDebug) { if fc.request == nil { fc.logger.LogAttrs(ctx, slog.LevelDebug, "request handling finished", slog.String("worker", fc.worker.name), slog.Int("thread", thread.threadIndex)) } else { fc.logger.LogAttrs(ctx, slog.LevelDebug, "request handling finished", slog.String("worker", fc.worker.name), slog.Int("thread", thread.threadIndex), slog.String("url", fc.request.RequestURI)) } } } // when frankenphp_finish_request() is directly called from PHP // //export go_frankenphp_finish_php_request func go_frankenphp_finish_php_request(threadIndex C.uintptr_t) { thread := phpThreads[threadIndex] fc := thread.frankenPHPContext() fc.closeContext() ctx := thread.context() if fc.logger.Enabled(ctx, slog.LevelDebug) { fc.logger.LogAttrs(ctx, slog.LevelDebug, "request handling finished", slog.Int("thread", thread.threadIndex), slog.String("url", fc.request.RequestURI)) } } ================================================ FILE: types.c ================================================ #include "types.h" zval *get_ht_packed_data(HashTable *ht, uint32_t index) { if (ht->u.flags & HASH_FLAG_PACKED) { return &ht->arPacked[index]; } return NULL; } Bucket *get_ht_bucket_data(HashTable *ht, uint32_t index) { if (!(ht->u.flags & HASH_FLAG_PACKED)) { return &ht->arData[index]; } return NULL; } void *__emalloc__(size_t size) { return malloc(size); } void __efree__(void *ptr) { free(ptr); } void __zend_hash_init__(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, bool persistent) { zend_hash_init(ht, nSize, NULL, pDestructor, persistent); } void __hash_update_string__(zend_array *ht, zend_string *k, zend_string *v) { zval zv = {0}; ZVAL_STR(&zv, v); zend_hash_update(ht, k, &zv); } void __zval_null__(zval *zv) { ZVAL_NULL(zv); } void __zval_bool__(zval *zv, bool val) { ZVAL_BOOL(zv, val); } void __zval_long__(zval *zv, zend_long val) { ZVAL_LONG(zv, val); } void __zval_double__(zval *zv, double val) { ZVAL_DOUBLE(zv, val); } void __zval_string__(zval *zv, zend_string *str) { ZVAL_STR(zv, str); } void __zval_empty_string__(zval *zv) { ZVAL_EMPTY_STRING(zv); } void __zval_arr__(zval *zv, zend_array *arr) { ZVAL_ARR(zv, arr); } zend_array *__zend_new_array__(uint32_t size) { return zend_new_array(size); } int __zend_is_callable__(zval *cb) { return zend_is_callable(cb, 0, NULL); } int __call_user_function__(zval *function_name, zval *retval, uint32_t param_count, zval params[]) { return call_user_function(CG(function_table), NULL, function_name, retval, param_count, params); } ================================================ FILE: types.go ================================================ package frankenphp /* #cgo nocallback __zend_new_array__ #cgo nocallback __zval_null__ #cgo nocallback __zval_bool__ #cgo nocallback __zval_long__ #cgo nocallback __zval_double__ #cgo nocallback __zval_string__ #cgo nocallback __zval_arr__ #cgo noescape __zend_new_array__ #cgo noescape __zval_null__ #cgo noescape __zval_bool__ #cgo noescape __zval_long__ #cgo noescape __zval_double__ #cgo noescape __zval_string__ #cgo noescape __zval_arr__ #cgo noescape __emalloc__ #cgo noescape __efree__ #include "types.h" */ import "C" import ( "errors" "fmt" "reflect" "strconv" "unsafe" ) type toZval interface { toZval(*C.zval) } // EXPERIMENTAL: GoString copies a zend_string to a Go string. func GoString(s unsafe.Pointer) string { if s == nil { return "" } zendStr := (*C.zend_string)(s) return C.GoStringN((*C.char)(unsafe.Pointer(&zendStr.val)), C.int(zendStr.len)) } // EXPERIMENTAL: PHPString converts a Go string to a zend_string with copy. The string can be // non-persistent (automatically freed after the request by the ZMM) or persistent. If you choose // the second mode, it is your repsonsability to free the allocated memory. func PHPString(s string, persistent bool) unsafe.Pointer { if s == "" { return nil } zendStr := C.zend_string_init( (*C.char)(unsafe.Pointer(unsafe.StringData(s))), C.size_t(len(s)), C._Bool(persistent), ) return unsafe.Pointer(zendStr) } // AssociativeArray represents a PHP array with ordered key-value pairs type AssociativeArray[T any] struct { Map map[string]T Order []string } func (a AssociativeArray[T]) toZval(zval *C.zval) { C.__zval_arr__(zval, (*C.zend_array)(PHPAssociativeArray[T](a))) } // EXPERIMENTAL: GoAssociativeArray converts a zend_array to a Go AssociativeArray func GoAssociativeArray[T any](arr unsafe.Pointer) (AssociativeArray[T], error) { entries, order, err := goArray[T](arr, true) return AssociativeArray[T]{entries, order}, err } // EXPERIMENTAL: GoMap converts a zend_array to an unordered Go map func GoMap[T any](arr unsafe.Pointer) (map[string]T, error) { entries, _, err := goArray[T](arr, false) return entries, err } func goArray[T any](arr unsafe.Pointer, ordered bool) (map[string]T, []string, error) { if arr == nil { return nil, nil, errors.New("received a nil pointer on array conversion") } array := (*C.zend_array)(arr) if array == nil { return nil, nil, fmt.Errorf("received a *zval that wasn't a HashTable on array conversion") } nNumUsed := array.nNumUsed entries := make(map[string]T, nNumUsed) var order []string if ordered { order = make([]string, 0, nNumUsed) } if htIsPacked(array) { // if the array is packed, convert all integer keys to strings // this is probably a bug by the dev using this function // still, we'll (inefficiently) convert to an associative array for i := C.uint32_t(0); i < nNumUsed; i++ { v := C.get_ht_packed_data(array, i) if v != nil && C.zval_get_type(v) != C.IS_UNDEF { strIndex := strconv.Itoa(int(i)) e, err := goValue[T](v) if err != nil { return nil, nil, err } entries[strIndex] = e if ordered { order = append(order, strIndex) } } } return entries, order, nil } var zeroVal T for i := C.uint32_t(0); i < nNumUsed; i++ { bucket := C.get_ht_bucket_data(array, i) if bucket == nil || C.zval_get_type(&bucket.val) == C.IS_UNDEF { continue } v, err := goValue[any](&bucket.val) if err != nil { return nil, nil, err } if bucket.key != nil { keyStr := GoString(unsafe.Pointer(bucket.key)) if v == nil { entries[keyStr] = zeroVal } else { entries[keyStr] = v.(T) } if ordered { order = append(order, keyStr) } continue } // as fallback convert the bucket index to a string key strIndex := strconv.Itoa(int(bucket.h)) entries[strIndex] = v.(T) if ordered { order = append(order, strIndex) } } return entries, order, nil } // EXPERIMENTAL: GoPackedArray converts a zend_array to a Go slice func GoPackedArray[T any](arr unsafe.Pointer) ([]T, error) { if arr == nil { return nil, errors.New("GoPackedArray received a nil value") } array := (*C.zend_array)(arr) if array == nil { return nil, fmt.Errorf("GoPackedArray received *zval that wasn't a HashTable") } nNumUsed := array.nNumUsed result := make([]T, 0, nNumUsed) if htIsPacked(array) { for i := C.uint32_t(0); i < nNumUsed; i++ { v := C.get_ht_packed_data(array, i) if v != nil && C.zval_get_type(v) != C.IS_UNDEF { v, err := goValue[T](v) if err != nil { return nil, err } result = append(result, v) } } return result, nil } // fallback if ht isn't packed - equivalent to array_values() for i := C.uint32_t(0); i < nNumUsed; i++ { bucket := C.get_ht_bucket_data(array, i) if bucket != nil && C.zval_get_type(&bucket.val) != C.IS_UNDEF { v, err := goValue[T](&bucket.val) if err != nil { return nil, err } result = append(result, v) } } return result, nil } // EXPERIMENTAL: PHPMap converts an unordered Go map to a zend_array func PHPMap[T any](arr map[string]T) unsafe.Pointer { return phpArray[T](arr, nil) } // EXPERIMENTAL: PHPAssociativeArray converts a Go AssociativeArray to a zend_array func PHPAssociativeArray[T any](arr AssociativeArray[T]) unsafe.Pointer { return phpArray[T](arr.Map, arr.Order) } func phpArray[T any](entries map[string]T, order []string) unsafe.Pointer { var zendArray *C.zend_array if len(order) != 0 { zendArray = createNewArray((uint32)(len(order))) for _, key := range order { val := entries[key] zval := phpValue(val) C.zend_hash_str_update(zendArray, toUnsafeChar(key), C.size_t(len(key)), zval) C.__efree__(unsafe.Pointer(zval)) } } else { zendArray = createNewArray((uint32)(len(entries))) for key, val := range entries { zval := phpValue(val) C.zend_hash_str_update(zendArray, toUnsafeChar(key), C.size_t(len(key)), zval) C.__efree__(unsafe.Pointer(zval)) } } return unsafe.Pointer(zendArray) } // EXPERIMENTAL: PHPPackedArray converts a Go slice to a PHP zval with a zend_array value. func PHPPackedArray[T any](slice []T) unsafe.Pointer { zendArray := createNewArray((uint32)(len(slice))) for _, val := range slice { zval := phpValue(val) C.zend_hash_next_index_insert(zendArray, zval) C.__efree__(unsafe.Pointer(zval)) } return unsafe.Pointer(zendArray) } // EXPERIMENTAL: GoValue converts a PHP zval to a Go value // // Zval having the null, bool, long, double, string and array types are currently supported. // Arrays can currently only be converted to any[] and AssociativeArray[any]. // Any other type will cause an error. // More types may be supported in the future. func GoValue[T any](zval unsafe.Pointer) (T, error) { return goValue[T]((*C.zval)(zval)) } func goValue[T any](zval *C.zval) (res T, err error) { var ( resAny any resZero T ) t := C.zval_get_type(zval) switch t { case C.IS_NULL: resAny = any(nil) case C.IS_FALSE: resAny = any(false) case C.IS_TRUE: resAny = any(true) case C.IS_LONG: v, err := extractZvalValue(zval, C.IS_LONG) if err != nil { return resZero, err } if v != nil { resAny = any(int64(*(*C.zend_long)(v))) break } resAny = any(int64(0)) case C.IS_DOUBLE: v, err := extractZvalValue(zval, C.IS_DOUBLE) if err != nil { return resZero, err } if v != nil { resAny = any(float64(*(*C.double)(v))) break } resAny = any(float64(0)) case C.IS_STRING: v, err := extractZvalValue(zval, C.IS_STRING) if err != nil { return resZero, err } if v == nil { resAny = any("") break } resAny = any(GoString(v)) case C.IS_ARRAY: v, err := extractZvalValue(zval, C.IS_ARRAY) if err != nil { return resZero, err } array := (*C.zend_array)(v) if array != nil && htIsPacked(array) { typ := reflect.TypeOf(res) if typ == nil || typ.Kind() == reflect.Interface && typ.NumMethod() == 0 { r, e := GoPackedArray[any](unsafe.Pointer(array)) if e != nil { return resZero, e } resAny = any(r) break } return resZero, fmt.Errorf("cannot convert packed array to non-any Go type %s", typ.String()) } a, err := GoAssociativeArray[T](unsafe.Pointer(array)) if err != nil { return resZero, err } resAny = any(a) default: return resZero, fmt.Errorf("unsupported zval type %d", t) } if resAny == nil { return resZero, nil } if castRes, ok := resAny.(T); ok { return castRes, nil } return resZero, fmt.Errorf("cannot cast value of type %T to type %T", resAny, res) } // EXPERIMENTAL: PHPValue converts a Go any to a PHP zval // // nil, bool, int, int64, float64, string, []any, and map[string]any are currently supported. // Any other type will cause a panic. // More types may be supported in the future. func PHPValue(value any) unsafe.Pointer { return unsafe.Pointer(phpValue(value)) } func phpValue(value any) *C.zval { zval := (*C.zval)(C.__emalloc__(C.size_t(unsafe.Sizeof(C.zval{})))) if toZvalObj, ok := value.(toZval); ok { toZvalObj.toZval(zval) return zval } switch v := value.(type) { case nil: C.__zval_null__(zval) case bool: C.__zval_bool__(zval, C._Bool(v)) case int: C.__zval_long__(zval, C.zend_long(v)) case int64: C.__zval_long__(zval, C.zend_long(v)) case float64: C.__zval_double__(zval, C.double(v)) case string: if v == "" { C.__zval_empty_string__(zval) break } str := (*C.zend_string)(PHPString(v, false)) C.__zval_string__(zval, str) case AssociativeArray[any]: C.__zval_arr__(zval, (*C.zend_array)(PHPAssociativeArray[any](v))) case map[string]any: C.__zval_arr__(zval, (*C.zend_array)(PHPMap[any](v))) case []any: C.__zval_arr__(zval, (*C.zend_array)(PHPPackedArray[any](v))) default: C.__efree__(unsafe.Pointer(zval)) panic(fmt.Sprintf("unsupported Go type %T", v)) } return zval } // createNewArray creates a new zend_array with the specified size. func createNewArray(size uint32) *C.zend_array { arr := C.__zend_new_array__(C.uint32_t(size)) return (*C.zend_array)(unsafe.Pointer(arr)) } // IsPacked determines if the given zend_array is a packed array (list). // Returns false if the array is nil or not packed. func IsPacked(arr unsafe.Pointer) bool { if arr == nil { return false } return htIsPacked((*C.zend_array)(arr)) } // htIsPacked checks if a zend_array is a list (packed) or hashmap (not packed). func htIsPacked(ht *C.zend_array) bool { flags := *(*C.uint32_t)(unsafe.Pointer(&ht.u[0])) return (flags & C.HASH_FLAG_PACKED) != 0 } // extractZvalValue returns a pointer to the zval value cast to the expected type func extractZvalValue(zval *C.zval, expectedType C.uint8_t) (unsafe.Pointer, error) { if zval == nil { if expectedType == C.IS_NULL { return nil, nil } return nil, fmt.Errorf("zval type mismatch: expected %d, got nil", expectedType) } if zType := C.zval_get_type(zval); zType != expectedType { return nil, fmt.Errorf("zval type mismatch: expected %d, got %d", expectedType, zType) } v := unsafe.Pointer(&zval.value[0]) switch expectedType { case C.IS_LONG, C.IS_DOUBLE: return v, nil case C.IS_STRING: return unsafe.Pointer(*(**C.zend_string)(v)), nil case C.IS_ARRAY: return unsafe.Pointer(*(**C.zend_array)(v)), nil } return nil, fmt.Errorf("unsupported zval type %d", expectedType) } func zendStringRelease(p unsafe.Pointer) { zs := (*C.zend_string)(p) C.zend_string_release(zs) } func zendHashDestroy(p unsafe.Pointer) { ht := (*C.zend_array)(p) C.zend_hash_destroy(ht) } // EXPERIMENTAL: CallPHPCallable executes a PHP callable with the given parameters. // Returns the result of the callable as a Go interface{}, or nil if the call failed. func CallPHPCallable(cb unsafe.Pointer, params []interface{}) interface{} { if cb == nil { return nil } callback := (*C.zval)(cb) if callback == nil { return nil } if C.__zend_is_callable__(callback) == 0 { return nil } paramCount := len(params) var paramStorage *C.zval if paramCount > 0 { paramStorage = (*C.zval)(C.__emalloc__(C.size_t(paramCount) * C.size_t(unsafe.Sizeof(C.zval{})))) defer func() { for i := 0; i < paramCount; i++ { targetZval := (*C.zval)(unsafe.Pointer(uintptr(unsafe.Pointer(paramStorage)) + uintptr(i)*unsafe.Sizeof(C.zval{}))) C.zval_ptr_dtor(targetZval) } C.__efree__(unsafe.Pointer(paramStorage)) }() for i, param := range params { targetZval := (*C.zval)(unsafe.Pointer(uintptr(unsafe.Pointer(paramStorage)) + uintptr(i)*unsafe.Sizeof(C.zval{}))) sourceZval := phpValue(param) *targetZval = *sourceZval C.__efree__(unsafe.Pointer(sourceZval)) } } var retval C.zval result := C.__call_user_function__(callback, &retval, C.uint32_t(paramCount), paramStorage) if result != C.SUCCESS { return nil } goResult, err := goValue[any](&retval) C.zval_ptr_dtor(&retval) if err != nil { return nil } return goResult } ================================================ FILE: types.h ================================================ #ifndef TYPES_H #define TYPES_H #include "frankenphp.h" #include #include #include #include #include zval *get_ht_packed_data(HashTable *, uint32_t index); Bucket *get_ht_bucket_data(HashTable *, uint32_t index); void *__emalloc__(size_t size); void __efree__(void *ptr); void __zend_hash_init__(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, bool persistent); void __hash_update_string__(zend_array *ht, zend_string *k, zend_string *v); int __zend_is_callable__(zval *cb); int __call_user_function__(zval *function_name, zval *retval, uint32_t param_count, zval params[]); void __zval_null__(zval *zv); void __zval_bool__(zval *zv, bool val); void __zval_long__(zval *zv, zend_long val); void __zval_double__(zval *zv, double val); void __zval_string__(zval *zv, zend_string *str); void __zval_empty_string__(zval *zv); void __zval_arr__(zval *zv, zend_array *arr); zend_array *__zend_new_array__(uint32_t size); #endif ================================================ FILE: types_test.go ================================================ package frankenphp import ( "log/slog" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // execute the function on a PHP thread directly // this is necessary if tests make use of PHP's internal allocation func testOnDummyPHPThread(t *testing.T, test func()) { t.Helper() globalLogger = slog.Default() _, err := initPHPThreads(1, 1, nil) // boot 1 thread assert.NoError(t, err) handler := convertToTaskThread(phpThreads[0]) task := newTask(test) handler.execute(task) task.waitForCompletion() drainPHPThreads() } func TestGoString(t *testing.T) { testOnDummyPHPThread(t, func() { originalString := "Hello, World!" phpString := PHPString(originalString, false) defer zendStringRelease(phpString) assert.Equal(t, originalString, GoString(phpString), "string -> zend_string -> string should yield an equal string") }) } func TestPHPMap(t *testing.T) { testOnDummyPHPThread(t, func() { originalMap := map[string]string{ "foo1": "bar1", "foo2": "bar2", } phpArray := PHPMap(originalMap) defer zendHashDestroy(phpArray) convertedMap, err := GoMap[string](phpArray) require.NoError(t, err) assert.Equal(t, originalMap, convertedMap, "associative array should be equal after conversion") }) } func TestOrderedPHPAssociativeArray(t *testing.T) { testOnDummyPHPThread(t, func() { originalArray := AssociativeArray[string]{ Map: map[string]string{ "foo1": "bar1", "foo2": "bar2", }, Order: []string{"foo2", "foo1"}, } phpArray := PHPAssociativeArray(originalArray) defer zendHashDestroy(phpArray) convertedArray, err := GoAssociativeArray[string](phpArray) require.NoError(t, err) assert.Equal(t, originalArray, convertedArray, "associative array should be equal after conversion") }) } func TestPHPPackedArray(t *testing.T) { testOnDummyPHPThread(t, func() { originalSlice := []string{"bar1", "bar2"} phpArray := PHPPackedArray(originalSlice) defer zendHashDestroy(phpArray) convertedSlice, err := GoPackedArray[string](phpArray) require.NoError(t, err) assert.Equal(t, originalSlice, convertedSlice, "slice should be equal after conversion") }) } func TestPHPPackedArrayToGoMap(t *testing.T) { testOnDummyPHPThread(t, func() { originalSlice := []string{"bar1", "bar2"} expectedMap := map[string]string{ "0": "bar1", "1": "bar2", } phpArray := PHPPackedArray(originalSlice) defer zendHashDestroy(phpArray) convertedMap, err := GoMap[string](phpArray) require.NoError(t, err) assert.Equal(t, expectedMap, convertedMap, "convert a packed to an associative array") }) } func TestPHPAssociativeArrayToPacked(t *testing.T) { testOnDummyPHPThread(t, func() { originalArray := AssociativeArray[string]{ Map: map[string]string{ "foo1": "bar1", "foo2": "bar2", }, Order: []string{"foo1", "foo2"}, } expectedSlice := []string{"bar1", "bar2"} phpArray := PHPAssociativeArray(originalArray) defer zendHashDestroy(phpArray) convertedSlice, err := GoPackedArray[string](phpArray) require.NoError(t, err) assert.Equal(t, expectedSlice, convertedSlice, "convert an associative array to a slice") }) } func TestNestedMixedArray(t *testing.T) { testOnDummyPHPThread(t, func() { originalArray := map[string]any{ "string": "value", "int": int64(123), "float": 1.2, "true": true, "false": false, "nil": nil, "packedArray": []any{"bar1", "bar2"}, "associativeArray": AssociativeArray[any]{ Map: map[string]any{"foo1": "bar1", "foo2": "bar2"}, Order: []string{"foo2", "foo1"}, }, } phpArray := PHPMap(originalArray) defer zendHashDestroy(phpArray) convertedArray, err := GoMap[any](phpArray) require.NoError(t, err) assert.Equal(t, originalArray, convertedArray, "nested mixed array should be equal after conversion") }) } ================================================ FILE: vcpkg.json ================================================ { "dependencies": ["brotli", "pthreads"] } ================================================ FILE: watcher-skip.go ================================================ //go:build nowatcher package frankenphp import "errors" type hotReloadOpt struct { } var errWatcherNotEnabled = errors.New("watcher support is not enabled") func initWatchers(o *opt) error { for _, o := range o.workers { if len(o.watch) != 0 { return errWatcherNotEnabled } } return nil } func drainWatchers() { } ================================================ FILE: watcher.go ================================================ //go:build !nowatcher package frankenphp import ( "sync/atomic" "github.com/dunglas/frankenphp/internal/watcher" watcherGo "github.com/e-dant/watcher/watcher-go" ) type hotReloadOpt struct { hotReload []*watcher.PatternGroup } var restartWorkers atomic.Bool func initWatchers(o *opt) error { watchPatterns := make([]*watcher.PatternGroup, 0, len(o.hotReload)) for _, o := range o.workers { if len(o.watch) == 0 { continue } watcherIsEnabled = true watchPatterns = append(watchPatterns, &watcher.PatternGroup{Patterns: o.watch, Callback: func(_ []*watcherGo.Event) { restartWorkers.Store(true) }}) } if watcherIsEnabled { watchPatterns = append(watchPatterns, &watcher.PatternGroup{ Callback: func(_ []*watcherGo.Event) { if restartWorkers.Swap(false) { RestartWorkers() } }, }) } return watcher.InitWatcher(globalCtx, globalLogger, append(watchPatterns, o.hotReload...)) } func drainWatchers() { watcher.DrainWatcher() } ================================================ FILE: watcher_test.go ================================================ //go:build !nowatcher package frankenphp_test import ( "net/http" "net/http/httptest" "os" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // we have to wait a few milliseconds for the watcher debounce to take effect const pollingTime = 250 // in tests checking for no reload: we will poll 3x250ms = 0.75s const minTimesToPollForChanges = 3 // in tests checking for a reload: we will poll a maximum of 60x250ms = 15s const maxTimesToPollForChanges = 60 func TestWorkersShouldReloadOnMatchingPattern(t *testing.T) { watch := []string{"./testdata/**/*.txt"} runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { requestBodyHasReset := pollForWorkerReset(t, handler, maxTimesToPollForChanges) assert.True(t, requestBodyHasReset) }, &testOptions{nbParallelRequests: 1, nbWorkers: 1, workerScript: "worker-with-counter.php", watch: watch}) } func TestWorkersShouldNotReloadOnExcludingPattern(t *testing.T) { watch := []string{"./testdata/**/*.php"} runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { requestBodyHasReset := pollForWorkerReset(t, handler, minTimesToPollForChanges) assert.False(t, requestBodyHasReset) }, &testOptions{nbParallelRequests: 1, nbWorkers: 1, workerScript: "worker-with-counter.php", watch: watch}) } func pollForWorkerReset(t *testing.T, handler func(http.ResponseWriter, *http.Request), limit int) bool { t.Helper() // first we make an initial request to start the request counter body, _ := testGet("http://example.com/worker-with-counter.php", handler, t) assert.Equal(t, "requests:1", body) // now we spam file updates and check if the request counter resets for range limit { updateTestFile(t, filepath.Join(".", "testdata", "files", "test.txt"), "updated") time.Sleep(pollingTime * time.Millisecond) body, _ := testGet("http://example.com/worker-with-counter.php", handler, t) if body == "requests:1" { return true } } return false } func updateTestFile(t *testing.T, fileName, content string) { absFileName, err := filepath.Abs(fileName) require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Dir(absFileName), 0700)) require.NoError(t, os.WriteFile(absFileName, []byte(content), 0644)) } ================================================ FILE: worker.go ================================================ package frankenphp // #include "frankenphp.h" import "C" import ( "fmt" "os" "path/filepath" "runtime" "strings" "sync" "sync/atomic" "time" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/dunglas/frankenphp/internal/state" ) // represents a worker script and can have many threads assigned to it type worker struct { mercureContext name string fileName string num int maxThreads int requestOptions []RequestOption requestChan chan contextHolder threads []*phpThread threadMutex sync.RWMutex allowPathMatching bool maxConsecutiveFailures int onThreadReady func(int) onThreadShutdown func(int) queuedRequests atomic.Int32 } var ( workers []*worker workersByName map[string]*worker workersByPath map[string]*worker watcherIsEnabled bool startupFailChan chan error ) func initWorkers(opt []workerOpt) error { if len(opt) == 0 { return nil } var ( workersReady sync.WaitGroup totalThreadsToStart int ) workers = make([]*worker, 0, len(opt)) workersByName = make(map[string]*worker, len(opt)) workersByPath = make(map[string]*worker, len(opt)) for _, o := range opt { w, err := newWorker(o) if err != nil { return err } totalThreadsToStart += w.num workers = append(workers, w) workersByName[w.name] = w if w.allowPathMatching { workersByPath[w.fileName] = w } } startupFailChan = make(chan error, totalThreadsToStart) for _, w := range workers { for i := 0; i < w.num; i++ { thread := getInactivePHPThread() convertToWorkerThread(thread, w) workersReady.Go(func() { thread.state.WaitFor(state.Ready, state.ShuttingDown, state.Done) }) } } workersReady.Wait() select { case err := <-startupFailChan: // at least 1 worker has failed, return an error return fmt.Errorf("failed to initialize workers: %w", err) default: // all workers started successfully startupFailChan = nil } return nil } func newWorker(o workerOpt) (*worker, error) { // Order is important! // This order ensures that FrankenPHP started from inside a symlinked directory will properly resolve any paths. // If it is started from outside a symlinked directory, it is resolved to the same path that we use in the Caddy module. absFileName, err := filepath.EvalSymlinks(filepath.FromSlash(o.fileName)) if err != nil { return nil, fmt.Errorf("worker filename is invalid %q: %w", o.fileName, err) } absFileName, err = fastabs.FastAbs(absFileName) if err != nil { return nil, fmt.Errorf("worker filename is invalid %q: %w", o.fileName, err) } if _, err := os.Stat(absFileName); err != nil { return nil, fmt.Errorf("worker file not found %q: %w", absFileName, err) } if o.name == "" { o.name = absFileName } // workers that have a name starting with "m#" are module workers // they can only be matched by their name, not by their path allowPathMatching := !strings.HasPrefix(o.name, "m#") if w := workersByPath[absFileName]; w != nil && allowPathMatching { return w, fmt.Errorf("two workers cannot have the same filename: %q", absFileName) } if w := workersByName[o.name]; w != nil { return w, fmt.Errorf("two workers cannot have the same name: %q", o.name) } if o.env == nil { o.env = make(PreparedEnv, 1) } o.env["FRANKENPHP_WORKER\x00"] = "1" w := &worker{ name: o.name, fileName: absFileName, requestOptions: o.requestOptions, num: o.num, maxThreads: o.maxThreads, requestChan: make(chan contextHolder), threads: make([]*phpThread, 0, o.num), allowPathMatching: allowPathMatching, maxConsecutiveFailures: o.maxConsecutiveFailures, onThreadReady: o.onThreadReady, onThreadShutdown: o.onThreadShutdown, } w.configureMercure(&o) w.requestOptions = append( w.requestOptions, WithRequestDocumentRoot(filepath.Dir(o.fileName), false), WithRequestPreparedEnv(o.env), ) if o.extensionWorkers != nil { o.extensionWorkers.internalWorker = w } return w, nil } // EXPERIMENTAL: DrainWorkers finishes all worker scripts before a graceful shutdown func DrainWorkers() { _ = drainWorkerThreads() } func drainWorkerThreads() []*phpThread { var ( ready sync.WaitGroup drainedThreads []*phpThread ) for _, worker := range workers { worker.threadMutex.RLock() ready.Add(len(worker.threads)) for _, thread := range worker.threads { if !thread.state.RequestSafeStateChange(state.Restarting) { ready.Done() // no state change allowed == thread is shutting down // we'll proceed to restart all other threads anyway continue } close(thread.drainChan) drainedThreads = append(drainedThreads, thread) go func(thread *phpThread) { thread.state.WaitFor(state.Yielding) ready.Done() }(thread) } worker.threadMutex.RUnlock() } ready.Wait() return drainedThreads } // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { // disallow scaling threads while restarting workers scalingMu.Lock() defer scalingMu.Unlock() threadsToRestart := drainWorkerThreads() for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) thread.state.Set(state.Ready) } } func (worker *worker) attachThread(thread *phpThread) { worker.threadMutex.Lock() worker.threads = append(worker.threads, thread) worker.threadMutex.Unlock() } func (worker *worker) detachThread(thread *phpThread) { worker.threadMutex.Lock() for i, t := range worker.threads { if t == thread { worker.threads = append(worker.threads[:i], worker.threads[i+1:]...) break } } worker.threadMutex.Unlock() } func (worker *worker) countThreads() int { worker.threadMutex.RLock() l := len(worker.threads) worker.threadMutex.RUnlock() return l } // check if max_threads has been reached func (worker *worker) isAtThreadLimit() bool { if worker.maxThreads <= 0 { return false } worker.threadMutex.RLock() atMaxThreads := len(worker.threads) >= worker.maxThreads worker.threadMutex.RUnlock() return atMaxThreads } func (worker *worker) handleRequest(ch contextHolder) error { metrics.StartWorkerRequest(worker.name) runtime.Gosched() if worker.queuedRequests.Load() == 0 { // dispatch requests to all worker threads in order worker.threadMutex.RLock() for _, thread := range worker.threads { select { case thread.requestChan <- ch: worker.threadMutex.RUnlock() <-ch.frankenPHPContext.done metrics.StopWorkerRequest(worker.name, time.Since(ch.frankenPHPContext.startedAt)) return nil default: // thread is busy, continue } } worker.threadMutex.RUnlock() } // if no thread was available, mark the request as queued and apply the scaling strategy worker.queuedRequests.Add(1) metrics.QueuedWorkerRequest(worker.name) for { workerScaleChan := scaleChan if worker.isAtThreadLimit() { workerScaleChan = nil // max_threads for this worker reached, do not attempt scaling } select { case worker.requestChan <- ch: worker.queuedRequests.Add(-1) metrics.DequeuedWorkerRequest(worker.name) <-ch.frankenPHPContext.done metrics.StopWorkerRequest(worker.name, time.Since(ch.frankenPHPContext.startedAt)) return nil case workerScaleChan <- ch.frankenPHPContext: // the request has triggered scaling, continue to wait for a thread case <-timeoutChan(maxWaitTime): // the request has timed out stalling worker.queuedRequests.Add(-1) metrics.DequeuedWorkerRequest(worker.name) metrics.StopWorkerRequest(worker.name, time.Since(ch.frankenPHPContext.startedAt)) ch.frankenPHPContext.reject(ErrMaxWaitTimeExceeded) return ErrMaxWaitTimeExceeded } } } ================================================ FILE: worker_test.go ================================================ package frankenphp_test import ( "context" "fmt" "io" "log" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "github.com/dunglas/frankenphp" "github.com/stretchr/testify/assert" ) func TestWorker(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { formData := url.Values{"baz": {"bat"}} req := httptest.NewRequest("POST", "http://example.com/worker.php?foo=bar", strings.NewReader(formData.Encode())) req.Header.Set("Content-Type", strings.Clone("application/x-www-form-urlencoded")) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), fmt.Sprintf("Requests handled: %d", i*2)) formData2 := url.Values{"baz2": {"bat2"}} req2 := httptest.NewRequest("POST", "http://example.com/worker.php?foo2=bar2", strings.NewReader(formData2.Encode())) req2.Header.Set("Content-Type", strings.Clone("application/x-www-form-urlencoded")) w2 := httptest.NewRecorder() handler(w2, req2) resp2 := w2.Result() body2, _ := io.ReadAll(resp2.Body) assert.Contains(t, string(body2), fmt.Sprintf("Requests handled: %d", i*2+1)) }, &testOptions{workerScript: "worker.php", nbWorkers: 1, nbParallelRequests: 1}) } func TestWorkerDie(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/die.php", nil) w := httptest.NewRecorder() handler(w, req) }, &testOptions{workerScript: "die.php", nbWorkers: 1, nbParallelRequests: 10}) } func TestNonWorkerModeAlwaysWorks(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/index.php", nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), "I am by birth a Genevese") }, &testOptions{workerScript: "phpinfo.php"}) } func TestCannotCallHandleRequestInNonWorkerMode(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/non-worker.php", nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), "Fatal error: Uncaught RuntimeException: frankenphp_handle_request() called while not in worker mode") }, nil) } func TestWorkerEnv(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/worker-env.php?i=%d", i), nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Equal(t, fmt.Sprintf("bar%d", i), string(body)) }, &testOptions{workerScript: "worker-env.php", nbWorkers: 1, env: map[string]string{"FOO": "bar"}, nbParallelRequests: 10}) } func TestWorkerGetOpt(t *testing.T) { logger, buf := newTestLogger(t) runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", fmt.Sprintf("http://example.com/worker-getopt.php?i=%d", i), nil) req.Header.Add("Request", strconv.Itoa(i)) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), fmt.Sprintf("[HTTP_REQUEST] => %d", i)) assert.Contains(t, string(body), fmt.Sprintf("[REQUEST_URI] => /worker-getopt.php?i=%d", i)) }, &testOptions{logger: logger, workerScript: "worker-getopt.php", env: map[string]string{"FOO": "bar"}}) assert.NotRegexp(t, buf.String(), "exit_status=[1-9]") } func ExampleServeHTTP_workers() { if err := frankenphp.Init( frankenphp.WithWorkers("worker1", "worker1.php", 4, frankenphp.WithWorkerEnv(map[string]string{"ENV1": "foo"}), frankenphp.WithWorkerWatchMode([]string{}), frankenphp.WithWorkerMaxFailures(0), ), frankenphp.WithWorkers("worker2", "worker2.php", 2, frankenphp.WithWorkerEnv(map[string]string{"ENV2": "bar"}), frankenphp.WithWorkerWatchMode([]string{}), frankenphp.WithWorkerMaxFailures(0), ), ); err != nil { panic(err) } defer frankenphp.Shutdown() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false)) if err != nil { panic(err) } if err := frankenphp.ServeHTTP(w, req); err != nil { panic(err) } }) log.Fatal(http.ListenAndServe(":8080", nil)) } func TestWorkerHasOSEnvironmentVariableInSERVER(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/worker.php", nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := io.ReadAll(resp.Body) assert.Contains(t, string(body), "CUSTOM_OS_ENV_VARIABLE") assert.Contains(t, string(body), "custom_env_variable_value") }, &testOptions{workerScript: "worker.php", nbWorkers: 1, nbParallelRequests: 1}) } func TestKeepRunningOnConnectionAbort(t *testing.T) { runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) { req := httptest.NewRequest("GET", "http://example.com/worker-with-counter.php", nil) ctx, cancel := context.WithCancel(req.Context()) req = req.WithContext(ctx) cancel() body1, _ := testRequest(req, handler, t) assert.Equal(t, "requests:1", body1, "should have handled exactly one request") body2, _ := testGet("http://example.com/worker-with-counter.php", handler, t) assert.Equal(t, "requests:2", body2, "should not have stopped execution after the first request was aborted") }, &testOptions{workerScript: "worker-with-counter.php", nbWorkers: 1, nbParallelRequests: 1}) } ================================================ FILE: workerextension.go ================================================ package frankenphp import ( "context" "net/http" ) // EXPERIMENTAL: Workers allows you to register a worker. type Workers interface { // SendRequest calls the closure passed to frankenphp_handle_request() and updates the PHP context . // The generated HTTP response will be written through the provided writer. SendRequest(rw http.ResponseWriter, r *http.Request) error // SendMessage calls the closure passed to frankenphp_handle_request(), passes message as a parameter, and returns the value produced by the closure. SendMessage(ctx context.Context, message any, rw http.ResponseWriter) (any, error) // NumThreads returns the number of available threads. NumThreads() int } type extensionWorkers struct { name string fileName string num int options []WorkerOption internalWorker *worker } // EXPERIMENTAL: SendRequest sends an HTTP request to the worker and writes the response to the provided ResponseWriter. func (w *extensionWorkers) SendRequest(rw http.ResponseWriter, r *http.Request) error { fr, err := NewRequestWithContext( r, WithOriginalRequest(r), WithWorkerName(w.name), ) if err != nil { return err } return ServeHTTP(rw, fr) } func (w *extensionWorkers) NumThreads() int { return w.internalWorker.countThreads() } // EXPERIMENTAL: SendMessage sends a message to the worker and waits for a response. func (w *extensionWorkers) SendMessage(ctx context.Context, message any, rw http.ResponseWriter) (any, error) { fc := newFrankenPHPContext() fc.logger = globalLogger fc.worker = w.internalWorker fc.responseWriter = rw fc.handlerParameters = message err := w.internalWorker.handleRequest(contextHolder{context.WithValue(ctx, contextKey, fc), fc}) return fc.handlerReturn, err } ================================================ FILE: workerextension_test.go ================================================ package frankenphp import ( "io" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestWorkersExtension(t *testing.T) { t.Cleanup(Shutdown) readyWorkers := 0 shutdownWorkers := 0 serverStarts := 0 serverShutDowns := 0 externalWorkers, o := WithExtensionWorkers( "extensionWorkers", "testdata/worker.php", 1, WithWorkerOnReady(func(id int) { readyWorkers++ }), WithWorkerOnShutdown(func(id int) { serverShutDowns++ }), WithWorkerOnServerStartup(func() { serverStarts++ }), WithWorkerOnServerShutdown(func() { shutdownWorkers++ }), ) require.NoError(t, Init(o)) t.Cleanup(func() { Shutdown() assert.Equal(t, 1, shutdownWorkers, "Worker shutdown hook should have been called") assert.Equal(t, 1, serverShutDowns, "Server shutdown hook should have been called") }) assert.Equal(t, readyWorkers, 1, "Worker thread should have called onReady()") assert.Equal(t, serverStarts, 1, "Server start hook should have been called") assert.Equal(t, externalWorkers.NumThreads(), 1, "NumThreads() should report 1 thread") // Create a test request req := httptest.NewRequest("GET", "https://example.com/test/?foo=bar", nil) req.Header.Set("X-Test-Header", "test-value") w := httptest.NewRecorder() // Inject the request into the worker through the extension err := externalWorkers.SendRequest(w, req) assert.NoError(t, err, "Sending request should not produce an error") resp := w.Result() body, _ := io.ReadAll(resp.Body) // The worker.php script should output information about the request // We're just checking that we got a response, not the specific content assert.NotEmpty(t, body, "Response body should not be empty") assert.Contains(t, string(body), "Requests handled: 0", "Response body should contain request information") } func TestWorkerExtensionSendMessage(t *testing.T) { externalWorker, o := WithExtensionWorkers("extensionWorkers", "testdata/message-worker.php", 1) err := Init(o) require.NoError(t, err) t.Cleanup(Shutdown) ret, err := externalWorker.SendMessage(t.Context(), "Hello Workers", nil) require.NoError(t, err) assert.Equal(t, "received message: Hello Workers", ret) } func TestErrorIf2WorkersHaveSameName(t *testing.T) { _, o1 := WithExtensionWorkers("duplicateWorker", "testdata/worker.php", 1) _, o2 := WithExtensionWorkers("duplicateWorker", "testdata/worker2.php", 1) t.Cleanup(Shutdown) require.Error(t, Init(o1, o2)) } ================================================ FILE: zizmor.yaml ================================================ --- rules: unpinned-uses: config: policies: "*": ref-pin