mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 16:14:02 +00:00
Synced resources - proof of concept
This commit is contained in:
parent
86a98b2bc8
commit
daae67c0f7
8 changed files with 393 additions and 0 deletions
14
src/Contracts/SyncMaster.php
Normal file
14
src/Contracts/SyncMaster.php
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
// todo rename?
|
||||
/**
|
||||
* @property-read Tenant[]|Collection $tenants
|
||||
*/
|
||||
interface SyncMaster extends Syncable
|
||||
{
|
||||
public function tenants(); // Probably should return BelongsToMany
|
||||
}
|
||||
12
src/Contracts/Syncable.php
Normal file
12
src/Contracts/Syncable.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Contracts;
|
||||
|
||||
// todo add comments
|
||||
interface Syncable
|
||||
{
|
||||
public function getGlobalIdentifierKeyName(): string;
|
||||
public function getGlobalIdentifierKey(): string;
|
||||
public function getCentralModelName(): string;
|
||||
public function getSyncedAttributeNames(): array;
|
||||
}
|
||||
16
src/Database/Models/Concerns/ResourceSyncing.php
Normal file
16
src/Database/Models/Concerns/ResourceSyncing.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Database\Models\Concerns;
|
||||
|
||||
use Stancl\Tenancy\Contracts\Syncable;
|
||||
use Stancl\Tenancy\Events\SyncedResourceSaved;
|
||||
|
||||
trait ResourceSyncing
|
||||
{
|
||||
public static function bootResourceSyncing()
|
||||
{
|
||||
static::saving(function (Syncable $model) {
|
||||
event(new SyncedResourceSaved($model, tenant()));
|
||||
});
|
||||
}
|
||||
}
|
||||
54
src/Events/Listeners/UpdateSyncedResource.php
Normal file
54
src/Events/Listeners/UpdateSyncedResource.php
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Events\Listeners;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Stancl\Tenancy\Contracts\SyncMaster;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Events\SyncedResourceSaved;
|
||||
|
||||
class UpdateSyncedResource
|
||||
{
|
||||
public function handle(SyncedResourceSaved $event)
|
||||
{
|
||||
$syncedAttributes = $event->model->only($event->model->getSyncedAttributeNames());
|
||||
|
||||
// We update the central record only if the event comes from tenant context.
|
||||
if ($event->tenant) {
|
||||
/** @var Model|SyncMaster $centralModel */
|
||||
$centralModel = $event->model->getCentralModelName()
|
||||
::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
|
||||
->first();
|
||||
|
||||
// We disable events for this call, to avoid triggering this event & listener again.
|
||||
$centralModel->withoutEvents(function () use ($centralModel, $syncedAttributes) {
|
||||
$centralModel->update($syncedAttributes);
|
||||
});
|
||||
|
||||
$tenants = $centralModel->tenants->except($event->tenant->getTenantKey());
|
||||
} else {
|
||||
$centralModel = $event->model;
|
||||
$tenants = $centralModel->tenants;
|
||||
}
|
||||
|
||||
foreach ($tenants as $tenant) {
|
||||
// todo: performance optimization - $tenant->run() does tenancy()->end() after each call.
|
||||
// we dont want that when we want to initialize for the next tenant afterwards rather than for the previous tenant
|
||||
// so we should write a method like run() for running things on multiple tenants efficiently
|
||||
|
||||
$tenant->run(function () use ($event, $syncedAttributes) {
|
||||
// Forget instance state and find the model,
|
||||
// again in the current tenant's context.
|
||||
|
||||
/** @var Tenant|Model $model */
|
||||
$localModel = $event->model::find($event->model->getKey());
|
||||
|
||||
// Also: We're syncing attributes, not columns, which is
|
||||
// why we're using Eloquent instead of direct DB queries.
|
||||
|
||||
// We disable events for this call, to avoid triggering this event & listener again.
|
||||
$localModel->update($syncedAttributes);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
22
src/Events/SyncedResourceSaved.php
Normal file
22
src/Events/SyncedResourceSaved.php
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Events;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Stancl\Tenancy\Contracts\Syncable;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
||||
class SyncedResourceSaved
|
||||
{
|
||||
/** @var Syncable|Model */
|
||||
public $model;
|
||||
|
||||
/** @var Tenant|Model|null */
|
||||
public $tenant;
|
||||
|
||||
public function __construct(Syncable $model, ?Tenant $tenant)
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->tenant = $tenant;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class CreateTenantUsersTable extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function up()
|
||||
{
|
||||
Schema::create('tenant_users', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('tenant_id');
|
||||
$table->string('global_user_id');
|
||||
|
||||
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
|
||||
$table->foreign('global_user_id')->references('global_id')->on('users')->onUpdate('cascade')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('tenant_users');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class CreateUsersTable extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function up()
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('global_id')->unique();
|
||||
$table->string('name');
|
||||
$table->string('email');
|
||||
$table->string('password');
|
||||
|
||||
$table->string('role');
|
||||
});
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('users');
|
||||
}
|
||||
}
|
||||
210
tests/v3/ResourceSyncingTest.php
Normal file
210
tests/v3/ResourceSyncingTest.php
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Tests\v3;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Contracts\Syncable;
|
||||
use Stancl\Tenancy\Contracts\SyncMaster;
|
||||
use Stancl\Tenancy\Database\Models\Concerns\CentralConnection;
|
||||
use Stancl\Tenancy\Database\Models\Concerns\ResourceSyncing;
|
||||
use Stancl\Tenancy\Database\Models\Tenant;
|
||||
use Stancl\Tenancy\Events\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Events\Listeners\JobPipeline;
|
||||
use Stancl\Tenancy\Events\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Events\Listeners\UpdateSyncedResource;
|
||||
use Stancl\Tenancy\Events\SyncedResourceSaved;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\TenancyBootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Tests\TestCase;
|
||||
|
||||
class ResourceSyncingTest extends TestCase
|
||||
{
|
||||
public function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config(['tenancy.bootstrappers' => [
|
||||
DatabaseTenancyBootstrapper::class
|
||||
]]);
|
||||
|
||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener());
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function an_event_is_triggered_when_a_synced_resource_is_changed()
|
||||
{
|
||||
$this->loadLaravelMigrations();
|
||||
|
||||
Event::fake([SyncedResourceSaved::class]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => 'Foo',
|
||||
'email' => 'foo@email.com',
|
||||
'password' => 'secret',
|
||||
]);
|
||||
|
||||
Event::assertDispatched(SyncedResourceSaved::class, function (SyncedResourceSaved $event) use ($user) {
|
||||
return $event->model === $user;
|
||||
});
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function only_the_synced_columns_are_updated_in_the_central_db()
|
||||
{
|
||||
Event::listen(SyncedResourceSaved::class, UpdateSyncedResource::class);
|
||||
|
||||
$this->artisan('migrate', [
|
||||
'--path' => [
|
||||
__DIR__ . '/../Etc/synced_resource_migrations',
|
||||
__DIR__ . '/../Etc/synced_resource_migrations/users'
|
||||
],
|
||||
'--realpath' => true,
|
||||
])->assertExitCode(0);
|
||||
|
||||
// Create user in central DB
|
||||
$user = CentralUser::create([
|
||||
'global_id' => 'acme',
|
||||
'name' => 'John Doe',
|
||||
'email' => 'john@localhost',
|
||||
'password' => 'secret',
|
||||
'role' => 'superadmin', // unsynced
|
||||
]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$this->artisan('tenants:migrate', [
|
||||
'--path' => __DIR__ . '/../Etc/synced_resource_migrations/users',
|
||||
'--realpath' => true,
|
||||
])->assertExitCode(0);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// Create the same user in tenant DB
|
||||
$user = User::create([
|
||||
'global_id' => 'acme',
|
||||
'name' => 'John Doe',
|
||||
'email' => 'john@localhost',
|
||||
'password' => 'secret',
|
||||
'role' => 'commenter', // unsynced
|
||||
]);
|
||||
|
||||
// Update user in tenant DB
|
||||
$user->update([
|
||||
'role' => 'admin', // unsynced
|
||||
'name' => 'John Foo', // synceed
|
||||
'email' => 'john@foreignhost', // synceed
|
||||
]);
|
||||
|
||||
// Assert new values
|
||||
$this->assertEquals([
|
||||
'id' => 1,
|
||||
'global_id' => 'acme',
|
||||
'name' => 'John Foo',
|
||||
'email' => 'john@foreignhost',
|
||||
'password' => 'secret',
|
||||
'role' => 'admin',
|
||||
], $user->getAttributes());
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
// Assert changes bubbled up
|
||||
$this->assertEquals([
|
||||
'id' => 1,
|
||||
'global_id' => 'acme',
|
||||
'name' => 'John Foo', // synced
|
||||
'email' => 'john@foreignhost', // synced
|
||||
'password' => 'secret', // no changes
|
||||
'role' => 'superadmin', // unsynced
|
||||
], User::first()->getAttributes());
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function the_synced_columns_are_updated_in_other_tenant_dbs_where_the_resource_exists()
|
||||
{
|
||||
// todo
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function global_id_is_generated_using_id_generatr_when_its_not_supplied()
|
||||
{
|
||||
// todo
|
||||
}
|
||||
}
|
||||
|
||||
class CentralUser extends Model implements SyncMaster
|
||||
{
|
||||
use ResourceSyncing, CentralConnection;
|
||||
|
||||
protected $guarded = [];
|
||||
public $timestamps = false;
|
||||
public $table = 'users';
|
||||
|
||||
public function tenants()
|
||||
{
|
||||
return $this->belongsToMany(Tenant::class, 'tenant_users', 'global_user_id', 'global_user_id');
|
||||
}
|
||||
|
||||
public function getGlobalIdentifierKey(): string
|
||||
{
|
||||
return $this->getAttribute($this->getGlobalIdentifierKeyName());
|
||||
}
|
||||
|
||||
public function getGlobalIdentifierKeyName(): string
|
||||
{
|
||||
return 'global_id';
|
||||
}
|
||||
|
||||
public function getCentralModelName(): string
|
||||
{
|
||||
return static::class;
|
||||
}
|
||||
|
||||
public function getSyncedAttributeNames(): array
|
||||
{
|
||||
return [
|
||||
'name',
|
||||
'password',
|
||||
'email',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class User extends Model implements Syncable
|
||||
{
|
||||
use ResourceSyncing;
|
||||
|
||||
protected $guarded = [];
|
||||
public $timestamps = false;
|
||||
|
||||
public function getGlobalIdentifierKey(): string
|
||||
{
|
||||
return $this->getAttribute($this->getGlobalIdentifierKeyName());
|
||||
}
|
||||
|
||||
public function getGlobalIdentifierKeyName(): string
|
||||
{
|
||||
return 'global_id';
|
||||
}
|
||||
|
||||
public function getCentralModelName(): string
|
||||
{
|
||||
return CentralUser::class;
|
||||
}
|
||||
|
||||
public function getSyncedAttributeNames(): array
|
||||
{
|
||||
return [
|
||||
'name',
|
||||
'password',
|
||||
'email',
|
||||
];
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue