Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,26 @@ permissions:
jobs:
build:
runs-on: ubuntu-latest
# The S3 connect-timeout test needs libcurl >= 8.11 (Debian trixie: 8.14); the runner's Ubuntu 24.04 has 8.5.
container: php:8.5-cli-trixie
env:
COMPOSER_CACHE_DIR: /tmp/composer-cache

steps:
- uses: actions/checkout@v7
- name: Install system tools and Composer
run: |
apt-get update
apt-get install -y --no-install-recommends git unzip libpng-dev libjpeg62-turbo-dev
docker-php-ext-configure gd --with-jpeg
docker-php-ext-install -j"$(nproc)" gd
curl -fsSL https://getcomposer.org/download/latest-2.x/composer.phar -o /usr/local/bin/composer
chmod +x /usr/local/bin/composer
echo 'memory_limit=-1' > /usr/local/etc/php/conf.d/ci.ini

- name: Show PHP and libcurl versions
run: php -r 'echo PHP_VERSION, " libcurl ", curl_version()["version"], PHP_EOL;'

- name: Setup PHP 8.5
uses: shivammathur/setup-php@v2
with:
php-version: "8.5"
tools: composer:v2
coverage: none
- uses: actions/checkout@v7

- name: Validate composer.json and composer.lock
run: composer validate --strict
Expand All @@ -32,10 +42,10 @@ jobs:
with:
path: |
vendor
~/.composer/cache/files
key: ${{ runner.os }}-php-8.5-composer-${{ hashFiles('**/composer.lock') }}
/tmp/composer-cache/files
key: ${{ runner.os }}-php-8.5-trixie-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-8.5-composer-
${{ runner.os }}-php-8.5-trixie-composer-

- name: Install dependencies
run: composer install --prefer-dist --no-progress --no-interaction
Expand Down
11 changes: 7 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ composer run-script cs-check

**FileSystemStorage** (`src/Storage/FileSystemStorage.php`): `readonly` local filesystem implementation. Constructed with `uploadPath` (absolute directory) and optional `uriPrefix` (web-accessible path prefix or CDN URL). `upload()` creates the target directory if needed, generates a filename via the naming strategy, validates the filename against path traversal (rejects `/`, `\`, `..`), moves the file to `{uploadPath}/{prefix}/`, and returns the relative path. `download()` copies the file from storage to a local target path. `resolvePath()` prepends the upload root. `resolveUri()` prepends the URI prefix (can be a CDN URL for absolute URIs).

**S3Storage** (`src/Storage/S3Storage.php`): `readonly` AWS S3 implementation. Constructed with `S3Client`, `bucket`, and optional `uriPrefix`. `upload()` puts the object to S3 and wraps `S3Exception` in a bundle `RuntimeException`. `remove()` catches `S3Exception` and returns `false` for `NoSuchKey`. `download()` uses `S3Client::getObject()` with `SaveAs` to download files to a local path. `resolveUri()` uses `S3Client::getObjectUrl()` when no URI prefix is configured.
**S3Storage** (`src/Storage/S3Storage.php`): `readonly` AWS S3 implementation. Constructed with `S3Client`, `bucket`, and optional `uriPrefix`. `upload()` puts the object to S3 and wraps `S3Exception` in a bundle `RuntimeException`. `remove()` catches `S3Exception`, returns `false` for `NoSuchKey` and rethrows any other unchanged (unwrapped), so a 3xx never reads as a missing object. `download()` uses `S3Client::getObject()` with `SaveAs` to download files to a local path; if it fails, the target file may hold a partial body or the S3 error answer's XML body (the SDK streams each attempt's body into it and nothing deletes it on error), so the caller deletes it — `Handler::archive` does not. `resolveUri()` uses `S3Client::getObjectUrl()` when no URI prefix is configured.

**S3RedirectGuard** (`src/Storage/S3RedirectGuard.php`): Middleware for an S3 storage with `http` (CI-8 R-B7). `register(S3Client)` appends one step named `S3RedirectGuard::NAME` to the client's `init` handler-list step, outside `retry` and `s3.permanent_redirect` (both in `sign`). The step turns a successful result with `@metadata.statusCode` 300–399 into exactly `S3Exception` (message with the status, `connection_error` false, the result attached; the body is not parsed, so `getAwsErrorCode()` is `null`, never `NoSuchKey`; the exception has no response, so `getStatusCode()` is `null` and the status is in `getResult()['@metadata']['statusCode']`). `retry` never sees that error, so a 3xx costs one HTTP request. A 301 is already a `PermanentRedirectException` from `s3.permanent_redirect`; the step passes rejected promises through unchanged. The extension registers it as the client definition's DI configurator only when `http` is set.

**StorageResolver** (`src/Storage/StorageResolver.php`): Registry of named storages. Each storage defined in the `storages` config is registered by name. The `'default'` alias always points to the configured default storage (explicit via `default_storage` option, or the first enabled storage). Handler uses the resolver to select storage per entity based on `#[Uploadable(storage: '...')]`.

Expand Down Expand Up @@ -125,7 +127,7 @@ All events carry `$entity` (the entity object), enabling listeners to filter by

Services are autowired and autoconfigured via `src/Resources/config/services.php`. The `Handler` is registered as `lazy: true`. Directories excluded from autowiring: `DependencyInjection`, `Resources`, `ExceptionInterface`, `NamingStrategy`, `Model`, `Mapping`, `Entity`, `Events`, `Storage`, `Form`.

Bundle configuration key is `chamber_orchestra_file`. Storages are defined under `storages` as a named map. Each storage has: `enabled` (default `true`), `driver` (`file_system` or `s3`), `path`, `uri_prefix` (null for private storage, or a CDN URL for absolute URIs), and S3-specific `bucket`, `region`, `endpoint`. S3 storages require `bucket` and `region` (validated at the Configuration tree level). The `default_storage` option selects which storage is the default (if omitted, the first enabled storage is used). The `archive_path` option (default `%kernel.project_dir%/var/archive`) sets the directory for `Behaviour::Archive`. The `FileNormalizer` receives `%env(APP_URL)%` as its base URL for resolving relative URIs. Entities select storage via `#[Uploadable(storage: 'name')]`.
Bundle configuration key is `chamber_orchestra_file`. Storages are defined under `storages` as a named map. Each storage has: `enabled` (default `true`), `driver` (`file_system` or `s3`), `path`, `uri_prefix` (null for private storage, or a CDN URL for absolute URIs), and S3-specific `bucket`, `region`, `endpoint`, `path_style`, `credentials` (`key`, `secret`), `http` (`connect_timeout`, `timeout`: seconds, a finite float >= 0.001, else `InvalidConfigurationException` with the key path (spec D-28: on such a value Guzzle 7 silently disables the timeout and Guzzle 8 rejects every request); int literals are cast to float; `%env(float:…)%` / `%env(int:…)%` placeholders fail validation, because Symfony checks them with a dummy 0, so the README asks for literals) and `retries` (`mode`: `legacy`/`standard`/`adaptive`; `max_attempts`: int >= 1). S3 storages require `bucket` and `region` (validated at the Configuration tree level). `http` and `retries` are optional blocks without defaults: if a block is set, every subkey is required, and a missing, unknown or invalid subkey throws `InvalidConfigurationException` with the key path; an unset block stays absent from the processed config and is not passed to `S3Client`, so without both blocks the client arguments are exactly those of 8.1.4 (`region`, `version`, then `endpoint`, `use_path_style_endpoint`, `credentials` when set; `http`, `retries` follow). A set `http` block also passes `allow_redirects: false` and `curl: [\CURLOPT_FORBID_REUSE => true]` in the client's `http` argument (so `http` is exactly `connect_timeout`, `timeout`, `allow_redirects`, `curl`) and sets the configurator `[S3RedirectGuard::class, 'register']` on the client definition; without `http` the definition has none of them (no `allow_redirects`, no `curl`, no configurator, no method calls). The `file_system` driver accepts and ignores both blocks (an `s3` base merged with a `file_system` override keeps them). The timeouts alone do not bound an operation. They need static `credentials` (otherwise the SDK provider chain runs outside them), Guzzle's curl handler and an asynchronous DNS resolver, and two client settings, both closed for a storage with `http`: redirects (`allow_redirects: false` + `S3RedirectGuard`, R-B7) and connection reuse (`CURLOPT_FORBID_REUSE`, R-B8: every request opens a new TCP (and TLS) connection, so Guzzle never re-sends a request on a dead reused connection and one SDK attempt is one transfer). A storage with `http` therefore requires ext-curl: the extension reads `\CURLOPT_FORBID_REUSE` in `load()`, so without ext-curl compiling the container fails with the `Error` `Undefined constant "CURLOPT_FORBID_REUSE"` (no separate check; a storage without `http` does not need ext-curl). On Guzzle 8+, requests with the `stream` request option to such a client fail: Guzzle's `StreamHandler` rejects the `curl` option (`InvalidArgumentException`). The `default_storage` option selects which storage is the default (if omitted, the first enabled storage is used). The `archive_path` option (default `%kernel.project_dir%/var/archive`) sets the directory for `Behaviour::Archive`. The `FileNormalizer` receives `%env(APP_URL)%` as its base URL for resolving relative URIs. Entities select storage via `#[Uploadable(storage: 'name')]`.

## Code Style

Expand All @@ -140,11 +142,12 @@ Bundle configuration key is `chamber_orchestra_file`. Storages are defined under

## Dependencies

- Requires PHP 8.5, Symfony 8.0 components (`dependency-injection`, `config`, `framework-bundle`, `runtime`, `options-resolver`), and `chamber-orchestra/metadata-bundle` 8.0
- Requires PHP 8.5, Symfony 8.1 components (`dependency-injection`, `config`, `framework-bundle`, `runtime`, `options-resolver`), and `chamber-orchestra/metadata-bundle` 8.1
- Dev: PHPUnit 13, `symfony/test-pack`, `symfony/mime`, `symfony/serializer`, `symfony/form`, `symfony/validator`, `aws/aws-sdk-php`, `friendsofphp/php-cs-fixer`, `phpstan/phpstan`
- Suggests: `aws/aws-sdk-php` (for S3 storage driver), `symfony/form` (for FileType form type), `symfony/validator` (for file validation constraints)
- Suggests: `aws/aws-sdk-php` (for S3 storage driver), `symfony/form` (for FileType form type), `symfony/validator` (for file validation constraints), `ext-curl` (required for an S3 storage with `http`)
- Main branch is `main`

## Testing Conventions

- Use music thematics for test fixtures and naming (e.g., entity names like `Composition`, `Instrument`, `Rehearsal`, `Score`; file names like `symphony_no_5.pdf`, `violin_concerto.mp3`, `moonlight_sonata.jpg`; prefixes like `scores`, `recordings`)
- S3 fault tests (`tests/Integrational/Storage/S3StorageFaultTest.php`) run each storage operation in a child process (`tests/Support/FakeS3/operation.php`: builds the storage through the extension, counts SDK attempts in the `attempt` step, prints one JSON line) against a fake TCP server in another child process (`server.php`: scenarios `silent`, `drip`, `unavailable_then_ok` (503 `ServiceUnavailable`, then 200), `no_such_key` (404) and `keep_alive` (below); journals every HTTP request as JSONL with its connection number, body length and sha256; answers with `Connection: close` except in `keep_alive`). The 503→200 test uploads 1 040 000 random bytes, so Guzzle streams the body (≥ 1 000 000 B) without `Expect: 100-Continue` (< 1 048 576 B), and checks the length and sha256 of the retried PUT's body; the 404 test checks one attempt and the kept `NoSuchKey` code. These two are ordinary regression tests: unlike the timeout tests, they do not need a client with timeouts to pass. `FakeS3Harness` kills the operation 10·T_test (T_test = 0.5 s) after `operation.php` prints `ready` (just before the operation starts; child start-up has its own 10·T_test deadline), so a client without timeouts fails instead of hanging; it also fails when the child exits non-zero or prints no JSON result. The A = 2 tests use one upper bound, A·T_test + 2 s + 1 s = 4 s; the single-attempt (A = 1) test uses T_test + 1 s. The server also closes each connection after 10·T_test and then stops accepting. The connect-timeout endpoint is a listener with a full backlog-1 accept queue on Linux and `192.0.2.1:81` (RFC 5737) on macOS, where a full queue answers RST; if a raw connection there does not time out, the test fails with an environment message and never skips. The connect-timeout test also fails (never skips) on libcurl < 8.11: older libcurl words a connect timeout as "Failed to connect … Timeout was reached", which Guzzle classifies as `NetworkTimeoutException`, not `ConnectTimeoutException`. CI (`.github/workflows/php.yml`) therefore runs the job in the `php:8.5-cli-trixie` container (libcurl 8.14), not on the runner's Ubuntu 24.04 (libcurl 8.5). The class takes about 30 s. `tests/Integrational/Storage/S3StorageRedirectTest.php` uses the same harness with the server scenario `redirect_<status>` (an empty-body 3xx, with `Location` when the harness passes one) and a second harness as the silent `Location` target: for PUT and GET, 301 + `Location` gives `PermanentRedirectException`, 307 + `Location` and 307/302 without it give exactly `S3Exception` without a code, each after one request to the redirecting server, none to the target, one SDK attempt, within the bound. `tests/Integrational/Storage/S3StorageKeepAliveTest.php` (AC-20, R-B8) uses the scenario `keep_alive`: request 1 gets `200` with an empty body and `Connection: keep-alive`; after the complete body of request 2 the server waits 0.8·T_test and closes the connection request 2 came on, unanswered; requests 3+ get no answer. `runOperation(..., warmUp: true)` makes `operation.php` call `download()` once before `ready` (outside the guard and the attempt count), then the test uploads 1 040 000 B and asserts every HTTP request on its own connection, PUT requests = SDK attempts ≤ A, the 4 s bound and a connection-error `S3Exception` without `NoSuchKey`. Without R-B8 it is red: 4 requests on 3 connections (the PUT reuses the warm-up connection, Guzzle re-sends it on a new one, then SDK attempt 2), 3 PUTs for 2 attempts. `FakeS3Harness` holds the shared test values: `T_TEST`, `C_TEST`, `ATTEMPTS`, the one time bound `UPPER_BOUND` (4 s) and the storage config `storage()`.
Loading
Loading