Skip to content

Commit

Permalink
merge 3.x
Browse files Browse the repository at this point in the history
  • Loading branch information
stancl committed Jun 1, 2022
2 parents 5980c46 + 51228de commit eca7b33
Show file tree
Hide file tree
Showing 30 changed files with 517 additions and 140 deletions.
11 changes: 5 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ jobs:

strategy:
matrix:
php: ["7.4", "8.0.11"]
laravel: ["^6.0", "^8.0"]
php: ["7.3", "8.0"]
laravel: ["^6.0", "^8.0", "^9.0"]
exclude:
- laravel: "^9.0"
php: "7.3"

steps:
- uses: actions/checkout@v2
Expand All @@ -26,7 +29,3 @@ jobs:
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
- name: Run tests
run: ./test
- name: Send code coverage to codecov
env:
CODECOV_TOKEN: 24382d15-84e7-4a55-bea4-c4df96a24a9b
run: bash <(curl -s https://codecov.io/bash)
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ psysh
phpunit_var_*.xml
coverage/
clover.xml
tests/Etc/tmp/queuetest.json
docker-compose.override.yml
13 changes: 13 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,16 @@ StyleCI will flag code style violations in your pull requests.
Run `docker-compose up -d` to start the containers. Then run `./test` to run the tests.

When you're done testing, run `docker-compose down` to shut down the containers.

### Docker on M1

You can add:
```yaml
services:
mysql:
platform: linux/amd64
mysql2:
platform: linux/amd64
```
to `docker-compose.override.yml` to make `docker-compose up-d` work on M1.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
# && if [ "${PHP_VERSION}" = "7.4" ]; then docker-php-ext-configure gd --with-freetype --with-jpeg; else docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/; fi \
&& docker-php-ext-install -j$(nproc) gd pdo pdo_mysql pdo_pgsql pdo_sqlite pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
# install the redis php extension
&& pecl install redis-5.3.2 \
&& pecl install redis-5.3.7 \
&& docker-php-ext-enable redis \
# install the pcov extention
&& pecl install pcov \
Expand Down
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
</p>

<p align="center">
<a href="https://laravel.com"><img alt="Laravel 6.x/7.x/8.x" src="https://img.shields.io/badge/laravel-6.x/7.x/8.x-red.svg"></a>
<a href="https://laravel.com"><img alt="Laravel 9.x" src="https://img.shields.io/badge/laravel-9.x-red.svg"></a>
<a href="https://packagist.org/packages/stancl/tenancy"><img alt="Latest Stable Version" src="https://poser.pugx.org/stancl/tenancy/version"></a>
<a href="https://github.com/stancl/tenancy/actions"><img alt="GitHub Actions CI status" src="https://github.com/stancl/tenancy/workflows/CI/badge.svg"></a>
<a href="https://codecov.io/gh/stancl/tenancy"><img alt="codecov" src="https://codecov.io/gh/stancl/tenancy/branch/3.x/graph/badge.svg"></a>
<a href="https://github.com/stancl/tenancy/blob/3.x/DONATIONS.md"><img alt="Donate" src="https://img.shields.io/badge/Donate-%3C3-red"></a>
</p>

Expand Down
3 changes: 2 additions & 1 deletion assets/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
'central_connection' => env('DB_CONNECTION', 'central'),

/**
* Connection used as a "template" for the tenant database connection.
* Connection used as a "template" for the dynamically created tenant database connection.
* Note: don't name your template connection tenant. That name is reserved by package.
*/
'template_tenant_connection' => null,

Expand Down
9 changes: 4 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,16 @@
],
"require": {
"ext-json": "*",
"illuminate/support": "dev-master",
"illuminate/support": "^6.0|^7.0|^8.0|^9.0",
"facade/ignition-contracts": "^1.0",
"ramsey/uuid": "^3.7|^4.0",
"stancl/jobpipeline": "dev-master",
"stancl/virtualcolumn": "dev-master"
},
"require-dev": {
"vlucas/phpdotenv": "^3.3|^4.0|^5.0",
"laravel/framework": "dev-master",
"orchestra/testbench-browser-kit": "dev-master",
"league/flysystem-aws-s3-v3": "*",
"laravel/framework": "^6.0|^7.0|^8.0|^9.0",
"orchestra/testbench": "^4.0|^5.0|^6.0|^7.0",
"league/flysystem-aws-s3-v3": "^1.0|^3.0",
"doctrine/dbal": "^2.10",
"spatie/valuestore": "^1.2.5"
},
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ services:
build:
context: .
args:
PHP_VERSION: ${PHP_VERSION}
PHP_VERSION: ${PHP_VERSION:-8.1}
depends_on:
mysql:
condition: service_healthy
Expand Down
1 change: 1 addition & 0 deletions src/Bootstrappers/DatabaseTenancyBootstrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

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;

Expand Down
37 changes: 16 additions & 21 deletions src/Bootstrappers/FilesystemTenancyBootstrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
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;
Expand Down Expand Up @@ -54,23 +53,24 @@ public function bootstrap(Tenant $tenant)
}

// 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;
Expand All @@ -87,14 +87,9 @@ public function revert()
$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];
}
}
}
111 changes: 95 additions & 16 deletions src/Bootstrappers/QueueTenancyBootstrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@

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 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;
use Stancl\Tenancy\Contracts\Tenant;

class QueueTenancyBootstrapper implements TenancyBootstrapper
{
Expand All @@ -21,14 +25,24 @@ 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,
* we need to register the hook at service provider execution time.
*/
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)
Expand All @@ -39,25 +53,90 @@ public function __construct(Repository $config, QueueManager $queue)
$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;

$dispatcher->listen(JobProcessing::class, function ($event) use (&$previousTenant) {
$previousTenant = tenant();

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 (! $tenantId) {
return;
if (tenancy()->initialized) {
// Tenancy was initialized, so we revert back to the central context
tenancy()->end();
}

// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
if (tenancy()->initialized && tenant()->getTenantKey() === $tenantId) {
return;
return;
}

if (static::$forceRefresh) {
// Re-initialize tenancy between all jobs
if (tenancy()->initialized) {
tenancy()->end();
}

// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
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()
Expand Down
6 changes: 4 additions & 2 deletions src/CacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ public function __call($method, $parameters)
$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];
Expand Down
20 changes: 7 additions & 13 deletions src/Commands/Migrate.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,26 @@
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();
}

Expand Down
Loading

0 comments on commit eca7b33

Please sign in to comment.