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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 2 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
* text=auto eol=lf

# 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.
# src, config, database, routes, resources, helpers, README, LICENSE, CHANGELOG and composer.json ship.
/.github export-ignore
/.claude export-ignore
/benchmarks export-ignore
/docs export-ignore
/tests export-ignore
Expand Down
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- `laranail::settings.show {key} [--store=] [--owner=] [--locale=] [--reveal]`: prints how one
setting resolves (value, layer, scope, type, version, locked, encrypted and sensitive flags, and
the latest audit entry), through the same `ExplainSetting` action as `explain()`. Sensitive and
encrypted values print as `[protected]` unless `--reveal` is given.
- `doctor` warns, without failing, about a stored value or a code or config definition whose key's
first segment is not its category's slug (`<store>: category keys`, `definitions: category keys`).
- `Logging\LogContext`: every operational log entry's context now starts with `store`, `key`,
`scope`, `actor` and `channel`, in that order and `null` where the entry has none. Refusals,
write retries, cache failures, alert failures, skipped persisted entries, runtime configuration
changes and log-sink audit entries all use it, so one log query finds every entry about a setting.

- Consumer conveniences on the `Settings` contract, each a thin delegation onto the existing read
and write paths: `missing()`, `many()` (keys or `key => default` pairs), `setMany()` and
`forgetMany()` (one write each, not atomic), `remember()` (read-through: writes a computed value
Expand Down Expand Up @@ -198,6 +209,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Prepared for the public release. Source, config, migration, route, helper and test comments are
rewritten as short plain docblocks, with no references to internal planning documents; the
design rationale they carried is now in `docs/architecture.md`. Comment lines in `src/` went
from 3,784 to 2,743. No behaviour changed.
- The migration builds each table in one method with a flat column list; the values table's
indexes moved to `indexValues()`. Every column, type, index name and foreign key is unchanged,
verified by diffing the SQLite schema of the default and the full shape before and after.
- The service provider is split into one private method per concern (`registerDrivers()`,
`registerStores()`, `registerCache()`, `registerLogging()`, `registerAudit()`,
`registerAccess()`, `registerAlerts()`, `bootReadinessFlush()`, `bootListeners()`, …), so
`register()` and `boot()` read as a table of contents. No binding changed.
- README: the Tests, Static analysis and MIT badges, with a note that the package is not on
Packagist; `.gitattributes` also export-ignores `.claude`.
- The package is wired the way Laravel wires an application (conventions review, 2026-11-10).
`routes/api.php` declares every REST route by hand in named, nested groups, each `http.routes`
switch an `if` around its group; the service provider loads it once, under `http.prefix`/v1 and
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# laranail/settings

No badges yet: the package is not on a registry and its CI history is only days old.
They are added once each claim is true.
[![Tests](https://github.com/laranail/settings/actions/workflows/tests.yml/badge.svg)](https://github.com/laranail/settings/actions/workflows/tests.yml)
[![Static analysis](https://github.com/laranail/settings/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/laranail/settings/actions/workflows/static-analysis.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

`laranail/settings` is not published to Packagist, so there is no registry-version badge to show: see [Install](#install).

> Key-value settings for any Laravel owner (the application, a user, a tenant, a product), stored in layered stores that work before the database exists.

Expand Down
325 changes: 139 additions & 186 deletions config/settings.php

Large diffs are not rendered by default.

258 changes: 127 additions & 131 deletions database/migrations/create_laranail_settings_tables.php

Large diffs are not rendered by default.

113 changes: 103 additions & 10 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,22 @@ them. The design borrows from each and credits them here as each idea lands.
Driver names arrive from configuration, and in multi-tenant installs possibly from database rows.
Resolving them through an enum with an exhaustive `match` (the pattern `laranail/captcha` uses)
means a name that is not a known driver resolves to nothing, rather than being interpolated into a
method call. Custom drivers are registered with closures, never class names.
method call. Custom drivers are registered with closures, never class names. The same holds for a stored
`type`: it must be a registered caster alias, and the rules a definitions-table row carries are
filtered through `definitions.allowed_rules`, so no row can make the package run arbitrary code.

## Why fail closed after installation?

A short database outage on a live install must not quietly serve shipped defaults (for example a
maintenance flag) or scatter writes into each server's local file. Falling back is allowed only on
positive evidence that installation is still in progress.
positive evidence that installation is still in progress: the operator's `bootstrap` flag, or
laranail/installer-headless reporting an install under way. Its `isInstalled()` is not used,
because it probes the database, and an outage would read as "not installed". A required layer
that cannot be reached raises `DriverUnavailable`.

The encrypter is resolved only when a value is encrypted or decrypted, so an application without
an `APP_KEY` yet still boots and reads its unencrypted settings. Decryption also tries the keys in
`APP_PREVIOUS_KEYS`.

## Why version-checked writes?

Expand All @@ -96,13 +105,24 @@ index, which the driver reports as `ConcurrentModification`. A plain upsert cann
version, so it is not used. The insert runs in a savepoint, because on Postgres a failed
statement would otherwise abort the whole surrounding transaction.

A write tries an update at the expected version, then the restore of a trashed row at that
version, then an insert. The one retry of a plain `set()` re-reads the row `FOR UPDATE`, because
under MySQL's REPEATABLE READ a plain re-read returns the old snapshot. A row created again after
a forget continues its version from the history, so "version N" always names one value. An
approved change request is applied against the version it was opened at, and a rollback is
written as a new version through the same pipeline, so it can itself be rolled back.

## Why is the audit row in the write's transaction?

An audit trail that can miss a change is not an audit trail. With a database layer, the change
and its audit row commit together, so a failed audit insert rolls the change back. Denials and
failures are written outside any transaction, because there is nothing to roll back and the
record of the refusal must survive it.

`AuditedTransaction` is the single commit path for every write action, category change and
promotion. On failure it rolls back, records a `failed` entry outside the transaction and
rethrows the original exception, which still wins if recording the failure fails too.

## Why is `scope` a column, not just `settable_type` and `settable_id`?

A unique index treats `NULL`s as distinct, so global rows (no owner) could repeat. `scope`
Expand All @@ -114,7 +134,7 @@ Postgres. `settable_*` remain for reporting and for an application's own `morphT

The package is used from controllers, jobs, commands and other packages, and it cannot know which of those calls are on a person's behalf. So the caller says: `as($user)` makes every operation, reads included, go through one `Authorizer` seam (Laravel's gate by default, so a host's existing policies and `Gate::before` rules apply), and is audited with who did it and why. Code that passes no actor is the application itself and keeps working unchanged, audited as `system`; a host that wants every call attributed turns on `authorization.require_actor`, and trusted code then has to say `asSystem()`. Undefined abilities deny, so forgetting to define a gate fails closed. A token is a ceiling on top of the gate, never a grant, so a leaked token cannot exceed its owner.

Every write is one `final` action (`Actions\SetSetting`, …) that authorizes, writes and audits. The PHP API delegates to it today; console commands and the REST API will delegate to the same actions, so the rules cannot drift between channels.
Every write is one `final` action (`Actions\SetSetting`, …) that authorizes, writes and audits. The PHP API, the console commands and the REST API all delegate to these actions, so the rules cannot drift between channels.

## Why are the table shapes switches, and why are they recorded?

Expand Down Expand Up @@ -184,19 +204,26 @@ costs nothing. Another tenancy package adds its event to the list.

The cache holds each scope's raw rows (a "bag"), never resolved values. A resolved value depends
on every scope the cascade walked (owner, team, tenant, global), so caching it would make a write
to `team:7` stale in every user's entry that inherited from it, with no cheap way to find them
(G-32). A bag depends on one scope only: the write invalidates exactly one entry and every
to `team:7` stale in every user's entry that inherited from it, with no cheap way to find them.
A bag depends on one scope only: the write invalidates exactly one entry and every
inheriting user resolves the new value on the next read, in memory, from bags that are still
valid. Resolution stays a pure function of the bags, so `explain()` and the cascade behave the
same cached or not.

Invalidation replaces a random generation token instead of deleting the entry, so a
stale-while-revalidate refresh started before a write can only land under a generation no reader
uses any more (R-23), and an evicted token cannot revive an old entry the way a restarted counter
could (R-41). The key hashes connection, database, tenant, store, table and scope as a
uses any more, and an evicted token cannot revive an old entry the way a restarted counter
could. The key hashes connection, database, tenant, store, table and scope as a
length-prefixed tuple, so neither a shared cache store nor a `:` inside a scope can make two
tenants or databases meet (G-37, R-63). While a transaction is open on a layer's connection the
layer bypasses the cache, so nothing uncommitted is ever cached.
tenants or databases meet. While a transaction is open on a layer's connection the
layer bypasses the cache, so nothing uncommitted is ever cached; so does a layer in bootstrap
mode, so the empty answers before installation are never cached.

A bag holds every row of its scope, not only the autoload rows, because a cached bag is treated
as complete: a partial bag would turn a non-autoload value into a miss. It is stored as plain
arrays, never objects, so the cache never unserializes a package class (applications may restrict
`cache.serializable_classes`), and an entry written by another release, or a corrupted one, reads
as a miss, never as an empty scope.

Measured with `composer bench` (phpbench 1.7, PHP 8.5.7, SQLite file database, 200 revolutions x
5 iterations per subject; one revolution is one request reading ten settings through
Expand All @@ -222,12 +249,78 @@ The package ships no views, Blade components, Livewire, Filament or assets. A se

## Why the REST API lives in the package

The API is a channel, not a product: every endpoint runs an action the PHP API already runs, with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once. The routes are declared by hand in `routes/api.php`, each controller method takes the action it runs as a parameter, and a test reading the live router fails when a route names no controller method, a controller method is not routed, or one does not delegate to an action. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless.
The API is a channel, not a product: every endpoint runs an action the PHP API already runs, with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside and drift a release behind the engine whenever an action changed; it lives here so one pull request changes a capability in every channel at once. The routes are declared by hand in `routes/api.php`, each controller method takes the action it runs as a parameter, and a test reading the live router fails when a route names no controller method, a controller method is not routed, or one does not delegate to an action. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless.

## Why change requests are a table

A write that needs approval has to outlive the request that proposed it: the approver acts later, from another request, maybe another server, and a queue or a cache entry can be evicted before anyone looks. So a proposal is a row, written in the same transaction as its `pending` audit entry, on the store's own connection (one table per connection, like the history), with the proposed value stored exactly as the values table would store it, encrypted for an encrypted definition. Keeping the base version on the row is what makes applying it safe: the approval writes through the version-checked update, so a setting that changed in the meantime is never overwritten and the request becomes `stale`. Requests are keyed by ULID, so the table never depends on `ids.type`, and the table is a schema switch (`approvals.table`) like the history.

## Why code definitions win over the definitions table

The definitions table holds `is_system` copies of code and config definitions for admin screens,
and they are never read back: code stays the source of truth, so a synced copy from an older
release cannot override a new release's default. A row edited at runtime only answers for a key no
code definition covers.

## Why owners are stored by morph alias

Owners are referenced by alias and id (`user:7`), never by class name. Renaming a model class
orphans nothing, resolving a parent loads no model, and an alias read from the database is never
instantiated as a class. `rescope` renames an alias in values, history and change requests, and
leaves the audit trail as it was, because the trail records what happened under the old name.

## Why keys and locales are normalised

Keys are lower-cased and may not contain hyphens, which keeps the key-to-slug mapping one-to-one
(`mail.host` and `mail-host`). Locales normalise to `ll` or `ll_CC`, so two spellings never become
two rows. The identity columns are binary-collated so MySQL compares them the way the other
databases do.

## Why events carry no values

Every event carries identifiers only, so a queued listener cannot leak a secret into the jobs
table. Most events dispatch after commit. `AccessWasDenied` and `VerificationWasRequired`
dispatch at once, because the refusal usually rolls the surrounding transaction back and a
security listener must still hear of it.

## Why alerts never throw

An alert reports a change that has already committed, so an alert that cannot be sent is logged
rather than raised. When the throttle's cache fails the alert is sent anyway: a repeated alert is
better than a missed one.

## Why persisted configuration loads lazily

Persisted stores and layers are read on first use, never at boot, and an invalid row is logged and
skipped (`doctor` lists it), so a bad row cannot stop the application from booting. A persisted
entry may not re-layer a store the configuration file defines, because moving data between drivers
is `promote`'s job.

## Why promotion never copies shipped defaults

`promote` copies only values written to the runtime file before installation, so a later release
can still change a shipped default. The runtime file is archived afterwards, so a second run does
nothing. Its lock is only as wide as the cache store, so a multi-server install needs a shared
cache.

## Why install checks for foreign tables

A bare `settings` table plausibly belongs to the application. Installing over it would fail half
way or write into it, so `install` recognises the package's tables by columns only they have and
refuses to run over anything else. An unreachable database is not reported as foreign.

## Why `settings()` is namespaced

A global `settings()` function is a name many packages and applications already define, and a
second definition either fatals or silently wins. The helper lives in the package's namespace.

## Why the models get a static context

Eloquent builds models with `new static`, so nothing can be injected into them. The provider gives
`ModelContext` closures that resolve the scoped schema, tenant and default store on each call, so
no request or tenant state is held statically. The engine never reads through the models; they
exist for factories, seeders, admin screens and tests.

## How the container builds it

Most classes are autowired. A class's lifetime is an attribute on the class (`#[Scoped]` for
Expand Down
2 changes: 1 addition & 1 deletion docs/tools/approvals.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Approvals

Four-eyes changes (§16.7): a write to a setting that needs approval becomes a change request, and is applied only after someone else approves it.
Four-eyes changes: a write to a setting that needs approval becomes a change request, and is applied only after someone else approves it.

## Which writes need approval

Expand Down
18 changes: 17 additions & 1 deletion docs/tools/audit-and-logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,23 @@ Schedule::command('laranail::settings.prune-audit')->weekly();

## The operational log

Refusals are logged as warnings, and runtime configuration changes and log-sink audit entries at `info`, with store, key, scope and actor identifiers.
Refusals are logged as warnings, and runtime configuration changes and log-sink audit entries at `info`.

Every entry's context starts with the same five keys, in this order, `null` where the entry has
none, followed by anything specific to the entry (`reason`, `operation`, `event`, …). No context
holds a value.

| Context key | Holds |
|---|---|
| `store` | the store name |
| `key` | the setting key |
| `scope` | `global` or `alias:id` |
| `actor` | `type`, `alias` and `id` of the actor, plus its `channel` where known |
| `channel` | `php`, `rest`, `console` or `queue` |

So a log query such as `context.store = "settings" and context.key = "mail.host"` finds every
entry about one setting, whichever part of the package wrote it. The keys are listed in
`Logging\LogContext::KEYS`.

| Key | Default | Effect |
|---|---|---|
Expand Down
2 changes: 1 addition & 1 deletion docs/tools/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ A read through the cascade (owner, parents, global) costs, per distinct store in
A bag's key is `<prefix>:<sha1>:<sha1 of its generation>`. The first hash covers connection
name, database name, tenant, store, table and scope as a length-prefixed tuple, so
`a` + `b:c` and `a:b` + `c` never meet, and neither do two tenants or two databases that both
have a `global` scope (G-37). The tenant comes from the configured `TenantDiscriminator` in every
have a `global` scope. The tenant comes from the configured `TenantDiscriminator` in every
tenancy mode, `none` included.

## Invalidation
Expand Down
Loading
Loading