gdg-tangier / cloud-pubsub

Google Cloud Pub/Sub for Laravel
MIT License
48 stars 6 forks source link

How to always inject the tenant_id during the publishing #17

Closed kh-hani closed 4 years ago

kh-hani commented 4 years ago

I'm building a Microservice-based Multi-tenancy SaaS application.

We have noticed that publishing to PubSub is not touching the queue system. Therefore something like the following is not valid with this package:

// TenancyServiceProvider.php in the BFF Microservice

$this->app->extend('queue', function (QueueManager $queue) {
    // Store tenant key and identifier on job payload when a tenant is identified.
    $queue->createPayloadUsing(function () {
        return ['tenant_id' => $tenant_id];
    });

    // Resolve any tenant related meta data on job and allow resolving of tenant.
    $queue->before(function (JobProcessing $jobProcessing) {
        config()->set('database.connections.mysql.database', $jobProcessing->job->payload()['tenant_id']);
    });

    return $queue;
});

We want to inject the tenant_id as part of the payload like the following:

[
  'tenant_id' => '21a50087-cec8-44b8-b5f4-681614a1a05a'
  'data' => 'myData',
  'job' => 'App\\Subscribers\\CreateProfile',
]

Is it possible to achieve that using this package, or should I do something else?

amranidev commented 4 years ago

Yes you can do that, but it depends on how you will be handle the incoming queue message. Question: do you use laravel for both sides microservices right?

kh-hani commented 4 years ago

Yes, we use Laravel on both sides! The BFF microservice is Laravel. The backend microservices are Lumen, and in Lumen, we noticed that we could catch the subscriber as part of the queue system.

So the following part is how we handle the incoming queue messages in Lumen:

// TenancyServiceProvider.php 
// Resolve any tenant related meta data on job and allow resolving of tenant.
    $queue->before(function (JobProcessing $jobProcessing) {
        config()->set('database.connections.mysql.database', $jobProcessing->job->payload()['tenant_id']);
    });
amranidev commented 4 years ago

@kh-hani Aaah yes I see, with cloud-pubsub, that will be very easy, you just need to serialise your message before sending it through publisher, once the message is available through the queue, the subscriber can handle the message and deserialize it :)

kh-hani commented 4 years ago

thank you, I'll try to do that.