Skip to content
Advertisement

How to intercept a new file on S3 using Laravel Queues?

I have an S3 bucket, mybucket, and I want to execute something when a new file is copied into that bucket. For the notifications, I want to use an SQS queue, notifiqueue, because my goal is to access that queue with Laravel

Since I am creating my infrastructure in CloudFormation, the resources are created like this:

JavaScript

Each time a new file is saved on the bucket, S3 automatically creates a notification in SQS.

Sadly, the format of the payload is NOT COMPATIBLE with Laravel standard job payload, and if I run a worker process on the NotificationQueue I get this error:

JavaScript

To provide a more complete indication, here is what I get in the notification (after turning JSON into a PHP array)

JavaScript

Which is the working / best / right way to access the notification using Laravel so that I can trigger some other option in response to the file upload ?

Advertisement

Answer

I found a way to obtain the desired behavior, but I am not sure this is the best way, so I post it here and maybe can give me a feedback.

When we talk about Laravel Queues, a lot of configuration comes from app.php, and in particular from the Provider section. I managed to add the behavior that I needed overriding Original QueueServiceProvider class and substituting it:

JavaScript

The new QueueServiceProvider class is the following:

JavaScript

Notice the new connector sqsNotif, that will need to be added to the queue.php

JavaScript

In the new QueueServiceProvider we just register an extra connector, which code is:

JavaScript

The SqsQueue is redefined too, in this way:

JavaScript

And the last missing piece is SqsJob, defined like this:

JavaScript

At this point, I just need to define the processing Job, for example like the one below, in a NewMyBucketFileJob:

JavaScript

This process works, so this is a solution, but involves a lot of class extensions, and it’s quite fragile in case the internal queue implementation will be changed in the future releases. I am honestly wondering if there is something easier or more robust

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement