1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-06 03:34:04 +00:00

Merge branch '3.x' into 3.x

This commit is contained in:
Nick Kitchen 2022-02-20 08:30:33 +11:00 committed by GitHub
commit cbfefc6b20
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 398 additions and 88 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

@ -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,14 @@ 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.
*/
public static bool $forceRefresh = false;
/**
* The normal constructor is only executed after tenancy is bootstrapped.
* However, we're registering a hook to initialize tenancy. Therefore,
@ -28,7 +40,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 +51,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 (Str::startsWith(app()->version(), '8')) {
// JobRetryRequested only exists since Laravel 8
$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

@ -55,7 +55,7 @@ class Migrate extends MigrateCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new MigratingDatabase($tenant));

View file

@ -53,7 +53,7 @@ class Rollback extends RollbackCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new RollingBackDatabase($tenant));

View file

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

View file

@ -51,7 +51,7 @@ class Seed extends SeedCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new SeedingDatabase($tenant));

View file

@ -36,9 +36,9 @@ class TenantList extends Command
->cursor()
->each(function (Tenant $tenant) {
if ($tenant->domains) {
$this->line("[Tenant] id: {$tenant['id']} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
} else {
$this->line("[Tenant] id: {$tenant['id']}");
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()}");
}
});
}

View file

@ -38,7 +38,7 @@ class DatabaseManager
*/
public function connectToTenant(TenantWithDatabase $tenant)
{
$this->database->purge('tenant');
$this->purgeTenantConnection();
$this->createTenantConnection($tenant);
$this->setDefaultConnection('tenant');
}
@ -48,10 +48,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 +57,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 +66,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']);
}
/**

View file

@ -9,7 +9,7 @@ use Facade\IgnitionContracts\ProvidesSolution;
use Facade\IgnitionContracts\Solution;
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
// todo: in v3 this should be suffixed with Exception
// todo: in v4 this should be suffixed with Exception
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
{
public function __construct($tenant_id)

View file

@ -40,7 +40,7 @@ class UniversalRoutes implements Feature
}
// Loop one level deep and check if the route's middleware
// groups have the searhced middleware group inside them
// groups have the searched middleware group inside them
$middlewareGroups = Router::getMiddlewareGroups();
foreach ($route->gatherMiddleware() as $inner) {
if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) {

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,6 +7,7 @@ namespace Stancl\Tenancy;
use Illuminate\Cache\CacheManager;
use Illuminate\Support\ServiceProvider;
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
use Stancl\Tenancy\Contracts\Domain;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Resolvers\DomainTenantResolver;