using Raven.Client.Documents; using Raven.Client.Documents.Operations.CompareExchange; using System; using System.Threading.Tasks; namespace zero.Core.Extensions { public static class DocumentStoreExtensions { /// /// Create a new unique Id /// public static string Id(this IDocumentStore store, int length = -1) { if (length > 0) { return Convert.ToBase64String(Guid.NewGuid().ToByteArray()) .Replace("/", String.Empty) .Replace("+", String.Empty) .Replace("-", String.Empty) .ToLowerInvariant() .Substring(0, length); } return Guid.NewGuid().ToString(); } /// /// Reserves a key cluster-wide /// public static async Task ReserveAsync(this IDocumentStore store, string key, string value = null) { if (String.IsNullOrWhiteSpace(key)) { return false; } if (value == null) { value = key; } var operation = new PutCompareExchangeValueOperation(key, value, 0); CompareExchangeResult result = await store.Operations.SendAsync(operation).ConfigureAwait(false); return result.Successful; } /// /// Removes a cluster-wide key reservation /// public static async Task RemoveReservationAsync(this IDocumentStore store, string key) { if (!String.IsNullOrWhiteSpace(key)) { return false; } CompareExchangeValue readResult = store.Operations.Send(new GetCompareExchangeValueOperation(key)); if (readResult == null) { return false; } DeleteCompareExchangeValueOperation operation = new DeleteCompareExchangeValueOperation(key, readResult.Index); CompareExchangeResult result = await store.Operations.SendAsync(operation).ConfigureAwait(false); return result.Successful; } } }