Skip to content

Custom Lock Manager [v2]

Adrien Castex edited this page Apr 21, 2018 · 1 revision

A Lock Manager is an object instantiated for each resource in order to:

  • list the locks on this resource
  • get a specific lock on this resource
  • create a lock on this resource
  • remove a lock on this resource
  • refresh a lock on this resource

This object must be serializable in order to be saved with the architecture of the state of the server.

Implementation

interface ILockManager
{
    getLocks(callback : ReturnCallback<Lock[]>) : void
    setLock(lock : Lock, callback : SimpleCallback) : void
    removeLock(uuid : string, callback : ReturnCallback<boolean>) : void
    getLock(uuid : string, callback : ReturnCallback<Lock>) : void
    refresh(uuid : string, timeout : number, callback : ReturnCallback<Lock>) : void
}

LocalLockManager

You can instantiate a basic Lock Manager called LocalLockManager. It will store the locks in memory (in an object variable called locks) and manage the list.

Here is its implementation (which can be used as an example):

class LocalLockManager implements ILockManager
{
    locks : Lock[] = [];
    
    constructor(serializedData ?: any)
    {
        if(serializedData)
            for(const name in serializedData)
                this[name] = serializedData[name];
    }

    getLocks(callback : ReturnCallback<Lock[]>) : void
    {
        this.locks = this.locks.filter((lock) => !lock.expired());
        
        callback(null, this.locks);
    }

    setLock(lock : Lock, callback : SimpleCallback) : void
    {
        this.locks.push(lock);
        callback(null);
    }

    removeLock(uuid : string, callback : ReturnCallback<boolean>) : void
    {
        for(let index = 0; index < this.locks.length; ++index)
            if(this.locks[index].uuid === uuid)
            {
                this.locks.splice(index, 1);
                return callback(null, true);
            }
        
        callback(null, false);
    }

    getLock(uuid : string, callback : ReturnCallback<Lock>) : void
    {
        this.locks = this.locks.filter((lock) => !lock.expired());
        
        for(const lock of this.locks)
            if(lock.uuid === uuid)
                return callback(null, lock);
        
        callback();
    }

    refresh(uuid : string, timeout : number, callback : ReturnCallback<Lock>) : void
    {
        this.getLock(uuid, (e, lock) => {
            if(e || !lock)
                return callback(e);
            
            lock.refresh(timeout);
            callback(null, lock);
        })
    }
}
Clone this wiki locally