1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 18:04:03 +00:00

merge 3.x

This commit is contained in:
Samuel Štancl 2022-06-01 14:58:44 +02:00
commit eca7b336bc
30 changed files with 524 additions and 147 deletions

View file

@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Bootstrappers;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\DatabaseManager;
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;

View file

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
@ -54,23 +53,24 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
}
// Storage facade
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
/** @var FilesystemAdapter $filesystemDisk */
$filesystemDisk = Storage::disk($disk);
// todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
// todo0 @v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
$originalRoot = $this->app['config']["filesystems.disks.{$disk}.root"];
$this->originalPaths['disks'][$disk] = $originalRoot;
$this->originalPaths['disks'][$disk] = $filesystemDisk->getAdapter()->getPathPrefix();
$finalPrefix = str_replace(
['%storage_path%', '%tenant%'],
[storage_path(), $tenant->getTenantKey()],
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? '',
);
if ($root = str_replace(
'%storage_path%',
storage_path(),
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? ''
)) {
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root);
} else {
$root = $this->app['config']["filesystems.disks.{$disk}.root"];
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root . "/{$suffix}");
if (! $finalPrefix) {
$finalPrefix = $originalRoot
? rtrim($originalRoot, '/') . '/'. $suffix
: $suffix;
}
$this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix;
@ -87,14 +87,9 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
$this->app['url']->setAssetRoot($this->app['config']['app.asset_url']);
// Storage facade
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
/** @var FilesystemAdapter $filesystemDisk */
$filesystemDisk = Storage::disk($disk);
$root = $this->originalPaths['disks'][$disk];
$filesystemDisk->getAdapter()->setPathPrefix($root);
$this->app['config']["filesystems.disks.{$disk}.root"] = $root;
$this->app['config']["filesystems.disks.{$disk}.root"] = $this->originalPaths['disks'][$disk];
}
}
}

View file

@ -4,14 +4,18 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Support\Str;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\Testing\Fakes\QueueFake;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Queue\Events\JobRetryRequested;
use Illuminate\Support\Testing\Fakes\QueueFake;
use Illuminate\Contracts\Foundation\Application;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
class QueueTenancyBootstrapper implements TenancyBootstrapper
{
@ -21,6 +25,16 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
/** @var QueueManager */
protected $queue;
/**
* Don't persist the same tenant across multiple jobs even if they have the same tenant ID.
*
* This is useful when you're changing the tenant's state (e.g. properties in the `data` column) and want the next job to initialize tenancy again
* with the new data. Features like the Tenant Config are only executed when tenancy is initialized, so the re-initialization is needed in some cases.
*
* @var bool
*/
public static $forceRefresh = false;
/**
* The normal constructor is only executed after tenancy is bootstrapped.
* However, we're registering a hook to initialize tenancy. Therefore,
@ -28,7 +42,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
*/
public static function __constructStatic(Application $app)
{
static::setUpJobListener($app->make(Dispatcher::class));
static::setUpJobListener($app->make(Dispatcher::class), $app->runningUnitTests());
}
public function __construct(Repository $config, QueueManager $queue)
@ -39,25 +53,90 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
$this->setUpPayloadGenerator();
}
protected static function setUpJobListener($dispatcher)
protected static function setUpJobListener($dispatcher, $runningTests)
{
$dispatcher->listen(JobProcessing::class, function ($event) {
$tenantId = $event->job->payload()['tenant_id'] ?? null;
$previousTenant = null;
// The job is not tenant-aware
if (! $tenantId) {
return;
}
$dispatcher->listen(JobProcessing::class, function ($event) use (&$previousTenant) {
$previousTenant = tenant();
// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
if (tenancy()->initialized && tenant()->getTenantKey() === $tenantId) {
return;
}
// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
tenancy()->initialize(tenancy()->find($tenantId));
static::initializeTenancyForQueue($event->job->payload()['tenant_id'] ?? null);
});
if (version_compare(app()->version(), '8.64', '>=')) {
// JobRetryRequested only exists since Laravel 8.64
$dispatcher->listen(JobRetryRequested::class, function ($event) use (&$previousTenant) {
$previousTenant = tenant();
static::initializeTenancyForQueue($event->payload()['tenant_id'] ?? null);
});
}
// If we're running tests, we make sure to clean up after any artisan('queue:work') calls
$revertToPreviousState = function ($event) use (&$previousTenant, $runningTests) {
if ($runningTests) {
static::revertToPreviousState($event, $previousTenant);
}
};
$dispatcher->listen(JobProcessed::class, $revertToPreviousState); // artisan('queue:work') which succeeds
$dispatcher->listen(JobFailed::class, $revertToPreviousState); // artisan('queue:work') which fails
}
protected static function initializeTenancyForQueue($tenantId)
{
if (! $tenantId) {
// The job is not tenant-aware
if (tenancy()->initialized) {
// Tenancy was initialized, so we revert back to the central context
tenancy()->end();
}
return;
}
if (static::$forceRefresh) {
// Re-initialize tenancy between all jobs
if (tenancy()->initialized) {
tenancy()->end();
}
tenancy()->initialize(tenancy()->find($tenantId));
return;
}
if (tenancy()->initialized) {
// Tenancy is already initialized
if (tenant()->getTenantKey() === $tenantId) {
// It's initialized for the same tenant (e.g. dispatchNow was used, or the previous job also ran for this tenant)
return;
}
}
// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
tenancy()->initialize(tenancy()->find($tenantId));
}
protected static function revertToPreviousState($event, &$previousTenant)
{
$tenantId = $event->job->payload()['tenant_id'] ?? null;
// The job was not tenant-aware
if (! $tenantId) {
return;
}
// Revert back to the previous tenant
if (tenant() && $previousTenant && $previousTenant->isNot(tenant())) {
tenancy()->initialize($previousTenant);
}
// End tenancy
if (tenant() && (! $previousTenant)) {
tenancy()->end();
}
}
protected function setUpPayloadGenerator()

View file

@ -20,8 +20,10 @@ class CacheManager extends BaseCacheManager
$tags = [config('tenancy.cache.tag_base') . tenant()->getTenantKey()];
if ($method === 'tags') {
if (count($parameters) !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
$count = count($parameters);
if ($count !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. $count passed.");
}
$names = $parameters[0];

View file

@ -8,32 +8,26 @@ use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use Illuminate\Database\Migrations\Migrator;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Stancl\Tenancy\Events\DatabaseMigrated;
use Stancl\Tenancy\Events\MigratingDatabase;
class Migrate extends MigrateCommand
{
use HasATenantsOption, DealsWithMigrations;
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run migrations for tenant(s)';
/**
* Create a new command instance.
*
* @param Migrator $migrator
* @param Dispatcher $dispatcher
*/
protected static function getTenantCommandName(): string
{
return 'tenants:migrate';
}
public function __construct(Migrator $migrator, Dispatcher $dispatcher)
{
parent::__construct($migrator, $dispatcher);
$this->setName('tenants:migrate');
$this->specifyParameters();
}

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Commands;
use Illuminate\Console\Command;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Symfony\Component\Console\Input\InputOption;
final class MigrateFresh extends Command
{
@ -23,6 +24,8 @@ final class MigrateFresh extends Command
{
parent::__construct();
$this->addOption('--drop-views', null, InputOption::VALUE_NONE, 'Drop views along with tenant tables.', null);
$this->setName('tenants:migrate-fresh');
}
@ -37,6 +40,7 @@ final class MigrateFresh extends Command
$this->info('Dropping tables.');
$this->call('db:wipe', array_filter([
'--database' => 'tenant',
'--drop-views' => $this->option('drop-views'),
'--force' => true,
]));

View file

@ -7,13 +7,19 @@ namespace Stancl\Tenancy\Commands;
use Illuminate\Database\Console\Migrations\RollbackCommand;
use Illuminate\Database\Migrations\Migrator;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Stancl\Tenancy\Events\DatabaseRolledBack;
use Stancl\Tenancy\Events\RollingBackDatabase;
class Rollback extends RollbackCommand
{
use HasATenantsOption, DealsWithMigrations;
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
protected static function getTenantCommandName(): string
{
return 'tenants:rollback';
}
/**
* The console command description.
@ -31,8 +37,7 @@ class Rollback extends RollbackCommand
{
parent::__construct($migrator);
$this->setName('tenants:rollback');
$this->specifyParameters();
$this->specifyTenantSignature();
}
/**

View file

@ -34,7 +34,6 @@ class Run extends Command
{
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant->getTenantKey()}");
tenancy()->initialize($tenant);
$callback = function ($prefix = '') {
return function ($arguments, $argument) use ($prefix) {

View file

@ -0,0 +1,23 @@
<?php
namespace Stancl\Tenancy\Concerns;
trait ExtendsLaravelCommand
{
protected function specifyTenantSignature(): void
{
$this->specifyParameters();
}
public function getName(): ?string
{
return static::getTenantCommandName();
}
public static function getDefaultName(): ?string
{
return static::getTenantCommandName();
}
abstract protected static function getTenantCommandName(): string;
}

View file

@ -7,10 +7,12 @@ namespace Stancl\Tenancy\Database;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
/**
* @internal Class is subject to breaking changes in minor and patch versions.
@ -38,7 +40,7 @@ class DatabaseManager
*/
public function connectToTenant(TenantWithDatabase $tenant)
{
$this->database->purge('tenant');
$this->purgeTenantConnection();
$this->createTenantConnection($tenant);
$this->setDefaultConnection('tenant');
}
@ -48,10 +50,7 @@ class DatabaseManager
*/
public function reconnectToCentral()
{
if (tenancy()->initialized) {
$this->database->purge('tenant');
}
$this->purgeTenantConnection();
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
}
@ -60,7 +59,7 @@ class DatabaseManager
*/
public function setDefaultConnection(string $connection)
{
$this->app['config']['database.default'] = $connection;
$this->config['database.default'] = $connection;
$this->database->setDefaultConnection($connection);
}
@ -69,7 +68,19 @@ class DatabaseManager
*/
public function createTenantConnection(TenantWithDatabase $tenant)
{
$this->app['config']['database.connections.tenant'] = $tenant->database()->connection();
$this->config['database.connections.tenant'] = $tenant->database()->connection();
}
/**
* Purge the tenant database connection.
*/
public function purgeTenantConnection()
{
if (array_key_exists('tenant', $this->database->getConnections())) {
$this->database->purge('tenant');
}
unset($this->config['database.connections.tenant']);
}
/**
@ -81,8 +92,14 @@ class DatabaseManager
*/
public function ensureTenantCanBeCreated(TenantWithDatabase $tenant): void
{
if ($tenant->database()->manager()->databaseExists($database = $tenant->database()->getName())) {
$manager = $tenant->database()->manager();
if ($manager->databaseExists($database = $tenant->database()->getName())) {
throw new TenantDatabaseAlreadyExistsException($database);
}
if ($manager instanceof ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
throw new TenantDatabaseUserAlreadyExistsException($username);
}
}
}

View file

@ -36,8 +36,8 @@ class CreateDatabase implements ShouldQueue
return false;
}
$databaseManager->ensureTenantCanBeCreated($this->tenant);
$this->tenant->database()->makeCredentials();
$databaseManager->ensureTenantCanBeCreated($this->tenant);
$this->tenant->database()->manager()->createDatabase($this->tenant);
event(new DatabaseCreated($this->tenant));

View file

@ -5,7 +5,7 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Middleware;
use Closure;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
use Symfony\Component\HttpFoundation\IpUtils;
@ -29,7 +29,12 @@ class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
return $next($request);
}
throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
throw new HttpException(
503,
'Service Unavailable',
null,
isset($data['retry']) ? ['Retry-After' => $data['retry']] : []
);
}
return $next($request);

View file

@ -66,10 +66,10 @@ class Tenancy
return;
}
$this->initialized = false;
event(new Events\TenancyEnded($this));
$this->initialized = false;
$this->tenant = null;
}

View file

@ -7,7 +7,6 @@ namespace Stancl\Tenancy\TenantDatabaseManagers;
use Stancl\Tenancy\Concerns\CreatesDatabaseUsers;
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\DatabaseConfig;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
{
@ -26,10 +25,6 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
$hostname = $databaseConfig->connection()['host'];
$password = $databaseConfig->getPassword();
if ($this->userExists($username)) {
throw new TenantDatabaseUserAlreadyExistsException($username);
}
$this->database()->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}'");
$grants = implode(', ', static::$grants);

View file

@ -46,7 +46,11 @@ class PostgreSQLSchemaManager implements TenantDatabaseManager
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
{
$baseConfig['schema'] = $databaseName;
if (version_compare(app()->version(), '9.0', '>=')) {
$baseConfig['search_path'] = $databaseName;
} else {
$baseConfig['schema'] = $databaseName;
}
return $baseConfig;
}