Search code examples
ajaxlockingshared-resource

Check availability of resource used by another user


Building a web application.

User have access trough their browser to shared resources host on a server, however if UserA is already using Resource1, Resource1 should not be available to UserB until UserA release Resource1 or until a given amount of time.

For this part : I chose to use a MySQL table with a list of tuples (resource,currentuser) and run a cron task to delete expired tuples.

Now I want to be able to notify UserA that UserB wants to access Resource1 and if get not answer from UserA, then UserA lost his lock on Resource1 and then the Resource is then available to UserB.

For this part, I guess I have to use AJAX. I have thought about the following solution :

User's browser make periodic AJAX call (let's say each minute) to prove he is still alive and upon a call, if another User has requested the same resource, he has to challenge a server request in a given amount of time(for example a captcha). If the challenge fails, it means the user is not here anymore (maybe he left his browser opened or the webpage unfocused).

The tricky part is : "he has to challenge a server request in a given amount of time (for example a captcha)". How to do that?

Am I following the best path ?


Solution

  • Yes, what you've outlined is fine. Using ajax is also completely fine, especially if you're simply polling every minute.

    For example, let's say you have the following:

    setInterval(function() {
     $.get('/resource/status', function(response) {
        if (response.data.newRequest) {
           //This would signal a new request to the resource
        }
     })
    }, 60000)
    

    When handling the new request to access the resource, you could use something like reCaptcha and display that however appropriate (overlay or inline). When you do this, you could also start a timer to determine if it's exceeded the amount of time allocated or not. If it has, then you can do another ajax request and revoke this person's access to the resource, or however you want to handle that.