private async Task TryAcquireLeaseAsync()

in src/Microsoft.Azure.WebJobs.Host.Storage/Singleton/BlobLeaseDistributedLockManager.cs [161:228]


        private async Task<string> TryAcquireLeaseAsync(
            BlobClient blobClient,
            TimeSpan leasePeriod,
            string proposedLeaseId,
            CancellationToken cancellationToken)
        {
            bool blobDoesNotExist = false;
            try
            {
                // Check if a lease is available before trying to acquire. The blob may not
                // yet exist; if it doesn't we handle the 404, create it, and retry below.
                // The reason we're checking to see if the lease is available before trying
                // to acquire is to avoid the flood of 409 errors that Application Insights
                // picks up when a lease cannot be acquired due to conflict; see issue #2318.
                var blobProperties = await ReadLeaseBlobMetadata(blobClient, cancellationToken);

                switch (blobProperties?.LeaseState)
                {
                    case null:
                    case LeaseState.Available:
                    case LeaseState.Expired:
                    case LeaseState.Broken:
                        var leaseResponse = await GetBlobLeaseClient(blobClient, proposedLeaseId).AcquireAsync(leasePeriod, cancellationToken: cancellationToken);
                        return leaseResponse.Value.LeaseId;
                    default:
                        return null;
                }
            }
            catch (RequestFailedException exception)
            {
                if (exception.Status == 409)
                {
                    return null;
                }
                else if (exception.Status == 404)
                {
                    blobDoesNotExist = true;
                }
                else
                {
                    throw;
                }
            }

            if (blobDoesNotExist)
            {
                await TryCreateAsync(blobClient, cancellationToken);

                try
                {
                    var leaseResponse = await GetBlobLeaseClient(blobClient, proposedLeaseId).AcquireAsync(leasePeriod, cancellationToken: cancellationToken);
                    return leaseResponse.Value.LeaseId;
                }
                catch (RequestFailedException exception)
                {
                    if (exception.Status == 409)
                    {
                        return null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return null;
        }