Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4.x] Add command to bring the tenants up and down from maintenance and remove deprecated exception #761

Merged
merged 24 commits into from
Sep 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ec97965
Add bring up from maintenance function
stein-j Dec 2, 2021
db91130
Add up and down tenant maintenance commands
stein-j Dec 2, 2021
7875fbd
Rename commands signatures
stein-j Dec 2, 2021
829e149
Update TenancyServiceProvider.php
stein-j Dec 26, 2021
f430cd7
Complying to Laravel maintenance code and parameters
stein-j Dec 27, 2021
e009ce9
Update MaintenanceModeTest.php
stein-j Dec 27, 2021
7498b1b
Add maintenance mode via commands test
stein-j Dec 28, 2021
87025cf
Merge branch 'archtechx:3.x' into 3.x
stein-j Jan 6, 2022
3a4cd1b
Merge branch '3.x' into 3.x
stein-j Mar 8, 2022
5e1e263
Update CheckTenantForMaintenanceMode.php
stein-j Mar 8, 2022
179f00c
Update MaintenanceModeTest.php
stein-j Mar 8, 2022
dbdd7fd
Cookie bypass only for > Laravel 8
stein-j Mar 8, 2022
2c977b2
minor formatting change, trigger CI
stancl Jun 1, 2022
c90ae84
Merge branch 'master' of https://github.com/archtechx/tenancy into st…
lukinovec Aug 1, 2022
b97f409
clean
stein-j Aug 1, 2022
53d3553
Update MaintenanceModeTest.php
stein-j Aug 1, 2022
01cd60d
Merge branch '3.x' of github.com:stein-j/tenancy into stein-j/3.x
lukinovec Aug 2, 2022
0a2bbc5
Add comments for using the 'tenants' option in runForMultiple
lukinovec Aug 2, 2022
f478038
improve code
stancl Sep 29, 2022
147b2fe
Merge branch 'master' into stein-j/3.x
stancl Sep 29, 2022
abbeae3
php-cs-fixer
stancl Sep 29, 2022
99b86bf
fix php cs fixer config
stancl Sep 29, 2022
9358819
improve test logic
stancl Sep 29, 2022
b8a5516
remove version check since v4 will be L9+
stancl Sep 29, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'operators' => [
'=>' => null,
'|' => 'no_space',
'&' => 'no_space',
]
],
'blank_line_after_namespace' => true,
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"docker-m1": "ln -s docker-compose-m1.override.yml docker-compose.override.yml",
"coverage": "open coverage/phpunit/html/index.html",
"phpstan": "vendor/bin/phpstan",
"cs": "php-cs-fixer fix --config=.php-cs-fixer.php",
"test": "PHP_VERSION=8.1 ./test --no-coverage",
"test-full": "PHP_VERSION=8.1 ./test"
},
Expand Down
52 changes: 52 additions & 0 deletions src/Commands/Down.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Stancl\Tenancy\Commands;

use Illuminate\Foundation\Console\DownCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;

class Down extends DownCommand
{
use HasATenantsOption;

protected $signature = 'tenants:down
{--redirect= : The path that users should be redirected to}
{--retry= : The number of seconds after which the request may be retried}
{--refresh= : The number of seconds after which the browser may refresh}
{--secret= : The secret phrase that may be used to bypass maintenance mode}
{--status=503 : The status code that should be used when returning the maintenance mode response}';

protected $description = 'Put tenants into maintenance mode.';

public function handle(): void
{
// The base down command is heavily used. Instead of saving the data inside a file,
// the data is stored the tenant database, which means some Laravel features
// are not available with tenants.

$payload = $this->getDownDatabasePayload();

// This runs for all tenants if no --tenants are specified
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) use ($payload) {
$this->line("Tenant: {$tenant['id']}");
$tenant->putDownForMaintenance($payload);
});

$this->comment('Tenants are now in maintenance mode.');
}

/** Get the payload to be placed in the "down" file. */
protected function getDownDatabasePayload()
{
return [
'except' => $this->excludedPaths(),
'redirect' => $this->redirectPath(),
'retry' => $this->getRetryTime(),
'refresh' => $this->option('refresh'),
'secret' => $this->option('secret'),
'status' => (int) $this->option('status', 503),
];
}
}
27 changes: 27 additions & 0 deletions src/Commands/Up.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Stancl\Tenancy\Commands;

use Illuminate\Console\Command;
use Stancl\Tenancy\Concerns\HasATenantsOption;

class Up extends Command
{
use HasATenantsOption;

protected $signature = 'tenants:up';

protected $description = 'Put tenants out of maintenance mode.';

public function handle(): void
{
tenancy()->runForMultiple($this->getTenants(), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$tenant->bringUpFromMaintenance();
});

$this->comment('Tenants are now out of maintenance mode.');
}
}
28 changes: 19 additions & 9 deletions src/Database/Concerns/MaintenanceMode.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,27 @@

namespace Stancl\Tenancy\Database\Concerns;

use Carbon\Carbon;

/**
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait MaintenanceMode
{
public function putDownForMaintenance($data = [])
public function putDownForMaintenance($data = []): void
{
$this->update([
'maintenance_mode' => [
'except' => $data['except'] ?? null,
'redirect' => $data['redirect'] ?? null,
'retry' => $data['retry'] ?? null,
'refresh' => $data['refresh'] ?? null,
'secret' => $data['secret'] ?? null,
'status' => $data['status'] ?? 503,
],
]);
}

public function bringUpFromMaintenance(): void
{
$this->update(['maintenance_mode' => [
'time' => $data['time'] ?? Carbon::now()->getTimestamp(),
'message' => $data['message'] ?? null,
'retry' => $data['retry'] ?? null,
'allowed' => $data['allowed'] ?? [],
]]);
$this->update(['maintenance_mode' => null]);
}
}
3 changes: 2 additions & 1 deletion src/Jobs/CreateStorageSymlinks.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class CreateStorageSymlinks implements ShouldQueue

public function __construct(
public Tenant $tenant,
) {}
) {
}

public function handle(): void
{
Expand Down
30 changes: 24 additions & 6 deletions src/Middleware/CheckTenantForMaintenanceMode.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Closure;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
Expand All @@ -21,19 +20,38 @@ public function handle($request, Closure $next)
if (tenant('maintenance_mode')) {
$data = tenant('maintenance_mode');

if (isset($data['allowed']) && IpUtils::checkIp($request->ip(), (array) $data['allowed'])) {
return $next($request);
if (isset($data['secret']) && $request->path() === $data['secret']) {
return $this->bypassResponse($data['secret']);
}

if ($this->inExceptArray($request)) {
if ($this->hasValidBypassCookie($request, $data) ||
$this->inExceptArray($request)) {
return $next($request);
}

if (isset($data['redirect'])) {
$path = $data['redirect'] === '/'
? $data['redirect']
: trim($data['redirect'], '/');

if ($request->path() !== $path) {
return redirect($path);
}
}

if (isset($data['template'])) {
return response(
$data['template'],
(int) ($data['status'] ?? 503),
$this->getHeaders($data)
);
}

throw new HttpException(
503,
(int) ($data['status'] ?? 503),
'Service Unavailable',
null,
isset($data['retry']) ? ['Retry-After' => $data['retry']] : []
$this->getHeaders($data)
);
}

Expand Down
2 changes: 2 additions & 0 deletions src/TenancyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ public function boot(): void
Commands\TenantList::class,
Commands\TenantDump::class,
Commands\MigrateFresh::class,
Commands\Down::class,
Commands\Up::class,
]);

$this->publishes([
Expand Down
3 changes: 2 additions & 1 deletion tests/Etc/Tenant.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Stancl\Tenancy\Database\Models;

/**
* @method static static create(array $attributes = [])
*/
class Tenant extends Models\Tenant implements TenantWithDatabase
{
use HasDatabase, HasDomains;
use HasDatabase, HasDomains, MaintenanceMode;
}
42 changes: 33 additions & 9 deletions tests/MaintenanceModeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

declare(strict_types=1);

use Illuminate\Support\Facades\Artisan;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Tests\Etc\Tenant;

test('tenant can be in maintenance mode', function () {
test('tenants can be in maintenance mode', function () {
Route::get('/foo', function () {
return 'bar';
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
Expand All @@ -19,16 +19,40 @@
'domain' => 'acme.localhost',
]);

pest()->get('http://acme.localhost/foo')
->assertSuccessful();

tenancy()->end(); // flush stored tenant instance
pest()->get('http://acme.localhost/foo')->assertStatus(200);

$tenant->putDownForMaintenance();

pest()->expectException(HttpException::class);
pest()->withoutExceptionHandling()
->get('http://acme.localhost/foo');
tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(503);

$tenant->bringUpFromMaintenance();

tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(200);
});

test('tenants can be put into maintenance mode using artisan commands', function() {
Route::get('/foo', function () {
return 'bar';
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);

$tenant = MaintenanceTenant::create();
$tenant->domains()->create([
'domain' => 'acme.localhost',
]);

pest()->get('http://acme.localhost/foo')->assertStatus(200);

Artisan::call('tenants:down');

tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(503);

Artisan::call('tenants:up');

tenancy()->end(); // End tenancy before making a request
pest()->get('http://acme.localhost/foo')->assertStatus(200);
});

class MaintenanceTenant extends Tenant
Expand Down