diff --git a/assets/TenancyServiceProvider.stub.php b/assets/TenancyServiceProvider.stub.php index d8e76e6f2..a36262256 100644 --- a/assets/TenancyServiceProvider.stub.php +++ b/assets/TenancyServiceProvider.stub.php @@ -28,6 +28,7 @@ public function events() Jobs\CreateDatabase::class, Jobs\MigrateDatabase::class, // Jobs\SeedDatabase::class, + Jobs\CreateStorageSymlinks::class, // Your own jobs to prepare the tenant. // Provision API keys, create S3 buckets, anything you want! @@ -52,6 +53,7 @@ public function events() Events\TenantDeleted::class => [ JobPipeline::make([ Jobs\DeleteDatabase::class, + Jobs\RemoveStorageSymlinks::class, ])->send(function (Events\TenantDeleted $event) { return $event->tenant; })->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production. @@ -95,6 +97,12 @@ public function events() Listeners\UpdateSyncedResource::class, ], + // Storage symlinks + Events\CreatingStorageSymlink::class => [], + Events\StorageSymlinkCreated::class => [], + Events\RemovingStorageSymlink::class => [], + Events\StorageSymlinkRemoved::class => [], + // Fired only when a synced resource is changed in a different DB than the origin DB (to avoid infinite loops) Events\SyncedResourceChangedInForeignDatabase::class => [], ]; diff --git a/assets/config.php b/assets/config.php index 68a954403..7aff2b650 100644 --- a/assets/config.php +++ b/assets/config.php @@ -119,6 +119,24 @@ 'public' => '%storage_path%/app/public/', ], + /* + * Tenant-aware Storage::disk()->url() can be enabled for specific local disks here + * by mapping the disk's name to a name with '%tenant_id%' (this will be used as the public name of the disk). + * Doing that will override the disk's default URL with a URL containing the current tenant's key. + * + * For example, Storage::disk('public')->url('') will return https://your-app.test/storage/ by default. + * After adding 'public' => 'public-%tenant_id%' to 'url_override', + * the returned URL will be https://your-app.test/public-1/ (%tenant_id% gets substitued by the current tenant's ID). + * + * Use `php artisan tenants:link` to create a symbolic link from the tenant's storage to its public directory. + */ + 'url_override' => [ + // Note that the local disk you add must exist in the tenancy.filesystem.root_override config + // todo@v4 Rename %tenant_id% to %tenant_key% + // todo@v4 Rename url_override to something that describes the config key better + 'public' => 'public-%tenant_id%', + ], + /** * Should storage_path() be suffixed. * diff --git a/src/Actions/CreateStorageSymlinksAction.php b/src/Actions/CreateStorageSymlinksAction.php new file mode 100644 index 000000000..779a42af5 --- /dev/null +++ b/src/Actions/CreateStorageSymlinksAction.php @@ -0,0 +1,55 @@ + $storagePath) { + static::createLink($publicPath, $storagePath, $tenant, $relativeLink, $force); + } + } + } + + protected static function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void + { + event(new CreatingStorageSymlink($tenant)); + + if (static::symlinkExists($publicPath)) { + // If $force isn't passed, don't overwrite the existing symlink + throw_if(! $force, new Exception("The [$publicPath] link already exists.")); + + app()->make('files')->delete($publicPath); + } + + // Make sure the storage path exists before we create a symlink + if (! is_dir($storagePath)) { + mkdir($storagePath, 0777, true); + } + + if ($relativeLink) { + app()->make('files')->relativeLink($storagePath, $publicPath); + } else { + app()->make('files')->link($storagePath, $publicPath); + } + + event((new StorageSymlinkCreated($tenant))); + } +} diff --git a/src/Actions/RemoveStorageSymlinksAction.php b/src/Actions/RemoveStorageSymlinksAction.php new file mode 100644 index 000000000..bfbcfa0a5 --- /dev/null +++ b/src/Actions/RemoveStorageSymlinksAction.php @@ -0,0 +1,40 @@ + $storagePath) { + static::removeLink($publicPath, $tenant); + } + } + } + + protected static function removeLink(string $publicPath, Tenant $tenant): void + { + if (static::symlinkExists($publicPath)) { + event(new RemovingStorageSymlink($tenant)); + + app()->make('files')->delete($publicPath); + + event(new StorageSymlinkRemoved($tenant)); + } + } +} diff --git a/src/Bootstrappers/FilesystemTenancyBootstrapper.php b/src/Bootstrappers/FilesystemTenancyBootstrapper.php index 6f720e7c3..d90d36d0c 100644 --- a/src/Bootstrappers/FilesystemTenancyBootstrapper.php +++ b/src/Bootstrappers/FilesystemTenancyBootstrapper.php @@ -57,9 +57,10 @@ public function bootstrap(Tenant $tenant) foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) { // todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2 + $diskConfig = $this->app['config']["filesystems.disks.{$disk}"]; + $originalRoot = $diskConfig['root'] ?? null; - $originalRoot = $this->app['config']["filesystems.disks.{$disk}.root"]; - $this->originalPaths['disks'][$disk] = $originalRoot; + $this->originalPaths['disks']['path'][$disk] = $originalRoot; $finalPrefix = str_replace( ['%storage_path%', '%tenant%'], @@ -74,6 +75,19 @@ public function bootstrap(Tenant $tenant) } $this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix; + + // Storage Url + if ($diskConfig['driver'] === 'local') { + $this->originalPaths['disks']['url'][$disk] = $diskConfig['url'] ?? null; + + if ($url = str_replace( + '%tenant_id%', + $tenant->getTenantKey(), + $this->app['config']["tenancy.filesystem.url_override.{$disk}"] ?? '' + )) { + $this->app['config']["filesystems.disks.{$disk}.url"] = url($url); + } + } } } @@ -88,8 +102,16 @@ public function revert() // Storage facade Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']); - foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) { - $this->app['config']["filesystems.disks.{$disk}.root"] = $this->originalPaths['disks'][$disk]; + foreach ($this->app['config']['tenancy.filesystem.disks'] as $diskName) { + $this->app['config']["filesystems.disks.$diskName.root"] = $this->originalPaths['disks']['path'][$diskName]; + $diskConfig = $this->app['config']['filesystems.disks.' . $diskName]; + + // Storage Url + $url = $this->originalPaths['disks.url.' . $diskName] ?? null; + + if ($diskConfig['driver'] === 'local' && ! is_null($url)) { + $$this->app['config']["filesystems.disks.$diskName.url"] = $url; + } } } } diff --git a/src/Commands/Link.php b/src/Commands/Link.php new file mode 100644 index 000000000..061f2d3d0 --- /dev/null +++ b/src/Commands/Link.php @@ -0,0 +1,73 @@ +getTenants(); + + try { + if ($this->option('remove')) { + $this->removeLinks($tenants); + } else { + $this->createLinks($tenants); + } + } catch (Exception $exception) { + $this->error($exception->getMessage()); + } + } + + protected function removeLinks(LazyCollection $tenants): void + { + RemoveStorageSymlinksAction::handle($tenants); + + $this->info('The links have been removed.'); + } + + protected function createLinks(LazyCollection $tenants): void + { + CreateStorageSymlinksAction::handle( + $tenants, + $this->option('relative') ?? false, + $this->option('force') ?? false, + ); + + $this->info('The links have been created.'); + } +} diff --git a/src/Concerns/DealsWithTenantSymlinks.php b/src/Concerns/DealsWithTenantSymlinks.php new file mode 100644 index 000000000..a4c972bb5 --- /dev/null +++ b/src/Concerns/DealsWithTenantSymlinks.php @@ -0,0 +1,44 @@ + 'storage path']). + * + * Tenants can have a symlink for each disk registered in the tenancy.filesystem.url_override config. + * + * This is used for creating all possible tenant symlinks and removing all existing tenant symlinks. + */ + protected static function possibleTenantSymlinks(Tenant $tenant): Collection + { + $diskUrls = config('tenancy.filesystem.url_override'); + $disks = config('tenancy.filesystem.root_override'); + $suffixBase = config('tenancy.filesystem.suffix_base'); + $symlinks = collect(); + $tenantKey = $tenant->getTenantKey(); + + foreach ($diskUrls as $disk => $publicPath) { + $storagePath = str_replace('%storage_path%', $suffixBase . $tenantKey, $disks[$disk]); + $publicPath = str_replace('%tenant_id%', $tenantKey, $publicPath); + + tenancy()->central(function () use ($symlinks, $publicPath, $storagePath) { + $symlinks->push([public_path($publicPath) => storage_path($storagePath)]); + }); + } + + return $symlinks->mapWithKeys(fn ($item) => $item); + } + + /** Determine if the provided path is an existing symlink. */ + protected static function symlinkExists(string $link): bool + { + return file_exists($link) && is_link($link); + } +} diff --git a/src/Events/CreatingStorageSymlink.php b/src/Events/CreatingStorageSymlink.php new file mode 100644 index 000000000..13937174c --- /dev/null +++ b/src/Events/CreatingStorageSymlink.php @@ -0,0 +1,9 @@ +tenant = $tenant; + } + + /** + * Execute the job. + * + * @return void + */ + public function handle() + { + CreateStorageSymlinksAction::handle($this->tenant); + } +} diff --git a/src/Jobs/RemoveStorageSymlinks.php b/src/Jobs/RemoveStorageSymlinks.php new file mode 100644 index 000000000..3022da799 --- /dev/null +++ b/src/Jobs/RemoveStorageSymlinks.php @@ -0,0 +1,40 @@ +tenant = $tenant; + } + + /** + * Execute the job. + * + * @return void + */ + public function handle() + { + RemoveStorageSymlinksAction::handle($this->tenant); + } +} diff --git a/src/TenancyServiceProvider.php b/src/TenancyServiceProvider.php index 3850720c5..b8eee487b 100644 --- a/src/TenancyServiceProvider.php +++ b/src/TenancyServiceProvider.php @@ -78,6 +78,7 @@ public function boot(): void { $this->commands([ Commands\Run::class, + Commands\Link::class, Commands\Seed::class, Commands\Install::class, Commands\Migrate::class, diff --git a/tests/ActionTest.php b/tests/ActionTest.php new file mode 100644 index 000000000..cc0950ea7 --- /dev/null +++ b/tests/ActionTest.php @@ -0,0 +1,69 @@ + [ + FilesystemTenancyBootstrapper::class, + ], + 'tenancy.filesystem.suffix_base' => 'tenant-', + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' + ]); + + /** @var Tenant $tenant */ + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); + + tenancy()->initialize($tenant); + + $this->assertDirectoryDoesNotExist($publicPath = public_path("public-$tenantKey")); + + CreateStorageSymlinksAction::handle($tenant); + + $this->assertDirectoryExists($publicPath); + $this->assertEquals(storage_path("app/public/"), readlink($publicPath)); +}); + +test('remove storage symlinks action works', function() { + config([ + 'tenancy.bootstrappers' => [ + FilesystemTenancyBootstrapper::class, + ], + 'tenancy.filesystem.suffix_base' => 'tenant-', + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' + ]); + + /** @var Tenant $tenant */ + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); + + tenancy()->initialize($tenant); + + CreateStorageSymlinksAction::handle($tenant); + + $this->assertDirectoryExists($publicPath = public_path("public-$tenantKey")); + + RemoveStorageSymlinksAction::handle($tenant); + + $this->assertDirectoryDoesNotExist($publicPath); +}); diff --git a/tests/BootstrapperTest.php b/tests/BootstrapperTest.php index ada6b9643..a610fbd24 100644 --- a/tests/BootstrapperTest.php +++ b/tests/BootstrapperTest.php @@ -14,16 +14,19 @@ use Stancl\Tenancy\Events\TenancyEnded; use Stancl\Tenancy\Jobs\CreateDatabase; use Stancl\Tenancy\Events\TenantCreated; +use Stancl\Tenancy\Events\TenantDeleted; +use Stancl\Tenancy\Events\DeletingTenant; use Illuminate\Filesystem\FilesystemAdapter; use Stancl\Tenancy\Events\TenancyInitialized; +use Stancl\Tenancy\Jobs\CreateStorageSymlinks; +use Stancl\Tenancy\Jobs\RemoveStorageSymlinks; use Stancl\Tenancy\Listeners\BootstrapTenancy; +use Stancl\Tenancy\Listeners\DeleteTenantStorage; use Stancl\Tenancy\Listeners\RevertToCentralContext; use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper; -use Stancl\Tenancy\Events\DeletingTenant; -use Stancl\Tenancy\Listeners\DeleteTenantStorage; beforeEach(function () { $this->mockConsoleOutput = false; @@ -192,8 +195,121 @@ 'tenancy.bootstrappers' => [ FilesystemTenancyBootstrapper::class, ], + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' ]); + $tenant1 = Tenant::create(); + $tenant2 = Tenant::create(); + $tenant1StorageUrl = 'http://localhost/public-' . $tenant1->getKey().'/'; + $tenant2StorageUrl = 'http://localhost/public-' . $tenant2->getKey().'/'; + + tenancy()->initialize($tenant1); + + $this->assertEquals( + $tenant1StorageUrl, + Storage::disk('public')->url('') + ); + + Storage::disk('public')->put($tenant1FileName = 'tenant1.txt', 'text'); + + $this->assertEquals( + $tenant1StorageUrl . $tenant1FileName, + Storage::disk('public')->url($tenant1FileName) + ); + + tenancy()->initialize($tenant2); + + $this->assertEquals( + $tenant2StorageUrl, + Storage::disk('public')->url('') + ); + + Storage::disk('public')->put($tenant2FileName = 'tenant2.txt', 'text'); + + $this->assertEquals( + $tenant2StorageUrl . $tenant2FileName, + Storage::disk('public')->url($tenant2FileName) + ); +}); + +test('files can get fetched using the storage url', function() { + config([ + 'tenancy.bootstrappers' => [ + FilesystemTenancyBootstrapper::class, + ], + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' + ]); + + $tenant1 = Tenant::create(); + $tenant2 = Tenant::create(); + + pest()->artisan('tenants:link'); + + // First tenant + tenancy()->initialize($tenant1); + Storage::disk('public')->put($tenantFileName = 'tenant1.txt', $tenantKey = $tenant1->getTenantKey()); + + $url = Storage::disk('public')->url($tenantFileName); + $tenantDiskName = Str::of(config('tenancy.filesystem.url_override.public'))->replace('%tenant_id%', $tenantKey); + $hostname = Str::of($url)->before($tenantDiskName); + $parsedUrl = Str::of($url)->after($hostname); + + expect(file_get_contents(public_path($parsedUrl)))->toBe($tenantKey); + + // Second tenant + tenancy()->initialize($tenant2); + Storage::disk('public')->put($tenantFileName = 'tenant2.txt', $tenantKey = $tenant2->getTenantKey()); + + $url = Storage::disk('public')->url($tenantFileName); + $tenantDiskName = Str::of(config('tenancy.filesystem.url_override.public'))->replace('%tenant_id%', $tenantKey); + $hostname = Str::of($url)->before($tenantDiskName); + $parsedUrl = Str::of($url)->after($hostname); + + expect(file_get_contents(public_path($parsedUrl)))->toBe($tenantKey); +}); + +test('create and delete storage symlinks jobs work', function() { + Event::listen( + TenantCreated::class, + JobPipeline::make([CreateStorageSymlinks::class])->send(function (TenantCreated $event) { + return $event->tenant; + })->toListener() + ); + + Event::listen( + TenantDeleted::class, + JobPipeline::make([RemoveStorageSymlinks::class])->send(function (TenantDeleted $event) { + return $event->tenant; + })->toListener() + ); + + config([ + 'tenancy.bootstrappers' => [ + FilesystemTenancyBootstrapper::class, + ], + 'tenancy.filesystem.suffix_base' => 'tenant-', + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' + ]); + + /** @var Tenant $tenant */ + $tenant = Tenant::create(); + + tenancy()->initialize($tenant); + + $tenantKey = $tenant->getTenantKey(); + + $this->assertDirectoryExists(storage_path("app/public")); + $this->assertEquals(storage_path("app/public/"), readlink(public_path("public-$tenantKey"))); + + $tenant->delete(); + + $this->assertDirectoryDoesNotExist(public_path("public-$tenantKey")); +}); + +test('local storage public urls are generated correctly', function() { Event::listen(DeletingTenant::class, DeleteTenantStorage::class); tenancy()->initialize(Tenant::create()); @@ -220,14 +336,14 @@ function getDiskPrefix(string $disk): string return $adapter->getPathPrefix(); } - $prefixer = (new ReflectionObject($adapter))->getProperty('prefixer'); - $prefixer->setAccessible(true); + $prefixer = (new ReflectionObject($adapter))->getProperty('prefixer'); + $prefixer->setAccessible(true); - // reflection -> instance - $prefixer = $prefixer->getValue($adapter); + // reflection -> instance + $prefixer = $prefixer->getValue($adapter); - $prefix = (new ReflectionProperty($prefixer, 'prefix')); - $prefix->setAccessible(true); + $prefix = (new ReflectionProperty($prefixer, 'prefix')); + $prefix->setAccessible(true); - return $prefix->getValue($prefixer); + return $prefix->getValue($prefixer); } diff --git a/tests/CommandsTest.php b/tests/CommandsTest.php index ebabdb365..f7785bf22 100644 --- a/tests/CommandsTest.php +++ b/tests/CommandsTest.php @@ -29,6 +29,15 @@ DatabaseTenancyBootstrapper::class, ]]); + config([ + 'tenancy.bootstrappers' => [ + DatabaseTenancyBootstrapper::class, + ], + 'tenancy.filesystem.suffix_base' => 'tenant-', + 'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/', + 'tenancy.filesystem.url_override.public' => 'public-%tenant_id%' + ]); + Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class); }); @@ -196,6 +205,43 @@ ->expectsOutput('Tenant: ' . $tenantId2); }); +test('link command works', function() { + $tenantId1 = Tenant::create()->getTenantKey(); + $tenantId2 = Tenant::create()->getTenantKey(); + pest()->artisan('tenants:link'); + + $this->assertDirectoryExists(storage_path("tenant-$tenantId1/app/public")); + $this->assertEquals(storage_path("tenant-$tenantId1/app/public/"), readlink(public_path("public-$tenantId1"))); + + $this->assertDirectoryExists(storage_path("tenant-$tenantId2/app/public")); + $this->assertEquals(storage_path("tenant-$tenantId2/app/public/"), readlink(public_path("public-$tenantId2"))); + + pest()->artisan('tenants:link', [ + '--remove' => true, + ]); + + $this->assertDirectoryDoesNotExist(public_path("public-$tenantId1")); + $this->assertDirectoryDoesNotExist(public_path("public-$tenantId2")); +}); + +test('link command works with a specified tenant', function() { + $tenantKey = Tenant::create()->getTenantKey(); + + pest()->artisan('tenants:link', [ + '--tenants' => [$tenantKey], + ]); + + $this->assertDirectoryExists(storage_path("tenant-$tenantKey/app/public")); + $this->assertEquals(storage_path("tenant-$tenantKey/app/public/"), readlink(public_path("public-$tenantKey"))); + + pest()->artisan('tenants:link', [ + '--remove' => true, + '--tenants' => [$tenantKey], + ]); + + $this->assertDirectoryDoesNotExist(public_path("public-$tenantKey")); +}); + test('run command works when sub command asks questions and accepts arguments', function () { $tenant = Tenant::create(); $id = $tenant->getTenantKey(); diff --git a/tests/SingleDatabaseTenancyTest.php b/tests/SingleDatabaseTenancyTest.php index e980e4eb5..8914a6d77 100644 --- a/tests/SingleDatabaseTenancyTest.php +++ b/tests/SingleDatabaseTenancyTest.php @@ -61,7 +61,7 @@ expect(Comment::count())->toBe(2); }); -test('secondary models a r e scoped to the current tenant when accessed directly and parent relationship traitis used', function () { +test('secondary models ARE scoped to the current tenant when accessed directly and parent relationship trait is used', function () { $acme = Tenant::create([ 'id' => 'acme', ]);