From 97eaeda958cdef3e28b8f09ae471b5fcf34d34d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 18:20:26 +0000 Subject: [PATCH] Keep the GraphQL schema array under the version token of the other local caches The stitched schema stays a local PHP array that a request includes from OPcache, but it now uses the same storage, version token and write fence as every other FastBoot cache, through Magento's own cache API. It needs no configuration, works on every Magento cache backend and is on by default under the schema_array switch. The separate Redis transport, its settings, its invalidation plugins, its test suites and the Credis requirement are removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P4jLu4fTNqMe3WuJern5CW --- .github/workflows/ci.yml | 27 +-- CHANGELOG.md | 1 + CLAUDE.md | 8 +- README.md | 1 - composer.json | 3 +- dev/ARCHITECTURE.md | 89 ++++---- dev/README.md | 2 +- dev/bench/online/prepare.py | 1 - dev/ci/README.md | 6 +- dev/ci/prepare.py | 10 +- dev/release/install-smoke.py | 2 +- dev/tests/README.md | 26 +-- dev/tests/schema-l1/.gitignore | 2 - dev/tests/schema-l1/README.md | 25 --- dev/tests/schema-l1/concurrency.py | 23 -- dev/tests/schema-l1/concurrent.php | 27 --- dev/tests/schema-l1/edge-cases.php | 113 ---------- dev/tests/schema-l1/redis-failure.php | 78 ------- dev/tests/schema-l1/redis-failure.py | 37 ---- dev/tests/schema-l1/tests.php | 81 ------- dev/tests/without-redis.py | 37 ---- src/FastBoot/Console/StatusCommand.php | 15 +- src/FastBoot/README.md | 17 +- src/FastBootCache/Model/Schema/Local.php | 156 ------------- src/FastBootCache/Model/Schema/Metrics.php | 14 -- src/FastBootCache/Model/Schema/Remote.php | 184 ---------------- src/FastBootCache/Model/Schema/Settings.php | 75 ------- src/FastBootCache/README.md | 44 +--- .../Test/Unit/Model/ReleaseTest.php | 22 +- .../Test/Unit/Model/SchemaSettingsTest.php | 55 ----- src/FastBootCache/composer.json | 3 - src/FastBootCache/etc/di.xml | 3 - .../Model/Config/OpcacheData.php | 80 ++++--- src/FastBootGraphQl/Plugin/Schema/Flush.php | 24 -- .../Plugin/Schema/Invalidate.php | 31 --- .../Unit/Model/Config/OpcacheDataTest.php | 205 ++++++++++++++---- src/FastBootGraphQl/etc/di.xml | 5 +- 37 files changed, 274 insertions(+), 1258 deletions(-) delete mode 100644 dev/tests/schema-l1/.gitignore delete mode 100644 dev/tests/schema-l1/README.md delete mode 100644 dev/tests/schema-l1/concurrency.py delete mode 100644 dev/tests/schema-l1/concurrent.php delete mode 100644 dev/tests/schema-l1/edge-cases.php delete mode 100644 dev/tests/schema-l1/redis-failure.php delete mode 100644 dev/tests/schema-l1/redis-failure.py delete mode 100644 dev/tests/schema-l1/tests.php delete mode 100644 dev/tests/without-redis.py delete mode 100644 src/FastBootCache/Model/Schema/Local.php delete mode 100644 src/FastBootCache/Model/Schema/Metrics.php delete mode 100644 src/FastBootCache/Model/Schema/Remote.php delete mode 100644 src/FastBootCache/Model/Schema/Settings.php delete mode 100644 src/FastBootCache/Test/Unit/Model/SchemaSettingsTest.php delete mode 100644 src/FastBootGraphQl/Plugin/Schema/Flush.php delete mode 100644 src/FastBootGraphQl/Plugin/Schema/Invalidate.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d915ae..12f9ae6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,15 +45,6 @@ jobs: fail-fast: false matrix: php: ['8.3', '8.4'] - services: - redis: - image: redis:7-alpine - ports: ['6379:6379'] - options: >- - --health-cmd "redis-cli ping" - --health-interval 5s - --health-timeout 3s - --health-retries 10 env: MAGENTO_ROOT: ${{ github.workspace }}/../fastboot-ci-magento COMPOSER_NO_INTERACTION: '1' @@ -63,7 +54,7 @@ jobs: - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: php-version: ${{ matrix.php }} - extensions: bcmath, curl, dom, ftp, gd, intl, mbstring, pdo_mysql, redis, soap, sodium, xsl, zip + extensions: bcmath, curl, dom, ftp, gd, intl, mbstring, pdo_mysql, soap, sodium, xsl, zip ini-values: memory_limit=1G coverage: none tools: composer:v2 @@ -71,21 +62,6 @@ jobs: run: python3 dev/ci/prepare.py --root "$MAGENTO_ROOT" - name: Unit regressions run: php "$MAGENTO_ROOT/vendor/bin/phpunit" --no-configuration --bootstrap dev/tests/bootstrap.php --log-junit .ci/unit.xml src - - name: Schema publication, TTL and failure invariants - run: | - php dev/tests/schema-l1/tests.php - php dev/tests/schema-l1/edge-cases.php - python3 dev/tests/schema-l1/concurrency.py - python3 dev/tests/schema-l1/redis-failure.py - - name: Repeat schema and unit regressions without ext-redis - run: | - python3 dev/tests/without-redis.py -- sh -ec ' - php "$MAGENTO_ROOT/vendor/bin/phpunit" --no-configuration --bootstrap dev/tests/bootstrap.php src - php dev/tests/schema-l1/tests.php - php dev/tests/schema-l1/edge-cases.php - python3 dev/tests/schema-l1/concurrency.py - python3 dev/tests/schema-l1/redis-failure.py - ' - name: Compile fresh Magento DI metadata working-directory: ${{ env.MAGENTO_ROOT }} run: php bin/magento setup:di:compile @@ -95,7 +71,6 @@ jobs: python3 dev/release/build.py --version 0.0.0-rc0 --output .ci/rebuild cmp .ci/artifacts/*.zip .ci/rebuild/*.zip python3 dev/release/install-smoke.py --archive .ci/artifacts/graphcommerce-magento-fast-boot-0.0.0-rc0.zip --magento-root "$MAGENTO_ROOT" --output .ci/install - python3 dev/tests/without-redis.py -- python3 dev/release/install-smoke.py --archive .ci/artifacts/graphcommerce-magento-fast-boot-0.0.0-rc0.zip --magento-root "$MAGENTO_ROOT" --output .ci/install-no-redis - name: Collect fixture logs if: always() run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index a3851ce..9050bda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- The stitched GraphQL schema is a local PHP array under the version token of the other local caches, on by default with the `schema_array` switch. It needs no configuration and works on every Magento cache backend. The separate Redis transport, its `fastboot.schema_l1` settings and the `colinmollenhour/credis` requirement are removed; a `fastboot.schema_l1` block in `env.php` is not read. - A new website, group or store is in the scopes the same request reads right after it: the scopes and website-stores entries carry the config cache tag, so the store manager's reinit drops them. Before, creating a website from the CLI failed Inventory's sales channel validation ("The website with code … does not exist"). - The configuration values a request read are answered from a request memo on the second read, under the `config_memo` switch: no scope resolution and no type lookup per read. diff --git a/CLAUDE.md b/CLAUDE.md index 288d07a..05bfaed 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,11 +2,11 @@ The combined Composer package contains FastBootCache, FastBoot, FastBootGraphQl and FastBootPreload. Keep implementation in these modules; prototypes are not runtime dependencies. -- Optimize ordinary PHP-FPM. Each mechanism has an independently configurable `fastboot` switch. Schema L1 uses the installation identity and Magento's static-content deployment version; do not add a separate release setting. Never weaken request-specific GraphQL security checks or bypass Magento's processor/plugin chain to cache validation. -- Local PHP files contain scalars and arrays only. Redis/shared Magento caches remain authoritative. Preserve proven backend TTLs; unknown expiry must not be promoted. Schema metadata uses atomic Redis generation fences and strict validation by default; generic files snapshot the shared version once per request. -- Files are immutable, content-addressed, private and admission-bounded. Mutable indexes carry expiry. Do not preload runtime data files. A failed local write is a cache miss; a strict schema Redis failure is an error, not permission to serve stale data. +- Optimize ordinary PHP-FPM. Each mechanism has an independently configurable `fastboot` switch. Local caches use Magento's static-content deployment version as the build identity; do not add a separate release setting. Never weaken request-specific GraphQL security checks or bypass Magento's processor/plugin chain to cache validation. +- Local PHP files contain scalars and arrays only. Magento's shared caches remain authoritative, and FastBoot reaches them only through Magento's cache API: no connection or keys of its own. Preserve proven backend TTLs; unknown expiry must not be promoted. Every local cache, the GraphQL schema included, lives under the version token in Magento's cache; a request snapshots the version once. +- Files are immutable, content-addressed, private and admission-bounded. Mutable indexes carry expiry. Do not preload runtime data files. A failed local write is a cache miss; a cache failure while reading the version token is an error, not permission to serve stale files. - Changed PHP/DI/config artifacts need a new Magento static-content deployment version and an FPM restart. Clean config/compiled_config before DI compilation. The preparation command must rebuild area differences after compilation, including when operating repeatedly in a development workspace. -- Keep unit and portable Redis tests under `dev/tests` and module `Test/Unit` directories. Validate combined real Magento responses, configuration saves, cache invalidation and memory as well as individual shortcuts. Compare timings relatively on the same host; PHP allocated memory and shared OPcache memory are separate measurements. +- Keep unit tests under module `Test/Unit` directories and test tooling under `dev/tests`. Validate combined real Magento responses, configuration saves, cache invalidation and memory as well as individual shortcuts. Compare timings relatively on the same host; PHP allocated memory and shared OPcache memory are separate measurements. - `dev/release/build.py` builds the reproducible Composer artifact; `install-smoke.py` validates archive hashes and installation against an existing dependency tree. Neither publishes anything. Keep installation and operation in the root/module READMEs. Keep implementation/design notes, switches, tests and measurements under dev. - Never attach cache interception to broad bootstrap decorators such as TagScope: the compiled plugin-list cache needs those decorators before interceptors can be resolved. Bind only the supported application cache types. diff --git a/README.md b/README.md index 8871250..a7e3a17 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,6 @@ Median PHP execution time on a deployed AMD EPYC server, with 600 measured reque - Magento 2.4.8 or compatible Mage-OS APIs. - PHP 8.2–8.5, subject to the installed Magento version. -- A writable Redis primary for schema L1. - Private, node-local cache storage. Release candidate. diff --git a/composer.json b/composer.json index 099a958..5631633 100644 --- a/composer.json +++ b/composer.json @@ -18,8 +18,7 @@ "magento/module-catalog-graph-ql": "^100.4.8", "magento/module-tax": "^100.4.8", "magento/module-customer": "^103.0.8", - "webonyx/graphql-php": "^15.0", - "colinmollenhour/credis": "^1.17" + "webonyx/graphql-php": "^15.0" }, "replace": { "graphcommerce/module-fast-boot-cache": "self.version", diff --git a/dev/ARCHITECTURE.md b/dev/ARCHITECTURE.md index 2cecd2b..d985059 100644 --- a/dev/ARCHITECTURE.md +++ b/dev/ARCHITECTURE.md @@ -1,89 +1,74 @@ # FastBoot implementation notes -FastBoot stores Magento's assembled GraphQL schema in two places: - -- **L1:** a private PHP-array file on each server, reused through OPcache. -- **L2:** the authoritative schema record in Redis, shared by the installation's servers. - -The Redis transport uses phpredis when available and Credis otherwise, with identical atomic scripts. The PHP extension is optional. - -Servers never share the L1 directory. A server that needs a schema version it does not have reads it from Redis and creates its own local copy. If Redis has no current schema, Magento rebuilds it from the source configuration. +FastBoot keeps Magento cache entries, and data derived from them, as private PHP-array files on each server, reused through OPcache. Magento's own cache is authoritative and shared by the servers; the local files are copies of it. The stitched GraphQL schema is one of these local caches and uses the same storage, version token and write fence as the others. No FastBoot cache needs a connection of its own: everything goes through Magento's cache API, so any cache backend works. Customer setup and operating instructions belong in the [module READMEs](../README.md). This document records implementation behavior and constraints for future development. -## A warm read +## The version token + +`FastBootCache/Model/Version` holds a random token in Magento's cache under the `config` tag. Every local index path contains that token, so a new token makes every server stop reading the files of the old one. These operations change the token on every server, because the token lives in the shared cache: -With `schema_l1.grace=0`, loading the schema follows these steps: +| Operation | How the token changes | +|---|---| +| A save, remove or clean on a covered cache type (`config`, `eav`, `translate`, `db_ddl`, `reflection`, `collections`) | `Plugin/OpcacheLayer` calls `Version::bump()`. | +| A clean of the `config` tag in the default frontend, a flush of the cache | The token entry is removed; the next request that finds no token starts a new one. | +| A direct reset of the GraphQL schema data | `FastBootGraphQl/Plugin/Schema/Reset` bumps before and after the reset. | -1. Read Redis metadata in one atomic operation: the schema revision, installation invalidation generation and remaining TTL. -2. Check that the local copy matches that metadata and has not expired. -3. Include the local PHP array. The schema payload does not need to be downloaded or decoded again. +A request reads the token once and keeps it until the request ends (`ResetAfterRequestInterface`). A positive `grace` (di.xml argument of `Version`) keeps the token in a local stamp file for that many seconds, which trades immediate cross-server freshness for fewer cache reads. The default is zero. -This Redis check happens when the schema is loaded. Reading individual schema fields or array elements does not trigger another check. Connection establishment can additionally require authentication and database selection; the cost depends on the connection and network. +## The write fence -**Strict freshness means current at the Redis metadata check.** It does not prevent another node invalidating the cache immediately afterward. A request can finish with the schema it already loaded; subsequent schema loads observe the invalidation. Generic FastBoot caches use their own once-per-request generation check. +A writer captures the version (`PhpFiles::generation()`) before it reads or computes its data, and passes it to `PhpFiles::write(..., $expectedVersion)`. The write is refused when the current version differs. A clean on any server while a build is in progress thus never leaves the old build's data under the new version. The request that built the data still finishes with it. -## A local miss or a cold cache +## The GraphQL schema -| State | What happens | -|---|---| -| Local copy is missing or outdated; Redis has a current schema | Fetch and verify the shared payload, then write a local copy. Preserve Redis's remaining TTL. | -| Redis has no current schema | Capture its generation, build through Magento, then publish only if that generation is still valid. | -| Several readers miss on the same server | A local lock coalesces promotion and the waiting readers recheck the result. | -| Several servers miss together | Each server may perform source work. Conditional publication prevents a stale or losing build from replacing a newer result. | +`FastBootGraphQl/Model/Config/OpcacheData` is the class behind the `Magento\Framework\GraphQl\Config\Data` virtual type. Magento's own path loads about 1 MB of JSON from the config cache and decodes it on every request. With the `schema_array` switch on and the `config` cache type enabled: -The Redis record publishes the payload, content hash, revision, invalidation generation and expiry atomically. If invalidation, eviction, expiry or another publication overtakes a build, the old build cannot repopulate Redis. Its current request may still finish using its own snapshot. +1. Read the array from the local files (group `SCHEMA`, id = the schema cache id). A hit is an include from OPcache; the config cache is not read. +2. On a miss, capture the version, run Magento's path (the config cache, else the schema reader and a save to the config cache) and write the array under the captured version. -## Invalidation across servers and releases +A save of the schema to the config cache is a save on a covered type, so it changes the version. The request that builds the schema from the reader therefore writes no file; the next request reads the config cache and writes the file. `fastboot:prepare` reads the schema twice for that reason. -FastBoot integrates with Magento's config-cache clean/remove operations, application cache clean, manager flush and direct schema-data reset. The installation has a shared invalidation generation, so a configuration change reaches both old and new release records during a rolling deployment. +A blob is content-addressed: the same schema under a new version reuses the same PHP file and its compiled OPcache entry; only a small index file is written. The schema blob is subject to `max_entry_bytes` (2 MiB of PHP source by default; a real schema is about 1.1 MiB). A larger schema is a miss on every request and is served by Magento's path. -Use one installation ID for the shop/environment and Magento's static-content deployment version for each application build. Keep these hooks active on every web, admin and CLI node while any node uses schema L1. Diagnostic bypasses are described in the [developer guide](README.md#feature-switches). +The schema is written without an expiry: it derives from the code of the release, which is part of the namespace, and from the config cache, whose changes change the version. -Deleting only legacy Magento cache keys through external tooling does not necessarily invalidate FastBoot's schema record. Integrate external writers with the supported cache APIs. A failed invalidation is an error and must be retried; it is not reported as a successful clean. +## OPcache and memory -## TTL and grace +Local files contain arrays and scalar values. Their names are based on content hashes, and writes use atomic rename. Identical payloads reuse the same filename; different payloads use new files. This also works with `opcache.validate_timestamps=0` because runtime data is not overwritten at an already compiled path. An index file holds the hash of its blob and the expiry of the entry, so an expiry change does not change the compiled file. -**TTL answers when an entry expires. Invalidation answers whether it became outdated before then.** A TTL alone cannot tell one server that an admin save on another server has changed configuration. +These files are **not preloaded**. PHP class preload is a separate optimization whose definitions remain fixed until the FPM master/service restarts. Cache freshness is decided by the version token and the index expiry, not by OPcache's source-file timestamp validation. -The PHP file contains the immutable data. A separate, mutable JSON stamp holds freshness and expiry metadata. This lets an identical rebuilt schema reuse the same compiled PHP file while its expiry changes. Putting the TTL into that immutable file would couple metadata changes to compiled-file changes without solving cross-server invalidation. +Source size is not compiled-memory usage. Include shared OPcache, worker allocations and the preload master's footprint in capacity planning. Deleting files alone does not reclaim compiled memory; retire cache namespaces with the release/FPM lifecycle. -A positive `schema_l1.grace` allows the server to reuse a recently validated local schema without contacting Redis during that interval. This trades immediate validation for fewer network calls. Entry expiry always wins, even inside the grace interval. The default is zero. +Whole-object serialization is not used here. It would require reconstructing object graphs in each request; the cache instead stores the reusable data from which Magento operates. ## Failure behavior | Failure or limit | Result | |---|---| -| Local file missing or syntactically damaged | Fetch a verified shared copy again. | -| Local directory cannot be written | Use current authoritative data without saving a local copy. | -| Local admission limit reached | Use current authoritative data; existing valid local files remain available. | -| Redis validation fails in strict mode | Propagate the failure. Do not serve the old local schema. | -| Redis record or invalidation generation is evicted/flushed | Treat the old local copy as a miss when validation resumes. | -| Invalidation overtakes a schema rebuild | Reject that build's shared-cache publication. | +| Local file missing or syntactically damaged | Read Magento's cache again and write a new local copy. | +| Local directory cannot be written | Use Magento's cache without saving a local copy. | +| Local admission limit reached | Use Magento's cache; existing valid local files remain available. | +| The cache backend fails to answer the token | The error of Magento's cache propagates; a backend that answers no token gives a new version. Old local files are not served in either case. | +| The token is evicted or flushed | A new token; the old local files are not read again. | +| Invalidation overtakes a build | The write of that build is refused. | -The local directory is trusted application storage. Warm reads do not hash the complete PHP file on every include. Keep the directory private and writable only by trusted application users. - -## OPcache and memory - -Local files contain arrays and scalar values. Their names are based on content hashes, and writes use atomic rename. Identical payloads reuse the same filename; different payloads use new files. This also works with `opcache.validate_timestamps=0` because runtime data is not overwritten at an already compiled path. +Deleting keys in the cache backend outside Magento's cache API does not change the token. Integrate external writers with the supported cache APIs. -These files are **not preloaded**. PHP class preload is a separate optimization whose definitions remain fixed until the FPM master/service restarts. Cache freshness is decided by FastBoot's runtime metadata checks, not by OPcache's source-file timestamp validation. - -Schema L1 admits at most 16 files and 32 MiB of PHP source per local namespace by default. Source size is not compiled-memory usage. Include shared OPcache, worker allocations and the preload master's footprint in capacity planning. Deleting files alone does not reclaim compiled memory; retire cache namespaces with the release/FPM lifecycle. - -Whole-object serialization is not used here. It would require reconstructing object graphs in each request; the cache instead stores the reusable data from which Magento operates. +The local directory is trusted application storage. Warm reads do not hash the complete PHP file on every include. Keep the directory private and writable only by trusted application users. ## Deployment identity -`FastBootCache/Model/Release` reads Magento's static-content deployment version once per request. There is no manual FastBoot release override. Missing or empty versions prevent generic cache publication and fail schema setup; area DI differences can fall back to hashing their compiled source files. Local paths follow Magento's configured cache directory. +`FastBootCache/Model/Release` reads Magento's static-content deployment version once per request. There is no manual FastBoot release override. A missing or empty version prevents local cache writes; area DI differences can fall back to hashing their compiled source files. Local paths follow Magento's configured cache directory. -Generic local namespaces and shared schema keys include this build identity. The shared schema invalidation epoch belongs to the installation, so invalidation reaches both builds during rolling deployment. Preserve this distinction when changing key formats. +The local namespace includes this build identity, so a new build never reads the files of another. The token is shared by both builds during a rolling deployment, so a clean reaches the files of both. ## Module responsibilities -- `FastBootCache` owns value-file storage, shared generations, schema transport and invalidation hooks. Both Redis clients must use identical Lua scripts and discard failed sockets without replaying uncertain writes. -- `FastBoot` owns compiled area DI differences, system/scope configuration and storefront helper optimizations. Capture the generation before deriving values and fence publication afterward. -- `FastBootGraphQl` owns parsed-document and structural-validation reuse. Never bypass Magento's query processor, custom validation, request limits or scalar coercion. Schema invalidation must retire cached validation proofs. +- `FastBootCache` owns value-file storage, the version token and the invalidation plugins on the covered cache types. +- `FastBoot` owns compiled area DI differences, system/scope configuration and storefront helper optimizations. Capture the version before deriving values and fence the write with it. +- `FastBootGraphQl` owns the schema array, parsed-document and structural-validation reuse. Never bypass Magento's query processor, custom validation, request limits or scalar coercion. Schema invalidation must retire cached validation proofs. - `FastBootPreload` records class definitions during a bounded window and loads them at master startup. It never preloads runtime cache values. Recording paths follow Magento's cache directory; the startup entry point remains in the package. Avoid cache interception on broad bootstrap decorators such as TagScope: compiled plugin-list loading uses those decorators before interceptors can be resolved. Test changes in fresh compiled Magento, including cache-disabled paths and cross-node invalidation. diff --git a/dev/README.md b/dev/README.md index 638a8e8..da26e4c 100644 --- a/dev/README.md +++ b/dev/README.md @@ -14,7 +14,7 @@ Production installs use the default-enabled optimizations. These switches suppor |---|---|---| | `cache_files` | Local PHP values for covered Magento configuration caches. | Yes | | `system_config_array` | Local system configuration loaded by requested scope. | Yes | -| `schema_array` | Local GraphQL schema arrays; also requires schema L1 configuration. | Yes | +| `schema_array` | The stitched GraphQL schema as a local PHP array. | Yes | | `schema_scalars` | Faster scalar lookup in the GraphQL schema. | No | | `parsed_queries` | Parsed GraphQL document reuse. | Yes | | `validated_queries` | Reuse of successful built-in structural validation. | Yes | diff --git a/dev/bench/online/prepare.py b/dev/bench/online/prepare.py index 8a6c302..358f209 100644 --- a/dev/bench/online/prepare.py +++ b/dev/bench/online/prepare.py @@ -51,7 +51,6 @@ $frontend['id_prefix'] = ''' + quote('fbonline_' + run_id + '_' + mode + '_') + '''; } unset($frontend); -$config['fastboot']['schema_l1']['installation'] .= ''' + quote(':benchmark:' + run_id + ':' + mode) + '''; return $config; ''') if mode == 'native': diff --git a/dev/ci/README.md b/dev/ci/README.md index 8e72a2e..3c2736d 100644 --- a/dev/ci/README.md +++ b/dev/ci/README.md @@ -5,11 +5,11 @@ | Job | Checks | |---|---| | PHP 8.2–8.5 syntax | Composer metadata, Python tooling syntax and syntax for runtime PHP and test fixtures. | -| Magento 2.4.8 / PHP 8.3 and 8.4 | Unit regressions, real Redis TTL/invalidation/concurrency and failure recovery, fresh DI compilation, reproducible ZIPs and Composer artifact installation. | +| Magento 2.4.8 / PHP 8.3 and 8.4 | Unit regressions, fresh DI compilation, reproducible ZIPs and Composer artifact installation. | The integration jobs download official public Magento 2.4.8 source and install its dependencies with Composer. They register a copy of the working package. No Adobe Marketplace or customer credentials are needed. Dependencies resolve against a PHP 8.3 baseline and run on both PHP versions; PHPUnit 11.5 supplies the older-target runner. The Symfony-adapter and newer parser-policy tests skip where the corresponding APIs are absent. -The unit, schema and installation checks run both with phpredis and with the Redis extension absent, exercising Credis fallback. Redis is an isolated job service. Failure testing creates and removes a separate disposable Valkey container. Magento has no business database in this fixture: CI verifies units, cache invariants, application DI and packaging, not end-to-end storefront behavior. Customer GraphQL, Luma rendering, configuration saves and performance measurements still require an installed application with representative data. +The fixture uses Magento's file cache and has no Redis service and no business database: CI verifies units, application DI and packaging, not end-to-end storefront behavior. Customer GraphQL, Luma rendering, configuration saves and performance measurements still require an installed application with representative data. JUnit results, package artifacts and fixture logs are retained for seven days. CI artifacts use the synthetic version `0.0.0-rc0`; they are verification outputs, not published releases. CI does not tag, release, merge or deploy. @@ -19,4 +19,4 @@ For a local fixture, run from the package repository root: python3 dev/ci/prepare.py --root /absolute/path/to/an/empty/magento-fixture ``` -Use a root outside the package directory so Composer's local package copy cannot include its own fixture. Supply `--archive /path/to/magento-2.4.8.tar.gz` to reuse an official source archive. Then set `MAGENTO_ROOT` to that fixture and run the workflow's test commands. Local schema tests expect disposable Redis on localhost port 6379, DB 12. +Use a root outside the package directory so Composer's local package copy cannot include its own fixture. Supply `--archive /path/to/magento-2.4.8.tar.gz` to reuse an official source archive. Then set `MAGENTO_ROOT` to that fixture and run the workflow's test commands. diff --git a/dev/ci/prepare.py b/dev/ci/prepare.py index 17007a6..65e651e 100644 --- a/dev/ci/prepare.py +++ b/dev/ci/prepare.py @@ -35,22 +35,14 @@ manifest.write_text(json.dumps(config, indent=4) + '\n') (root / 'composer.lock').unlink(missing_ok=True) subprocess.run(['composer', 'install', '--no-interaction', '--no-progress', '--no-plugins', '--no-scripts'], cwd=root, check=True) -# No business DB is needed for units, schema Redis invariants or DI compilation. +# No business DB is needed for units or DI compilation. modules = ['Magento_' + p.name for p in sorted((root / 'app/code/Magento').iterdir()) if (p / 'registration.php').is_file()] modules += ['GraphCommerce_' + name for name in ['FastBootCache', 'FastBoot', 'FastBootGraphQl', 'FastBootPreload']] (root / 'app/etc/config.php').write_text(" [\n" + ''.join(" '" + m + "' => 1,\n" for m in modules) + "]];\n") (root / 'app/etc/env.php').write_text(""" ['key' => 'fastboot-disposable-ci-fixture'], - 'cache' => ['frontend' => ['default' => [ - 'backend' => 'Magento\\\\Framework\\\\Cache\\\\Backend\\\\Redis', - 'backend_options' => ['server' => '127.0.0.1', 'port' => 6379, 'database' => 12], - 'id_prefix' => 'fastboot_ci_', - ]]], 'session' => ['save' => 'files'], - 'fastboot' => ['schema_l1' => [ - 'enabled' => true, 'installation' => 'fastboot-disposable-ci', 'grace' => 0, - ]], ]; """) (root/'pub/static').mkdir(parents=True, exist_ok=True) diff --git a/dev/release/install-smoke.py b/dev/release/install-smoke.py index 099aa1b..efc0e1d 100644 --- a/dev/release/install-smoke.py +++ b/dev/release/install-smoke.py @@ -17,5 +17,5 @@ project={'name':'fastboot/installation-smoke','type':'project','require':{manifest['name']:manifest['version']},'replace':replacements,'repositories':[{'type':'artifact','url':str(archive.parent)},{'packagist.org':False}],'autoload':{'psr-4':psr4},'config':{'allow-plugins':False}} (target/'composer.json').write_text(json.dumps(project,indent=2)+'\n') subprocess.run(['composer','install','--no-interaction','--no-scripts','--no-plugins','--no-progress'],cwd=target,check=True) -check='''require $argv[1].'/vendor/autoload.php';$base=$argv[1].'/vendor/graphcommerce/magento-fast-boot/';foreach(['FastBootCache','FastBoot','FastBootGraphQl','FastBootPreload']as$name){$path=(new Magento\\Framework\\Component\\ComponentRegistrar())->getPath('module','GraphCommerce_'.$name);if(realpath($path)!==realpath($base.'src/'.$name))throw new RuntimeException('Module registration mismatch');}foreach([GraphCommerce\\FastBootCache\\Model\\Schema\\Local::class,GraphCommerce\\FastBoot\\Console\\PrepareCommand::class,GraphCommerce\\FastBootGraphQl\\Plugin\\Query\\ValidatedQueries::class,GraphCommerce\\FastBootPreload\\Model\\Dependencies::class]as$class){$r=new ReflectionClass($class);if(!str_starts_with(realpath($r->getFileName()),realpath($base)))throw new RuntimeException('Class escaped installed archive');}echo "PASS Composer artifact installation, four registrations, runtime autoload paths and build hashes\\n";''' +check='''require $argv[1].'/vendor/autoload.php';$base=$argv[1].'/vendor/graphcommerce/magento-fast-boot/';foreach(['FastBootCache','FastBoot','FastBootGraphQl','FastBootPreload']as$name){$path=(new Magento\\Framework\\Component\\ComponentRegistrar())->getPath('module','GraphCommerce_'.$name);if(realpath($path)!==realpath($base.'src/'.$name))throw new RuntimeException('Module registration mismatch');}foreach([GraphCommerce\\FastBootCache\\Model\\PhpFiles::class,GraphCommerce\\FastBoot\\Console\\PrepareCommand::class,GraphCommerce\\FastBootGraphQl\\Plugin\\Query\\ValidatedQueries::class,GraphCommerce\\FastBootPreload\\Model\\Dependencies::class]as$class){$r=new ReflectionClass($class);if(!str_starts_with(realpath($r->getFileName()),realpath($base)))throw new RuntimeException('Class escaped installed archive');}echo "PASS Composer artifact installation, four registrations, runtime autoload paths and build hashes\\n";''' subprocess.run(['php','-r',check,str(target)],cwd=target,check=True) diff --git a/dev/tests/README.md b/dev/tests/README.md index 271628b..7410ffc 100644 --- a/dev/tests/README.md +++ b/dev/tests/README.md @@ -24,30 +24,6 @@ php "$MAGENTO_ROOT/vendor/bin/phpunit" -c phpunit.xml.dist The Symfony cache-adapter and newer parser-policy fixtures skip on Magento 2.4.8 where those APIs are absent. The older Zend backend's expiry behavior is tested directly. -## Redis integration tests - -With the same `MAGENTO_ROOT`, run from the package root: - -```sh -php dev/tests/schema-l1/tests.php -php dev/tests/schema-l1/edge-cases.php -python3 dev/tests/schema-l1/concurrency.py -python3 dev/tests/schema-l1/redis-failure.py -``` - -The first three commands require local Redis at port 6379, database 12. They use unique test keys and delete only their own keys; they do not flush the database or change Magento business data. Local fixture directories remain under the selected installation's `var` directory. - -The failure test requires Python, Docker and the `valkey/valkey:8-alpine` image. It creates its own loopback-only container, pauses/restarts only that container, and removes it afterward. See the [schema test guide](schema-l1/README.md) for coverage. - -Run a test command with the Redis extension disabled, without changing system PHP configuration: - -```sh -python3 dev/tests/without-redis.py -- php dev/tests/schema-l1/tests.php -python3 dev/tests/without-redis.py -- python3 dev/tests/schema-l1/redis-failure.py -``` - -The wrapper also disables the extension for child PHP processes. CI repeats units, schema invariants, concurrency, failure and package installation checks through this path. - ## Build a release artifact Run from the package repository root: @@ -71,4 +47,4 @@ This check verifies hashes, resolves the package with Composer against the exist ## Application checks -Units and portable Redis tests do not replace an application run. Exercise representative GraphQL operations, admin configuration saves, stores, customer sessions, tax, cross-node invalidation and rollback using the customer's extensions. Use a dedicated FPM service for comparisons and inspect both cold and warm memory. +Unit tests do not replace an application run. Exercise representative GraphQL operations, admin configuration saves, stores, customer sessions, tax, cross-node invalidation and rollback using the customer's extensions. Use a dedicated FPM service for comparisons and inspect both cold and warm memory. diff --git a/dev/tests/schema-l1/.gitignore b/dev/tests/schema-l1/.gitignore deleted file mode 100644 index d5b7c83..0000000 --- a/dev/tests/schema-l1/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/concurrency.json -/__pycache__/ diff --git a/dev/tests/schema-l1/README.md b/dev/tests/schema-l1/README.md deleted file mode 100644 index dbc4f87..0000000 --- a/dev/tests/schema-l1/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Schema L1 integration tests - -These source-repository tests exercise the schema cache against real Redis. They are excluded from the runtime ZIP. - -Set `MAGENTO_ROOT` to a disposable Magento installation containing this package. Tests support both phpredis and the Credis fallback. From this directory, run: - -```sh -php tests.php -php edge-cases.php -python3 concurrency.py -python3 redis-failure.py -``` - -| Script | Checks | -|---|---| -| `tests.php` | Two local nodes, shared publication, invalidation and local reuse. | -| `edge-cases.php` | Tag modes, expiry/grace, corruption, failed local writes, admission limits and stale-publication rejection. | -| `concurrency.py` | Eight cold readers, then concurrent writers/readers producing coherent values. | -| `redis-failure.py` | Password/ACL authentication, database isolation, authentication failure, real read timeout, same-client recovery, empty restart and connection refusal. | - -The first three use unique test keys on localhost Redis, port 6379, database 12. They delete only their own keys and do not flush a database. Change the fixture options if using a different dedicated Redis instance. Local fixture files remain under Magento's `var` directory for inspection. - -The failure test requires Docker and the `valkey/valkey:8-alpine` image. It creates a uniquely named, loopback-only container and removes it afterward. It pauses/restarts that container, not the installation's Redis service. - -Actual Magento clean/reset/flush behavior and GraphQL response parity require an application-specific harness. See the [measurement notes](../../bench/RESULTS.md) for application measurements and the [test/build guide](../README.md) for units and artifact verification. diff --git a/dev/tests/schema-l1/concurrency.py b/dev/tests/schema-l1/concurrency.py deleted file mode 100644 index b1cc447..0000000 --- a/dev/tests/schema-l1/concurrency.py +++ /dev/null @@ -1,23 +0,0 @@ -import os -import pathlib,subprocess,json,time,secrets -D=pathlib.Path(__file__).resolve().parent;ROOT=pathlib.Path(os.environ.get('MAGENTO_ROOT',D.parents[4])) -base=ROOT/('var/schema-l1-tests/concurrency-'+secrets.token_hex(6));base.mkdir(parents=True,exist_ok=True) -opts={'key':'fba:schema-concurrency:'+secrets.token_hex(8),'database':12};(base/'options.json').write_text(json.dumps(opts)) -seed='require "vendor/autoload.php"; $r=new \\GraphCommerce\\FastBootCache\\Model\\Schema\\Remote(json_decode($argv[1],true)); $r->save(json_encode(["v"=>0,"body"=>str_repeat("0",500)]),"schema",[],30);' -results={} -for phase in ['cold','stress']: - (base/'go').unlink(missing_ok=True) - subprocess.run(['php','-r',seed,json.dumps(opts)],cwd=ROOT,check=True) - args=[('cold','0')]*8 if phase=='cold' else [('writer','0'),('writer','1')]+[('read',str(i%2))for i in range(4)] - children=[subprocess.Popen(['php',str(D/'concurrent.php'),str(base),mode,node],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)for mode,node in args] - time.sleep(.1);(base/'go').touch();rows=[] - for p in children: - out,err=p.communicate(timeout=30) - if p.returncode:raise RuntimeError(err+out) - rows.append(json.loads(out)) - results[phase]=rows - if phase=='cold': - assert sum(r['metrics'].get('promotions',0)for r in rows)==1 - assert sum(r['metrics'].get('redis_commands',0)for r in rows)==3 # SELECT, metadata, payload -subprocess.run(['php','-r',seed.split('$r->save')[0]+'$r->command("del",[$argv[2],$argv[2].":epoch"]);',json.dumps(opts),opts['key']],cwd=ROOT,check=True) -(D/'concurrency.json').write_text(json.dumps(results,indent=2));print('PASS eight cold readers: one promotion / three Redis commands total. PASS two writers and four readers: 200 coherent reads.') diff --git a/dev/tests/schema-l1/concurrent.php b/dev/tests/schema-l1/concurrent.php deleted file mode 100644 index d8f76f9..0000000 --- a/dev/tests/schema-l1/concurrent.php +++ /dev/null @@ -1,27 +0,0 @@ -save(json_encode(['v' => $i,'body' => str_repeat((string)$i, 500)]), 'schema', [], 30); - } - echo json_encode(['writer' => true]); - exit; -} -$l = new Local($r, $root.'/node-'.($mode === 'cold' ? 'cold' : $argv[3]), $mode === 'cold' ? 2 : 0); -$iterations = $mode === 'cold' ? 1 : 50; -for ($i = 0;$i < $iterations;$i++) { - $v = $l->load(); - if ($v === null || $v['body'] !== str_repeat((string)$v['v'], 500)) { - throw new RuntimeException('Torn record'); - } -} -echo json_encode(['metrics' => Metrics::$values,'iterations' => $iterations]); diff --git a/dev/tests/schema-l1/edge-cases.php b/dev/tests/schema-l1/edge-cases.php deleted file mode 100644 index 44fff4c..0000000 --- a/dev/tests/schema-l1/edge-cases.php +++ /dev/null @@ -1,113 +0,0 @@ - 'fba:schema-edge:'.bin2hex(random_bytes(8)),'database' => 12]; -$r = new Remote($options); -$root = (getenv('MAGENTO_ROOT') ?: dirname(__DIR__, 5)).'/var/schema-edge/'.bin2hex(random_bytes(8)); -$a = new Local($r, $root, 0); -try { - $generation = $r->generation(); - $r->clean('matchingAnyTag', ['CONFIG']); - check(!$r->publish('{"old":1}', [], 20, $generation) && $r->metadata() === null, 'config clean fences an in-flight first build'); - $generation = $r->generation(); - $r->remove('schema'); - check(!$r->publish('{"old":1}', [], 20, $generation), 'remove fences a cold build'); - $generation = $r->generation(); - check($r->publish('{"v":1}', [], 20, $generation), 'unchanged generation publishes'); - check(!$r->publish('{"v":2}', [], 20, $generation) && $a->load() === ['v' => 1], 'a competing rebuild cannot overwrite the winner'); - $generation = $r->generation(); - $r->command('del', [$options['key']]); - check(!$r->publish('{"old":1}', [], 20, $generation), 'physical Redis eviction also fences publication'); - $r->save('{"v":3}', 'schema', [], 20); - $a->load(); - $file = $root.'/'.hash('sha256', '{"v":3}').'.php'; - unlink($file); - check($a->load() === ['v' => 3], 'missing PHP file repromotes'); - file_put_contents($file, 'load() === ['v' => 3], 'PHP syntax corruption repairs from Redis'); - file_put_contents($file, 'load() === ['v' => 3], 'non-array local file repairs from Redis'); - $stamp = json_decode(file_get_contents($root.'/stamp.json'), true); - $stamp['checked'] = microtime(true) + 3600; - file_put_contents($root.'/stamp.json', json_encode($stamp)); - $r->save('{"v":4}', 'schema', [], 20); - check((new Local($r, $root, 60))->load() === ['v' => 4], 'future validation stamp does not extend grace'); - $r->save('{"v":5}', 'schema', [], 20); - $a->load(); - $r->clean('notMatchingTag', ['CONFIG']); - check($a->load() === ['v' => 5], 'inverse clean retains matching schema'); - $r->clean('notMatchingTag', ['OTHER']); - check($a->load() === null, 'inverse clean invalidates nonmatching schema'); - $r->save('{"v":6}', 'schema', [], 20); - $race = new class ($options) extends Remote { - public function entry(): ?array - { - $this->remove('schema'); - return parent::entry(); - } - }; - check((new Local($race, $root.'/race', 0))->load() === null, 'invalidation between metadata and payload read returns miss'); - $r->save('{"v":7}', 'schema', [], 20); - $r->command('hSet', [$options['key'],'hash',str_repeat('0', 64)]); - foreach ([$root.'/fresh',$root.'/blocked/subdir'] as $dir) { - if (str_contains($dir, 'blocked')) { - file_put_contents($root.'/blocked', 'file'); - }try { - (new Local($r, $dir, 0))->load(); - check(false, 'damaged remote hash should fail'); - } catch (RuntimeException $e) { - check($e->getMessage() === 'Schema record mismatch', 'remote hash mismatch rejected including disk-failure fallback'); - } - } - $expired = new class ($options) extends Remote { - public function entry(): ?array - { - return ['version' => 'v','data' => '{"v":8}','hash' => hash('sha256', '{"v":8}'),'expires' => microtime(true) - 1]; - } - }; - check((new Local($expired, $root.'/blocked/subdir', 0))->load() === null, 'disk-failure fallback does not revive expired data'); - $r->save('{"v":9}', 'schema', [], 20); - $a->load(); - $otherOptions = $options; - $otherOptions['key'] .= ':other'; - $other = new Remote($otherOptions); - $other->save('{"v":10}', 'schema', [], 20); - check((new Local($other, $root, 0))->load() === ['v' => 10] && $a->load() === ['v' => 9], 'even accidentally shared local root validates remote identity via unique revision'); - $other->command('del', [$otherOptions['key'],$otherOptions['key'].':epoch']); - $rolling = $options; - $rolling['key'] .= ':release-b'; - $rolling['epoch_key'] = $options['key'].':epoch'; - $releaseB = new Remote($rolling); - $r->save('{"release":"a"}', 'schema', [], 20); - $releaseB->save('{"release":"b"}', 'schema', [], 20); - $localB = new Local($releaseB, $root.'/release-b', 0); - check($a->load() === ['release' => 'a'] && $localB->load() === ['release' => 'b'], 'rolling releases keep distinct schemas'); - $pending = $releaseB->generation(); - $r->clean('matchingAnyTag', ['CONFIG']); - check($a->load() === null && $localB->load() === null && !$releaseB->publish('{"stale":1}', [], 20, $pending), 'one release config clean invalidates both releases and fences both builds'); - $r->command('del', [$options['key'].':epoch']); - check($releaseB->metadata() === null, 'evicted installation epoch never revives old data'); - $releaseB->command('del', [$rolling['key']]); - $cap = new Local($r, $root.'/bounded', 0, 1, 1000000); - $r->save('{"v":11}', 'schema', [], 20); - $cap->load(); - $r->save('{"v":12}','schema',[],20); - check($cap->load() === ['v' => 12] && count(glob($root.'/bounded/*.php')) === 1,'schema admission cap keeps correct Redis fallback without growing compiled file count'); - try { - new Local($r,$root,-1); - check(false,'negative grace'); - } catch (InvalidArgumentException) { - check(true,'negative grace rejected'); - } -} finally { - $r->command('del',[$options['key'],$options['key'].':epoch']); -} diff --git a/dev/tests/schema-l1/redis-failure.php b/dev/tests/schema-l1/redis-failure.php deleted file mode 100644 index b549c12..0000000 --- a/dev/tests/schema-l1/redis-failure.php +++ /dev/null @@ -1,78 +0,0 @@ - '127.0.0.1','port' => (int)$port,'database' => 0,'key' => 'failure-fixture','password' => 'audit-fixture-only','timeout' => 0.15,'read_timeout' => 0.15]; -if ($mode === 'persistent-acl') { - $options['username'] = 'fastboot-fixture'; - $options['password'] = 'acl-fixture-only'; - $options['database'] = 3; -} -$r = new Remote($options); -$l = new Local($r, $dir, 0); -if (in_array($mode, ['persistent', 'persistent-acl'], true)) { - $r->save('{"ok":1}', 'schema', [], 60); - $l->load(); - echo "READY\n"; - flush(); - while (($action = trim((string)fgets(STDIN))) !== 'quit') { - if ($action === 'timeout') { - try { - $l->load(); - throw new RuntimeException('Expected timeout'); - } catch (RedisException|CredisException) { - } - } elseif ($action === 'recovered') { - if ($l->load() !== ['ok' => 1]) { - throw new RuntimeException('Same-client recovery failed'); - } - } else { - throw new RuntimeException('Unknown action'); - } - echo "PASS $action\n"; - flush(); - } - exit; -} - -switch ($mode) { - case 'acl': - $r->command('acl', ['SETUSER', 'fastboot-fixture', 'on', '>acl-fixture-only', '~*', '+@all']); - $options['username'] = 'fastboot-fixture'; - $options['password'] = 'acl-fixture-only'; - $options['database'] = 3; - $acl = new Remote($options); - $acl->save('{"acl":true}', 'schema', [], 60); - if ($acl->load('schema') !== '{"acl":true}' || $r->load('schema') !== '{"ok":1}') { - throw new RuntimeException('ACL authentication or database isolation failed'); - } - break; - case 'seed':$r->save('{"ok":1}', 'schema', [], 60); - if ($l->load() !== ['ok' => 1]) { - throw new RuntimeException('Seed failure'); - }break; - case 'bad-auth':$options['password'] = 'wrong'; - try { - (new Remote($options))->metadata(); - throw new RuntimeException('Wrong credentials accepted'); - } catch (RedisException|CredisException) { - }break; - case 'failed':$start = microtime(true); - try { - $l->load(); - throw new RuntimeException('Stale value accepted'); - } catch (RedisException|CredisException) { - }if (microtime(true) - $start > 2) { - throw new RuntimeException('Unbounded timeout'); - }break; - case 'grace':if ((new Local($r, $dir, 60))->load() !== ['ok' => 1]) { - throw new RuntimeException('Expected bounded grace'); - }break; - case 'empty':if ($l->load() !== null) { - throw new RuntimeException('Restart resurrected L1'); - }break; - default:throw new RuntimeException('Bad mode'); -} -echo "PASS $mode\n"; diff --git a/dev/tests/schema-l1/redis-failure.py b/dev/tests/schema-l1/redis-failure.py deleted file mode 100644 index 882457f..0000000 --- a/dev/tests/schema-l1/redis-failure.py +++ /dev/null @@ -1,37 +0,0 @@ -import os -import subprocess,pathlib,secrets,json,time,socket -D=pathlib.Path(__file__).resolve().parent -name='fba-schema-chaos-'+secrets.token_hex(5) -def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip() -def check(mode):subprocess.run(['php',str(D/'redis-failure.php'),port,str(pathlib.Path(os.environ.get('MAGENTO_ROOT',D.parents[4]))/'var'/name),mode],check=True,timeout=5) -try: - docker('run','-d','--name',name,'-p','127.0.0.1::6379','valkey/valkey:8-alpine','valkey-server','--save','','--appendonly','no','--requirepass','audit-fixture-only') - port=docker('port',name,'6379/tcp').rsplit(':',1)[1] - time.sleep(.5) - check('seed');check('bad-auth');check('acl') - live=subprocess.Popen(['php',str(D/'redis-failure.php'),port,str(pathlib.Path(os.environ.get('MAGENTO_ROOT',D.parents[4]))/'var'/name/'persistent'),'persistent-acl'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) - try: - assert live.stdout.readline().strip()=='READY' - docker('pause',name) - try: - live.stdin.write('timeout\n');live.stdin.flush();assert live.stdout.readline().strip()=='PASS timeout' - finally:docker('unpause',name) - live.stdin.write('recovered\n');live.stdin.flush();assert live.stdout.readline().strip()=='PASS recovered' - print('PASS same PHP process and Remote object recover after real read timeout') - finally: - live.communicate('quit\n',timeout=5) - if live.returncode:raise RuntimeError('Persistent client failed') - docker('pause',name) - try:check('failed');check('grace') - finally:docker('unpause',name) - docker('restart',name) - port=docker('port',name,'6379/tcp').rsplit(':',1)[1] - for _ in range(50): - try: - with socket.create_connection(('127.0.0.1',int(port)),timeout=.1):break - except OSError:time.sleep(.1) - check('empty');check('seed') - docker('stop',name);check('failed') - print('PASS actual Redis pause/timeout, bad authentication, empty restart, recovery and connection refusal') -finally: - subprocess.run(['docker','rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) diff --git a/dev/tests/schema-l1/tests.php b/dev/tests/schema-l1/tests.php deleted file mode 100644 index 8731555..0000000 --- a/dev/tests/schema-l1/tests.php +++ /dev/null @@ -1,81 +0,0 @@ - 'fba:schema-lab:test:'.bin2hex(random_bytes(8)),'database' => 12]; -$r = new Remote($options); -$a = new Local($r, $root.'/a', 0); -$b = new Local($r, $root.'/b', 0); -try { - check(extension_loaded('redis') ? $r->getBackend() instanceof \Redis : $r->getBackend() instanceof \Credis_Client, 'available Redis client selected automatically'); - $r->save('{"v":1}', 'schema', ['CONFIG'], 20); - check($a->load() === ['v' => 1] && $b->load() === ['v' => 1], 'two local roots promote from shared Redis'); - $r->save('{"v":2}', 'schema', ['CONFIG'], 20); - check($b->load() === ['v' => 2] && $a->load() === ['v' => 2], 'strict readers observe completed remote writes'); - $r->clean('matchingAnyTag', ['unrelated']); - check($a->load() === ['v' => 2], 'unrelated tag keeps schema'); - $r->clean('matchingTag', ['CONFIG','missing']); - check($a->load() === ['v' => 2], 'all-tag clean requires every tag'); - $r->clean('matchingAnyTag', ['CONFIG']); - check($a->load() === null && $b->load() === null, 'matching tag invalidates both nodes'); - $r->save('{"v":3}', 'schema', [], 20); - $g = new Local($r, $root.'/grace', 0.15); - check($g->load() === ['v' => 3], 'grace node seeded'); - $r->save('{"v":4}', 'schema', [], 20); - Metrics::$values = []; - check($g->load() === ['v' => 3] && (Metrics::$values['redis_commands'] ?? 0) === 0, 'within grace local hit makes zero Redis commands'); - usleep(180000); - check($g->load() === ['v' => 4], 'after grace node observes remote change'); - $r->save('{"v":5}', 'schema', [], 1); - $ttl = new Local($r, $root.'/ttl', 60); - check($ttl->load() === ['v' => 5], 'TTL node seeded'); - usleep(1050000); - check($ttl->load() === null, 'entry TTL overrides longer validation grace'); - $r->save('{"v":6}', 'schema', [], 20); - $a->load(); - $r->remove('schema'); - check($a->load() === null, 'explicit delete does not serve old local data'); - $r->save('{"v":7}', 'schema', [], 20); - $a->load(); - $failed = new class ($options) extends Remote { - public function metadata(): ?array - { - throw new \CredisException('injected outage'); - }public function entry(): ?array - { - throw new \CredisException('injected outage'); - } - }; - try { - (new Local($failed, $root.'/a', 0))->load(); - check(false, 'outage must not return stale data'); - } catch (\CredisException $e) { - check(true, 'strict Redis failure propagates without serving stale data'); - } - check($a->load() === ['v' => 7], 'reader recovers after Redis returns'); - file_put_contents($root.'/a/stamp.json', 'broken'); - check($a->load() === ['v' => 7], 'malformed stamp recovers from Redis'); - $before = count(glob($root.'/a/*.php')); - for ($i = 0;$i < 10;$i++) { - $r->remove('schema'); - $r->save('{"v":7}', 'schema', [], 20); - check($a->load() === ['v' => 7], 'identical rebuild '.$i); - } - check(count(glob($root.'/a/*.php')) === $before, 'identical schema invalidations reuse the PHP file'); - file_put_contents($root.'/block', 'file'); - check((new Local($r, $root.'/block/nested', 0))->load() === ['v' => 7], 'unwritable local directory falls back to remote'); - // Stash only private test connection settings for concurrent processes. - file_put_contents($root.'/options.json',json_encode($options)); - echo 'CONCURRENCY_ROOT='.$root."\n"; -} finally { - $r->command('del',[$options['key'],$options['key'].':epoch']); -} diff --git a/dev/tests/without-redis.py b/dev/tests/without-redis.py deleted file mode 100644 index 3f778e3..0000000 --- a/dev/tests/without-redis.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python3 -"""Run a command and its PHP children without ext-redis; leave system PHP settings untouched.""" -import json -import os -import pathlib -import re -import shlex -import shutil -import subprocess -import sys -import tempfile - -command = sys.argv[1:] -if command[:1] == ['--']: - command = command[1:] -if not command: - sys.exit('Usage: python3 dev/tests/without-redis.py -- COMMAND [ARG ...]') -php = shutil.which('php') -files = json.loads(subprocess.check_output([ - php, '-r', 'echo json_encode([php_ini_loaded_file(), php_ini_scanned_files()]);' -], text=True)) -sources = ([files[0]] if files[0] else []) + ([p.strip() for p in files[1].split(',') if p.strip()] if files[1] else []) -with tempfile.TemporaryDirectory(prefix='fastboot-no-redis-') as temporary: - root = pathlib.Path(temporary) - ini = root / 'php.ini' - # Match extension=redis, redis.so, or an absolute module path, with optional quotes/comments. - extension = re.compile(r'^\s*extension\s*=\s*["\']?(?:[^\n;"\']*/)?(?:php_)?redis(?:\.(?:so|dll))?["\']?\s*(?:;.*)?$', re.I) - lines = [] - for source in sources: - lines.extend(line for line in pathlib.Path(source).read_text().splitlines() if not extension.match(line)) - ini.write_text('\n'.join(lines) + '\n') - wrapper = root / 'php' - wrapper.write_text('#!/bin/sh\nexec ' + shlex.quote(php) + ' -c ' + shlex.quote(str(ini)) + ' "$@"\n') - wrapper.chmod(0o700) - env = dict(os.environ, PHP_INI_SCAN_DIR='', PATH=str(root) + os.pathsep + os.environ.get('PATH', '')) - subprocess.run(['php', '-r', 'if (extension_loaded("redis") || class_exists("Redis", false)) exit(1); echo "PASS ext-redis is absent\\n";'], env=env, check=True) - sys.exit(subprocess.run(command, env=env).returncode) diff --git a/src/FastBoot/Console/StatusCommand.php b/src/FastBoot/Console/StatusCommand.php index ee03e04..4015b39 100644 --- a/src/FastBoot/Console/StatusCommand.php +++ b/src/FastBoot/Console/StatusCommand.php @@ -5,20 +5,19 @@ namespace GraphCommerce\FastBoot\Console; use GraphCommerce\FastBootCache\Model\{Feature,PhpFiles,Release}; -use GraphCommerce\FastBootCache\Model\Schema\Settings; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class StatusCommand extends Command { - public function __construct(private Feature $feature, private Settings $settings, private PhpFiles $files, private Release $release) + public function __construct(private Feature $feature, private PhpFiles $files, private Release $release) { parent::__construct('fastboot:status'); } protected function configure(): void { - $this->setDescription('Check FastBoot release configuration, private cache directory and Redis connectivity.'); + $this->setDescription('Check the FastBoot release identity, the private cache directory and the feature switches.'); } protected function execute(InputInterface $input, OutputInterface $output): int { @@ -33,16 +32,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int } elseif (!is_writable($directory)) { $errors[] = 'FastBoot cache directory is not writable by this CLI user; also check the FPM user.'; } - if ($this->settings->configuredMode() !== 'native') { - try { - $this->settings->remote()->metadata(); - $output->writeln('Schema Redis: reachable'); - } catch (\Throwable $error) { - $errors[] = $error instanceof \InvalidArgumentException ? $error->getMessage() : 'Schema Redis check failed ('.get_class($error).'). Check endpoint, credentials and extension.'; - } - } else { - $output->writeln('Schema L1: disabled; configure fastboot.schema_l1 to enable.'); - } $output->writeln('Release: '.($release ?: '(missing)')); foreach (['schema_array','schema_scalars','cache_files','system_config_array','parsed_queries','validated_queries','area_config_diff','quote_without_connection','deploy_config_unchanged','scopes_cache','website_stores','default_store','view_config','guest_tax_factor','placeholder_url'] as $name) { $output->writeln($name.': '.($this->feature->on($name) ? 'enabled' : 'disabled')); diff --git a/src/FastBoot/README.md b/src/FastBoot/README.md index cc757d3..b09d721 100644 --- a/src/FastBoot/README.md +++ b/src/FastBoot/README.md @@ -9,20 +9,7 @@ bin/magento module:enable GraphCommerce_FastBootCache GraphCommerce_FastBoot Gra ## Configuration -`app/etc/env.php`: - -```php -'fastboot' => [ - 'schema_l1' => [ - 'enabled' => true, - 'installation' => 'my-shop-production', - ], -], -``` - -`installation` identifies the environment across web, admin and CLI nodes. Redis connection settings default to Magento's default cache frontend. - -Cache namespaces use `pub/static/deployed_version.txt`. Each PHP/DI/config build needs a distinct static-content version, shared across its nodes. `setup:static-content:deploy --content-version="$BUILD_ID"` supplies that identity. +No configuration is required. Cache namespaces use `pub/static/deployed_version.txt`. Each PHP/DI/config build needs a distinct static-content version, shared across its nodes. `setup:static-content:deploy --content-version="$BUILD_ID"` supplies that identity. ## Deployment @@ -33,6 +20,6 @@ bin/magento fastboot:status bin/magento fastboot:prepare ``` -`status` checks the deployment identity, cache directory and schema Redis connection. `prepare` writes area DI differences, schema data and store configuration to the local cache. +`status` checks the deployment identity and the cache directory, and prints the feature switches. `prepare` writes area DI differences, the GraphQL schema and store configuration to the local cache. All optimizations are enabled by default. No database patches are installed. diff --git a/src/FastBootCache/Model/Schema/Local.php b/src/FastBootCache/Model/Schema/Local.php deleted file mode 100644 index 8f9f048..0000000 --- a/src/FastBootCache/Model/Schema/Local.php +++ /dev/null @@ -1,156 +0,0 @@ -directory.'/stamp.json'; - if (!is_file($file)) { - return null; - } - $v = json_decode((string)@file_get_contents($file), true); - return is_array($v) && isset($v['version'],$v['hash'],$v['checked']) && is_string($v['version']) && is_string($v['hash']) && is_numeric($v['checked']) && array_key_exists('expires', $v) && ($v['expires'] === null || is_numeric($v['expires'])) && preg_match('/^[a-f0-9]{64}$/D', $v['hash']) ? $v : null; - } - private function alive(array $s): bool - { - return $s['expires'] === null || $s['expires'] > microtime(true); - } - private function value(array $s): ?array - { - $file = $this->directory.'/'.$s['hash'].'.php'; - if (!is_file($file)) { - return null; - } - try { - $v = @include $file; - } catch (\ParseError $error) { - $v = null; - } - if (!is_array($v)) { - // Broken cache files must be removed so the next promotion can repair them. - if (function_exists('opcache_invalidate')) { - @opcache_invalidate($file, true); - } - @unlink($file); - } - return is_array($v) ? $v : null; - } - private function atomic(string $path, string $bytes): bool - { - $tmp = $path.'.'.bin2hex(random_bytes(8)).'.tmp'; - if (@file_put_contents($tmp, $bytes) !== strlen($bytes)) { - @unlink($tmp); - return false; - } - @chmod($tmp, 0600); - if (!@rename($tmp, $path)) { - @unlink($tmp); - return false; - } - return true; - } - public function load(): ?array - { - $s = $this->stamp(); - $now = microtime(true); - if ($s && $this->alive($s) && $now >= $s['checked'] && $now - $s['checked'] < $this->grace && ($v = $this->value($s)) !== null) { - Metrics::add('local_hits'); - return $v; - } - // Strict warm hits validate independently; do not serialize all FPM readers on a file lock. - if ($this->grace <= 0 && $s) { - $meta = $this->remote->metadata(); - if ($meta === null) { - return null; - } - if ($s['version'] === $meta['version'] && $this->alive($meta) && ($v = $this->value($s)) !== null) { - Metrics::add('validated_hits'); - return $v; - } - } - if (!is_dir($this->directory) && !@mkdir($this->directory, 0700, true) && !is_dir($this->directory)) { - return $this->fallback(); - } - $lock = @fopen($this->directory.'/validate.lock', 'c'); - if (!$lock) { - return $this->fallback(); - } - try { - if (!flock($lock, LOCK_EX)) { - return $this->fallback(); - } - // Recheck after acquiring the process-shared lock to coalesce grace refreshes. - $s = $this->stamp(); - $checked = microtime(true); - if ($s && $this->alive($s) && $checked >= $s['checked'] && $checked - $s['checked'] < $this->grace && ($v = $this->value($s)) !== null) { - Metrics::add('local_hits'); - return $v; - } - $meta = $this->remote->metadata(); - if ($meta === null) { - @unlink($this->directory.'/stamp.json'); - return null; - } - if ($s && $s['version'] === $meta['version'] && $this->alive($meta) && ($v = $this->value($s)) !== null) { - if ($this->grace > 0) { - $s['checked'] = $checked; - $s['expires'] = $meta['expires']; - $this->atomic($this->directory.'/stamp.json', json_encode($s, JSON_THROW_ON_ERROR)); - } - Metrics::add('validated_hits'); - return $v; - } - $e = $this->remote->entry(); - if ($e === null || !$this->alive($e)) { - @unlink($this->directory.'/stamp.json'); - return null; - } - $v = json_decode($e['data'], true, 512, JSON_THROW_ON_ERROR); - if (!is_array($v) || !hash_equals($e['hash'], hash('sha256', $e['data']))) { - throw new \RuntimeException('Schema record mismatch'); - } - $file = $this->directory.'/'.$e['hash'].'.php'; - if (!is_file($file)) { - $files = glob($this->directory.'/*.php') ?: []; - $content = "= $this->maxFiles || array_sum(array_map('filesize', $files)) + strlen($content) > $this->maxBytes) { - Metrics::add('admission_rejections'); - return $v; - } - } - // Content-addressed files are never overwritten; identical rebuilds reuse OPcache. - if (!is_file($file) && !$this->atomic($file, "atomic($this->directory.'/stamp.json', json_encode(['version' => $e['version'],'hash' => $e['hash'],'checked' => $checked,'expires' => $e['expires']], JSON_THROW_ON_ERROR)); - Metrics::add('promotions'); - return $v; - } finally { - flock($lock, LOCK_UN); - fclose($lock); - } - } - private function fallback(): ?array - { - $e = $this->remote->entry(); - if ($e === null || !$this->alive($e)) { - return null; - } - $v = json_decode($e['data'], true, 512, JSON_THROW_ON_ERROR); - if (!is_array($v) || !hash_equals($e['hash'], hash('sha256', $e['data']))) { - throw new \RuntimeException('Schema record mismatch'); - } - return $v; - } -} diff --git a/src/FastBootCache/Model/Schema/Metrics.php b/src/FastBootCache/Model/Schema/Metrics.php deleted file mode 100644 index af90a09..0000000 --- a/src/FastBootCache/Model/Schema/Metrics.php +++ /dev/null @@ -1,14 +0,0 @@ -redis !== null) { - return $this->redis; - } - $start = hrtime(true); - // Persistent sockets are scoped by endpoint, database and authentication identity. - $persistentId = 'fastboot-schema-'.hash('sha256', json_encode($this->options, JSON_THROW_ON_ERROR)); - $host = $this->options['host'] ?? '127.0.0.1'; - $port = (int)($this->options['port'] ?? 6379); - $timeout = (float)($this->options['timeout'] ?? 0.3); - $readTimeout = (float)($this->options['read_timeout'] ?? 0.3); - if (extension_loaded('redis')) { - $r = new \Redis(); - } else { - // Use Magento's PHP client when phpredis is unavailable. Its EVAL API is adapted below. - $r = new \Credis_Client($host, $port, $timeout, $persistentId, 0, null, null, $this->options['context']['stream'] ?? []); - $r->forceStandalone()->setMaxConnectRetries(0)->setReadTimeout($readTimeout); - } - try { - if ($r instanceof \Redis) { - $r->pconnect($host, $port, $timeout, $persistentId, 0, $readTimeout, $this->options['context'] ?? []); - $r->setOption(\Redis::OPT_READ_TIMEOUT, $readTimeout); - $r->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_NONE); - } else { - $r->connect(); - } - if (isset($this->options['password']) && $this->options['password'] !== '') { - $username = empty($this->options['username']) ? null : $this->options['username']; - $authenticated = $r instanceof \Redis - ? $r->auth($username === null ? $this->options['password'] : [$username, $this->options['password']]) - : $r->auth($this->options['password'], $username); - if (!$authenticated) { - throw new \RuntimeException('FastBoot schema Redis authentication failed'); - } - Metrics::add('redis_commands'); - } - if (!$r->select((int)($this->options['database'] ?? 0))) { - throw new \RuntimeException('FastBoot schema Redis SELECT failed'); - } - Metrics::add('redis_commands'); - } catch (\Throwable $error) { - $this->disconnect($r); - throw $error; - } - Metrics::add('connect_ms', (hrtime(true) - $start) / 1e6); - return $this->redis = $r; - } - private function disconnect(\Redis|\Credis_Client $connection): void - { - try { - // Credis otherwise retains persistent streams, including unread replies after a timeout. - $connection instanceof \Credis_Client ? $connection->close(true) : $connection->close(); - } catch (\Throwable) { - } - } - private function key(): string - { - return $this->options['key']; - } - private function epochKey(): string - { - return $this->options['epoch_key'] ?? $this->key().':epoch'; - } - public function command(string $method, array $args): mixed - { - $r = $this->connection(); - $start = hrtime(true); - Metrics::add('redis_commands'); - try { - if ($r instanceof \Credis_Client && in_array(strtolower($method), ['eval', 'evalsha'], true)) { - [$script, $values, $keyCount] = $args; - return $r->$method($script, array_slice($values, 0, $keyCount), array_slice($values, $keyCount)); - } - return $r->$method(...$args); - } catch (\Throwable $error) { - // Discard a timed-out socket; do not retry a write whose outcome is unknown. - $this->redis = null; - $this->disconnect($r); - throw $error; - } finally { - Metrics::add('redis_ms', (hrtime(true) - $start) / 1e6); - } - } - public function metadata(): ?array - { - $start = microtime(true); - $r = $this->command('eval', ["local v=redis.call('HGET',KEYS[1],'version'); if not v or redis.call('HGET',KEYS[1],'epoch')~=redis.call('GET',KEYS[2]) or redis.call('HEXISTS',KEYS[1],'data')==0 then return {} end; return {v,redis.call('PTTL',KEYS[1])}",[$this->key(),$this->epochKey()],2]); - if (!$r) { - return null; - } - return ['version' => $r[0],'expires' => $r[1] < 0 ? null : $start + max(0, $r[1]) / 1000]; - } - public function entry(): ?array - { - $start = microtime(true); - $r = $this->command('eval', ["local v=redis.call('HMGET',KEYS[1],'version','data','hash'); if not v[1] or not v[2] or redis.call('HGET',KEYS[1],'epoch')~=redis.call('GET',KEYS[2]) then return {} end; return {v[1],v[2],v[3],redis.call('PTTL',KEYS[1])}",[$this->key(),$this->epochKey()],2]); - if (!$r) { - return null; - } - Metrics::add('payload_bytes', strlen($r[1])); - return ['version' => $r[0],'data' => $r[1],'hash' => $r[2],'expires' => $r[3] < 0 ? null : $start + max(0, $r[3]) / 1000]; - } - public function load($identifier) - { - $entry = $this->entry(); - return $entry === null ? false : $entry[str_ends_with((string)$identifier, ':hash') ? 'hash' : 'data']; - } - public function save($data, $identifier, array $tags = [], $lifeTime = null) - { - // SymfonyL2 writes a separate :hash; our payload save already writes it atomically. - if (str_ends_with((string)$identifier, ':hash')) { - return $this->load($identifier) === $data; - } - return $this->publish($data, $tags, $lifeTime); - } - /** Capture before reading source configuration. A concurrent clean/write/expiry fences publication. */ - public function generation(): string - { - return $this->command('eval', ["redis.call('SETNX',KEYS[2],ARGV[1]); redis.call('HSETNX',KEYS[1],'version',ARGV[1]); return redis.call('GET',KEYS[2])..':'..redis.call('HGET',KEYS[1],'version')", [$this->key(), $this->epochKey(), bin2hex(random_bytes(16))], 2]); - } - public function publish(string $data, array $tags = [], $lifeTime = null, ?string $expected = null): bool - { - $ttl = $lifeTime === false ? 7200 : ($lifeTime === null ? 0 : (int)$lifeTime); - if ($lifeTime !== null && $lifeTime !== false && $ttl <= 0) { - return $this->remove('schema'); - } - $tags = array_values(array_unique(array_merge(['CONFIG'], $tags))); - $lua = "local epoch=redis.call('GET',KEYS[2]); local v=redis.call('HGET',KEYS[1],'version'); if ARGV[6]~='' and (not epoch or not v or epoch..':'..v~=ARGV[6]) then return 0 end; if not epoch then epoch=ARGV[3]; redis.call('SET',KEYS[2],epoch) end; redis.call('HSET',KEYS[1],'epoch',epoch,'data',ARGV[1],'hash',ARGV[2],'version',ARGV[3],'tags',ARGV[4]); if tonumber(ARGV[5])>0 then redis.call('PEXPIRE',KEYS[1],ARGV[5]) else redis.call('PERSIST',KEYS[1]) end; return 1"; - return (bool)$this->command('eval', [$lua, [$this->key(), $this->epochKey(), $data, hash('sha256', $data), bin2hex(random_bytes(16)), json_encode($tags, JSON_THROW_ON_ERROR), $ttl * 1000, $expected ?? ''], 2]); - } - public function remove($identifier) - { - return $this->clean(); - } - public function clean($mode = 'all', array $tags = []) - { - $lua = <<<'LUA' -local raw=redis.call('HGET',KEYS[1],'tags') -local have=raw and cjson.decode(raw) or {'CONFIG'}; local want=cjson.decode(ARGV[2]); local matched=0 -for _,w in ipairs(want) do for _,h in ipairs(have) do if w==h then matched=matched+1;break end end end -local m=ARGV[1] -if m=='all' or (m=='matchingTag' and matched==#want) or (m=='matchingAnyTag' and matched>0) or (m=='notMatchingTag' and matched==0) then - redis.call('SET',KEYS[2],ARGV[3]); redis.call('DEL',KEYS[1]); redis.call('HSET',KEYS[1],'version',ARGV[3]) -end -return 1 -LUA; - if (!in_array($mode, ['all','old','matchingTag','matchingAnyTag','notMatchingTag'], true)) { - throw new \InvalidArgumentException('Unsupported clean mode'); - } - return (bool)$this->command('eval', [$lua, [$this->key(), $this->epochKey(), $mode, json_encode(array_values(array_unique($tags)), JSON_THROW_ON_ERROR), bin2hex(random_bytes(16))], 2]); - } - public function test($identifier) - { - return $this->metadata() === null ? false : time(); - } - public function getBackend() - { - return $this->connection(); - } - public function getLowLevelFrontend() - { - return $this; - } -} diff --git a/src/FastBootCache/Model/Schema/Settings.php b/src/FastBootCache/Model/Schema/Settings.php deleted file mode 100644 index a5e938c..0000000 --- a/src/FastBootCache/Model/Schema/Settings.php +++ /dev/null @@ -1,75 +0,0 @@ -get('fastboot/schema_l1', []); - $frontend = (array)$deploymentConfig->get('cache/frontend/default', []); - $backend = (array)($frontend['backend_options'] ?? []); - $this->options = $options + [ - 'host' => $backend['server'] ?? null, - 'port' => $backend['port'] ?? 6379, - 'database' => $backend['database'] ?? 0, - 'password' => $backend['password'] ?? null, - 'username' => $backend['username'] ?? null, - 'installation' => $frontend['id_prefix'] ?? null, - ]; - } - - public function configuredMode(): string - { - return ($this->options['enabled'] ?? false) === true ? 'opcache' : 'native'; - } - - public function mode(): string - { - return $this->cacheState->isEnabled('config') && $this->feature->on(self::SWITCH) ? $this->configuredMode() : 'native'; - } - - public function remote(): Remote - { - $this->options['release'] = $this->release->id(); - if ($this->options['release'] === null) { - throw new \InvalidArgumentException('FastBoot requires a static content deployment version. Run setup:static-content:deploy before enabling schema L1.'); - } - foreach (['host', 'installation', 'release'] as $required) { - if (!is_string($this->options[$required] ?? null) || $this->options[$required] === '') { - throw new \InvalidArgumentException('FastBoot schema_l1 requires '.$required.'; configure it before enabling.'); - } - } - $prefix = 'fastboot:schema:v1:{'.hash('sha256', $this->options['installation']).'}:'; - return $this->remote ??= new Remote(array_replace($this->options, [ - 'key' => $prefix.hash('sha256', $this->options['release']), - 'epoch_key' => $prefix.'epoch', - ])); - } - - public function local(): Local - { - $remote = $this->remote(); - $identity = hash('sha256', json_encode([$this->options['host'], $this->options['port'], $this->options['database'], $this->options['installation'], $this->options['release']], JSON_THROW_ON_ERROR)); - $cache = $this->directories->getPath(DirectoryList::CACHE); - return new Local($remote, rtrim($cache, '/').'/fastboot/schema/'.$identity, (float)($this->options['grace'] ?? 0), (int)($this->options['max_files'] ?? 16), (int)($this->options['max_bytes'] ?? 33554432)); - } - - public function frontend(?\Magento\Framework\Cache\FrontendInterface $native = null): \Magento\Framework\Cache\FrontendInterface - { - return $this->remote(); - } -} diff --git a/src/FastBootCache/README.md b/src/FastBootCache/README.md index 9af68fe..7748326 100644 --- a/src/FastBootCache/README.md +++ b/src/FastBootCache/README.md @@ -2,35 +2,6 @@ Settings in `app/etc/env.php`. -## Redis connection - -```php -'fastboot' => [ - 'schema_l1' => [ - 'enabled' => true, // Default: false. - 'installation' => 'my-shop-production', // Defaults to the cache frontend's id_prefix. - - // Cache defaults: - 'grace' => 0, // Seconds between validations; 0 = strict freshness. - 'max_files' => 16, // Immutable schema files per local namespace. - 'max_bytes' => 33554432, // 32 MiB of PHP source per local namespace. - - // Connection overrides; omitted values inherit Magento's default cache frontend: - // 'host' => 'redis-cache.internal', - // 'port' => 6379, - // 'database' => 0, - // 'username' => 'cache-user', - // 'password' => '...', - - 'timeout' => 0.3, // Connection timeout, seconds. - 'read_timeout' => 0.3, // Socket read timeout, seconds. - 'context' => [], // TLS options under context['stream']. - ], -], -``` - -Direct primary connections are supported. Sentinel discovery and Cluster routing are not implemented. For TLS, use a `tls://` host and `context['stream']` options. - ## Local cache limits Defaults under `fastboot.files`: @@ -46,6 +17,8 @@ Defaults under `fastboot.files`: `max_files` and `max_bytes` apply to immutable blobs in a local release namespace. `max_queries` limits each of the parsed-query and validated-query index groups per generation. Once a limit is reached, new entries use their native computation or authoritative data path. Existing valid entries remain usable. +The stitched GraphQL schema is one entry. A schema larger than `max_entry_bytes` as PHP source is not kept locally, and each request decodes it from Magento's config cache; raise the limit to keep it local. + Limits bound admitted PHP source per namespace. There is no LRU eviction. Retired namespaces remain until deployment cleanup. ## Local paths @@ -55,17 +28,20 @@ Paths below are relative to Magento's configured cache directory, normally `var/ | Data | Path | |---|---| | Generic PHP blobs and indexes | `fastboot/v2//` | -| GraphQL schema files and freshness stamps | `fastboot/schema//` | | Compiled area differences | `fastboot/metadata/` | Files can contain decrypted configuration. Removing them causes repopulation; deleting source files does not reclaim their compiled OPcache memory. ## Freshness -The authoritative schema is shared in Redis; its local copy is private to each server. A missing local copy is fetched from Redis and saved locally. If Redis has no current schema, Magento rebuilds it. +Magento's cache is authoritative; the local files hold copies of its entries and of data derived from them, the stitched GraphQL schema included. All local files of a namespace belong to one version token, which FastBoot keeps in Magento's cache under the `config` tag. Each of these operations, on any server, gives every server a new version: + +- a save, remove or clean on a covered cache type (`config`, `eav`, `translate`, `db_ddl`, `reflection`, `collections`); +- a clean of the `config` tag, or a flush of the cache; +- a direct reset of the GraphQL schema data. -Strict freshness is the default. A schema load checks its current revision and remaining TTL in Redis before using the local copy. Generic FastBoot caches check their shared generation once per request. An in-flight request can finish with data it already loaded. +A request reads the token from Magento's cache once and uses that version until it ends. A write captures the version before it computes its data and is refused when the version changed in between, so a clean during a build does not leave old data under the new version. An in-flight request can finish with data it already loaded. -Invalidation hooks must remain active on every web, admin and CLI node. External deletion of legacy Magento cache keys does not necessarily invalidate FastBoot records. +The invalidation plugins must remain active on every web, admin and CLI node. A change made outside Magento's cache API, such as deleting keys in the cache backend directly, does not change the version. -A local disk failure falls back to authoritative data. A Redis validation failure is reported as an error; it does not permit serving an old local schema. A positive schema grace period deliberately allows bounded stale reads; entry expiry still wins. +A local disk failure falls back to Magento's cache. diff --git a/src/FastBootCache/Test/Unit/Model/ReleaseTest.php b/src/FastBootCache/Test/Unit/Model/ReleaseTest.php index eb8fc18..be73270 100644 --- a/src/FastBootCache/Test/Unit/Model/ReleaseTest.php +++ b/src/FastBootCache/Test/Unit/Model/ReleaseTest.php @@ -4,32 +4,26 @@ namespace GraphCommerce\FastBootCache\Test\Unit\Model; -use GraphCommerce\FastBootCache\Model\{Release,PhpFiles,Version,Feature}; -use GraphCommerce\FastBootCache\Model\Schema\Settings; -use Magento\Framework\App\{DeploymentConfig,Cache\StateInterface,Filesystem\DirectoryList}; +use GraphCommerce\FastBootCache\Model\{Release,PhpFiles,Version}; +use Magento\Framework\App\{DeploymentConfig,Filesystem\DirectoryList}; use Magento\Framework\Filesystem; use PHPUnit\Framework\TestCase; class ReleaseTest extends TestCase { - public function testDeploymentChangesIsolateLocalAndSharedDataWithoutAnExplicitId(): void + public function testDeploymentChangesIsolateLocalDataWithoutAnExplicitId(): void { $root = sys_get_temp_dir().'/fastboot-release-'.bin2hex(random_bytes(8)); mkdir($root.'/static', 0700, true); $config = $this->createStub(DeploymentConfig::class); $config->method('get')->willReturnCallback(static fn ($key, $default = null) => match ($key) { 'fastboot/release' => 'ignored-legacy-build', - 'fastboot/schema_l1' => ['enabled' => true, 'installation' => 'release-test', 'release' => 'ignored-schema-build'], 'cache/frontend/default' => ['backend_options' => ['server' => '127.0.0.1']], default => $default, }); $dirs = new DirectoryList($root, [DirectoryList::STATIC_VIEW => ['path' => $root.'/static'], DirectoryList::CACHE => ['path' => $root.'/private-cache']]); $version = $this->createStub(Version::class); $version->method('current')->willReturn('unchanged-cache-generation'); - $state = $this->createStub(StateInterface::class); - $state->method('isEnabled')->willReturn(true); - $feature = $this->createStub(Feature::class); - $feature->method('on')->willReturn(true); $read = $this->createStub(\Magento\Framework\Filesystem\Directory\ReadInterface::class); $read->method('getAbsolutePath')->willReturn($root.'/private-cache/'); $fs = $this->createStub(Filesystem::class); @@ -38,7 +32,6 @@ public function testDeploymentChangesIsolateLocalAndSharedDataWithoutAnExplicitI return $read; }); $files = fn ($release) => new PhpFiles($fs, $version, $config, $release); - $settings = fn ($release) => new Settings($config, $state, $feature, $dirs, $release); try { $missing = new Release($dirs); self::assertNull($missing->id()); @@ -55,14 +48,7 @@ public function testDeploymentChangesIsolateLocalAndSharedDataWithoutAnExplicitI self::assertSame('build-one', $first->id()); // In-flight request keeps its build snapshot. self::assertSame('build-two', $second->id()); self::assertNull($files($second)->read('CONFIG', 'example')); - $options = new \ReflectionProperty(\GraphCommerce\FastBootCache\Model\Schema\Remote::class, 'options'); - $firstSettings = $settings($first); - $directory = new \ReflectionProperty(\GraphCommerce\FastBootCache\Model\Schema\Local::class, 'directory'); - self::assertStringStartsWith($root.'/private-cache/fastboot/schema/', $directory->getValue($firstSettings->local())); - $a = $options->getValue($firstSettings->remote()); - $b = $options->getValue($settings($second)->remote()); - self::assertNotSame($a['key'], $b['key']); - self::assertSame($a['epoch_key'], $b['epoch_key']); + self::assertNotSame($files($first)->namespaceDirectory(), $files($second)->namespaceDirectory()); } finally { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $file) { diff --git a/src/FastBootCache/Test/Unit/Model/SchemaSettingsTest.php b/src/FastBootCache/Test/Unit/Model/SchemaSettingsTest.php deleted file mode 100644 index 3336010..0000000 --- a/src/FastBootCache/Test/Unit/Model/SchemaSettingsTest.php +++ /dev/null @@ -1,55 +0,0 @@ -settings([])->mode()); - } - public function testCacheDisableBypassesReadsButKeepsInvalidationEnabled(): void - { - $settings = $this->settings(['enabled' => true], false); - self::assertSame('native', $settings->mode()); - self::assertSame('opcache', $settings->configuredMode()); - } - public function testFeatureSwitchBypassesReadsButKeepsInvalidationEnabled(): void - { - $settings = $this->settings(['enabled' => true], true, false); - self::assertSame('native', $settings->mode()); - self::assertSame('opcache', $settings->configuredMode()); - } - public function testEnablingWithoutReleaseFailsBeforeOpeningRedis(): void - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('static content deployment version'); - $this->settings(['enabled' => true,'installation' => 'test'])->remote(); - } - private function settings(array $options, bool $cacheEnabled = true, bool $featureEnabled = true): Settings - { - $config = $this->createStub(DeploymentConfig::class); - $config->method('get')->willReturnCallback(static fn ($key, $default = null) => match($key) { - 'fastboot/schema_l1' => $options, - 'cache/frontend/default' => ['backend_options' => ['server' => '127.0.0.1','database' => 12]], - default => $default, - }); - $state = $this->createStub(StateInterface::class); - $state->method('isEnabled')->willReturn($cacheEnabled); - $feature = $this->createStub(Feature::class); - $feature->method('on')->willReturn($featureEnabled); - $directories = $this->createStub(DirectoryList::class); - $directories->method('getPath')->willReturn('/missing-fastboot-test-static'); - return new Settings($config, $state, $feature, $directories, new Release($directories)); - } -} diff --git a/src/FastBootCache/composer.json b/src/FastBootCache/composer.json index c962133..83901ea 100644 --- a/src/FastBootCache/composer.json +++ b/src/FastBootCache/composer.json @@ -16,8 +16,5 @@ "psr-4": { "GraphCommerce\\FastBootCache\\": "" } - }, - "suggest": { - "ext-redis": "Required when the optional schema_l1 Redis transport is enabled" } } diff --git a/src/FastBootCache/etc/di.xml b/src/FastBootCache/etc/di.xml index 7e38095..8a60405 100644 --- a/src/FastBootCache/etc/di.xml +++ b/src/FastBootCache/etc/di.xml @@ -4,9 +4,6 @@ Magento\Framework\App\Cache\StateInterface - - Magento\Framework\App\Filesystem\DirectoryList - diff --git a/src/FastBootGraphQl/Model/Config/OpcacheData.php b/src/FastBootGraphQl/Model/Config/OpcacheData.php index c3006a9..ed709d2 100644 --- a/src/FastBootGraphQl/Model/Config/OpcacheData.php +++ b/src/FastBootGraphQl/Model/Config/OpcacheData.php @@ -4,60 +4,54 @@ namespace GraphCommerce\FastBootGraphQl\Model\Config; -use GraphCommerce\FastBootCache\Model\Schema\{Settings, Metrics}; +use GraphCommerce\FastBootCache\Model\Feature; +use GraphCommerce\FastBootCache\Model\PhpFiles; +use Magento\Framework\Config\CacheInterface; +use Magento\Framework\Config\Data; +use Magento\Framework\Config\ReaderInterface; +use Magento\Framework\Serialize\SerializerInterface; -class OpcacheData extends \Magento\Framework\Config\Data +/** + * The stitched GraphQL schema as a PHP array in the local files, under the + * version token of the other local caches: a request includes the array from + * OPcache where Magento decodes about 1 MB of JSON from the config cache. + * A miss captures the version, runs Magento's path (the config cache, else + * the reader and a save to the config cache) and writes the array under the + * captured version, so a clean on any server during the build refuses the + * write. The save of a fresh build changes the version too, so the request + * that builds the schema writes no file; the next request reads the config + * cache and writes it. + */ +class OpcacheData extends Data { - private \Magento\Framework\Serialize\SerializerInterface $schemaSerializer; - private \Magento\Framework\Cache\FrontendInterface $schemaCache; + private const SWITCH = 'schema_array'; + private const GROUP = 'SCHEMA'; + public function __construct( - \Magento\Framework\Config\ReaderInterface $reader, - \Magento\Framework\Config\CacheInterface $cache, - $cacheId, - private Settings $settings, - ?\Magento\Framework\Serialize\SerializerInterface $serializer = null, + ReaderInterface $reader, + CacheInterface $cache, + private readonly string $cacheId, + private readonly PhpFiles $files, + private readonly Feature $feature, + ?SerializerInterface $serializer = null, ?array $cacheTags = null, ) { - $this->schemaSerializer = $serializer ?? new \Magento\Framework\Serialize\Serializer\Json(); - $this->schemaCache = $settings->mode() === 'native' ? $cache : $settings->frontend($cache); - // Parent requires Config CacheInterface. Override initData/reset to use our chosen frontend. - $this->_reader = $reader; - $this->_cacheId = $cacheId; - parent::__construct($reader, $cache, $cacheId, $this->schemaSerializer, $cacheTags); + parent::__construct($reader, $cache, $cacheId, $serializer, $cacheTags); } - protected function initData() - { - $start = hrtime(true); - try { - if ($this->settings->mode() === 'native') { - parent::initData(); - return; - } - $data = $this->settings->local()->load(); - if ($data === null || $data === false) { - $generation = $this->settings->remote()->generation(); - $data = $this->_reader->read(); - if (!$this->settings->remote()->publish(json_encode($data, JSON_THROW_ON_ERROR), $this->cacheTags, 7200, $generation)) { - Metrics::add('rejected_publications'); - } - } - $this->merge($data); - } finally { - Metrics::add('schema_ms', (hrtime(true) - $start) / 1e6); - } - } - public function reset() + protected function initData() { - if ($this->settings->mode() === 'native') { - parent::reset(); + if (!$this->feature->on(self::SWITCH)) { + parent::initData(); return; } - $this->schemaCache->remove($this->_cacheId); - $this->_data = []; - $data = $this->_reader->read(); - if ($data) { + $data = $this->files->read(self::GROUP, $this->cacheId); + if (is_array($data)) { $this->merge($data); + return; } + $version = $this->files->generation(); + parent::initData(); + $this->files->write(self::GROUP, $this->cacheId, $this->_data, null, $version); } } diff --git a/src/FastBootGraphQl/Plugin/Schema/Flush.php b/src/FastBootGraphQl/Plugin/Schema/Flush.php deleted file mode 100644 index 35e70e5..0000000 --- a/src/FastBootGraphQl/Plugin/Schema/Flush.php +++ /dev/null @@ -1,24 +0,0 @@ -settings->configuredMode() !== 'native') { - $this->settings->remote()->clean($tags ? 'matchingAnyTag' : 'all', (array)$tags); - }return $result; - } - public function afterFlush($subject, $result, $types) - { - if ($types && $this->settings->configuredMode() !== 'native') { - $this->settings->remote()->clean(); - }return $result; - } -} diff --git a/src/FastBootGraphQl/Plugin/Schema/Invalidate.php b/src/FastBootGraphQl/Plugin/Schema/Invalidate.php deleted file mode 100644 index 8c3d468..0000000 --- a/src/FastBootGraphQl/Plugin/Schema/Invalidate.php +++ /dev/null @@ -1,31 +0,0 @@ -settings->configuredMode() !== 'native') { - $this->settings->remote()->clean(); - }return $result; - } - public function afterSave($subject, $result, $data, $identifier, array $tags = [], $lifeTime = null) - { - if ($result) { - $this->afterRemove($subject, $result, $identifier); - } - return $result; - } - public function afterRemove($subject, $result, $identifier) - { - if ($identifier === 'Magento_Framework_GraphQlSchemaStitching_Config_Data' && $this->settings->configuredMode() !== 'native') { - $this->settings->remote()->remove($identifier); - }return $result; - } -} diff --git a/src/FastBootGraphQl/Test/Unit/Model/Config/OpcacheDataTest.php b/src/FastBootGraphQl/Test/Unit/Model/Config/OpcacheDataTest.php index 937d73c..4bd1c02 100644 --- a/src/FastBootGraphQl/Test/Unit/Model/Config/OpcacheDataTest.php +++ b/src/FastBootGraphQl/Test/Unit/Model/Config/OpcacheDataTest.php @@ -4,64 +4,193 @@ namespace GraphCommerce\FastBootGraphQl\Test\Unit\Model\Config; -use GraphCommerce\FastBootCache\Model\Schema\{Settings, Remote, Local}; +use GraphCommerce\FastBootCache\Model\{Feature, PhpFiles, Release, Version}; use GraphCommerce\FastBootGraphQl\Model\Config\OpcacheData; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Config\{CacheInterface, ReaderInterface}; +use Magento\Framework\Filesystem; +use Magento\Framework\Filesystem\Directory\ReadInterface; use Magento\Framework\Serialize\Serializer\Json; use PHPUnit\Framework\TestCase; class OpcacheDataTest extends TestCase { - public function testNativeModeUsesMagentoCache(): void + private const SCHEMA = ['types' => ['Query' => ['fields' => ['products' => ['type' => 'Products']]]]]; + + private string $root; + + protected function setUp(): void { - $settings = $this->createMock(Settings::class); - $settings->method('mode')->willReturn('native'); - $settings->expects(self::never())->method('remote'); - $cache = $this->createStub(CacheInterface::class); - $cache->method('load')->willReturn('{"types":{"Query":[]}}'); - $reader = $this->createMock(ReaderInterface::class); - $reader->expects(self::never())->method('read'); - $data = new OpcacheData($reader, $cache, 'schema', $settings, new Json()); - self::assertSame(['types' => ['Query' => []]], $data->get(null)); + $this->root = sys_get_temp_dir() . '/fastboot-schema-' . bin2hex(random_bytes(8)); + mkdir($this->root, 0700, true); + } + + protected function tearDown(): void + { + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->root, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); + foreach ($iterator as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->root); } - public function testWarmArrayDoesNotReadSourceOrPublish(): void + + public function testFileHitReadsNeitherCacheNorReader(): void { - $remote = $this->createMock(Remote::class); - $remote->expects(self::never())->method('publish'); - $local = $this->createStub(Local::class); - $local->method('load')->willReturn(['types' => ['Query' => []]]); - $settings = $this->settings($remote, $local); + $files = $this->createMock(PhpFiles::class); + $files->method('read')->with('SCHEMA', 'schema')->willReturn(self::SCHEMA); + $files->expects(self::never())->method('write'); + $cache = $this->createMock(CacheInterface::class); + $cache->expects(self::never())->method('load'); $reader = $this->createMock(ReaderInterface::class); $reader->expects(self::never())->method('read'); - $data = new OpcacheData($reader, $this->createStub(CacheInterface::class), 'schema', $settings, new Json()); - self::assertSame(['types' => ['Query' => []]], $data->get(null)); + + $data = new OpcacheData($reader, $cache, 'schema', $files, $this->feature(true), new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); } - public function testBuildCapturesGenerationBeforeSourceReadAndRejectsPublicationWithoutRetrying(): void + + public function testMissRunsMagentoPathAndWritesUnderVersionCapturedBeforeTheBuild(): void { $captured = false; - $remote = $this->createMock(Remote::class); - $remote->expects(self::once())->method('generation')->willReturnCallback(function () use (&$captured) { + $files = $this->createMock(PhpFiles::class); + $files->method('read')->willReturn(null); + $files->expects(self::once())->method('generation')->willReturnCallback(function () use (&$captured) { $captured = true; - return 'before-clean'; + return 'before-build'; }); - $remote->expects(self::once())->method('publish')->with('{"types":[]}', self::anything(), 7200, 'before-clean')->willReturn(false); - $local = $this->createStub(Local::class); - $local->method('load')->willReturn(null); - $reader = $this->createMock(ReaderInterface::class); - $reader->expects(self::once())->method('read')->willReturnCallback(function () use (&$captured) { + $files->expects(self::once())->method('write')->with('SCHEMA', 'schema', self::SCHEMA, null, 'before-build'); + $cache = $this->createMock(CacheInterface::class); + $cache->method('load')->willReturnCallback(function () use (&$captured) { self::assertTrue($captured); - return ['types' => []]; + return false; + }); + $cache->expects(self::once())->method('save')->with(json_encode(self::SCHEMA), 'schema'); + $reader = $this->createMock(ReaderInterface::class); + $reader->expects(self::once())->method('read')->willReturn(self::SCHEMA); + + $data = new OpcacheData($reader, $cache, 'schema', $files, $this->feature(true), new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); + } + + public function testMissFromConfigCacheWritesTheDecodedArray(): void + { + $files = $this->createMock(PhpFiles::class); + $files->method('read')->willReturn(null); + $files->method('generation')->willReturn('current'); + $files->expects(self::once())->method('write')->with('SCHEMA', 'schema', self::SCHEMA, null, 'current'); + $cache = $this->createStub(CacheInterface::class); + $cache->method('load')->willReturn(json_encode(self::SCHEMA)); + $reader = $this->createMock(ReaderInterface::class); + $reader->expects(self::never())->method('read'); + + $data = new OpcacheData($reader, $cache, 'schema', $files, $this->feature(true), new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); + } + + public function testSwitchOffRunsMagentoPathOnly(): void + { + $this->assertMagentoPathOnly($this->feature(false)); + } + + public function testDisabledConfigCacheRunsMagentoPathOnly(): void + { + $config = $this->createStub(DeploymentConfig::class); + $config->method('get')->willReturn([]); + $state = $this->createStub(StateInterface::class); + $state->method('isEnabled')->willReturnCallback(static fn ($type) => $type !== 'config'); + + $this->assertMagentoPathOnly(new Feature($config, $state)); + } + + public function testFileOfOneRequestServesTheNext(): void + { + $version = 'v1'; + $files = $this->files($version); + $cache = $this->createStub(CacheInterface::class); + $cache->method('load')->willReturn(json_encode(self::SCHEMA)); + new OpcacheData($this->createStub(ReaderInterface::class), $cache, 'schema', $files, $this->feature(true), new Json()); + + $untouched = $this->createMock(CacheInterface::class); + $untouched->expects(self::never())->method('load'); + $data = new OpcacheData($this->createStub(ReaderInterface::class), $untouched, 'schema', $this->files($version), $this->feature(true), new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); + } + + public function testVersionChangeDuringTheBuildRefusesTheWrite(): void + { + $version = 'v1'; + $reader = $this->createStub(ReaderInterface::class); + $reader->method('read')->willReturnCallback(function () use (&$version) { + $version = 'v2'; + return self::SCHEMA; }); - $data = new OpcacheData($reader, $this->createStub(CacheInterface::class), 'schema', $this->settings($remote, $local), new Json()); - self::assertSame(['types' => []], $data->get(null)); + $cache = $this->createStub(CacheInterface::class); + $cache->method('load')->willReturn(false); + + $data = new OpcacheData($reader, $cache, 'schema', $this->files($version), $this->feature(true), new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); + self::assertNull($this->files($version)->read('SCHEMA', 'schema')); + $version = 'v1'; + self::assertNull($this->files($version)->read('SCHEMA', 'schema')); } - private function settings(Remote $remote, Local $local): Settings + + public function testSchemaOfOneAndAHalfMegabytesFitsTheDefaultLimits(): void { - $settings = $this->createStub(Settings::class); - $settings->method('mode')->willReturn('opcache'); - $settings->method('frontend')->willReturn($remote); - $settings->method('remote')->willReturn($remote); - $settings->method('local')->willReturn($local); - return $settings; + $schema = ['types' => []]; + foreach (range(1, 480) as $type) { + $schema['types']['Type' . $type] = ['name' => 'Type' . $type, 'type' => 'graphql_type', 'fields' => array_fill_keys(array_map(static fn ($field) => 'field_' . $field, range(1, 20)), ['type' => 'String', 'required' => false, 'description' => 'A field of the schema'])]; + } + self::assertGreaterThan(1572864, strlen(var_export($schema, true))); + $version = 'v1'; + $cache = $this->createStub(CacheInterface::class); + $cache->method('load')->willReturn(json_encode($schema)); + new OpcacheData($this->createStub(ReaderInterface::class), $cache, 'schema', $this->files($version), $this->feature(true), new Json()); + + self::assertSame($schema, $this->files($version)->read('SCHEMA', 'schema')); + } + + private function assertMagentoPathOnly(Feature $feature): void + { + $files = $this->createMock(PhpFiles::class); + $files->expects(self::never())->method('read'); + $files->expects(self::never())->method('write'); + $cache = $this->createStub(CacheInterface::class); + $cache->method('load')->willReturn(json_encode(self::SCHEMA)); + $reader = $this->createMock(ReaderInterface::class); + $reader->expects(self::never())->method('read'); + + $data = new OpcacheData($reader, $cache, 'schema', $files, $feature, new Json()); + + self::assertSame(self::SCHEMA, $data->get(null)); + } + + private function feature(bool $on): Feature + { + $feature = $this->createStub(Feature::class); + $feature->method('on')->willReturn($on); + return $feature; + } + + /** Real local files of one release; `$version` is the token every read and write sees at that moment. */ + private function files(string &$version): PhpFiles + { + $directory = $this->createStub(ReadInterface::class); + $directory->method('getAbsolutePath')->willReturn($this->root . '/'); + $filesystem = $this->createStub(Filesystem::class); + $filesystem->method('getDirectoryRead')->willReturn($directory); + $token = $this->createStub(Version::class); + $token->method('current')->willReturnCallback(static function () use (&$version) { + return $version; + }); + $config = $this->createStub(DeploymentConfig::class); + $config->method('get')->willReturnCallback(static fn ($key, $default = null) => $default); + $release = $this->createStub(Release::class); + $release->method('id')->willReturn('build'); + return new PhpFiles($filesystem, $token, $config, $release); } } diff --git a/src/FastBootGraphQl/etc/di.xml b/src/FastBootGraphQl/etc/di.xml index b81f447..c103ef3 100644 --- a/src/FastBootGraphQl/etc/di.xml +++ b/src/FastBootGraphQl/etc/di.xml @@ -1,6 +1,6 @@ - + Magento\Framework\GraphQlSchemaStitching\Reader @@ -45,7 +45,4 @@ - - -