diff --git a/.gitattributes b/.gitattributes index 4e9e1ad..0b0023f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,7 +2,7 @@ * text=auto eol=lf # Keep the Composer dist lean: exclude dev-only paths from package archives. -# Source, config, database stubs, README, LICENSE, CHANGELOG and composer.json ship. +# Source, config, database (migration, factories, seeders), README, LICENSE, CHANGELOG and composer.json ship. /.github export-ignore /docs export-ignore /tests export-ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 646d703..6aadcc0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -79,13 +79,13 @@ jobs: - name: Run the database group run: vendor/bin/pest --group=database - # §13: the full product of the schema switches (576 shapes) on SQLite, weekly and on demand. + # §13: the full product of the schema switches (1,152 shapes, tenancy included) on SQLite, weekly and on demand. # Pull requests run the pairwise set (10 shapes) inside the jobs above. matrix-full: name: Schema switches · full product if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 40 env: LARANAIL_SETTINGS_MATRIX: full COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ secrets.GITHUB_TOKEN }}"}}' diff --git a/CHANGELOG.md b/CHANGELOG.md index e3879db..67be44d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- 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 + models included, is limited to it. A `TenantDiscriminator` contract (`NullTenantDiscriminator`, + `ClosureTenantDiscriminator`) picked by `tenancy.discriminator` (`auto` detects stancl/tenancy, + then spatie/laravel-multitenancy; both only suggested). Preloaded records are kept per tenant + in every mode. New enum `TenancyMode`. +- Default categories: `DefaultCategoriesSeeder` (in `database/seeders`, registered with the + application's `db:seed`) creates `seed.categories` (general, appearance, localisation, mail, + notifications, security) as system categories in `seed.stores`, through the settings API as + the system actor; idempotent; `seed.enabled` switches it off. `NewCategory` takes `system`. +- Eloquent models (`Models\Setting`, `SettingCategory`, `SettingDefinition`, + `SettingAuditEntry`) and their factories in `database/factories`, for tests, seeding and admin + screens; they follow the recorded shape and tenancy. The engine itself stays on the query + builder. - Schema switches (design phase 2b, §4.0): `identity.mode` (`slug_uid`, `slug_per_row`, `uid_only`), `ids.type` (`bigint`, `uuid`, `ulid`; follows `laranail.db-tools.id_type` unless set) with matching category keys, `ids.owner_key` (`string`, `typed`), `stores..mode` @@ -46,6 +61,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- The four migration stubs are replaced by one migration, + `database/migrations/create_laranail_settings_tables.php`, which creates categories, the + optional definitions table, every recorded database store's values table (on its own + connection, with that connection's categories and audit tables) and the audit table, in + that order, and drops them in reverse. `install` publishes it; migrations published from the + stubs keep working. `make-store` writes one migration per store, a copy of it pinned to the + store (and connection), instead of up to three stub copies. +- The schema-switch matrix covers `tenancy.mode`: 10 pairwise shapes for 177 pairs per pull + request, 1,152 shapes in the weekly full product. - The migration stubs read the recorded schema shape (or configuration, when nothing is recorded) instead of individual config keys, and run on the store's recorded connection. - `laranail::settings.install` publishes a fourth migration (`create_settings_definitions_table`, diff --git a/README.md b/README.md index da2809e..3afe5c3 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,8 @@ They are added once each claim is true. Requires PHP 8.4.1+ or 8.5 and Laravel 13. Works on MySQL, PostgreSQL and SQLite; SQL Server is not supported in 0.x. -> **Pre-release.** The engine reads and writes through file and config layers today; the -> database layer, caching and history arrive in the next phases. See -> [Getting started](docs/getting-started.md). +> **Pre-release.** The engine reads and writes through database, file and config layers; +> caching and history arrive in the next phases. See [Getting started](docs/getting-started.md). ## Install @@ -24,15 +23,20 @@ composer require laranail/settings ### Getting started -Publish the config and the migrations (`settings`, `settings_categories`, `settings_audit`), then -migrate: the default store reads the database first, then its runtime file, then shipped defaults -from `settings/defaults.php` when that file exists. +Publish the config and the package's one migration (it creates `settings_categories`, a values +table per database store, and `settings_audit`), migrate, and optionally seed the default +categories: the default store reads the database first, then its runtime file, then shipped +defaults from `settings/defaults.php` when that file exists. ```bash php artisan laranail::settings.install php artisan migrate +php artisan db:seed # general, appearance, localisation, mail, notifications, security ``` +For multi-tenant applications set `tenancy.mode` before migrating (see +[Tenancy](docs/tools/tenancy.md)). + An application without a database drops `database` from `stores.settings.layers` and keeps its values in `storage/app/private/laranail/settings/settings.json`. @@ -86,6 +90,8 @@ The hosted docs live at abilities a ceiling on what the token may do." + "laravel/sanctum": "Enables the sanctum actor resolver, which makes a token's settings: abilities a ceiling on what the token may do.", + "stancl/tenancy": "Detected automatically (tenancy.discriminator = auto): settings, categories, audit rows and in-memory reads are kept per tenant.", + "spatie/laravel-multitenancy": "Detected automatically (tenancy.discriminator = auto), like stancl/tenancy." }, "autoload": { "psr-4": { - "Simtabi\\Laranail\\Settings\\": "src/" + "Simtabi\\Laranail\\Settings\\": "src/", + "Simtabi\\Laranail\\Settings\\Database\\Factories\\": "database/factories/", + "Simtabi\\Laranail\\Settings\\Database\\Seeders\\": "database/seeders/" } }, "autoload-dev": { diff --git a/config/settings.php b/config/settings.php index b6a094a..c435dde 100644 --- a/config/settings.php +++ b/config/settings.php @@ -12,10 +12,11 @@ | | php artisan laranail::settings.install | -| The default store keeps its values in the database (publish and run the -| migrations with the install command above), above a JSON runtime file and -| the shipped PHP defaults. An application without a database drops -| `database` from the store's `layers`. +| The default store keeps its values in the database (the install command +| above publishes the package's one migration; then run `php artisan +| migrate`), above a JSON runtime file and the shipped PHP defaults. An +| application without a database drops `database` from the store's +| `layers`. | */ @@ -91,8 +92,9 @@ | Schema switches (migration-time) |-------------------------------------------------------------------------- | - | Read by `install` and `make-store`, which record the shape they produce - | in the schema file (`schema.path`, default database/settings-schema.php). + | Read by `install` and `make-store`, which record the shape the package + | migration produces in the schema file (`schema.path`, default + | database/settings-schema.php); the migration reads that file. | The package then reads that file, not these keys, so changing a switch | after migrating changes nothing until a migration says so; `doctor` | reports the drift. The defaults are the recommended shape. @@ -128,6 +130,54 @@ 'soft_deletes' => false, ], + /* + |-------------------------------------------------------------------------- + | Tenancy + |-------------------------------------------------------------------------- + | + | mode (migration-time, recorded in the schema file): + | `none` one set of settings for the application (the default); + | `column` one database: the values, categories and audit tables get a + | `tenant` column, every row is stamped with the current tenant + | and every query is limited to it ('' is the central rows); + | `database` a database per tenant, switched by the tenancy package: no + | tenant column; publish the migration into the tenant + | migrations folder. + | discriminator: who the current tenant is. `auto` uses stancl/tenancy or + | spatie/laravel-multitenancy when installed (neither is required), else + | none; or `null`, `stancl`, `spatie`, or a class implementing + | Simtabi\Laranail\Settings\Contracts\TenantDiscriminator. In every mode + | the tenant also keys what is held in memory during a request or job. + | Definitions are shared by every tenant. + */ + 'tenancy' => [ + 'mode' => env('LARANAIL_SETTINGS_TENANCY', 'none'), + 'discriminator' => 'auto', + ], + + /* + | Default data, seeded with the application's `php artisan db:seed` (or + | `db:seed --class="Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder"`). + | `categories` are created as system categories in each of `stores` (empty: + | the default store), as the system actor, so they are validated and + | audited; one that already exists is left as it is, so seeding twice + | changes nothing. A category is `slug => title` or `slug => [title, + | description, icon, parent, sort_order, translations]`. No setting values + | and never any credentials are seeded. `enabled` false switches it off. + */ + 'seed' => [ + 'enabled' => env('LARANAIL_SETTINGS_SEED', true), + 'stores' => [], + 'categories' => [ + 'general' => ['title' => 'General', 'description' => 'Site name, contact details and other application-wide settings.', 'icon' => 'cog'], + 'appearance' => ['title' => 'Appearance', 'description' => 'Theme, branding and layout.', 'icon' => 'swatch'], + 'localisation' => ['title' => 'Localisation', 'description' => 'Language, time zone, date and number formats.', 'icon' => 'globe'], + 'mail' => ['title' => 'Mail', 'description' => 'Sender name and address, and other mail options.', 'icon' => 'envelope'], + 'notifications' => ['title' => 'Notifications', 'description' => 'Which notifications are sent, and how.', 'icon' => 'bell'], + 'security' => ['title' => 'Security', 'description' => 'Sign-in, sessions and other security options.', 'icon' => 'shield'], + ], + ], + /* | Writes. `retry_on_conflict` retries a plain set() once when another writer | changed the row between the read and the write (re-reading it under a row diff --git a/database/factories/SettingAuditEntryFactory.php b/database/factories/SettingAuditEntryFactory.php new file mode 100644 index 0000000..ee14b95 --- /dev/null +++ b/database/factories/SettingAuditEntryFactory.php @@ -0,0 +1,54 @@ + + */ +final class SettingAuditEntryFactory extends Factory +{ + protected $model = SettingAuditEntry::class; + + /** @return array */ + public function definition(): array + { + return [ + 'occurred_at' => now(), + 'action' => AuditAction::Update->value, + 'outcome' => AuditOutcome::Allowed->value, + 'store' => ModelContext::defaultStore()->value, + 'scope' => 'global', + 'key' => 'test.key', + 'actor_type' => ActorType::System->value, + 'channel' => Channel::Console->value, + ]; + } + + public function action(AuditAction $action, AuditOutcome $outcome = AuditOutcome::Allowed): static + { + return $this->state(['action' => $action->value, 'outcome' => $outcome->value]); + } + + public function by(string $alias, int|string $id): static + { + return $this->state(['actor_type' => ActorType::User->value, 'actor_alias' => $alias, 'actor_id' => (string) $id]); + } + + public function at(DateTimeInterface $when): static + { + return $this->state(['occurred_at' => $when]); + } +} diff --git a/database/factories/SettingCategoryFactory.php b/database/factories/SettingCategoryFactory.php new file mode 100644 index 0000000..27b39c1 --- /dev/null +++ b/database/factories/SettingCategoryFactory.php @@ -0,0 +1,76 @@ +forStore('user_settings')->system()->create(['slug' => 'mail']); + * SettingCategory::factory()->parent($general)->create(); + * + * @extends Factory + */ +final class SettingCategoryFactory extends Factory +{ + protected $model = SettingCategory::class; + + /** Text as `translations.mode` stores it: as is, or `{"": text}` (the text for any locale), as the engine writes it. */ + public static function text(string $text): string + { + if (ModelContext::shape()->translations !== TranslationsMode::Json) { + return $text; + } + + return json_encode(['' => $text], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + /** @return array */ + public function definition(): array + { + $slug = 'category-' . Str::lower(Str::random(10)); + + return [ + 'store' => ModelContext::defaultStore()->value, + 'slug' => $slug, + 'title' => self::text(Str::headline($slug)), + 'description' => null, + 'icon' => null, + 'sort_order' => 0, + 'is_system' => false, + ]; + } + + /** In this store (default: the default store). */ + public function forStore(string $store): static + { + return $this->state(['store' => $store]); + } + + /** Shipped by code: `is_system`, which UIs do not let anyone delete. */ + public function system(): static + { + return $this->state(['is_system' => true]); + } + + /** Under a parent, in the parent's store. */ + public function parent(SettingCategory $parent): static + { + return $this->state(['parent_id' => $parent->getKey(), 'store' => $parent->store]); + } + + /** A title (and optionally a description) as the shape stores them. */ + public function titled(string $title, ?string $description = null): static + { + return $this->state(['title' => self::text($title), 'description' => $description === null ? null : self::text($description)]); + } +} diff --git a/database/factories/SettingDefinitionFactory.php b/database/factories/SettingDefinitionFactory.php new file mode 100644 index 0000000..99776d5 --- /dev/null +++ b/database/factories/SettingDefinitionFactory.php @@ -0,0 +1,52 @@ + + */ +final class SettingDefinitionFactory extends Factory +{ + protected $model = SettingDefinition::class; + + /** @return array */ + public function definition(): array + { + $key = 'test.' . Str::lower(Str::random(12)); + + return [ + 'store' => ModelContext::defaultStore()->value, + 'key' => $key, + 'slug' => str_replace('.', '-', $key), + 'group' => 'test', + 'type' => 'string', + 'default' => null, + 'is_system' => false, + ]; + } + + public function forStore(string $store): static + { + return $this->state(['store' => $store]); + } + + public function key(string $key): static + { + return $this->state(['key' => $key, 'slug' => str_replace('.', '-', $key), 'group' => explode('.', $key, 2)[0]]); + } + + public function system(): static + { + return $this->state(['is_system' => true]); + } +} diff --git a/database/factories/SettingFactory.php b/database/factories/SettingFactory.php new file mode 100644 index 0000000..9b10395 --- /dev/null +++ b/database/factories/SettingFactory.php @@ -0,0 +1,100 @@ +forStore('settings')->key('site.name')->value('Acme')->create(); + * Setting::factory()->owner('user', 42)->key('ui.theme')->value('dark')->create(); + * + * @extends Factory + */ +final class SettingFactory extends Factory +{ + protected $model = Setting::class; + + /** @return array */ + public function definition(): array + { + $key = 'test.' . Str::lower(Str::random(12)); + + return $this->identity($key) + [ + 'scope' => 'global', + 'key' => $key, + 'group' => 'test', + 'locale' => '', + 'value' => json_encode(null), + 'version' => 1, + ]; + } + + /** Rows of this store's table (default: the default store). */ + public function forStore(string $store): static + { + return $this->afterMaking(static function (Setting $setting) use ($store): void { + $setting->inStore($store); + }); + } + + public function key(string $key): static + { + return $this->state(fn (): array => ['key' => $key, 'group' => explode('.', $key, 2)[0]] + $this->identity($key)); + } + + /** The value, encoded as the pipeline encodes an unencrypted value. */ + public function value(mixed $value): static + { + return $this->state(['value' => json_encode($value, JSON_THROW_ON_ERROR)]); + } + + /** An owner row of a polymorphic store: scope `:`. */ + public function owner(string $alias, int|string $id): static + { + return $this->state(['scope' => $alias . ':' . $id, 'settable_type' => $alias, 'settable_id' => (string) $id]); + } + + public function locale(string $locale): static + { + return $this->state(['locale' => $locale]); + } + + public function locked(): static + { + return $this->state(['is_locked' => true]); + } + + public function inCategory(SettingCategory $category): static + { + return $this->state(['category_id' => $category->getKey(), 'category_store' => $category->store]); + } + + /** @return array the slug and uid columns the identity mode has */ + private function identity(string $key): array + { + $mode = ModelContext::shape()->identity; + $columns = []; + + if ($mode->hasSlug()) { + $columns['slug'] = $mode === IdentityMode::SlugPerRow ? sha1('global|' . $key . '|') : str_replace('.', '-', $key); + } + + if ($mode->hasUid()) { + $columns['uid'] = (string) Str::ulid(); + } + + return $columns; + } +} diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php new file mode 100644 index 0000000..a30e61b --- /dev/null +++ b/database/migrations/create_laranail_settings_tables.php @@ -0,0 +1,391 @@ +pinnedConnection ?? $this->shape()->store($this->primaryStore())->connection; + } + + public function up(): void + { + foreach ($this->plan() as $connection => $tables) { + $shape = $this->shape(); + + if ($tables['shared'] && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->categories()))) { + $this->createCategories($connection, $shape); + } + + if ($tables['definitions']) { + $this->createDefinitions($connection, $shape); + } + + foreach ($tables['stores'] as $store) { + // A store's own copy skips a table the full migration already created (a + // `migrate:fresh` replays both: the full one creates every recorded store). + if ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->store($store->name, $store->table))) { + $this->createValues($connection, $shape, $store); + } + } + + if ($tables['shared'] && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->audit()))) { + $this->createAudit($connection, $shape); + } + } + } + + public function down(): void + { + $shape = $this->shape(); + + foreach (array_reverse($this->plan(), true) as $connection => $tables) { + $schema = Schema::connection($connection); + + if ($tables['shared']) { + $schema->dropIfExists($shape->names->audit()); + } + + foreach (array_reverse($tables['stores']) as $store) { + $schema->dropIfExists($shape->names->store($store->name, $store->table)); + } + + if ($tables['definitions']) { + $schema->dropIfExists($shape->names->definitions()); + } + + if ($tables['shared']) { + $schema->dropIfExists($shape->names->categories()); + } + } + } + + /** + * What to create on each connection, the default store's connection first. + * + * @return array}> + */ + private function plan(): array + { + $shape = $this->shape(); + $main = $this->connectionOf($shape->store($this->primaryStore())); + + if ($this->only !== null) { + $store = $shape->store(new StoreName($this->only)); + $connection = $this->pinnedConnection ?? $this->connectionOf($store); + + return [$connection => ['shared' => $this->pinnedConnection !== null, 'definitions' => false, 'stores' => [$store]]]; + } + + $plan = [$main => ['shared' => true, 'definitions' => $shape->definitionsTable, 'stores' => []]]; + + foreach ($shape->stores as $store) { + $connection = $this->connectionOf($store); + $plan[$connection] ??= ['shared' => true, 'definitions' => false, 'stores' => []]; + $plan[$connection]['stores'][] = $store; + } + + return $plan; + } + + private function createCategories(string $connection, SchemaShape $shape): void + { + $name = $shape->names->categories(); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($name, $shape): void { + $this->key($table, 'id', $shape->ids, primary: true); + $this->tenant($table, $shape); + $table->string('store', 64); + $this->key($table, 'parent_id', $shape->ids)->nullable(); + $this->translatable($table, 'title', $shape, nullable: false); + $table->string('slug', 128); + $this->translatable($table, 'description', $shape); + $table->string('icon')->nullable(); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('is_system')->default(false); + $table->json('meta')->nullable(); + $table->timestamps(); + + if ($shape->categoriesSoftDeletes) { + $table->timestamp('deleted_at')->nullable(); + } + + $table->unique([...$this->tenantColumns($shape), 'store', 'slug'], $name . '_store_slug_unique'); + $table->unique(['id', 'store'], $name . '_id_store_unique'); + $table->index('parent_id', $name . '_parent_index'); + $table->foreign('parent_id', $name . '_parent_foreign')->references('id')->on($name)->nullOnDelete(); + }); + } + + private function createDefinitions(string $connection, SchemaShape $shape): void + { + $name = $shape->names->definitions(); + $categories = $shape->names->categories(); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($categories, $name, $shape): void { + $this->key($table, 'id', $shape->ids, primary: true); + $table->string('store', 64); + $table->string('slug', 191); + $table->string('key', 191); + $table->string('group', 64); + $this->key($table, 'category_id', $shape->ids)->nullable(); + $table->string('type', 64)->nullable(); + $table->longText('default')->nullable(); + $this->translatable($table, 'label', $shape); + $this->translatable($table, 'description', $shape); + $table->json('rules')->nullable(); + $table->boolean('is_encrypted')->default(false); + $table->boolean('is_public')->default(false); + $table->boolean('is_locked')->default(false); + $table->boolean('autoload')->default(true); + $table->boolean('inherits')->nullable(); + $table->json('overridable_by')->nullable(); + $table->boolean('is_system')->default(false); + $table->json('meta')->nullable(); + $table->timestamps(); + + $table->unique(['store', 'key'], $name . '_store_key_unique'); + $table->unique(['store', 'slug'], $name . '_store_slug_unique'); + $table->index('category_id', $name . '_category_index'); + $table->foreign('category_id', $name . '_category_foreign')->references('id')->on($categories)->nullOnDelete(); + }); + } + + /** + * One store's values. Identity is (tenant, scope, key, locale); those columns are + * binary-collated so `Theme` and `theme`, or `pt_BR` and `pt_br`, cannot become one row on + * MySQL only (G-38). + */ + private function createValues(string $connection, SchemaShape $shape, StoreSchema $store): void + { + $name = $shape->names->store($store->name, $store->table); + $categories = $shape->names->categories(); + $index = substr($name, 0, 40); + $binary = match (DB::connection($connection)->getDriverName()) { + 'mysql', 'mariadb' => 'utf8mb4_bin', + 'pgsql' => 'C', + default => null, + }; + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $categories, $index, $shape, $store): void { + $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); + + $this->key($table, 'id', $shape->ids, primary: true); + + if ($shape->tenancy === TenancyMode::Column) { + $collate($table->string('tenant', 64)->default('')); + } + + if ($store->isDedicated()) { + $this->key($table, 'owner_id', $store->ownerKeyType); + } else { + $table->string('settable_type', 64)->nullable(); + $shape->ownerKey === OwnerKeyType::Typed + ? $this->key($table, 'settable_id', $shape->ownerKeyType)->nullable() + : $table->string('settable_id', 36)->nullable(); + } + + $collate($table->string('scope', 128)); + $this->key($table, 'category_id', $shape->ids)->nullable(); + $table->string('category_store', 64)->nullable(); + $table->string('group', 64); + $collate($table->string('key', 191)); + + if ($shape->identity->hasSlug()) { + $collate($table->string('slug', $shape->identity === IdentityMode::SlugPerRow ? 40 : 191)->nullable()); + } + + if ($shape->identity->hasUid()) { + $table->char('uid', 26)->nullable(); + } + + $collate($table->string('locale', 16)->default('')); + $table->longText('value')->nullable(); + $table->string('type', 64)->nullable(); + $this->translatable($table, 'label', $shape); + $this->translatable($table, 'description', $shape); + $table->boolean('is_encrypted')->default(false); + $table->boolean('is_locked')->default(false); + $table->boolean('is_public')->default(false); + $table->boolean('autoload')->default(true); + $table->unsignedInteger('sort_order')->default(0); + $table->json('meta')->nullable(); + $table->unsignedInteger('version')->default(1); + $table->timestamps(); + + if ($store->softDeletes) { + $table->timestamp('deleted_at')->nullable(); + } + + $tenant = $this->tenantColumns($shape); + $table->unique([...$tenant, 'scope', 'key', 'locale'], $index . '_identity_unique'); + + if ($shape->identity->hasUid()) { + $table->unique('uid', $index . '_uid_unique'); + } + + match ($shape->identity) { + IdentityMode::SlugPerRow => $table->unique([...$tenant, 'slug'], $index . '_slug_unique'), + IdentityMode::SlugUid => $table->index('slug', $index . '_slug_index'), + IdentityMode::UidOnly => null, + }; + + if ($store->isDedicated()) { + $table->index('owner_id', $index . '_owner_index'); + $table->foreign('owner_id', $index . '_owner_foreign') + ->references($store->ownerKey)->on((string) $store->ownerTable)->cascadeOnDelete(); + } else { + $table->index(['settable_type', 'settable_id'], $index . '_settable_index'); + } + + $table->index('category_id', $index . '_category_index'); + $table->index(['autoload', 'scope'], $index . '_autoload_index'); + $table->foreign(['category_id', 'category_store'], $index . '_category_foreign') + ->references(['id', 'store'])->on($categories)->nullOnDelete(); + }); + } + + /** The audit trail (§16.8): who did what, when and through which channel. No value column. */ + private function createAudit(string $connection, SchemaShape $shape): void + { + $name = $shape->names->audit(); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($name, $shape): void { + $table->char('id', 26)->primary(); + $this->tenant($table, $shape); + $table->timestamp('occurred_at'); + $table->string('action', 32); + $table->string('outcome', 16); + $table->string('store', 64)->nullable(); + $table->string('scope', 128)->nullable(); + $table->string('key', 191)->nullable(); + $table->string('locale', 16)->nullable(); + $table->unsignedInteger('version_from')->nullable(); + $table->unsignedInteger('version_to')->nullable(); + $table->char('change_request', 26)->nullable(); + $table->string('actor_type', 16); + $table->string('actor_alias', 64)->nullable(); + $table->string('actor_id', 64)->nullable(); + $table->string('channel', 16); + $table->string('ip', 45)->nullable(); + $table->string('user_agent')->nullable(); + $table->string('request_id')->nullable(); + $table->text('reason')->nullable(); + $table->json('meta')->nullable(); + + $table->index('occurred_at', $name . '_occurred_index'); + $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key'], $name . '_subject_index'); + $table->index(['actor_alias', 'actor_id'], $name . '_actor_index'); + }); + } + + /** + * A key column typed per `ids.type`. The primary key is an explicit command, not the fluent + * ->primary(): Laravel appends fluent indexes after every other command, so PostgreSQL would + * see a self-referencing foreign key before the key it references (SQLSTATE 42830). + */ + private function key(Blueprint $table, string $column, IdType $type, bool $primary = false): ColumnDefinition + { + if ($primary && $type === IdType::Bigint) { + return $table->bigIncrements($column); + } + + $definition = match ($type) { + IdType::Bigint => $table->unsignedBigInteger($column), + IdType::Uuid => $table->char($column, 36), + IdType::Ulid => $table->char($column, 26), + }; + + if ($primary) { + $table->primary($column); + } + + return $definition; + } + + /** A title, label or description: text, or a JSON map of locale to text (D-8). */ + private function translatable(Blueprint $table, string $column, SchemaShape $shape, bool $nullable = true): void + { + $definition = $shape->translations === TranslationsMode::Json + ? $table->json($column) + : ($column === 'title' ? $table->string($column) : $table->text($column)); + + if ($nullable) { + $definition->nullable(); + } + } + + /** The tenant column of column-mode tenancy: '' is the central (no tenant) partition. */ + private function tenant(Blueprint $table, SchemaShape $shape): void + { + if ($shape->tenancy === TenancyMode::Column) { + $table->string('tenant', 64)->default(''); + } + } + + /** @return list */ + private function tenantColumns(SchemaShape $shape): array + { + return $shape->tenancy === TenancyMode::Column ? ['tenant'] : []; + } + + private function primaryStore(): StoreName + { + if ($this->only !== null) { + return new StoreName($this->only); + } + + $default = config('laranail.settings.default', 'settings'); + + return new StoreName(is_string($default) ? $default : 'settings'); + } + + private function connectionOf(StoreSchema $store): string + { + return $store->connection ?? DB::getDefaultConnection(); + } + + private function shape(): SchemaShape + { + return app(SchemaShapeRepository::class)->current(); + } +}; diff --git a/database/migrations/create_settings_audit_table.php.stub b/database/migrations/create_settings_audit_table.php.stub deleted file mode 100644 index d00d500..0000000 --- a/database/migrations/create_settings_audit_table.php.stub +++ /dev/null @@ -1,81 +0,0 @@ -pinnedConnection !== null) { - return $this->pinnedConnection; - } - - $default = config('laranail.settings.default', 'settings'); - - return $this->shape()->store(new StoreName(is_string($default) ? $default : 'settings'))->connection; - } - - public function up(): void - { - $name = $this->table(); - - Schema::connection($this->getConnection())->create($name, static function (Blueprint $table) use ($name): void { - $table->char('id', 26)->primary(); - $table->timestamp('occurred_at'); - $table->string('action', 32); - $table->string('outcome', 16); - $table->string('store', 64)->nullable(); - $table->string('scope', 128)->nullable(); - $table->string('key', 191)->nullable(); - $table->string('locale', 16)->nullable(); - $table->unsignedInteger('version_from')->nullable(); - $table->unsignedInteger('version_to')->nullable(); - $table->char('change_request', 26)->nullable(); - $table->string('actor_type', 16); - $table->string('actor_alias', 64)->nullable(); - $table->string('actor_id', 64)->nullable(); - $table->string('channel', 16); - $table->string('ip', 45)->nullable(); - $table->string('user_agent')->nullable(); - $table->string('request_id')->nullable(); - $table->text('reason')->nullable(); - $table->json('meta')->nullable(); - - $table->index('occurred_at', $name . '_occurred_index'); - $table->index(['store', 'scope', 'key'], $name . '_subject_index'); - $table->index(['actor_alias', 'actor_id'], $name . '_actor_index'); - }); - } - - public function down(): void - { - Schema::connection($this->getConnection())->dropIfExists($this->table()); - } - - private function table(): string - { - return $this->shape()->names->audit(); - } - - private function shape(): Simtabi\Laranail\Settings\Database\SchemaShape - { - return app(SchemaShapeRepository::class)->current(); - } -}; diff --git a/database/migrations/create_settings_categories_table.php.stub b/database/migrations/create_settings_categories_table.php.stub deleted file mode 100644 index cbadaa5..0000000 --- a/database/migrations/create_settings_categories_table.php.stub +++ /dev/null @@ -1,106 +0,0 @@ -pinnedConnection !== null) { - return $this->pinnedConnection; - } - - $default = config('laranail.settings.default', 'settings'); - - return $this->shape()->store(new StoreName(is_string($default) ? $default : 'settings'))->connection; - } - - public function up(): void - { - $shape = $this->shape(); - $name = $shape->names->categories(); - - Schema::connection($this->getConnection())->create($name, static function (Blueprint $table) use ($name, $shape): void { - match ($shape->ids) { - IdType::Bigint => $table->bigIncrements('id'), - IdType::Uuid => $table->char('id', 36), - IdType::Ulid => $table->char('id', 26), - }; - - // An explicit command, not the fluent ->primary(): Laravel appends fluent indexes after - // every other command, so PostgreSQL would see the parent_id foreign key below before - // the key it references and refuse it (SQLSTATE 42830). - if ($shape->ids !== IdType::Bigint) { - $table->primary('id'); - } - - $table->string('store', 64); - - match ($shape->ids) { - IdType::Bigint => $table->unsignedBigInteger('parent_id')->nullable(), - IdType::Uuid => $table->char('parent_id', 36)->nullable(), - IdType::Ulid => $table->char('parent_id', 26)->nullable(), - }; - - if ($shape->translations === TranslationsMode::Json) { - $table->json('title'); - } else { - $table->string('title'); - } - - $table->string('slug', 128); - - if ($shape->translations === TranslationsMode::Json) { - $table->json('description')->nullable(); - } else { - $table->text('description')->nullable(); - } - - $table->string('icon')->nullable(); - $table->unsignedInteger('sort_order')->default(0); - $table->boolean('is_system')->default(false); - $table->json('meta')->nullable(); - $table->timestamps(); - - if ($shape->categoriesSoftDeletes) { - $table->timestamp('deleted_at')->nullable(); - } - - $table->unique(['store', 'slug'], $name . '_store_slug_unique'); - $table->unique(['id', 'store'], $name . '_id_store_unique'); - $table->index('parent_id', $name . '_parent_index'); - $table->foreign('parent_id', $name . '_parent_foreign')->references('id')->on($name)->nullOnDelete(); - }); - } - - public function down(): void - { - Schema::connection($this->getConnection())->dropIfExists($this->shape()->names->categories()); - } - - private function shape(): Simtabi\Laranail\Settings\Database\SchemaShape - { - return app(SchemaShapeRepository::class)->current(); - } -}; diff --git a/database/migrations/create_settings_definitions_table.php.stub b/database/migrations/create_settings_definitions_table.php.stub deleted file mode 100644 index d76e13c..0000000 --- a/database/migrations/create_settings_definitions_table.php.stub +++ /dev/null @@ -1,103 +0,0 @@ -pinnedConnection !== null) { - return $this->pinnedConnection; - } - - $default = config('laranail.settings.default', 'settings'); - - return $this->shape()->store(new StoreName(is_string($default) ? $default : 'settings'))->connection; - } - - public function up(): void - { - $shape = $this->shape(); - - if (! $shape->definitionsTable) { - return; - } - - $name = $shape->names->definitions(); - $categories = $shape->names->categories(); - - Schema::connection($this->getConnection())->create($name, static function (Blueprint $table) use ($categories, $name, $shape): void { - match ($shape->ids) { - IdType::Bigint => $table->bigIncrements('id'), - IdType::Uuid => $table->char('id', 36)->primary(), - IdType::Ulid => $table->char('id', 26)->primary(), - }; - - $table->string('store', 64); - $table->string('slug', 191); - $table->string('key', 191); - $table->string('group', 64); - - match ($shape->ids) { - IdType::Bigint => $table->unsignedBigInteger('category_id')->nullable(), - IdType::Uuid => $table->char('category_id', 36)->nullable(), - IdType::Ulid => $table->char('category_id', 26)->nullable(), - }; - - $table->string('type', 64)->nullable(); - $table->longText('default')->nullable(); - - if ($shape->translations === TranslationsMode::Json) { - $table->json('label')->nullable(); - $table->json('description')->nullable(); - } else { - $table->text('label')->nullable(); - $table->text('description')->nullable(); - } - - $table->json('rules')->nullable(); - $table->boolean('is_encrypted')->default(false); - $table->boolean('is_public')->default(false); - $table->boolean('is_locked')->default(false); - $table->boolean('autoload')->default(true); - $table->boolean('inherits')->nullable(); - $table->json('overridable_by')->nullable(); - $table->boolean('is_system')->default(false); - $table->json('meta')->nullable(); - $table->timestamps(); - - $table->unique(['store', 'key'], $name . '_store_key_unique'); - $table->unique(['store', 'slug'], $name . '_store_slug_unique'); - $table->index('category_id', $name . '_category_index'); - $table->foreign('category_id', $name . '_category_foreign')->references('id')->on($categories)->nullOnDelete(); - }); - } - - public function down(): void - { - Schema::connection($this->getConnection())->dropIfExists($this->shape()->names->definitions()); - } - - private function shape(): Simtabi\Laranail\Settings\Database\SchemaShape - { - return app(SchemaShapeRepository::class)->current(); - } -}; diff --git a/database/migrations/create_settings_table.php.stub b/database/migrations/create_settings_table.php.stub deleted file mode 100644 index 635d01b..0000000 --- a/database/migrations/create_settings_table.php.stub +++ /dev/null @@ -1,154 +0,0 @@ -pinnedConnection ?? $this->shape()->store(new StoreName($this->store))->connection; - } - - public function up(): void - { - $shape = $this->shape(); - $store = $shape->store(new StoreName($this->store)); - $name = $shape->names->store($store->name, $store->table); - $categories = $shape->names->categories(); - $index = substr($name, 0, 40); - $binary = match (Schema::connection($this->getConnection())->getConnection()->getDriverName()) { - 'mysql', 'mariadb' => 'utf8mb4_bin', - 'pgsql' => 'C', - default => null, - }; - - Schema::connection($this->getConnection())->create($name, static function (Blueprint $table) use ($binary, $categories, $index, $shape, $store): void { - $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); - $key = static fn (string $column, IdType $type): ColumnDefinition => match ($type) { - IdType::Bigint => $table->unsignedBigInteger($column), - IdType::Uuid => $table->char($column, 36), - IdType::Ulid => $table->char($column, 26), - }; - - match ($shape->ids) { - IdType::Bigint => $table->bigIncrements('id'), - default => $key('id', $shape->ids)->primary(), - }; - - if ($store->isDedicated()) { - $key('owner_id', $store->ownerKeyType); - } else { - $table->string('settable_type', 64)->nullable(); - $shape->ownerKey === OwnerKeyType::Typed - ? $key('settable_id', $shape->ownerKeyType)->nullable() - : $table->string('settable_id', 36)->nullable(); - } - - $collate($table->string('scope', 128)); - $key('category_id', $shape->ids)->nullable(); - $table->string('category_store', 64)->nullable(); - $table->string('group', 64); - $collate($table->string('key', 191)); - - if ($shape->identity->hasSlug()) { - $collate($table->string('slug', $shape->identity === IdentityMode::SlugPerRow ? 40 : 191)->nullable()); - } - - if ($shape->identity->hasUid()) { - $table->char('uid', 26)->nullable(); - } - - $collate($table->string('locale', 16)->default('')); - $table->longText('value')->nullable(); - $table->string('type', 64)->nullable(); - - if ($shape->translations === TranslationsMode::Json) { - $table->json('label')->nullable(); - $table->json('description')->nullable(); - } else { - $table->text('label')->nullable(); - $table->text('description')->nullable(); - } - - $table->boolean('is_encrypted')->default(false); - $table->boolean('is_locked')->default(false); - $table->boolean('is_public')->default(false); - $table->boolean('autoload')->default(true); - $table->unsignedInteger('sort_order')->default(0); - $table->json('meta')->nullable(); - $table->unsignedInteger('version')->default(1); - $table->timestamps(); - - if ($store->softDeletes) { - $table->timestamp('deleted_at')->nullable(); - } - - $table->unique(['scope', 'key', 'locale'], $index . '_identity_unique'); - - if ($shape->identity->hasUid()) { - $table->unique('uid', $index . '_uid_unique'); - } - - match ($shape->identity) { - IdentityMode::SlugPerRow => $table->unique('slug', $index . '_slug_unique'), - IdentityMode::SlugUid => $table->index('slug', $index . '_slug_index'), - IdentityMode::UidOnly => null, - }; - - if ($store->isDedicated()) { - $table->index('owner_id', $index . '_owner_index'); - $table->foreign('owner_id', $index . '_owner_foreign') - ->references($store->ownerKey)->on((string) $store->ownerTable)->cascadeOnDelete(); - } else { - $table->index(['settable_type', 'settable_id'], $index . '_settable_index'); - } - - $table->index('category_id', $index . '_category_index'); - $table->index(['autoload', 'scope'], $index . '_autoload_index'); - $table->foreign(['category_id', 'category_store'], $index . '_category_foreign') - ->references(['id', 'store'])->on($categories)->nullOnDelete(); - }); - } - - public function down(): void - { - $shape = $this->shape(); - $store = $shape->store(new StoreName($this->store)); - - Schema::connection($this->getConnection())->dropIfExists($shape->names->store($store->name, $store->table)); - } - - private function shape(): Simtabi\Laranail\Settings\Database\SchemaShape - { - return app(SchemaShapeRepository::class)->current(); - } -}; diff --git a/database/seeders/DefaultCategoriesSeeder.php b/database/seeders/DefaultCategoriesSeeder.php new file mode 100644 index 0000000..772fd7f --- /dev/null +++ b/database/seeders/DefaultCategoriesSeeder.php @@ -0,0 +1,138 @@ +get('laranail.settings.seed', []); + + if (! is_array($seed) || ($seed['enabled'] ?? true) !== true) { + return; + } + + foreach ($this->stores($seed, $config) as $store) { + $manager = $settings->asSystem('laranail::settings.seed')->store($store)->categories(); + $existing = []; + + foreach ($manager->all() as $category) { + $existing[$category->slug->value] = true; + } + + foreach ($this->categories($seed) as $category) { + if (! isset($existing[$category->slug->value])) { + $manager->create($category); + $existing[$category->slug->value] = true; + } + } + } + } + + /** + * @param array $seed + * + * @return list + */ + private function stores(array $seed, Repository $config): array + { + $stores = $seed['stores'] ?? null; + + if ($stores === null || $stores === []) { + $default = $config->get('laranail.settings.default', 'settings'); + + return [is_string($default) ? $default : 'settings']; + } + + if (! is_array($stores) || array_filter($stores, is_string(...)) !== $stores) { + throw new InvalidConfiguration('laranail.settings.seed.stores: a list of store names.'); + } + + return array_values($stores); + } + + /** + * Parents first, so a child's parent always exists when the child is created. + * + * @param array $seed + * + * @return list + */ + private function categories(array $seed): array + { + $entries = $seed['categories'] ?? []; + + if (! is_array($entries)) { + throw new InvalidConfiguration('laranail.settings.seed.categories: a map of slug => attributes.'); + } + + $categories = []; + $order = 0; + + foreach ($entries as $slug => $entry) { + $entry = is_string($entry) ? ['title' => $entry] : $entry; + + if (! is_string($slug) || ! is_array($entry) || ! is_string($entry['title'] ?? null)) { + throw new InvalidConfiguration(sprintf('laranail.settings.seed.categories.%s: needs at least a title.', $slug)); + } + + $parent = $entry['parent'] ?? null; + $categories[] = new NewCategory( + slug: $slug, + title: $entry['title'], + parent: is_string($parent) ? $parent : null, + description: is_string($entry['description'] ?? null) ? $entry['description'] : null, + icon: is_string($entry['icon'] ?? null) ? $entry['icon'] : null, + sortOrder: is_int($entry['sort_order'] ?? null) ? $entry['sort_order'] : $order, + translations: is_array($entry['translations'] ?? null) ? $entry['translations'] : [], + system: true, + ); + $order += 10; + } + + // Each pass emits the categories whose parent is already placed; a pass that places + // nothing means a parent is missing from the list or the parents form a cycle. + $ordered = []; + $placed = []; + + while ($categories !== []) { + $before = count($categories); + + foreach ($categories as $index => $category) { + if ($category->parent === null || isset($placed[$category->parent->value])) { + $ordered[] = $category; + $placed[$category->slug->value] = true; + unset($categories[$index]); + } + } + + if (count($categories) === $before) { + throw new InvalidConfiguration(sprintf('laranail.settings.seed.categories: [%s] name a parent that is not in the list, or parents that form a cycle.', implode(', ', array_map(static fn (NewCategory $category): string => $category->slug->value, $categories)))); + } + } + + return $ordered; + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 6119b7f..a9af21a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -75,8 +75,8 @@ edits definitions), so they are switches (see [Schema switches](tools/schema-swi A switch decides a column, so it is migration-time, and the package must not trust configuration for it afterwards: flipping `soft_deletes` on after migrating would make every read filter on a -`deleted_at` column that does not exist. So `install` and `make-store` record the shape they -produce in a schema file the application commits, the runtime and the migrations read that file, +`deleted_at` column that does not exist. So `install` and `make-store` record the shape the +migration produces in a schema file the application commits, the runtime and the migration read that file, and `doctor` reports any drift between configuration, the file and the database. A later `make-store` keeps the file's key type, so a new table's `category_id` can never disagree with the categories key it points at. @@ -85,6 +85,31 @@ Every combination is a shape the suite has to keep working. A pairwise set (ever values meets at least once, asserted along with the number of shapes) runs on every pull request on SQLite, MySQL and PostgreSQL, and the full product weekly. +## Why one migration? + +Every table the package uses is created by one migration file, in dependency order (categories, +definitions, each store's values, audit), with a `down()` that drops them in reverse. Four +migration stubs used to do this, each repeating the same connection and shape lookups, and a new +store meant copying a stub. Nothing in the migration varies per application any more (the shape +comes from the schema file), so it ships as a real PHP file. Its table definitions stay inline, +in short private methods, rather than in a schema-builder class: a migration is read when it +fails, and one file that says what it creates is easier to maintain than a migration delegating +to code elsewhere. `make-store` copies that same file and pins one store (and, with +`--connection`, a connection), so there is still exactly one definition of each table. + +## Why tenancy this way? + +Settings are a tenant's own data, so tenancy is in the core rather than a companion package, and +it needs neither tenancy package: a `TenantDiscriminator` says who the current tenant is, with +adapters for stancl/tenancy and spatie/laravel-multitenancy picked by `class_exists`. A tenant +column (one database) and a database per tenant are both common, so both are modes, and the +default is none. In column mode the filter sits where every query is built (the database driver, +the categories repository, the audit sink and queries), so no call path can forget it, and the +tenant leads the unique keys so two tenants can hold the same key. Definitions describe settings +rather than hold values, so they stay shared. Memoised reads are keyed by tenant in every mode, +because a job that loops over tenants is the easiest way to leak one tenant's settings into +another's. + ## Why does a plain set retry once, and an expected-version write never? A plain `set()` means "make it this value"; losing a race to another writer between the read and diff --git a/docs/configuration.md b/docs/configuration.md index fc6f3a5..bd45f39 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -31,6 +31,11 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `categories.soft_deletes` | `false` | trash deleted categories and restore them when the slug is created again (migration-time) | | `writes.retry_on_conflict` | `true` | retry a plain `set()` once after a concurrent change | | `readiness.flush_on` | the stancl and spatie tenancy events | events after which schema readiness is re-checked | +| `tenancy.mode` | `none` (`LARANAIL_SETTINGS_TENANCY`) | `column` adds a `tenant` column to the values, categories and audit tables; `database` relies on a database per tenant (migration-time) | +| `tenancy.discriminator` | `auto` | who the current tenant is: `auto` (stancl/tenancy, then spatie/laravel-multitenancy, when installed), `null`, `stancl`, `spatie`, or a class implementing `TenantDiscriminator` | +| `seed.enabled` | `true` (`LARANAIL_SETTINGS_SEED`) | whether `db:seed` creates the default categories | +| `seed.stores` | `[]` | the stores to seed; empty means the default store | +| `seed.categories` | general, appearance, localisation, mail, notifications, security | `slug => title` or `slug => [title, description, icon, parent, sort_order, translations]` | | `layers..driver` | — | `database`, `json`, `php`, `config`, `array`, or a custom driver | | `layers..connection` | `null` (`LARANAIL_SETTINGS_DB_CONNECTION` for `database`) | database driver: the connection; null is the default one | | `layers..writable` | `true` | set `false` for a read-only layer | @@ -57,7 +62,7 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. Store names, keys, locales and owner aliases are validated, and a misconfiguration (an unknown driver, sink, verifier, resolver, level or ability included) raises `InvalidConfiguration` naming the config path on first use. The `password_confirmation` verifier also reads Laravel's own `auth.password_timeout`. -Migration-time switches are read by `install` and `make-store` and recorded in the schema file; after that the package reads the file, and `doctor` reports configuration that differs from it. See [Schema switches](tools/schema-switches.md). +Migration-time switches (`tenancy.mode` among them) are read by `install` and `make-store` and recorded in the schema file; after that the package reads the file, and `doctor` reports configuration that differs from it. See [Schema switches](tools/schema-switches.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). diff --git a/docs/getting-started.md b/docs/getting-started.md index 39bbfb7..2a233d6 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -41,8 +41,9 @@ Add a store for user settings in `config/laranail/settings.php`: ], ``` -Generate its table with `php artisan laranail::settings.make-store user_settings --owner=user` -and migrate. Give the model a morph alias (`Relation::enforceMorphMap(['user' => User::class])`), +A store configured before `install` gets its table from the package migration. One added +later gets its own: `php artisan laranail::settings.make-store user_settings --owner=user`, +then migrate. Give the model a morph alias (`Relation::enforceMorphMap(['user' => User::class])`), implement `Settable` and use `HasSettings` (see [Owners and inheritance](tools/owners.md)), then: ```php diff --git a/docs/installation.md b/docs/installation.md index 7842f1c..40e8e4d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -40,10 +40,34 @@ php artisan laranail::settings.install php artisan migrate ``` -Install publishes `config/laranail/settings.php` (tag `laranail::settings-config`) and three -migrations (tag `laranail::settings-migrations`): `settings_categories`, `settings` (the -default store's values) and `settings_audit`. The default store reads the database first, so -run the migrations before the first read; until then a read raises `DriverUnavailable`. +Install publishes `config/laranail/settings.php` (tag `laranail::settings-config`) and the +package's one migration (tag `laranail::settings-migrations`, +`…_create_laranail_settings_tables.php`), and records the schema it will produce in +`database/settings-schema.php`. The migration creates, in order, `settings_categories`, the +optional `settings_definitions`, one values table per database store (`settings` for the default +store) and `settings_audit`, and `down()` drops them in reverse. Set the +[schema switches](tools/schema-switches.md) and `tenancy.mode` before installing. The default store +reads the database first, so run the migrations before the first read; until then a read raises +`DriverUnavailable`. + +## Default categories + +```bash +php artisan db:seed +``` + +The package registers its seeder with the application's `db:seed`, so `DatabaseSeeder` does not +name it. It creates the `seed.categories` set (general, appearance, localisation, mail, +notifications, security) as system categories and changes nothing when run again. See +[Seed the default categories](recipes/seeding-default-categories.md). + +## Upgrading from the four migration stubs + +Before the single migration, install published four migrations (`create_settings_categories_table`, +`create_settings_table`, `create_settings_audit_table`, `create_settings_definitions_table`). +They stay in your `database/migrations` and keep working; do not publish the new one next to +them, or the tables would be created twice. Store migrations written by an older `make-store` +keep working too. Install refuses to publish anything when a table of the same name already exists and is not this package's (a `settings` table of your own, say). Rename the package's tables with diff --git a/docs/recipes/seeding-default-categories.md b/docs/recipes/seeding-default-categories.md new file mode 100644 index 0000000..5090a18 --- /dev/null +++ b/docs/recipes/seeding-default-categories.md @@ -0,0 +1,47 @@ +# Seed the default categories + +Create the shipped set of system categories with `db:seed`, change the set, or seed each tenant. + +```bash +php artisan db:seed +``` + +The package registers `DefaultCategoriesSeeder` with the application's `db:seed`, so +`DatabaseSeeder` does not name it. To run it alone: + +```bash +php artisan db:seed --class="Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder" +``` + +It creates general, appearance, localisation, mail, notifications and security as system +categories (`is_system`) in the default store, through the settings API as the system actor, so +each is validated and audited. A slug the store already has is left exactly as it is, so seeding +again changes nothing. + +## Your own set + +```php +// config/laranail/settings.php +'seed' => [ + 'enabled' => true, + 'stores' => ['settings', 'billing'], + 'categories' => [ + 'mail' => 'Mail', + 'smtp' => ['title' => 'SMTP', 'parent' => 'mail', 'icon' => 'server'], + ], +], +``` + +Parents are created before their children whatever the order; the listed order is the display +order. A parent must be in the same list. `enabled => false` (or `LARANAIL_SETTINGS_SEED=false`) +switches it off. Categories carry no secrets, and the seeder writes no setting values. + +## Per tenant + +In column-mode [tenancy](../tools/tenancy.md) the seeder seeds the current tenant, and outside a +tenant the central rows. Run it once per tenant with your tenancy package's seed command (for +stancl/tenancy, `php artisan tenants:seed --class=...`). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/audit-and-logging.md b/docs/tools/audit-and-logging.md index e633db6..38108f5 100644 --- a/docs/tools/audit-and-logging.md +++ b/docs/tools/audit-and-logging.md @@ -55,7 +55,10 @@ both survive the refusal. The table has no value column. | `ip`, `user_agent`, `request_id`, `reason` | the actor's context | | `meta` | identifiers only (the refusal, the category operation) | -Every connection a store uses has its own audit table; `make-store --connection` generates it. +Every connection a store uses has its own audit table; the package migration creates it (and +`make-store --connection` for a store added later). In column-mode tenancy each row carries the +tenant, and `Settings::audit()` reads the current tenant's rows only; `prune-audit` applies the +retention to every tenant. ## Querying the trail diff --git a/docs/tools/commands.md b/docs/tools/commands.md index fd38f28..2d635d2 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -6,8 +6,8 @@ Eight Artisan commands, all named `laranail::settings.`. | Command | Does | |---|---| -| `laranail::settings.install` | publishes the config and the migrations, records the schema file, syncs definitions once the table exists; refuses to run over a foreign table of the same name | -| `laranail::settings.make-store {store} [--owner=*] [--connection=]` | writes a new store's migration, records it in the schema file and prints its configuration entry | +| `laranail::settings.install` | publishes the config and the package's one migration, records the schema file, syncs definitions once the table exists; refuses to run over a foreign table of the same name | +| `laranail::settings.make-store {store} [--owner=*] [--connection=]` | writes a new store's migration (a copy of the package migration pinned to that store), records it in the schema file and prints its configuration entry | | `laranail::settings.promote [store] [--force] [--from=]` | copies values written before install from the runtime file into the database | | `laranail::settings.doctor [--json] [--fix]` | checks readiness, schema drift against the schema file and rows the database cannot guard; `--fix` syncs definitions first | | `laranail::settings.sync-definitions` | copies code and config definitions into the definitions table as system rows | @@ -24,9 +24,17 @@ php artisan laranail::settings.make-store user_settings --owner=user php artisan migrate ``` -It writes `…_create_settings_user_settings_table.php` and prints the entry to add under -`stores`. With `--connection=archive` it also writes the categories and audit tables for that -connection and prints the layer to add. It refuses a store that already has a migration. +It writes one file, `…_create_settings_user_settings_table.php`: a copy of the package migration +whose `$only` line names the store, so it creates that store's values table and nothing else. +With `--connection=archive` the copy's `$pinnedConnection` line names the connection too, and it +also creates that connection's categories and audit tables (each skipped when it already +exists); it prints the layer to add. It refuses a store that already has a migration. + +## Seeding + +`php artisan db:seed` runs the package's `DefaultCategoriesSeeder` (registered by the package, so +`DatabaseSeeder` does not name it); `db:seed --class` runs it alone. See +[Seed the default categories](../recipes/seeding-default-categories.md). ## `doctor` diff --git a/docs/tools/database.md b/docs/tools/database.md index 9f705a5..93b7823 100644 --- a/docs/tools/database.md +++ b/docs/tools/database.md @@ -13,6 +13,9 @@ The `database` driver keeps a store's values in a table, through the query build `tables.prefix` goes in front of all of them. Every connection a store uses has its own categories and audit tables, so a store's foreign keys and transactions never cross connections. +One migration creates them all, in that order (`down()` in reverse): see +[Installation](../installation.md). In column-mode [tenancy](tenancy.md) the values, categories +and audit tables have a `tenant` column that leads their unique keys. The values table, in the default shape (polymorphic owners, identity mode `slug_uid`, bigint ids, string owner key). Every other shape is a [schema switch](schema-switches.md): `uuid` / `ulid` diff --git a/docs/tools/models-and-factories.md b/docs/tools/models-and-factories.md new file mode 100644 index 0000000..01d20f3 --- /dev/null +++ b/docs/tools/models-and-factories.md @@ -0,0 +1,46 @@ +# Models and factories + +Four Eloquent models, `Setting`, `SettingCategory`, `SettingDefinition` and `SettingAuditEntry`, with factories for tests, seeding and admin screens. + +## The models + +| Model | Table | Notes | +|---|---|---| +| `Models\SettingCategory` | categories | `parent()`, `children()`, `forStore()` scope; trashed rows hidden | +| `Models\Setting` | one store's values | `Setting::forStore('billing')`, `->inStore('billing')`; `category()`; trashed rows hidden | +| `Models\SettingDefinition` | the optional definitions table | shared by every tenant | +| `Models\SettingAuditEntry` | the audit trail | ULID key, no timestamps | + +Table names, key types and connections come from the recorded schema shape, so the models follow +the [schema switches](schema-switches.md): uuid and ulid keys are generated on create. In +column-mode [tenancy](tenancy.md) they are limited to the current tenant and stamp it on create. + +The engine never uses them: reads and writes go through the drivers on the query builder. A +change made through a model skips validation, casting, encryption, locks, authorization and the +audit trail, and `Setting::$value` is the encoded payload, so application code changes settings +and categories through `Settings::`. + +## Factories + +No Faker is needed. + +```php +use Simtabi\Laranail\Settings\Models\Setting; +use Simtabi\Laranail\Settings\Models\SettingCategory; + +$general = SettingCategory::factory()->system()->create(['slug' => 'general']); +SettingCategory::factory()->parent($general)->titled('Mail', 'Outgoing mail')->create(['slug' => 'mail']); +SettingCategory::factory()->forStore('billing')->create(); + +Setting::factory()->key('site.name')->value('Acme')->inCategory($general)->create(); +Setting::factory()->owner('user', 42)->key('ui.theme')->value('dark')->locked()->create(); +Setting::factory()->forStore('billing')->key('billing.currency')->locale('fr')->value('EUR')->create(); +``` + +`SettingDefinitionFactory` has `forStore()`, `key()` and `system()`; `SettingAuditEntryFactory` +has `action()`, `by()` and `at()`. `value()` encodes as the value pipeline encodes an unencrypted +value, so `Settings::get()` reads it back; an encrypted setting is arranged with `Settings::set()`. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/schema-switches.md b/docs/tools/schema-switches.md index 07c63e3..fd92367 100644 --- a/docs/tools/schema-switches.md +++ b/docs/tools/schema-switches.md @@ -104,8 +104,8 @@ registered caster alias, and an encrypted definition's default is never copied i ## The schema file `install` writes `database/settings-schema.php` (or `schema.path`): a `shape_version`, the -switches, the table names and one entry per database store. `make-store` adds its store's entry. -The migrations and the runtime read this file, not configuration, so changing a switch after +switches (`tenancy` included), the table names and one entry per database store. `make-store` +adds its store's entry. The package migration and the runtime read this file, not configuration, so changing a switch after migrating changes nothing until a migration does. Commit it. An existing record always wins: recording again only adds stores that are new. @@ -118,10 +118,11 @@ type fails). A database store with no entry in the file fails. ## Keeping the switches tested `tests/Feature/Database/SchemaMatrixTest.php` builds a pairwise set of shapes (every pair of -switch values meets in at least one; 10 shapes covering all 141 pairs, both counts asserted) and -runs each end to end, finishing with `doctor`. It runs on SQLite with the suite and on MySQL and -PostgreSQL in the `database` group; `LARANAIL_SETTINGS_MATRIX=full` runs all 576 shapes, which -the weekly CI job does. +switch values meets in at least one; 10 shapes covering all 177 pairs of the nine switches, +`tenancy.mode` none and column included, both counts asserted) and runs each end to end, inside a +tenant in column mode, finishing with `doctor`. It runs on SQLite with the suite and on MySQL and +PostgreSQL in the `database` group; `LARANAIL_SETTINGS_MATRIX=full` runs all 1,152 shapes, which +the weekly CI job does. (`database` mode adds no column, so it is not a separate shape.) --- diff --git a/docs/tools/tenancy.md b/docs/tools/tenancy.md new file mode 100644 index 0000000..c282f0f --- /dev/null +++ b/docs/tools/tenancy.md @@ -0,0 +1,81 @@ +# Tenancy + +Three modes keep each tenant's settings apart: none, a tenant column, or a database per tenant, chosen with `tenancy.mode`. + +## Modes + +| `tenancy.mode` | What changes | For | +|---|---|---| +| `none` (default) | nothing: one set of settings | single-tenant applications | +| `column` | the values, categories and audit tables get a `tenant` column; every row is stamped with the current tenant and every query is limited to it | one database shared by every tenant | +| `database` | no column: the tenancy package switches the connection, and the store follows it | a database per tenant | + +The mode is migration-time, like the other [schema switches](schema-switches.md): set it before +`install`, and the schema file records it. In `column` mode the tenant leads the unique keys +(`unique(tenant, scope, key, locale)` on values, `unique(tenant, store, slug)` on categories), so +two tenants can hold the same key, and `''` is the central application's rows. The column is +`string(64)` and binary-collated, like `scope`. + +Definitions are shared by every tenant: they describe settings, they hold no tenant's values. In +`column` mode, synced definitions link to the central (`''`) categories. + +## Who the current tenant is + +```php +// config/laranail/settings.php +'tenancy' => [ + 'mode' => 'column', + 'discriminator' => 'auto', +], +``` + +`discriminator` is `auto` (stancl/tenancy when installed, else spatie/laravel-multitenancy, else +none), `null`, `stancl`, `spatie`, or a class implementing +`Simtabi\Laranail\Settings\Contracts\TenantDiscriminator`: + +```php +use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; + +final readonly class TeamTenant implements TenantDiscriminator +{ + public function __construct(private CurrentTeam $team) {} + + public function current(): ?string + { + return $this->team->id(); // null outside a tenant + } +} +``` + +Neither tenancy package is required: both are `suggest`ed and detected with `class_exists`. A key +is an integer, a string or a `Stringable` of 1 to 64 characters; anything else raises +`InvalidConfiguration` rather than being truncated, because two tenants must never share a key. +The discriminator is bound `scoped`, so Octane requests and queued jobs each ask again. + +## What is kept apart + +| | `column` | `database` | +|---|---|---| +| values (reads, writes, forget, flush) | filtered on `tenant` | by connection | +| categories | filtered on `tenant` | by connection | +| audit trail (`Settings::audit()`) | the current tenant's rows | by connection | +| records preloaded in memory | per tenant | per tenant | +| the Eloquent models | global scope on `tenant`, stamped on create | by connection | + +Records preloaded during one request or job are kept per tenant in every mode, so a command that +loops over tenants never answers one tenant's read from another's. Schema readiness is +re-checked on the tenancy packages' switch events (`readiness.flush_on`). + +`prune-audit` applies the retention to every tenant's rows: retention is one policy for the whole +application. + +## Database per tenant + +Publish the package migration into the folder your tenancy package migrates tenants from (for +stancl/tenancy, `database/migrations/tenant`), leave the store's `connection` null so it follows +the tenant connection, and seed each tenant with the tenancy package's own seed command. The file +layers (`runtime`, `shipped`) are application-wide in every mode. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index 3f9f842..409d504 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -139,10 +139,11 @@ private function drift(Store $store, DatabaseDriver $database): Finding $schema = $shape->store($store->name); $missing = []; $unexpected = []; + $tenant = $shape->tenancy->hasColumn() ? ['tenant'] : []; $expected = [ - $database->tableFor($store->name) => [...self::VALUES_COLUMNS, ...$this->switchColumns($shape, $schema->isDedicated(), $schema->softDeletes)], - $shape->names->categories() => [...self::CATEGORY_COLUMNS, ...($shape->categoriesSoftDeletes ? ['deleted_at'] : [])], - $shape->names->audit() => self::AUDIT_COLUMNS, + $database->tableFor($store->name) => [...self::VALUES_COLUMNS, ...$tenant, ...$this->switchColumns($shape, $schema->isDedicated(), $schema->softDeletes)], + $shape->names->categories() => [...self::CATEGORY_COLUMNS, ...$tenant, ...($shape->categoriesSoftDeletes ? ['deleted_at'] : [])], + $shape->names->audit() => [...self::AUDIT_COLUMNS, ...$tenant], ]; if ($shape->definitionsTable) { @@ -160,7 +161,7 @@ private function drift(Store $store, DatabaseDriver $database): Finding $missing[] = $table . '.' . $column; } - foreach (array_diff(array_intersect($present, ['deleted_at', 'slug', 'uid', 'settable_type', 'settable_id', 'owner_id']), $columns) as $column) { + foreach (array_diff(array_intersect($present, ['deleted_at', 'slug', 'uid', 'settable_type', 'settable_id', 'owner_id', 'tenant']), $columns) as $column) { $unexpected[] = $table . '.' . $column; } } diff --git a/src/Actions/MakeStore.php b/src/Actions/MakeStore.php index 9ac6654..ed2b6c3 100644 --- a/src/Actions/MakeStore.php +++ b/src/Actions/MakeStore.php @@ -14,25 +14,35 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * Generate a new database store (G-3: no runtime DDL): a migration for its values table, copied - * from the package's stub with the store name filled in, plus the categories and audit tables - * when the store lives on a connection of its own (each connection keeps its own). Returns the - * files written and the configuration entry to add by hand. + * Generate a new database store (G-3: no runtime DDL): one migration for it, a copy of the + * package's migration (`create_laranail_settings_tables.php`) with its `$only` line naming the + * store and, with a connection, its `$pinnedConnection` line naming that connection. The copy + * creates the store's values table and, on a connection of its own, that connection's categories + * and audit tables (each connection keeps its own). Returns the file written and the + * configuration entry to add by hand. * * The store's shape (mode, soft deletes, owner table) is recorded in the schema file (§4.0): * taken from its configuration entry when it has one, else the default polymorphic shape on the - * given connection. The file's switches (key type, identity, translations) are kept, so the new - * table's `category_id` always matches the categories key it points at. + * given connection. The file's switches (key type, identity, translations, tenancy) are kept, so + * the new table's `category_id` always matches the categories key it points at. */ final readonly class MakeStore { - private const string STORE_LINE = "private string \$store = 'settings';"; + /** The package migration, without its extension. */ + public const string MIGRATION = 'create_laranail_settings_tables'; + + private const string ONLY_LINE = 'private ?string $only = null;'; private const string CONNECTION_LINE = 'private ?string $pinnedConnection = null;'; + /** + * @param string $migration the package migration file make-store copies (a directory, as + * before 0.1's single migration, means that directory's copy of it) + * @param string $migrations the application's migrations directory + */ public function __construct( private Filesystem $files, - private string $stubs, + private string $migration, private string $migrations, private ?SchemaShapeRepository $shapes = null, ) {} @@ -58,20 +68,10 @@ public function handle(StoreName $store, ?string $connection = null, array $owne throw new InvalidConfiguration(sprintf('A migration for store [%s] already exists: %s', $store, basename($existing[0]))); } - $now = CarbonImmutable::now(); - $pinned = $connection === null ? self::CONNECTION_LINE : sprintf("private ?string \$pinnedConnection = '%s';", $connection); - $written = []; - - if ($connection !== null) { - foreach (['create_settings_categories_table', 'create_settings_audit_table'] as $index => $stub) { - $written[] = $this->write($stub, sprintf('create_settings_%s_%s', $store->value, $index === 0 ? 'categories' : 'audit'), $now->addSeconds($index), [self::CONNECTION_LINE => $pinned]); - } - } - - $written[] = $this->write('create_settings_table', "create_settings_{$store->value}_table", $now->addSeconds(2), [ - self::STORE_LINE => sprintf("private string \$store = '%s';", $store->value), - self::CONNECTION_LINE => $pinned, - ]); + $written = [$this->write("create_settings_{$store->value}_table", CarbonImmutable::now(), [ + self::ONLY_LINE => sprintf("private ?string \$only = '%s';", $store->value), + self::CONNECTION_LINE => $connection === null ? self::CONNECTION_LINE : sprintf("private ?string \$pinnedConnection = '%s';", $connection), + ])]; if ($this->shapes instanceof SchemaShapeRepository) { $this->shapes->recordStore($this->shapes->configured()->stores[$store->value] ?? new StoreSchema($store, connection: $connection)); @@ -81,13 +81,14 @@ public function handle(StoreName $store, ?string $connection = null, array $owne } /** @param array $replacements */ - private function write(string $stub, string $name, CarbonImmutable $at, array $replacements): string + private function write(string $name, CarbonImmutable $at, array $replacements): string { - $source = $this->files->get(rtrim($this->stubs, '/') . "/{$stub}.php.stub"); + $file = $this->files->isDirectory($this->migration) ? rtrim($this->migration, '/') . '/' . self::MIGRATION . '.php' : $this->migration; + $source = $this->files->get($file); foreach ($replacements as $search => $replace) { if (! str_contains($source, $search)) { - throw new InvalidConfiguration(sprintf('The stub [%s] no longer contains [%s]; it cannot be copied for another store.', $stub, $search)); + throw new InvalidConfiguration(sprintf('The migration [%s] no longer contains [%s]; it cannot be copied for another store.', basename($file), $search)); } $source = str_replace($search, $replace, $source); diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index 5d31607..504d2ce 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -54,6 +54,7 @@ public function handle(int $keepDays, ?Actor $actor = null): int $seen[$database->connectionName()] = true; + // Retention is one policy for the whole application, so it prunes every tenant's rows. $removed += $database->attempt($store->name, static fn (): int => $database->connection() ->table($database->names()->audit()) ->where('occurred_at', '<', $cutoff) diff --git a/src/Actions/QueryAudit.php b/src/Actions/QueryAudit.php index a9d1f94..41708a7 100644 --- a/src/Actions/QueryAudit.php +++ b/src/Actions/QueryAudit.php @@ -88,7 +88,8 @@ private function query(AuditFilter $filter, ?Actor $actor): Builder throw new DriverUnavailable(sprintf('Store [%s] has no active database layer, so its audit trail went to the log and cannot be queried.', $store->name)); } - $query = $database->connection()->table($database->names()->audit()); + // In column-mode tenancy a tenant reads its own trail only. + $query = $database->scoped($database->connection()->table($database->names()->audit())); if ($filter->store instanceof StoreName) { $query->where('store', $filter->store->value); diff --git a/src/Actions/SyncDefinitions.php b/src/Actions/SyncDefinitions.php index 93ff0ab..4def4d7 100644 --- a/src/Actions/SyncDefinitions.php +++ b/src/Actions/SyncDefinitions.php @@ -126,10 +126,18 @@ private function sync(Store $store, DatabaseDriver $database, array $definitions /** @return array */ private function columns(DatabaseDriver $database, Store $store, Definition $definition, bool $json): array { - $category = $definition->category === null ? null : $database->connection()->table($database->names()->categories()) - ->where('store', $store->name->value) - ->where('slug', $definition->category) - ->value('id'); + $category = null; + + if ($definition->category !== null) { + $categories = $database->connection()->table($database->names()->categories()); + + // Definitions are shared by every tenant, so they link to the central categories (''). + if ($database->shape()->tenancy->hasColumn()) { + $categories->where('tenant', ''); + } + + $category = $categories->where('store', $store->name->value)->where('slug', $definition->category)->value('id'); + } return [ 'slug' => $definition->key->slug(), diff --git a/src/Audit/DatabaseAuditSink.php b/src/Audit/DatabaseAuditSink.php index bcc1f19..fa64c12 100644 --- a/src/Audit/DatabaseAuditSink.php +++ b/src/Audit/DatabaseAuditSink.php @@ -60,7 +60,7 @@ public function record(AuditEntry $entry): void 'request_id' => $entry->requestId, 'reason' => $entry->reason, 'meta' => $this->meta($entry), - ])); + ] + $database->tenantColumns())); } private function target(AuditEntry $entry): ?DatabaseDriver diff --git a/src/Contracts/TenantDiscriminator.php b/src/Contracts/TenantDiscriminator.php new file mode 100644 index 0000000..fc6cfd1 --- /dev/null +++ b/src/Contracts/TenantDiscriminator.php @@ -0,0 +1,16 @@ + 255) { throw new InvalidIdentifier(sprintf('Category [%s] needs a title of 1-255 characters.', $slug)); diff --git a/src/Database/CategoryRepository.php b/src/Database/CategoryRepository.php index b37bf52..0dbfc16 100644 --- a/src/Database/CategoryRepository.php +++ b/src/Database/CategoryRepository.php @@ -91,7 +91,7 @@ public function create(NewCategory $category): Category 'description' => $category->description === null ? null : $this->encode($category->description), 'icon' => $category->icon, 'sort_order' => $category->sortOrder, - 'is_system' => false, + 'is_system' => $category->system, 'updated_at' => $now, ]; @@ -104,7 +104,7 @@ public function create(NewCategory $category): Category return $this->get($category->slug); } - $this->database->attempt($this->store, fn (): bool => $this->table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + [ + $this->database->attempt($this->store, fn (): bool => $this->table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + $this->database->tenantColumns() + [ 'store' => $this->store->value, 'slug' => $category->slug->value, 'created_at' => $now, @@ -299,8 +299,9 @@ private function texts(string $stored): array return $texts === [] ? ['' => $stored] : $texts; } + /** The categories table, limited to the current tenant (column-mode tenancy). */ private function table(): Builder { - return $this->database->connection()->table($this->database->names()->categories()); + return $this->database->scoped($this->database->connection()->table($this->database->names()->categories())); } } diff --git a/src/Database/SchemaShape.php b/src/Database/SchemaShape.php index 945f836..2a8c4b9 100644 --- a/src/Database/SchemaShape.php +++ b/src/Database/SchemaShape.php @@ -8,6 +8,7 @@ use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Enums\StoreMode; +use Simtabi\Laranail\Settings\Enums\TenancyMode; use Simtabi\Laranail\Settings\Enums\IdentityMode; use Simtabi\Laranail\Settings\Enums\OwnerKeyType; use Simtabi\Laranail\Settings\Enums\TranslationsMode; @@ -41,6 +42,7 @@ public function __construct( public bool $definitionsTable = false, public SchemaNames $names = new SchemaNames, public array $stores = [], + public TenancyMode $tenancy = TenancyMode::None, ) {} /** @@ -63,6 +65,7 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): $ownerKey = self::enum($ids, 'owner_key', OwnerKeyType::String, OwnerKeyType::tryFrom(...), 'laranail.settings.ids.owner_key: use [string] or [typed].'); $identity = self::enum(self::section($settings, 'identity'), 'mode', IdentityMode::SlugUid, IdentityMode::tryFrom(...), 'laranail.settings.identity.mode: use slug_uid, slug_per_row or uid_only.'); $translations = self::enum(self::section($settings, 'translations'), 'mode', TranslationsMode::Lang, TranslationsMode::tryFrom(...), 'laranail.settings.translations.mode: use [lang] or [json].'); + $tenancy = self::enum(self::section($settings, 'tenancy'), 'mode', TenancyMode::None, TenancyMode::tryFrom(...), 'laranail.settings.tenancy.mode: use none, column or database.'); $categories = self::section($settings, 'categories'); $definitions = $settings['definitions'] ?? []; @@ -90,6 +93,7 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): $definitionsTable, SchemaNames::fromConfig(self::section($settings, 'tables')), self::storesFromConfig($settings, $followed ?? IdType::Bigint, $default), + $tenancy, ); } @@ -131,6 +135,7 @@ public static function fromArray(array $data): self ($switches['definitions_table'] ?? false) === true, SchemaNames::fromConfig($tables), $stores, + TenancyMode::tryFrom(self::text($switches, 'tenancy', 'none')) ?? throw $invalid('tenancy'), ); } @@ -155,6 +160,7 @@ public function toArray(): array 'translations' => $this->translations->value, 'categories_soft_deletes' => $this->categoriesSoftDeletes, 'definitions_table' => $this->definitionsTable, + 'tenancy' => $this->tenancy->value, ], 'tables' => $this->names->toArray(), 'stores' => $stores, @@ -179,7 +185,7 @@ public function withStore(StoreSchema $store): self return $this; } - return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store]); + return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy); } /** diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index 7649809..eb0a84b 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -61,6 +61,7 @@ * @param ?string $table the store's configured table (`stores..table`); null uses the store name * @param Closure(): ReadinessProbe $probe resolved only after a database error * @param (Closure(): SchemaShape)|null $shape the recorded schema shape; null is the default shape over $names + * @param (Closure(): ?string)|null $tenant the current tenant (column-mode tenancy); null is no tenant */ public function __construct( private ConnectionResolverInterface $db, @@ -70,6 +71,7 @@ public function __construct( private bool $writable, private Closure $probe, private ?Closure $shape = null, + private ?Closure $tenant = null, ) {} /** @@ -129,6 +131,36 @@ public function tableFor(StoreName $store): string return $shape->names->store($store, $shape->hasStore($store) ? $shape->store($store)->table : $this->table); } + /** + * The tenant the rows of this call belong to, in column-mode tenancy: the discriminator's + * key, or '' (the central rows) outside any tenant. Always '' in the other modes. + */ + public function tenant(): string + { + if (! $this->shape()->tenancy->hasColumn() || ! $this->tenant instanceof Closure) { + return ''; + } + + $tenant = ($this->tenant)(); + + return is_string($tenant) ? $tenant : ''; + } + + /** + * Limit a query on a values, categories or audit table to the current tenant (column-mode + * tenancy); any other mode leaves it as it is. + */ + public function scoped(Builder $query): Builder + { + return $this->shape()->tenancy->hasColumn() ? $query->where('tenant', $this->tenant()) : $query; + } + + /** @return array{tenant?: string} the tenant column a new row carries */ + public function tenantColumns(): array + { + return $this->shape()->tenancy->hasColumn() ? ['tenant' => $this->tenant()] : []; + } + public function names(): SchemaNames { return $this->shape()->names; @@ -214,7 +246,7 @@ public function put(StoreName $store, Record $record): void try { // A savepoint: on Postgres a unique violation would otherwise abort the // whole surrounding transaction, not just this statement. - $this->connection()->transaction(fn (): bool => $this->table($store)->insert($columns + $this->identityColumns($record) + [ + $this->connection()->transaction(fn (): bool => $this->table($store)->insert($columns + $this->identityColumns($record) + $this->tenantColumns() + [ 'scope' => $record->scope->value, 'key' => $record->key->value, 'locale' => $record->locale->value, @@ -404,9 +436,10 @@ private function signalsUnavailable(Exception $exception): bool || str_contains($exception->getMessage(), 'no such table'); } + /** The store's values table, limited to the current tenant (column-mode tenancy). */ private function table(StoreName $store): Builder { - return $this->connection()->table($this->tableFor($store)); + return $this->scoped($this->connection()->table($this->tableFor($store))); } /** Rows that are not trashed (every row, without soft deletes). */ @@ -524,7 +557,7 @@ private function categoryId(StoreName $store, Record $record): int|string|null return null; } - $categories = $this->connection()->table($this->names()->categories())->where('slug', $record->category); + $categories = $this->scoped($this->connection()->table($this->names()->categories()))->where('slug', $record->category); if ($this->shape()->categoriesSoftDeletes) { $categories->whereNull('deleted_at'); diff --git a/src/Drivers/DriverFactory.php b/src/Drivers/DriverFactory.php index f37fcb9..1eec3e7 100644 --- a/src/Drivers/DriverFactory.php +++ b/src/Drivers/DriverFactory.php @@ -37,6 +37,7 @@ public function __construct( private readonly SchemaNames $names = new SchemaNames, private readonly ?Closure $probe = null, private readonly ?Closure $shape = null, + private readonly ?Closure $tenant = null, ) {} /** @param Closure(LayerConfig): Driver $factory */ @@ -119,7 +120,10 @@ private function database(LayerConfig $layer): DatabaseDriver /** @var (Closure(): SchemaShape)|null $shape */ $shape = $this->shape; - return new DatabaseDriver($this->db, $connection, $this->names, $table, $layer->writable, $probe, $shape); + /** @var (Closure(): ?string)|null $tenant */ + $tenant = $this->tenant; + + return new DatabaseDriver($this->db, $connection, $this->names, $table, $layer->writable, $probe, $shape, $tenant); } private function json(LayerConfig $layer): JsonDriver diff --git a/src/Enums/TenancyMode.php b/src/Enums/TenancyMode.php new file mode 100644 index 0000000..c03d105 --- /dev/null +++ b/src/Enums/TenancyMode.php @@ -0,0 +1,36 @@ +getModel(); + + if (ModelContext::hasTenantColumn() && method_exists($model, 'usesTenantColumn') && $model->usesTenantColumn()) { + $query->where($query->qualifyColumn('tenant'), ModelContext::tenant()); + } + }); + + static::creating(static function (self $model): void { + if (ModelContext::hasTenantColumn() && $model->usesTenantColumn() && $model->getAttribute('tenant') === null) { + $model->setAttribute('tenant', ModelContext::tenant()); + } + + if ($model->getKey() === null) { + foreach (DatabaseDriver::newId($model->idType()) as $column => $id) { + $model->setAttribute($column, $id); + } + } + }); + } + + public function getIncrementing(): bool + { + return $this->idType() === IdType::Bigint; + } + + public function getKeyType(): string + { + return $this->idType() === IdType::Bigint ? 'int' : 'string'; + } + + /** Whether this table carries the tenant column in column-mode tenancy. */ + public function usesTenantColumn(): bool + { + return true; + } + + protected function idType(): IdType + { + return ModelContext::shape()->ids; + } +} diff --git a/src/Models/ModelContext.php b/src/Models/ModelContext.php new file mode 100644 index 0000000..a94eb2a --- /dev/null +++ b/src/Models/ModelContext.php @@ -0,0 +1,73 @@ +tenancy->hasColumn(); + } + + public static function defaultStore(): StoreName + { + return new StoreName(self::$defaultStore instanceof Closure ? (self::$defaultStore)() : 'settings'); + } + + /** The connection a store's tables live on; null is the default connection. */ + public static function connectionOf(StoreName $store): ?string + { + return self::shape()->store($store)->connection; + } +} diff --git a/src/Models/Setting.php b/src/Models/Setting.php new file mode 100644 index 0000000..921d5f8 --- /dev/null +++ b/src/Models/Setting.php @@ -0,0 +1,135 @@ + */ + use HasFactory; + + use UsesSettingsSchema; + + protected $guarded = []; + + private ?string $store = null; + + /** @return Builder a query on a store's values table */ + public static function forStore(string $store): Builder + { + return new self()->inStore($store)->newQuery(); + } + + /** Point this instance at a store's values table and connection. */ + public function inStore(string $store): static + { + $this->store = new StoreName($store)->value; + $this->setTable($this->storeTable()); + $this->setConnection(ModelContext::connectionOf($this->storeName())); + + return $this; + } + + public function storeName(): StoreName + { + return $this->store === null ? ModelContext::defaultStore() : new StoreName($this->store); + } + + #[Override] + public function getTable(): string + { + return $this->table ?? $this->storeTable(); + } + + #[Override] + public function getConnectionName(): ?string + { + return parent::getConnectionName() ?? ModelContext::connectionOf($this->storeName()); + } + + /** + * Copies keep the store, so rows read from a store's table stay in that store. + * + * @param array $attributes + */ + #[Override] + public function newInstance($attributes = [], $exists = false): static + { + $model = parent::newInstance($attributes, $exists); + $model->store = $this->store; + + return $model; + } + + /** @return BelongsTo */ + public function category(): BelongsTo + { + return $this->belongsTo(SettingCategory::class, 'category_id'); + } + + #[Override] + protected static function booted(): void + { + self::addGlobalScope('laranail-settings.live', static function (Builder $query): void { + $model = $query->getModel(); + + if ($model instanceof self && ModelContext::shape()->store($model->storeName())->softDeletes) { + $query->whereNull($query->qualifyColumn('deleted_at')); + } + }); + } + + protected static function newFactory(): SettingFactory + { + return SettingFactory::new(); + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return [ + 'is_encrypted' => 'boolean', + 'is_locked' => 'boolean', + 'is_public' => 'boolean', + 'autoload' => 'boolean', + 'sort_order' => 'integer', + 'version' => 'integer', + 'meta' => 'array', + ]; + } + + private function storeTable(): string + { + $shape = ModelContext::shape(); + $store = $this->storeName(); + + return $shape->names->store($store, $shape->store($store)->table); + } +} diff --git a/src/Models/SettingAuditEntry.php b/src/Models/SettingAuditEntry.php new file mode 100644 index 0000000..0d2a0d3 --- /dev/null +++ b/src/Models/SettingAuditEntry.php @@ -0,0 +1,64 @@ + */ + use HasFactory; + + use UsesSettingsSchema; + + public $timestamps = false; + + protected $guarded = []; + + #[Override] + public function getTable(): string + { + return ModelContext::shape()->names->audit(); + } + + #[Override] + public function getConnectionName(): ?string + { + return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + } + + protected static function newFactory(): SettingAuditEntryFactory + { + return SettingAuditEntryFactory::new(); + } + + /** Always a ULID, whatever `ids.type` says. */ + protected function idType(): IdType + { + return IdType::Ulid; + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return ['occurred_at' => 'immutable_datetime', 'meta' => 'array', 'version_from' => 'integer', 'version_to' => 'integer']; + } +} diff --git a/src/Models/SettingCategory.php b/src/Models/SettingCategory.php new file mode 100644 index 0000000..b7b7002 --- /dev/null +++ b/src/Models/SettingCategory.php @@ -0,0 +1,99 @@ + $meta + */ +final class SettingCategory extends Model +{ + /** @use HasFactory */ + use HasFactory; + + use UsesSettingsSchema; + + protected $guarded = []; + + #[Override] + public function getTable(): string + { + return ModelContext::shape()->names->categories(); + } + + #[Override] + public function getConnectionName(): ?string + { + return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + } + + /** @return BelongsTo */ + public function parent(): BelongsTo + { + return $this->belongsTo(self::class, 'parent_id'); + } + + /** @return HasMany */ + public function children(): HasMany + { + return $this->hasMany(self::class, 'parent_id'); + } + + /** + * @param Builder $query + * + * @return Builder + */ + public function scopeForStore(Builder $query, string $store): Builder + { + return $query->where('store', $store); + } + + #[Override] + protected static function booted(): void + { + self::addGlobalScope('laranail-settings.live', static function (Builder $query): void { + if (ModelContext::shape()->categoriesSoftDeletes) { + $query->whereNull($query->qualifyColumn('deleted_at')); + } + }); + } + + protected static function newFactory(): SettingCategoryFactory + { + return SettingCategoryFactory::new(); + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return ['is_system' => 'boolean', 'sort_order' => 'integer', 'meta' => 'array']; + } +} diff --git a/src/Models/SettingDefinition.php b/src/Models/SettingDefinition.php new file mode 100644 index 0000000..80e9db4 --- /dev/null +++ b/src/Models/SettingDefinition.php @@ -0,0 +1,79 @@ + */ + use HasFactory; + + use UsesSettingsSchema; + + protected $guarded = []; + + #[Override] + public function getTable(): string + { + return ModelContext::shape()->names->definitions(); + } + + #[Override] + public function getConnectionName(): ?string + { + return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + } + + /** Definitions are shared by every tenant. */ + public function usesTenantColumn(): bool + { + return false; + } + + /** @return BelongsTo */ + public function category(): BelongsTo + { + return $this->belongsTo(SettingCategory::class, 'category_id'); + } + + protected static function newFactory(): SettingDefinitionFactory + { + return SettingDefinitionFactory::new(); + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return [ + 'rules' => 'array', + 'overridable_by' => 'array', + 'meta' => 'array', + 'is_encrypted' => 'boolean', + 'is_public' => 'boolean', + 'is_locked' => 'boolean', + 'autoload' => 'boolean', + 'inherits' => 'boolean', + 'is_system' => 'boolean', + ]; + } +} diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index 3c2bff8..aa862c6 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -44,6 +44,7 @@ use Simtabi\Laranail\Settings\Audit\NullAuditSink; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Events\LayerSkipped; +use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Resolution\Resolver; use Simtabi\Laranail\Settings\Actions\PromoteStore; use Simtabi\Laranail\Settings\Actions\PruneOrphans; @@ -86,6 +87,7 @@ use Simtabi\Laranail\Settings\Authorization\GateAuthorizer; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Authorization\ChainAuthorizer; +use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Database\SchemaReadinessProbe; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Support\LaravelValueValidator; @@ -94,15 +96,19 @@ use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Tenancy\NullTenantDiscriminator; use Simtabi\Laranail\Settings\Authentication\GuardActorResolver; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; use Simtabi\Laranail\Settings\Authentication\SanctumActorResolver; use Simtabi\Laranail\Settings\Authorization\PermissionsAuthorizer; use Simtabi\Laranail\Settings\Verification\ActorTimestampVerifier; use Simtabi\Laranail\Package\Tools\Providers\PackageServiceProvider; use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; +use Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder; use Simtabi\Laranail\Settings\Verification\PasswordConfirmationVerifier; +use Simtabi\Laranail\Package\Tools\Support\Definitions\AutoSeederDefinition; /** * Registers laranail/settings with the host application. @@ -119,13 +125,21 @@ */ final class SettingsServiceProvider extends PackageServiceProvider { + private const string STANCL = 'Stancl\\Tenancy\\Tenancy'; + public function configurePackage(Package $package): void { $package ->name('laranail/settings') ->setPublishTagId('settings') ->hasConfigFile('settings') - ->hasMigrations(['create_settings_categories_table', 'create_settings_table', 'create_settings_audit_table', 'create_settings_definitions_table']) + ->hasMigrations(['create_laranail_settings_tables']) + // Runs with the host's `php artisan db:seed`; the seeder itself honours seed.enabled. + // Foreign keys stay checked (a child category needs its parent) and events fire (the + // settings API dispatches CategorySaving/Saved and writes the audit trail). + ->hasPackageSeeders(AutoSeederDefinition::make('laranail/settings:defaults') + ->seeders([DefaultCategoriesSeeder::class]) + ->options(['disable_foreign_key_checks' => false, 'fire_events' => true])) ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class]) ->hasInstallCommand(static function (InstallCommand $command): void { $command @@ -165,6 +179,8 @@ public function packageBooted(): void #[Override] public function packageRegistered(): void { + $this->registerTenancy(); + $this->app->singleton(CasterRegistry::class); $this->app->singleton(ValueEncoder::class); $this->app->singleton(RecordSerializer::class); @@ -195,6 +211,7 @@ public function packageRegistered(): void SchemaNames::fromConfig(self::array($app, 'laranail.settings.tables')), static fn (): ReadinessProbe => $app->make(ReadinessProbe::class), static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), )); // The recorded schema shape (§4.0). Scoped: read once per request or job, never at boot. @@ -259,6 +276,7 @@ static function (string $change) use ($app): void { $app->make(StoreRegistry::class), $app->make(ValuePipeline::class), self::string($app, 'app.fallback_locale', 'en'), + tenant: $app->make(TenantDiscriminator::class), )); $this->app->singleton(SettingWriter::class, static fn (Application $app): SettingWriter => new SettingWriter( @@ -335,7 +353,7 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $this->app->bind(MakeStore::class, static fn (Application $app): MakeStore => new MakeStore( $app->make(Filesystem::class), - dirname(__DIR__, 2) . '/database/migrations', + dirname(__DIR__, 2) . '/database/migrations/' . MakeStore::MIGRATION . '.php', $app->databasePath('migrations'), $app->make(SchemaShapeRepository::class), )); @@ -496,6 +514,72 @@ private static function array(Application $app, string $key): array return is_array($value) ? $value : []; } + /** stancl/tenancy's current tenant key, or null when tenancy is not initialised. */ + private static function stanclTenant(Application $app): mixed + { + $tenancy = $app->make(self::STANCL); + + if (! is_object($tenancy) || ! property_exists($tenancy, 'initialized') || $tenancy->initialized !== true || ! property_exists($tenancy, 'tenant')) { + return null; + } + + $tenant = $tenancy->tenant; + + return is_object($tenant) && method_exists($tenant, 'getTenantKey') ? $tenant->getTenantKey() : null; + } + + /** spatie/laravel-multitenancy's current tenant key (its container binding), or null. */ + private static function spatieTenant(Application $app): mixed + { + $binding = $app->make(Repository::class)->get('multitenancy.current_tenant_container_key', 'currentTenant'); + + if (! is_string($binding) || ! $app->bound($binding)) { + return null; + } + + $tenant = $app->make($binding); + + return is_object($tenant) && method_exists($tenant, 'getKey') ? $tenant->getKey() : null; + } + + /** + * Tenancy (Amendment B): who the current tenant is, and the context the Eloquent models read + * it from. `tenancy.discriminator`: `auto` (stancl/tenancy, then spatie/laravel-multitenancy, + * when installed; otherwise none), `null`, `stancl`, `spatie`, or a class implementing + * TenantDiscriminator. Bound `scoped`: the tenant changes between requests and jobs. + */ + private function registerTenancy(): void + { + $this->app->scoped(TenantDiscriminator::class, static function (Application $app): TenantDiscriminator { + $driver = $app->make(Repository::class)->get('laranail.settings.tenancy.discriminator', 'auto'); + $path = 'laranail.settings.tenancy.discriminator'; + + if ($driver === 'auto') { + $driver = match (true) { + class_exists(self::STANCL) => 'stancl', + class_exists('Spatie\\Multitenancy\\Models\\Tenant') => 'spatie', + default => 'null', + }; + } + + return match ($driver) { + 'null', null => new NullTenantDiscriminator, + 'stancl' => class_exists(self::STANCL) + ? new ClosureTenantDiscriminator(static fn (): mixed => self::stanclTenant($app)) + : throw new InvalidConfiguration($path . ': [stancl] needs stancl/tenancy.'), + 'spatie' => new ClosureTenantDiscriminator(static fn (): mixed => self::spatieTenant($app)), + default => self::instance($app, $driver, TenantDiscriminator::class, $path), + }; + }); + + $app = $this->app; + ModelContext::use( + static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), + static fn (): string => self::string($app, 'laranail.settings.default', 'settings'), + ); + } + /** Actor resolution, authorization, verification, audit and the operational log. */ private function registerAccess(): void { diff --git a/src/Resolution/PreloadedRecords.php b/src/Resolution/PreloadedRecords.php index 28ea5dd..1d55e0a 100644 --- a/src/Resolution/PreloadedRecords.php +++ b/src/Resolution/PreloadedRecords.php @@ -13,21 +13,23 @@ * Records loaded ahead of time for a list of owners (`preload()`, `withSettings()`), so reading a * page of owners costs one query per store instead of one per owner (G-9). Held for the request * only (the resolver that owns it is scoped) and dropped for a scope when that scope is written. + * Records are kept per tenant, so a tenant switch inside one request or job can never answer one + * tenant's read from another tenant's preload. */ final class PreloadedRecords { - /** @var array>>> store => scope => layer => records */ + /** @var array>>> tenant|store => scope => layer => records */ private array $records = []; /** * @param list $scopes * @param array $loaded layer => records, as the store loaded them for these scopes */ - public function remember(StoreName $store, array $scopes, array $loaded): void + public function remember(StoreName $store, array $scopes, array $loaded, string $tenant = ''): void { foreach ($scopes as $scope) { foreach ($loaded as $layer => $records) { - $this->records[$store->value][$scope->value][$layer] = array_values(array_filter( + $this->records[$this->slot($store, $tenant)][$scope->value][$layer] = array_values(array_filter( $records->all(), static fn (Record $record): bool => $record->scope->equals($scope), )); @@ -35,19 +37,25 @@ public function remember(StoreName $store, array $scopes, array $loaded): void } } - public function has(StoreName $store, Scope $scope): bool + public function has(StoreName $store, Scope $scope, string $tenant = ''): bool { - return isset($this->records[$store->value][$scope->value]); + return isset($this->records[$this->slot($store, $tenant)][$scope->value]); } /** @return array> layer => records */ - public function get(StoreName $store, Scope $scope): array + public function get(StoreName $store, Scope $scope, string $tenant = ''): array { - return $this->records[$store->value][$scope->value] ?? []; + return $this->records[$this->slot($store, $tenant)][$scope->value] ?? []; } - public function forget(StoreName $store, Scope $scope): void + public function forget(StoreName $store, Scope $scope, string $tenant = ''): void { - unset($this->records[$store->value][$scope->value]); + unset($this->records[$this->slot($store, $tenant)][$scope->value]); + } + + /** One slot per tenant and store; `|` cannot occur in a store name. */ + private function slot(StoreName $store, string $tenant): string + { + return $tenant . '|' . $store->value; } } diff --git a/src/Resolution/Resolver.php b/src/Resolution/Resolver.php index c7085cf..1307aa1 100644 --- a/src/Resolution/Resolver.php +++ b/src/Resolution/Resolver.php @@ -15,6 +15,7 @@ use Simtabi\Laranail\Settings\Enums\Precedence; use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\ValuePipeline; +use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; /** * Resolves a read through the cascade: @@ -34,6 +35,7 @@ public function __construct( private ValuePipeline $pipeline, private string $fallbackLocale, private PreloadedRecords $preloaded = new PreloadedRecords, + private ?TenantDiscriminator $tenant = null, ) {} /** @@ -45,14 +47,14 @@ public function __construct( public function preload(array $groups): void { foreach ($groups as [$store, $scopes]) { - $this->preloaded->remember($store->name, $scopes, $store->load($scopes)); + $this->preloaded->remember($store->name, $scopes, $store->load($scopes), $this->tenant()); } } /** Drop what was preloaded for one scope (it was just written). */ public function forgetPreloaded(Store $store, Scope $scope): void { - $this->preloaded->forget($store->name, $scope); + $this->preloaded->forget($store->name, $scope, $this->tenant()); } /** @param list $parents */ @@ -154,7 +156,8 @@ private function loadAll(array $plan): array */ private function load(Store $store, array $scopes): array { - $missing = array_values(array_filter($scopes, fn (Scope $scope): bool => ! $this->preloaded->has($store->name, $scope))); + $tenant = $this->tenant(); + $missing = array_values(array_filter($scopes, fn (Scope $scope): bool => ! $this->preloaded->has($store->name, $scope, $tenant))); if ($missing === $scopes) { return $store->load($scopes); @@ -167,7 +170,7 @@ private function load(Store $store, array $scopes): array $records = isset($fresh[$layer->name]) ? $fresh[$layer->name]->all() : []; foreach ($scopes as $scope) { - $records = [...$records, ...($this->preloaded->get($store->name, $scope)[$layer->name] ?? [])]; + $records = [...$records, ...($this->preloaded->get($store->name, $scope, $tenant)[$layer->name] ?? [])]; } $merged[$layer->name] = new RecordSet($records); @@ -191,4 +194,10 @@ private function locales(Locale $requested, ?Definition $definition): array return array_values($candidates); } + + /** The current tenant's key ('' outside any tenant), which partitions the preloaded records. */ + private function tenant(): string + { + return $this->tenant?->current() ?? ''; + } } diff --git a/src/Tenancy/ClosureTenantDiscriminator.php b/src/Tenancy/ClosureTenantDiscriminator.php new file mode 100644 index 0000000..551b0a3 --- /dev/null +++ b/src/Tenancy/ClosureTenantDiscriminator.php @@ -0,0 +1,46 @@ +resolve)(); + + if ($tenant === null) { + return null; + } + + $key = match (true) { + is_string($tenant) => $tenant, + is_int($tenant) => (string) $tenant, + $tenant instanceof Stringable => (string) $tenant, + default => throw new InvalidConfiguration(sprintf('The tenant discriminator returned a %s; return a string or integer key, or null.', get_debug_type($tenant))), + }; + + if ($key === '' || strlen($key) > 64) { + throw new InvalidConfiguration(sprintf('Tenant key [%s] must be 1-64 characters.', $key)); + } + + return $key; + } +} diff --git a/src/Tenancy/NullTenantDiscriminator.php b/src/Tenancy/NullTenantDiscriminator.php new file mode 100644 index 0000000..bd2bf1f --- /dev/null +++ b/src/Tenancy/NullTenantDiscriminator.php @@ -0,0 +1,16 @@ +set('laranail.settings.stores.settings.layers', ['database', 'runtime', 'shipped']); $this->artisan('laranail::settings.install')->assertSuccessful(); @@ -41,7 +41,7 @@ function settingsMigrations(): array $names = array_map(static fn (string $path): string => preg_replace('/^\d{4}_\d{2}_\d{2}_\d{6}_/', '', basename($path)) ?? '', settingsMigrations()); sort($names); - expect($names)->toBe(['create_settings_audit_table.php', 'create_settings_categories_table.php', 'create_settings_definitions_table.php', 'create_settings_table.php']) + expect($names)->toBe(['create_laranail_settings_tables.php']) ->and(app(SchemaShapeRepository::class)->recorded()?->hasStore(new StoreName('settings')))->toBeTrue(); }); @@ -73,7 +73,7 @@ function settingsMigrations(): array $files = settingsMigrations(); expect($files)->toHaveCount(1) - ->and(File::get($files[0]))->toContain("private string \$store = 'user_settings';") + ->and(File::get($files[0]))->toContain("private ?string \$only = 'user_settings';") ->and(File::get($files[0]))->toContain('private ?string $pinnedConnection = null;'); $this->artisan('laranail::settings.make-store', ['store' => 'user_settings'])->expectsOutputToContain('already exists')->assertFailed(); @@ -92,14 +92,33 @@ function settingsMigrations(): array }); it('generates the categories and audit tables too for a store on its own connection', function (): void { + config()->set('database.connections.archive_db', ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', 'foreign_key_constraints' => true]); $generated = app(MakeStore::class)->handle(new StoreName('archive'), 'archive_db', ['ledger']); - expect($generated->migrations)->toHaveCount(3) + expect($generated->migrations)->toHaveCount(1) ->and(File::get($generated->migrations[0]))->toContain("private ?string \$pinnedConnection = 'archive_db';") - ->and(File::get($generated->migrations[2]))->toContain("private string \$store = 'archive';") + ->and(File::get($generated->migrations[0]))->toContain("private ?string \$only = 'archive';") ->and($generated->config)->toContain("'database_archive_db' => ['driver' => 'database', 'connection' => 'archive_db']") ->and(fn () => app(MakeStore::class)->handle(new StoreName('other'), 'bad connection!'))->toThrow(InvalidConfiguration::class) ->and(fn () => app(MakeStore::class)->handle(new StoreName('other'), null, ['Bad Alias']))->toThrow(InvalidIdentifier::class); + + // The one generated migration creates the store's table and that connection's own + // categories and audit tables, and drops all three again. + $migration = require $generated->migrations[0]; + $migration->up(); + $schema = Schema::connection('archive_db'); + + expect($migration->getConnection())->toBe('archive_db') + ->and($schema->hasTable('archive'))->toBeTrue() + ->and($schema->hasTable('settings_categories'))->toBeTrue() + ->and($schema->hasTable('settings_audit'))->toBeTrue() + ->and($schema->hasTable('settings_definitions'))->toBeFalse(); + + $migration->down(); + + expect($schema->hasTable('archive'))->toBeFalse() + ->and($schema->hasTable('settings_categories'))->toBeFalse() + ->and($schema->hasTable('settings_audit'))->toBeFalse(); }); it('reports readiness, schema drift and rows the database cannot guard', function (): void { diff --git a/tests/Feature/Database/DatabaseLayerTest.php b/tests/Feature/Database/DatabaseLayerTest.php index 82ae9ea..ebfe3a2 100644 --- a/tests/Feature/Database/DatabaseLayerTest.php +++ b/tests/Feature/Database/DatabaseLayerTest.php @@ -69,12 +69,14 @@ function databaseDriver(bool $writable = true): DatabaseDriver ->and($unique->pluck('columns')->flatten()->all())->not->toContain('group'); }); -it('keeps the identity index inside the utf8mb4 byte budget (G-5)', function (): void { - $stub = (string) file_get_contents(dirname(__DIR__, 3) . '/database/migrations/create_settings_table.php.stub'); - preg_match_all("/string\\('(scope|key|locale)', (\\d+)\\)/", $stub, $matches); +it('keeps the identity index inside the utf8mb4 byte budget, tenant column included (G-5)', function (): void { + $migration = (string) file_get_contents(dirname(__DIR__, 3) . '/database/migrations/create_laranail_settings_tables.php'); + $values = substr($migration, (int) strpos($migration, 'private function createValues'), 4000); + preg_match_all("/string\\('(tenant|scope|key|locale)', (\\d+)\\)/", $values, $matches); $lengths = array_combine($matches[1], array_map(intval(...), $matches[2])); + ksort($lengths); - expect($lengths)->toBe(['scope' => 128, 'key' => 191, 'locale' => 16]) + expect($lengths)->toBe(['key' => 191, 'locale' => 16, 'scope' => 128, 'tenant' => 64]) ->and(array_sum($lengths) * 4)->toBeLessThan(3072); }); diff --git a/tests/Feature/Database/MigrationTest.php b/tests/Feature/Database/MigrationTest.php new file mode 100644 index 0000000..513fbe8 --- /dev/null +++ b/tests/Feature/Database/MigrationTest.php @@ -0,0 +1,88 @@ +set('database.connections.archive_db', ['driver' => 'sqlite', 'database' => $other, 'prefix' => '', 'foreign_key_constraints' => true]); + config()->set('laranail.settings.layers.archive', ['driver' => 'database', 'connection' => 'archive_db']); + + useDatabase([ + 'tables.prefix' => 'app_', + 'stores.billing' => ['layers' => ['database'], 'table' => 'billing_values'], + 'stores.users' => ['layers' => ['database'], 'owners' => ['user'], 'mode' => 'dedicated', 'owner' => ['table' => 'members']], + 'stores.archive' => ['layers' => ['archive']], + 'stores.files' => ['layers' => ['runtime']], + ], ownerTables: ['members' => 'bigint']); + + $main = Schema::connection(DB::getDefaultConnection()); + $archive = Schema::connection('archive_db'); + + expect($main->hasTable('app_settings_categories'))->toBeTrue() + ->and($main->hasTable('app_settings'))->toBeTrue() + ->and($main->hasTable('app_billing_values'))->toBeTrue() + ->and($main->hasColumn('app_users', 'owner_id'))->toBeTrue() + ->and($main->hasTable('app_settings_audit'))->toBeTrue() + ->and($main->hasTable('app_files'))->toBeFalse() + // A store on a connection of its own gets that connection's categories and audit too. + ->and($archive->hasTable('app_archive'))->toBeTrue() + ->and($archive->hasTable('app_settings_categories'))->toBeTrue() + ->and($archive->hasTable('app_settings_audit'))->toBeTrue() + ->and($archive->hasTable('app_settings_definitions'))->toBeFalse(); + + settings()->store('billing')->set('billing.currency', 'EUR'); + settings()->store('archive')->set('kept.since', 2020); + + expect(settings()->store('billing')->get('billing.currency'))->toBe('EUR') + ->and(settings()->store('archive')->get('kept.since'))->toBe(2020); + + packageMigration()->down(); + + foreach (['app_settings_categories', 'app_settings', 'app_billing_values', 'app_users', 'app_settings_audit'] as $table) { + expect($main->hasTable($table))->toBeFalse(); + } + + expect($archive->getTables())->toBe([]) + ->and($main->hasTable('members'))->toBeTrue(); + + @unlink($other); +}); + +it('runs on the default store\'s connection', function (): void { + useDatabase(); + + expect(packageMigration()->getConnection())->toBeNull(); + + config()->set('laranail.settings.layers.database.connection', DB::getDefaultConnection()); + app()->forgetScopedInstances(); + + expect(packageMigration()->getConnection())->toBe(DB::getDefaultConnection()); +}); + +it('creates the definitions table on the default store\'s connection when it is on, after categories', function (): void { + useDatabase(['definitions.table' => true]); + + expect(Schema::hasTable('settings_definitions'))->toBeTrue() + ->and(collect(Schema::getForeignKeys('settings_definitions'))->pluck('foreign_table')->all())->toBe(['settings_categories']); + + packageMigration()->down(); + + expect(Schema::hasTable('settings_definitions'))->toBeFalse() + ->and(Schema::hasTable('settings_categories'))->toBeFalse(); +}); diff --git a/tests/Feature/Database/ModelsAndFactoriesTest.php b/tests/Feature/Database/ModelsAndFactoriesTest.php new file mode 100644 index 0000000..10cf284 --- /dev/null +++ b/tests/Feature/Database/ModelsAndFactoriesTest.php @@ -0,0 +1,115 @@ + $ids, 'stores.billing' => ['layers' => ['database']]], stores: ['billing']); + + $general = SettingCategory::factory()->system()->create(['slug' => 'general']); + $mail = SettingCategory::factory()->parent($general)->titled('Mail', 'Outgoing mail')->create(['slug' => 'mail']); + $billing = SettingCategory::factory()->forStore('billing')->create(); + + expect($general->is_system)->toBeTrue() + ->and($ids === 'bigint' ? is_int($general->getKey()) : strlen((string) $general->getKey()))->toBe($ids === 'bigint' ? true : ($ids === 'uuid' ? 36 : 26)) + ->and($mail->parent?->is($general))->toBeTrue() + ->and($general->children()->pluck('slug')->all())->toBe(['mail']) + ->and(SettingCategory::query()->forStore('billing')->sole()->is($billing))->toBeTrue() + // What the factory wrote is what the engine reads. + ->and(settings()->categories()->get('mail')->parent?->value)->toBe('general') + ->and(settings()->categories()->get('mail')->title)->toBe('Mail') + ->and(settings()->categories()->get('general')->system)->toBeTrue(); +})->with(['bigint', 'uuid', 'ulid']); + +it('writes JSON titles in json translations mode', function (): void { + useDatabase(['translations.mode' => 'json']); + + SettingCategory::factory()->titled('Mail')->create(['slug' => 'mail']); + + expect(settings()->categories()->get('mail')->title)->toBe('Mail'); +}); + +it('builds values rows the engine reads', function (string $identity): void { + useDatabase(['identity.mode' => $identity, 'stores.settings.owners' => ['user'], 'stores.billing' => ['layers' => ['database']]], stores: ['billing']); + $category = SettingCategory::factory()->create(['slug' => 'site']); + + $row = Setting::factory()->key('site.name')->value('Acme')->inCategory($category)->create(); + Setting::factory()->owner('user', 9)->key('ui.theme')->value('dark')->locked()->create(); + Setting::factory()->key('site.title')->locale('fr')->value('Bonjour')->create(); + Setting::factory()->forStore('billing')->key('billing.currency')->value('EUR')->create(); + + expect($row->category?->is($category))->toBeTrue() + ->and(settings()->get('site.name'))->toBe('Acme') + ->and(settings()->for(new OwnerRef('user', 9))->get('ui.theme'))->toBe('dark') + ->and(settings()->locale('fr')->get('site.title'))->toBe('Bonjour') + ->and(settings()->store('billing')->get('billing.currency'))->toBe('EUR') + ->and(Setting::forStore('billing')->pluck('key')->all())->toBe(['billing.currency']) + ->and(Setting::forStore('billing')->first()?->storeName()->value)->toBe('billing') + ->and(Setting::query()->count())->toBe(3); +})->with(['slug_uid', 'slug_per_row', 'uid_only']); + +it('hides trashed rows, as the engine does', function (): void { + useDatabase(['stores.settings.soft_deletes' => true, 'categories.soft_deletes' => true]); + settings()->set('site.name', 'Acme'); + settings()->forget('site.name'); + settings()->categories()->create(new NewCategory('mail', 'Mail')); + settings()->categories()->delete('mail'); + + expect(DB::table('settings')->count())->toBe(1) + ->and(Setting::query()->count())->toBe(0) + ->and(DB::table('settings_categories')->count())->toBe(1) + ->and(SettingCategory::query()->count())->toBe(0); +}); + +it('builds definition and audit rows', function (): void { + useDatabase(['definitions.table' => true]); + + $definition = SettingDefinition::factory()->key('mail.host')->system()->create(); + $entry = SettingAuditEntry::factory()->action(AuditAction::Forget, AuditOutcome::Denied)->by('user', 3)->at(now()->subDay())->create(); + + expect($definition->is_system)->toBeTrue() + ->and(SettingDefinition::query()->where('key', 'mail.host')->value('slug'))->toBe('mail-host') + ->and(strlen($entry->id))->toBe(26) + ->and(settings()->audit()->action(AuditAction::Forget)->get())->toHaveCount(1) + ->and(settings()->audit()->get()[0]->actorId)->toBe('3'); +}); + +it('refuses a store name it cannot turn into a table', function (): void { + useDatabase(); + + expect(fn (): Builder => Setting::forStore('Bad Store'))->toThrow(InvalidIdentifier::class) + ->and(ModelContext::defaultStore()->value)->toBe('settings') + ->and(ModelContext::hasTenantColumn())->toBeFalse() + ->and(ModelContext::tenant())->toBe(''); +}); + +it('says so when a model is used before the provider registered it', function (): void { + $shape = new ReflectionProperty(ModelContext::class, 'shape'); + $saved = $shape->getValue(); + $shape->setValue(null, null); + + try { + expect(fn (): SchemaShape => ModelContext::shape())->toThrow(InvalidConfiguration::class, 'before SettingsServiceProvider'); + } finally { + $shape->setValue(null, $saved); + } +}); diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php index 5add2fe..67a326e 100644 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ b/tests/Feature/Database/SchemaMatrixTest.php @@ -8,8 +8,10 @@ use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Tests\Support\Pairwise; use Simtabi\Laranail\Settings\Actions\SyncDefinitions; +use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /* * §13: the schema switches, kept tested. Every pair of switch values meets in at least one shape @@ -32,6 +34,7 @@ function switchFactors(): array 'translations' => ['lang', 'json'], 'definitions_table' => [false, true], 'categories_soft_deletes' => [false, true], + 'tenancy' => ['none', 'column'], ]; } @@ -59,8 +62,10 @@ function switchShapes(): array } } - expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 576 : 10) - ->and(count($all))->toBe(141) + // 141 pairs among the eight Phase 2b switches, plus tenancy's 2 values × the other 18 + // values = 177; the full product doubles from 576 to 1,152. + expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 1152 : 10) + ->and(count($all))->toBe(177) ->and(array_diff_key($all, $covered))->toBe([]); })->group('matrix'); @@ -75,6 +80,7 @@ function switchShapes(): array 'translations.mode' => $shape['translations'], 'definitions.table' => $shape['definitions_table'], 'categories.soft_deletes' => $shape['categories_soft_deletes'], + 'tenancy.mode' => $shape['tenancy'], 'stores.settings.owners' => $dedicated ? [] : ['user'], 'stores.settings.soft_deletes' => $shape['soft_deletes'], 'stores.settings.inherits' => true, @@ -92,6 +98,8 @@ function switchShapes(): array } useDatabase($config, stores: $dedicated ? ['user_settings'] : [], ownerTables: ['users' => 'bigint']); + // Column-mode tenancy runs the whole scenario inside tenant `acme`. + app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): ?string => $shape['tenancy'] === 'column' ? 'acme' : null)); app(SchemaShapeRepository::class)->record(); DB::table('users')->insert(['id' => 1, 'name' => 'Ada']); @@ -127,6 +135,7 @@ function switchShapes(): array ->and((int) DB::table($ownerStore)->where('scope', 'user:1')->value('version'))->toBe($shape['soft_deletes'] ? 4 : 3) ->and(DB::table('settings')->where('key', 'mail.host')->value('category_id'))->toBe($again->id) ->and($again->id === $mail->id)->toBe($shape['categories_soft_deletes']) + ->and(DB::table('settings')->distinct()->pluck($shape['tenancy'] === 'column' ? 'tenant' : 'scope')->contains('acme'))->toBe($shape['tenancy'] === 'column') ->and($report)->toContain('No schema drift.') ->and($report)->toContain('The configuration matches the recorded schema.') ->and($exit)->toBe(0); diff --git a/tests/Feature/Database/SeedingTest.php b/tests/Feature/Database/SeedingTest.php new file mode 100644 index 0000000..832d8b9 --- /dev/null +++ b/tests/Feature/Database/SeedingTest.php @@ -0,0 +1,102 @@ + DefaultCategoriesSeeder::class, '--force' => true]); +} + +/** @return list */ +function categorySlugs(?string $store = null): array +{ + $categories = $store === null ? settings()->categories() : settings()->store($store)->categories(); + + return array_map(static fn (Category $category): string => $category->slug->value, $categories->all()); +} + +it('seeds the default categories as system categories of the default store', function (): void { + useDatabase(); + + seedDefaults(); + + $general = settings()->categories()->get('general'); + + expect(categorySlugs())->toBe(['general', 'appearance', 'localisation', 'mail', 'notifications', 'security']) + ->and($general->system)->toBeTrue() + ->and($general->title)->toBe('General') + ->and($general->icon)->toBe('cog') + ->and(DB::table('settings_audit')->where('action', 'manage_categories')->where('actor_type', 'system')->count())->toBe(6); +}); + +it('changes nothing when it runs again, a renamed category included', function (): void { + useDatabase(); + seedDefaults(); + settings()->categories()->rename('mail', 'Email'); + $before = DB::table('settings_categories')->orderBy('slug')->get(['slug', 'title', 'updated_at'])->all(); + + seedDefaults(); + + expect(DB::table('settings_categories')->orderBy('slug')->get(['slug', 'title', 'updated_at'])->all())->toEqual($before) + ->and(settings()->categories()->get('mail')->title)->toBe('Email'); +}); + +it('seeds the configured set into the listed stores, parents first', function (): void { + useDatabase([ + 'stores.billing' => ['layers' => ['database']], + 'seed.stores' => ['settings', 'billing'], + 'seed.categories' => [ + 'smtp' => ['title' => 'SMTP', 'parent' => 'mail'], + 'mail' => 'Mail', + ], + ], stores: ['billing']); + + seedDefaults(); + + // Listed order is display order (sort_order); creation order is parents first. + expect(categorySlugs('billing'))->toBe(['smtp', 'mail']) + ->and(settings()->store('billing')->categories()->get('smtp')->parent?->value)->toBe('mail') + ->and(categorySlugs())->toBe(['smtp', 'mail']); +}); + +it('seeds nothing when switched off', function (): void { + useDatabase(['seed.enabled' => false]); + + seedDefaults(); + + expect(DB::table('settings_categories')->count())->toBe(0); +}); + +it('refuses a set it cannot seed', function (array $seed, string $message): void { + useDatabase($seed); + + expect(fn () => app(DefaultCategoriesSeeder::class)->run(settings(), config()))->toThrow(InvalidConfiguration::class, $message); +})->with([ + 'no title' => [['seed.categories' => ['mail' => ['icon' => 'x']]], 'seed.categories.mail'], + 'missing parent' => [['seed.categories' => ['smtp' => ['title' => 'SMTP', 'parent' => 'mail']]], 'smtp'], + 'not a map' => [['seed.categories' => 'mail'], 'seed.categories'], + 'bad stores' => [['seed.stores' => [1]], 'seed.stores'], +]); + +it('runs with the application\'s db:seed through the package seeder hook', function (): void { + useDatabase(); + + $bundle = app(SeederRegistry::class)->get('laranail/settings:defaults'); + + // Registered for db:seed, with foreign keys still checked and events firing. + expect($bundle?->seeders())->toBe([DefaultCategoriesSeeder::class]) + ->and($bundle?->disablesForeignKeyChecks())->toBeFalse() + ->and($bundle?->shouldFireEvents())->toBeTrue(); +}); diff --git a/tests/Feature/Database/TenancyTest.php b/tests/Feature/Database/TenancyTest.php new file mode 100644 index 0000000..4f76464 --- /dev/null +++ b/tests/Feature/Database/TenancyTest.php @@ -0,0 +1,167 @@ +id`. */ +function switchableTenant(): object +{ + $tenant = new class + { + public ?string $id = null; + }; + + app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): ?string => $tenant->id)); + + return $tenant; +} + +it('adds the tenant column and puts it first in the identity index', function (): void { + useDatabase(['tenancy.mode' => 'column']); + + $identity = collect(Schema::getIndexes('settings'))->first(static fn (array $index): bool => str_ends_with($index['name'], '_identity_unique')); + $categories = collect(Schema::getIndexes('settings_categories'))->first(static fn (array $index): bool => str_ends_with($index['name'], '_store_slug_unique')); + + expect(Schema::hasColumn('settings', 'tenant'))->toBeTrue() + ->and(Schema::hasColumn('settings_categories', 'tenant'))->toBeTrue() + ->and(Schema::hasColumn('settings_audit', 'tenant'))->toBeTrue() + ->and($identity['columns'] ?? null)->toBe(['tenant', 'scope', 'key', 'locale']) + ->and($categories['columns'] ?? null)->toBe(['tenant', 'store', 'slug']); +}); + +it('has no tenant column in the other modes', function (string $mode): void { + useDatabase(['tenancy.mode' => $mode]); + + expect(Schema::hasColumn('settings', 'tenant'))->toBeFalse() + ->and(Schema::hasColumn('settings_categories', 'tenant'))->toBeFalse() + ->and(Schema::hasColumn('settings_audit', 'tenant'))->toBeFalse(); +})->with(['none', 'database']); + +it('keeps each tenant\'s values, categories and audit trail apart', function (): void { + useDatabase(['tenancy.mode' => 'column', 'stores.settings.owners' => ['user']]); + $tenant = switchableTenant(); + + $tenant->id = 'acme'; + settings()->set('site.name', 'Acme'); + settings()->for(new OwnerRef('user', 1))->set('ui.theme', 'dark'); + settings()->categories()->create(new NewCategory('mail', 'Acme mail')); + + $tenant->id = 'globex'; + settings()->set('site.name', 'Globex'); + settings()->categories()->create(new NewCategory('mail', 'Globex mail')); + + $tenant->id = null; + settings()->set('site.name', 'Central'); + + expect(settings()->get('site.name'))->toBe('Central') + ->and(settings()->for(new OwnerRef('user', 1))->get('ui.theme'))->toBeNull() + ->and(settings()->categories()->all())->toBe([]) + ->and(DB::table('settings')->orderBy('tenant')->pluck('tenant')->all())->toBe(['', 'acme', 'acme', 'globex']); + + $tenant->id = 'acme'; + + expect(settings()->get('site.name'))->toBe('Acme') + ->and(settings()->for(new OwnerRef('user', 1))->get('ui.theme'))->toBe('dark') + ->and(settings()->categories()->get('mail')->title)->toBe('Acme mail') + ->and(settings()->audit()->key('site.name')->get())->toHaveCount(1) + ->and(DB::table('settings_audit')->where('key', 'site.name')->count())->toBe(3); + + $tenant->id = 'globex'; + + expect(settings()->get('site.name'))->toBe('Globex') + ->and(settings()->categories()->get('mail')->title)->toBe('Globex mail'); + + settings()->forget('site.name'); + $tenant->id = 'acme'; + + expect(settings()->get('site.name'))->toBe('Acme'); +}); + +it('never answers one tenant\'s read from another tenant\'s preload in the same request', function (): void { + useDatabase(['tenancy.mode' => 'column', 'stores.settings.owners' => ['user']]); + $tenant = switchableTenant(); + $owner = new OwnerRef('user', 7); + + $tenant->id = 'acme'; + settings()->for($owner)->set('ui.theme', 'dark'); + settings()->preload([$owner]); + + $tenant->id = 'globex'; + + expect(settings()->for($owner)->get('ui.theme'))->toBeNull(); + + $tenant->id = 'acme'; + + expect(settings()->for($owner)->get('ui.theme'))->toBe('dark'); +}); + +it('scopes and stamps the models by tenant', function (): void { + useDatabase(['tenancy.mode' => 'column']); + $tenant = switchableTenant(); + + $tenant->id = 'acme'; + $category = SettingCategory::factory()->create(['slug' => 'billing']); + + $tenant->id = 'globex'; + + expect($category->tenant)->toBe('acme') + ->and(ModelContext::tenant())->toBe('globex') + ->and(SettingCategory::query()->count())->toBe(0); + + $tenant->id = 'acme'; + + expect(SettingCategory::query()->pluck('slug')->all())->toBe(['billing']); +}); + +it('picks the discriminator from configuration', function (): void { + $resolve = static function (mixed $driver): TenantDiscriminator { + config()->set('laranail.settings.tenancy.discriminator', $driver); + app()->forgetScopedInstances(); + + return app(TenantDiscriminator::class); + }; + + expect($resolve('auto'))->toBeInstanceOf(NullTenantDiscriminator::class) + ->and($resolve('null'))->toBeInstanceOf(NullTenantDiscriminator::class) + ->and($resolve(null))->toBeInstanceOf(NullTenantDiscriminator::class) + ->and($resolve(NullTenantDiscriminator::class))->toBeInstanceOf(NullTenantDiscriminator::class) + ->and($resolve('spatie')->current())->toBeNull() + ->and(fn (): TenantDiscriminator => $resolve('stancl'))->toThrow(InvalidConfiguration::class, 'needs stancl/tenancy') + ->and(fn (): TenantDiscriminator => $resolve('nonsense'))->toThrow(InvalidConfiguration::class, 'laranail.settings.tenancy.discriminator'); + + // spatie/laravel-multitenancy keeps the current tenant in the container. + app()->instance('currentTenant', new class + { + public function getKey(): int + { + return 42; + } + }); + + expect($resolve('spatie')->current())->toBe('42'); +}); + +it('refuses an unknown tenancy mode', function (): void { + config()->set('laranail.settings.tenancy.mode', 'schema'); + app()->forgetScopedInstances(); + + expect(fn () => app(SchemaShapeRepository::class)->configured()) + ->toThrow(InvalidConfiguration::class, 'laranail.settings.tenancy.mode'); +}); diff --git a/tests/Feature/GuardedSettingsTest.php b/tests/Feature/GuardedSettingsTest.php index b77df27..bae3e45 100644 --- a/tests/Feature/GuardedSettingsTest.php +++ b/tests/Feature/GuardedSettingsTest.php @@ -201,6 +201,12 @@ function withSession(?int $confirmedAt): void }); describe('step-up verification', function (): void { + // The boundary tests build "exactly 300 seconds ago" from one clock reading and the verifier + // reads the clock again; on a slow run (coverage) a second can pass between the two. + beforeEach(function (): void { + $this->freezeTime(); + }); + it('requires verification for a definition marked requiresVerification', function (): void { defineSetting()->requiresVerification()->register(); allowGates(Ability::Update, Ability::View); diff --git a/tests/Pest.php b/tests/Pest.php index be1f027..1058fb3 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -64,7 +64,7 @@ function auditInMemory(): InMemoryAuditSink /** * Put the default store on the database (database, runtime, shipped), with any store - * overrides, and run the package's migrations from its stubs, as an application would after + * overrides, and run the package's migration, as an application would after * `install`. On MySQL and Postgres the schema is dropped first, so every test starts empty. * * @param array $config extra `laranail.settings.*` values, set before migrating @@ -85,9 +85,7 @@ function useDatabase(array $config = [], array $stores = [], array $ownerTables $directory = sys_get_temp_dir() . '/laranail-settings-migrations-' . bin2hex(random_bytes(4)); mkdir($directory); - foreach (['create_settings_categories_table', 'create_settings_table', 'create_settings_audit_table', 'create_settings_definitions_table'] as $index => $stub) { - copy(dirname(__DIR__) . "/database/migrations/{$stub}.php.stub", sprintf('%s/2026_01_01_00000%d_%s.php', $directory, $index, $stub)); - } + copy(__DIR__ . '/../database/migrations/create_laranail_settings_tables.php', $directory . '/2026_01_01_000000_create_laranail_settings_tables.php'); if ($ownerTables !== []) { file_put_contents($directory . '/2025_01_01_000000_create_owner_tables.php', ' $store) { - $source = (string) file_get_contents(__DIR__ . '/../database/migrations/create_settings_table.php.stub'); + $source = (string) file_get_contents(__DIR__ . '/../database/migrations/create_laranail_settings_tables.php'); file_put_contents( sprintf('%s/2026_01_01_0001%02d_create_settings_%s_table.php', $directory, $index, $store), - str_replace("private string \$store = 'settings';", "private string \$store = '{$store}';", $source), + str_replace('private ?string $only = null;', "private ?string \$only = '{$store}';", $source), ); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 3d67e49..5f7f697 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -9,6 +9,7 @@ use Simtabi\Laranail\Package\Tools\Testing\IsolatedTestCase; use Simtabi\Laranail\DbTools\Providers\DbToolsServiceProvider; use Simtabi\Laranail\Settings\Providers\SettingsServiceProvider; +use Simtabi\Laranail\Package\Tools\Providers\PackageToolsServiceProvider; abstract class TestCase extends IsolatedTestCase { @@ -62,6 +63,8 @@ protected function defineEnvironment($app): void #[Override] protected function getPackageProviders($app): array { - return [DbToolsServiceProvider::class, SettingsServiceProvider::class]; + // package-tools' own provider is auto-discovered in an application; it holds the seeder + // registry the package's seeders are registered into. + return [PackageToolsServiceProvider::class, DbToolsServiceProvider::class, SettingsServiceProvider::class]; } } diff --git a/tests/Unit/DocsConformanceTest.php b/tests/Unit/DocsConformanceTest.php index d06b116..a8373d1 100644 --- a/tests/Unit/DocsConformanceTest.php +++ b/tests/Unit/DocsConformanceTest.php @@ -9,7 +9,7 @@ // Floor = the 21 pages shipped today (5 guides, 12 reference, 4 recipes). Raise it as pages // are added; a glob that suddenly matches fewer has broken rather than found a clean tree. it('conforms to the org docs standard', function (): void { - $this->assertDocsConformToStandard(dirname(__DIR__, 2), 21); + $this->assertDocsConformToStandard(dirname(__DIR__, 2), 24); expect(true)->toBeTrue(); }); diff --git a/tests/Unit/SchemaShapeTest.php b/tests/Unit/SchemaShapeTest.php index 80289fd..80049bc 100644 --- a/tests/Unit/SchemaShapeTest.php +++ b/tests/Unit/SchemaShapeTest.php @@ -5,6 +5,7 @@ use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Enums\StoreMode; +use Simtabi\Laranail\Settings\Enums\TenancyMode; use Simtabi\Laranail\Settings\Enums\IdentityMode; use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Database\StoreSchema; @@ -108,3 +109,18 @@ function settingsConfig(array $extra = []): array ->and(IdentityMode::SlugPerRow->hasUid())->toBeFalse() ->and(IdentityMode::SlugUid->hasSlug() && IdentityMode::SlugUid->hasUid())->toBeTrue(); }); + +it('records the tenancy mode, and reads a file written before it existed as none', function (): void { + $shape = SchemaShape::fromConfig(settingsConfig(['tenancy' => ['mode' => 'column']])); + $written = $shape->toArray(); + $older = $written; + unset($older['switches']['tenancy']); + + expect($shape->tenancy)->toBe(TenancyMode::Column) + ->and($written['switches']['tenancy'])->toBe('column') + ->and(SchemaShape::fromArray($written)->tenancy)->toBe(TenancyMode::Column) + ->and(SchemaShape::fromArray($older)->tenancy)->toBe(TenancyMode::None) + ->and($shape->withStore(new StoreSchema(new StoreName('extra')))->tenancy)->toBe(TenancyMode::Column) + ->and(SchemaShape::fromConfig(settingsConfig())->differencesFrom($shape))->toContain('switches.tenancy: column → none') + ->and(fn (): SchemaShape => SchemaShape::fromArray(['switches' => ['tenancy' => 'schema']] + $written))->toThrow(InvalidConfiguration::class, 'tenancy'); +}); diff --git a/tests/Unit/TenantDiscriminatorTest.php b/tests/Unit/TenantDiscriminatorTest.php new file mode 100644 index 0000000..21ebb30 --- /dev/null +++ b/tests/Unit/TenantDiscriminatorTest.php @@ -0,0 +1,43 @@ +current())->toBeNull(); +}); + +it('turns a tenant key into a string', function (mixed $key, ?string $expected): void { + expect(new ClosureTenantDiscriminator(static fn (): mixed => $key)->current())->toBe($expected); +})->with([ + 'none' => [null, null], + 'string' => ['acme', 'acme'], + 'integer' => [42, '42'], + 'stringable' => [new class implements Stringable + { + public function __toString(): string + { + return 'globex'; + } + }, 'globex'], + 'longest' => [str_repeat('a', 64), str_repeat('a', 64)], +]); + +it('refuses a key two tenants could share', function (mixed $key, string $message): void { + expect(fn (): ?string => new ClosureTenantDiscriminator(static fn (): mixed => $key)->current())->toThrow(InvalidConfiguration::class, $message); +})->with([ + 'array' => [['acme'], 'returned a array'], + 'float' => [1.5, 'returned a float'], + 'empty' => ['', '1-64 characters'], + 'too long' => [str_repeat('a', 65), '1-64 characters'], +]); + +it('knows which mode carries a tenant column', function (): void { + expect(TenancyMode::Column->hasColumn())->toBeTrue() + ->and(TenancyMode::None->hasColumn())->toBeFalse() + ->and(TenancyMode::Database->hasColumn())->toBeFalse(); +});