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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# Keep the Composer dist lean: exclude dev-only paths from package archives.
# Source, config, database (migration, factories, seeders), README, LICENSE, CHANGELOG and composer.json ship.
/.github export-ignore
/benchmarks export-ignore
/docs export-ignore
/tests export-ignore
/.editorconfig export-ignore
Expand All @@ -13,6 +14,8 @@
/.gitleaks.toml export-ignore
/CONTRIBUTING.md export-ignore
/SECURITY.md export-ignore
/phpbench.json export-ignore
/tools export-ignore
/phpstan.neon export-ignore
/phpunit.xml export-ignore
/rector.php export-ignore
29 changes: 14 additions & 15 deletions .github/workflows/static-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ on:
pull_request:
branches: [main]
workflow_dispatch:
# The whole-package mutation run (every src file) is weekly; pull requests mutate only
# the files they change, so they finish in minutes.
inputs:
paths:
description: Comma-separated src/ files to mutate (empty = everything)
required: false
default: ''
# The whole-package mutation run (every src file) is weekly; pull requests skip it.
schedule:
- cron: '23 6 * * 1'

Expand Down Expand Up @@ -67,10 +71,12 @@ jobs:

mutation:
name: Mutation testing (Pest)
# Weekly and on dispatch only (owner decision, 2026-11-10): pull requests skip it to keep CI
# spend down. The scheduled run mutates the whole package and fails below 70 %. A dispatch
# with `paths` set mutates only those files.
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
# A pull request mutates only the src/ files it changes; the weekly and dispatched runs
# mutate everything with a longer limit.
timeout-minutes: ${{ github.event_name == 'pull_request' && 15 || 60 }}
timeout-minutes: 60

steps:
- name: Checkout
Expand Down Expand Up @@ -103,16 +109,10 @@ jobs:
- name: Choose what to mutate
id: scope
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
INPUT_PATHS: ${{ github.event.inputs.paths }}
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
files=$(git diff --name-only --diff-filter=AMR "$BASE_SHA"...HEAD -- 'src/*.php' | paste -sd, -)
echo "paths=$files" >> "$GITHUB_OUTPUT"
echo "Mutating: ${files:-nothing (no src/ changes)}"
else
echo "paths=" >> "$GITHUB_OUTPUT"
echo "Mutating: everything"
fi
echo "paths=${INPUT_PATHS}" >> "$GITHUB_OUTPUT"
echo "Mutating: ${INPUT_PATHS:-everything}"

- name: Mutation testing (minimum score 70)
# Pest's own mutator, not Infection: Infection has no Pest adapter, reads Pest's
Expand All @@ -123,7 +123,6 @@ jobs:
# group `mutation-excluded`, which is what is excluded: under --parallel Pest honours
# only the first --exclude-group, and a comma-separated list excludes nothing, so
# `--exclude-group=matrix,shared-app` ran every test and raced on the shared config file.
if: github.event_name != 'pull_request' || steps.scope.outputs.paths != ''
env:
MUTATE_PATHS: ${{ steps.scope.outputs.paths }}
run: |
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- The settings cache (design phase 3, §7.5): `Drivers\CachingDriver` puts each database layer
behind `Caching\SettingsCache`, which caches every scope's raw rows (a "bag", every locale,
misses as empty bags) keyed by a hashed, length-prefixed tuple of connection, database, tenant,
store, table and scope. Invalidation replaces ULID generation tokens (per scope, per store, and
a global epoch) on every write path: set, forget, lock, unlock, flush, owner deletion and
promotion, after the write's transaction commits. Past `cache.ttl` a bag is still answered for
`cache.stale` seconds through `Cache::flexible()` while it is refreshed; a refresh can never
restore an invalidated value. Reads inside an open transaction and while bootstrap mode skips
the layer go straight to the database. A failing cache store falls back to the database and is
logged. New keys `cache.enabled` (default `true`), `cache.store`, `cache.prefix`, `cache.ttl`
and `cache.stale`.
- `laranail::settings.warm` and `laranail::settings.clear-cache` (`--store=*`), and
`clearCache()` / `warmCache()` on a settings handle, through the new `Actions\WarmCache` and
`Actions\ClearCache`: gated by `manage_stores` when an actor is present and audited as a
`manage_stores` entry (`meta.operation` `cache.warm` / `cache.clear`).
- `Store::isCached()`, `forgetCached()`, `forgetCachedStore()` and `warmCache()`;
`Data\CacheTarget`; `Support\BagCodec`.
- A phpbench benchmark of one request's reads with and without the cache (`benchmarks/`,
`phpbench.json`, `composer bench`). phpbench installs into `tools/phpbench/`, outside the
package's dependencies.

- Tenancy (`tenancy.mode`: `none`, `column`, `database`; recorded in the schema file). Column
mode adds a `tenant` column to the values, categories and audit tables, leading their unique
keys; every row is stamped with the current tenant and every query, the audit trail and the
Expand Down Expand Up @@ -72,6 +93,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`Store::requireDatabase()`, `CategoryRepository::of()`. Behaviour, messages and audit entries
are unchanged.
- `FindOrphans` finds orphaned owners' settings; `PruneOrphans` removes them.
- With caching on (the default), a store's database layer is a `CachingDriver` in front of the
`DatabaseDriver`; `->database()` still returns the `DatabaseDriver`. Rows changed past the API
(raw queries, `Models\Setting` saves) are not seen until `clear-cache` runs or the bag expires.
- `Contracts\Settings` gains `clearCache()` and `warmCache()`; `Actions\StoreActions` gains the
optional `warmCache` and `clearCache` actions.

### Deprecated

Expand Down
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ Contributions are welcome via pull requests.
|---|---|
| `composer test` | the Pest suite (Arch, Unit, Feature) |
| `composer test-coverage` | the suite with line coverage, failing below 90 % |
| `composer mutate` | Pest mutation testing of the whole package, failing below a 70 % score (slow; CI runs it weekly). For your change only: `vendor/bin/pest --mutate --path=src/Changed.php,src/Other.php --min=70`, which is what pull requests run |
| `composer mutate` | Pest mutation testing of the whole package, failing below a 70 % score (slow; CI runs it weekly, not on pull requests). For your change only: `vendor/bin/pest --mutate --path=src/Changed.php,src/Other.php --exclude-group=mutation-excluded --min=70` |
| `composer lint` | Pint (shared laranail config), PHPStan at level max, Rector dry run; never changes files |
| `composer composer-audit` | known-vulnerable dependencies |
| `composer bench` | the phpbench read benchmark (`benchmarks/`): one request's reads uncached, cold and warm. Run it before and after a change to the read path or the cache, and quote both. phpbench installs into `tools/phpbench/` on first run, apart from the package, because it depends on the abandoned `doctrine/annotations` |

## Guidelines

Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [Drivers and layers](docs/tools/drivers.md) — the built-in drivers and custom ones.
- [Database](docs/tools/database.md) — the tables, version-checked writes, eager loading and `HasSettings`.
- [Categories](docs/tools/categories.md) — nested, per-store categories and the rules that guard them.
- [Commands](docs/tools/commands.md) — install, make-store, promote, doctor and the prune commands.
- [Commands](docs/tools/commands.md) — install, make-store, promote, doctor, warm, clear-cache and the prune commands.
- [Owners and inheritance](docs/tools/owners.md) — owner references, store routing and the cascade.
- [Access control](docs/tools/access-control.md) — actors, abilities, authorizers, guarded locks, sensitive reads and step-up verification.
- [Audit and logging](docs/tools/audit-and-logging.md) — the audit trail, its sinks and the operational log.
Expand All @@ -92,6 +92,7 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [Audit queries](docs/tools/audit-queries.md) — reading the audit trail from PHP, gated by `view_audit`.
- [Tenancy](docs/tools/tenancy.md) — tenant column or database per tenant, the discriminator, and the stancl and spatie adapters.
- [Models and factories](docs/tools/models-and-factories.md) — Eloquent models and factories for tests, seeding and admin screens.
- [Caching](docs/tools/caching.md) — per-scope bags, tenant-safe keys, generation tokens and stale-while-revalidate.

### Recipes

Expand All @@ -100,6 +101,7 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [Act as a user](docs/recipes/acting-as-a-user.md) — authorize and audit changes made on a user's behalf.
- [Move from files to the database](docs/recipes/moving-from-files-to-the-database.md) — bootstrap mode during install, then promotion.
- [Seed the default categories](docs/recipes/seeding-default-categories.md) — the shipped set, your own set, and per tenant.
- [Warm the cache after a deploy](docs/recipes/warming-the-cache.md) — warm, and reset after changing rows by hand.

## Contributing & security

Expand Down
31 changes: 31 additions & 0 deletions benchmarks/BenchOwner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Benchmarks;

use Simtabi\Laranail\Settings\Data\OwnerRef;
use Simtabi\Laranail\Settings\Contracts\Settable;

/**
* A settings owner with one parent, without a model or a table: the benchmark measures the
* settings read, not Eloquent.
*/
final readonly class BenchOwner implements Settable
{
public function __construct(
private int $id,
private int $team,
) {}

public function settingsOwner(): OwnerRef
{
return new OwnerRef('owner', (string) $this->id);
}

/** @return list<OwnerRef> */
public function settingsParents(): array
{
return [new OwnerRef('team', (string) $this->team)];
}
}
140 changes: 140 additions & 0 deletions benchmarks/ReadBench.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Benchmarks;

use PhpBench\Attributes\Revs;
use PhpBench\Attributes\Warmup;
use PhpBench\Attributes\Iterations;
use Illuminate\Foundation\Application;
use PhpBench\Attributes\BeforeMethods;
use Illuminate\Support\Facades\Artisan;
use Simtabi\Laranail\Settings\Data\OwnerRef;
use Simtabi\Laranail\Settings\Contracts\Settings;
use Simtabi\Laranail\Settings\Caching\SettingsCache;
use Orchestra\Testbench\Foundation\Application as Testbench;
use Simtabi\Laranail\DbTools\Providers\DbToolsServiceProvider;
use Simtabi\Laranail\Settings\Providers\SettingsServiceProvider;
use Simtabi\Laranail\Package\Tools\Providers\PackageToolsServiceProvider;

/**
* Phase 3's gate (design §7.5, §11): one request's reads, with and without the settings cache.
*
* Every revolution is one request: the scoped services (registry, resolver, the cache's
* in-request memory) are rebuilt, then ten settings of one owner are read through the cascade
* owner → team → global, all in one SQLite-file store. Subjects:
*
* - uncached: cache.enabled off: one query per request.
* - cold: caching on, every bag invalidated first: the query plus the cache writes.
* - warm: caching on, bags cached in the `array` store (in-process).
* - warm file: caching on, bags cached in the `file` store (serialised to disk, the nearest
* local stand-in for a networked store).
*
* Run with `composer bench`.
*/
#[Iterations(5)]
#[Revs(200)]
#[Warmup(1)]
final class ReadBench
{
private const array KEYS = ['ui.theme', 'ui.density', 'ui.language', 'mail.from', 'mail.name', 'site.name', 'site.tagline', 'site.timezone', 'feature.beta', 'feature.limit'];

private Application $app;

private BenchOwner $owner;

public function setUpUncached(): void
{
$this->boot(['enabled' => false]);
}

public function setUpCached(): void
{
$this->boot(['enabled' => true, 'store' => 'array']);
}

public function setUpCachedFile(): void
{
$this->boot(['enabled' => true, 'store' => 'file']);
}

#[BeforeMethods('setUpUncached')]
public function benchUncached(): void
{
$this->request();
}

#[BeforeMethods('setUpCached')]
public function benchCold(): void
{
$this->app->forgetScopedInstances();
$this->app->make(SettingsCache::class)->forgetAll();
$this->request();
}

#[BeforeMethods('setUpCached')]
public function benchWarm(): void
{
$this->request();
}

#[BeforeMethods('setUpCachedFile')]
public function benchWarmFileStore(): void
{
$this->request();
}

/** One request: fresh scoped services, then every key read through the cascade. */
private function request(): void
{
$this->app->forgetScopedInstances();
$settings = $this->app->make(Settings::class)->for($this->owner);

foreach (self::KEYS as $key) {
$settings->get($key);
}
}

/** @param array<string, mixed> $cache `laranail.settings.cache` */
private function boot(array $cache): void
{
$directory = sys_get_temp_dir() . '/laranail-settings-bench-' . bin2hex(random_bytes(4));
mkdir($directory);
touch($directory . '/database.sqlite');

$this->app = Testbench::create(options: ['extra' => [
'providers' => [PackageToolsServiceProvider::class, DbToolsServiceProvider::class, SettingsServiceProvider::class],
'dont-discover' => ['*'],
]]);

$config = $this->app->make('config');
$config->set('app.key', 'base64:' . base64_encode(random_bytes(32)));
$config->set('database.default', 'bench');
$config->set('database.connections.bench', ['driver' => 'sqlite', 'database' => $directory . '/database.sqlite', 'prefix' => '', 'foreign_key_constraints' => true]);
$config->set('cache.stores.file.path', $directory . '/cache');
$config->set('laranail.settings.schema.path', $directory . '/settings-schema.php');
$config->set('laranail.settings.layers.shipped.path', $directory . '/none.php');
$config->set('laranail.settings.stores.settings.layers', ['database']);
$config->set('laranail.settings.stores.settings.owners', ['owner', 'team']);
$config->set('laranail.settings.stores.settings.inherits', true);
$config->set('laranail.settings.audit.sinks', ['null']);
$config->set('laranail.settings.cache', $cache + ['prefix' => 'bench', 'ttl' => 3600, 'stale' => 300]);

Artisan::call('migrate', ['--path' => dirname(__DIR__) . '/database/migrations', '--realpath' => true]);

$settings = $this->app->make(Settings::class);
$this->owner = new BenchOwner(1, 7);

foreach (self::KEYS as $index => $key) {
match ($index % 3) {
0 => $settings->set($key, 'global-' . $index),
1 => $settings->for(new OwnerRef('team', '7'))->set($key, 'team-' . $index),
default => $settings->for(new OwnerRef('owner', '1'))->set($key, 'owner-' . $index),
};
}

// Fill the cache once, so the warm subjects start warm.
$this->request();
}
}
7 changes: 6 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@
},
"autoload-dev": {
"psr-4": {
"Simtabi\\Laranail\\Settings\\Tests\\": "tests/"
"Simtabi\\Laranail\\Settings\\Tests\\": "tests/",
"Simtabi\\Laranail\\Settings\\Benchmarks\\": "benchmarks/"
}
},
"scripts": {
Expand All @@ -76,6 +77,10 @@
"test-coverage": "@test --coverage --min=90",
"test-dirty": "@test --dirty --compact",
"mutate": "vendor/bin/pest --mutate --everything --exclude-group=matrix --min=70",
"bench": [
"@composer --working-dir=tools/phpbench update --no-interaction --no-progress --quiet",
"tools/phpbench/vendor/bin/phpbench run --config=phpbench.json --report=settings"
],
"lint": [
"@pint",
"@phpstan",
Expand Down
20 changes: 20 additions & 0 deletions config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,26 @@
'retry_on_conflict' => true,
],

/*
| The settings cache (database layers only; file layers are read directly).
| It holds each scope's raw rows (a "bag"), keyed by connection, database,
| tenant, store and scope, and is invalidated on every write by replacing a
| generation token, so a write is visible on the next read everywhere.
| `store` is a cache store from config/cache.php (null: the default one;
| it must exist, and a node-local store such as `array` or `file` is only
| right for a single server). `ttl` is how long a bag is fresh; for `stale`
| seconds after that it is still answered while it is refreshed in the
| background (Cache::flexible()); 0 turns that off. `prefix` starts every
| key, so two applications can share a cache store.
*/
'cache' => [
'enabled' => env('LARANAIL_SETTINGS_CACHE', true),
'store' => env('LARANAIL_SETTINGS_CACHE_STORE'),
'prefix' => 'laranail-settings',
'ttl' => 3600,
'stale' => 300,
],

/*
| Events after which the schema readiness memo is forgotten, besides
| migrations, queued jobs and Octane requests: tenant switches. db-tools has
Expand Down
Loading
Loading