Skip to content

Distributed Lockers Implementation for Distributed competing Nodes executing some action

License

MIT and 2 other licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.txt
Unknown
COPYING.txt
Notifications You must be signed in to change notification settings

davidrevoledo/DistributedLocks

Repository files navigation

DistributedLocks

DistributedLocks

  • Distributed Lockers Implementation for Distributed competing Nodes executing some action.
  • Azure Storage Client.

NuGet NuGet License: MIT Open Source Love PRs Welcome

Build Status CodeFactor
master Build status CodeFactor
dev Build status CodeFactor

Introduction

CAP Theorem is about distributed computing, always is convenient choosing availability over consistency, however there are some cases where consistency is a must.

Consider using a serverless solution to process messages from a queue, (simple implementation of Queue-Worker-Pattern), let's say you are using Azure Functions for it. The solution is perfect because you can control your work load without rejecting operations but... what about if a your are editing user's bank accounts and you should prevent other operation change the account until your process is complete. You want to still use a messaging-style arquitecture but in that point Consistency becomes more important that Availability.

Those scenarios are where this package comes to solve it providing strong-consistency in methods no matter if you are using a serverless approach or not.

Just block a call with a key (could be the account number in the example) and avoid other process executing any code blocked by your key, no matter in what machine process the code is being executed.

The usage is straight forward.

// Process 1
IDistributedLock locker = AzureStorageDistributedLock.Create(
            "a1239120391321", // account number
            options =>
            {
                options.ConnectionString = "Insert Storage Key here";
                options.Directory = "accountblocks";
            });
          
// Process a payment
await  locker.ExecuteAsync(async context =>
{
     BankAccount account = new BankAccount("a1239120391321")
     await account.ProcessPaymentAsync(500, "USD");
});
            
// Process 2
IDistributedLock locker = AzureStorageDistributedLock.Create(
            "a1239120391321", // account number
            options =>
            {
                options.ConnectionString = "Insert Storage Key here";
                options.Directory = "accountblocks";
            });
            
// Process cash extraction
await  locker.ExecuteAsync(async context =>
{
     BankAccount account = new BankAccount("a1239120391321")
     // this will wait until the lock is released by the process 1
     await account.ProcessExtractionAsync(1000, "USD");
});

Contents

  1. Features
  2. Installation
  3. Usage
  4. Versions
  5. License
  • Distributed Locks for competitor nodes process executing some action.
  • Renew lease to get more time.
  • Azure Storage Account implementation.
  • AspNet Core middleware for easy usage.

====================

Grab the latest DistributedLock NuGet package and install in the desired package. https://www.nuget.org/packages/DistributedLocks/

PM > Install-Package DistributedLocks
NET CLI - dotnet add package DistributedLocks
paket add DistributedLocks

====================

// Process 1
IDistributedLock locker = AzureStorageDistributedLock.Create(
            "AnyKey", // account number
            options =>
            {
                options.ConnectionString = "Insert Storage Key here";
            });
          
await  locker.ExecuteAsync(async context =>
{
     await Task.Delay(1000); // execute some action here
});
           

Options

    locker = AzureStorageDistributedLock.Create(
        "work",
        options =>
        {
            options.ConnectionString = storageKey; // azure storage account key
            options.Directory = "singlenode"; // directory where save checkpoints
            options.RetryTimes = 100; // intents until stop trying
            options.LeaseDuration = TimeSpan.FromSeconds(20); // lease duration in azure storage account is between 10 - 60 seconds
        });

Long Methods

If your method need more time to be executed the lease need be renewed, the control of when renew should be made by the program. The Renewal time should be less than the Lease Duration.

  private static Task DoHugeWork()
  {
      Console.WriteLine("Huge work launched");

      return locker.ExecuteAsync(async context =>
      {
          locker = AzureStorageDistributedLock.Create(
            "longmethod",
            options =>
            {
                options.ConnectionString = storageKey;
                options.Directory = "leaserenewal";
                options.LeaseDuration = TimeSpan.FromSeconds(30);
            });
      
          Console.WriteLine("Huge work starting");

          // stage 1 - 15 seconds
          await Task.Delay(15000);
          var moreTime = await context.RenewLeaseAsync(TimeSpan.FromSeconds(20));
          if(!moreTime)
            RollbackOperation();
          
          Console.WriteLine("Getting more time to get the work done");

          // stage 2 - 15 seconds
          await Task.Delay(15000);
          moreTime = await context.RenewLeaseAsync(TimeSpan.FromSeconds(20));
          if(!moreTime)
            RollbackOperation();
          Console.WriteLine("Getting more time to get the work done");

          // stage 3 - 15 seconds
          await Task.Delay(15000);
          moreTime = await context.RenewLeaseAsync(TimeSpan.FromSeconds(20));
          if(!moreTime)
            RollbackOperation();
          Console.WriteLine("Getting more time to get the work done");

          // stage 4 - 15 seconds
          await Task.Delay(15000);

          Console.WriteLine("Huge work finished");
      });
  }

For more examples please check samples folder in the repo.

====================

forthebadge

  • v1.0.0: Uses Microsoft.Azure.Storage.Blob v9.4.2
  • v1.0.2: Uses Microsoft.Azure.Storage.Blob v10.0.3 which has breaking changes because namespaces changed
  • v1.0.3: Uses Azure.Storage.Blob v12.6.0

MIT License Copyright (c) 2019 David Revoledo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Made with ❤

About

Distributed Lockers Implementation for Distributed competing Nodes executing some action

Resources

License

MIT and 2 other licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.txt
Unknown
COPYING.txt

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages