public static void ThrowOnError(this HttpResponseMessage msg, ManagementErrorContext ctx) { throw new CouchbaseException { Context = ctx }; }
public async Task CreateBucketAsync(BucketSettings settings, CreateBucketOptions?options = null) { options ??= new CreateBucketOptions(); var uri = GetUri(); _logger.LogInformation("Attempting to create bucket with name {settings.Name} - {uri}", _redactor.MetaData(settings.Name), _redactor.SystemData(uri)); try { // create bucket var content = new FormUrlEncodedContent(settings !.ToFormValues()); using var httpClient = _httpClientFactory.Create(); var result = await httpClient.PostAsync(uri, content, options.TokenValue).ConfigureAwait(false); if (result.IsSuccessStatusCode) { return; } var body = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = body, Statement = uri.ToString() }; //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(body, ctx); if (result.StatusCode == HttpStatusCode.BadRequest) { if (body.IndexOf("Bucket with given name already exists", StringComparison.InvariantCultureIgnoreCase) >= 0) { throw new BucketExistsException(settings.Name); } } //Throw any other error cases result.ThrowOnError(ctx); } catch (BucketExistsException) { _logger.LogError("Failed to create bucket with name {settings.Name} because it already exists", _redactor.MetaData(settings.Name)); throw; } catch (Exception exception) { _logger.LogError(exception, "Failed to create bucket with name {settings.Name} - {uri}", _redactor.MetaData(settings.Name), _redactor.SystemData(uri)); throw; } }
public async Task <BucketSettings> GetBucketAsync(string bucketName, GetBucketOptions?options = null) { options ??= new GetBucketOptions(); var uri = GetUri(bucketName); _logger.LogInformation("Attempting to get bucket with name {bucketName} - {uri}", _redactor.MetaData(bucketName), _redactor.SystemData(uri)); try { using var httpClient = _httpClientFactory.Create(); var result = await httpClient.GetAsync(uri, options.TokenValue).ConfigureAwait(false); if (!result.IsSuccessStatusCode) { var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = content, Statement = uri.ToString() }; if (result.StatusCode == HttpStatusCode.NotFound) { throw new BucketNotFoundException(bucketName) { Context = ctx }; } //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(content, ctx); //Throw any other error cases result.ThrowOnError(ctx); } using var contentStream = await result.Content.ReadAsStreamAsync().ConfigureAwait(false); return((await JsonSerializer.DeserializeAsync(contentStream, ManagementSerializerContext.Default.BucketSettings, options.TokenValue).ConfigureAwait(false)) !); } catch (Exception exception) { _logger.LogError(exception, $"Failed to get bucket with name {bucketName} - {uri}", _redactor.MetaData(bucketName), _redactor.SystemData(uri)); throw; } }
public async Task DropBucketAsync(string bucketName, DropBucketOptions?options = null) { options ??= new DropBucketOptions(); var uri = GetUri(bucketName); _logger.LogInformation("Attempting to drop bucket with name {bucketName} - {uri}", _redactor.MetaData(bucketName), _redactor.SystemData(uri)); try { // perform drop using var httpClient = _httpClientFactory.Create(); var result = await httpClient.DeleteAsync(uri, options.TokenValue).ConfigureAwait(false); if (result.IsSuccessStatusCode) { return; } if (result.StatusCode == HttpStatusCode.NotFound) { throw new BucketNotFoundException(bucketName); } var body = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = body, Statement = uri.ToString() }; //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(body, ctx); //Throw any other error cases result.ThrowOnError(ctx); } catch (BucketNotFoundException) { _logger.LogError("Unable to drop bucket with name {bucketName} because it does not exist", _redactor.MetaData(bucketName)); } catch (Exception exception) { _logger.LogError(exception, "Failed to drop bucket with name {bucketName}", _redactor.MetaData(bucketName)); throw; } }
public async Task <IEnumerable <ScopeSpec> > GetAllScopesAsync(GetAllScopesOptions?options = null) { options ??= GetAllScopesOptions.Default; var uri = GetUri(RestApi.GetScopes(_bucketName)); _logger.LogInformation("Attempting to get all scopes - {uri}", _redactor.SystemData(uri)); try { // get manifest using var httpClient = _httpClientFactory.Create(); var result = await httpClient.GetAsync(uri, options.TokenValue).ConfigureAwait(false); var body = await result.Content.ReadAsStringAsync().ConfigureAwait(false); //Throw any other error cases if (result.StatusCode != HttpStatusCode.OK) { var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = body, Statement = uri.ToString() }; //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(body, ctx); result.ThrowOnError(ctx); } using var stream = await result.Content.ReadAsStreamAsync().ConfigureAwait(false); using var jsonReader = new JsonTextReader(new StreamReader(stream, Encoding.UTF8)); // check scope & collection exists in manifest var json = await JToken.ReadFromAsync(jsonReader, options.TokenValue).ConfigureAwait(false); var scopes = json.SelectToken("scopes") !; return(scopes.Select(scope => new ScopeSpec(scope["name"]?.Value <string>()) { Collections = scope["collections"] !.Select(collection => new CollectionSpec(scope["name"]?.Value <string>(), collection["name"]?.Value <string>()) { MaxExpiry = collection["maxTTL"] == null ? (TimeSpan?)null : TimeSpan.FromSeconds(collection["maxTTL"] !.Value <long>()) } ).ToList() }).ToList());
public async Task <Dictionary <string, BucketSettings> > GetAllBucketsAsync(GetAllBucketsOptions?options = null) { options ??= new GetAllBucketsOptions(); var uri = GetUri(); _logger.LogInformation("Attempting to get all buckets - {uri}", _redactor.SystemData(uri)); try { using var httpClient = _httpClientFactory.Create(); var result = await httpClient.GetAsync(uri, options.TokenValue).ConfigureAwait(false); if (!result.IsSuccessStatusCode) { var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = content, Statement = uri.ToString() }; //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(content, ctx); //Throw any other error cases result.ThrowOnError(ctx); } using var contentStream = await result.Content.ReadAsStreamAsync().ConfigureAwait(false); var buckets = await JsonSerializer.DeserializeAsync(contentStream, ManagementSerializerContext.Default.ListBucketSettings, options.TokenValue).ConfigureAwait(false); return(buckets !.ToDictionary( p => p.Name, p => p)); } catch (Exception exception) { _logger.LogError(exception, "Failed to get all buckets - {uri}", _redactor.SystemData(uri)); throw; } }
public async Task UpdateBucketAsync(BucketSettings settings, UpdateBucketOptions?options = null) { options ??= new UpdateBucketOptions(); var uri = GetUri(settings.Name); _logger.LogInformation("Attempting to upsert bucket with name {settings.Name} - {uri}", _redactor.MetaData(settings.Name), _redactor.SystemData(uri)); try { // upsert bucket var content = new FormUrlEncodedContent(settings !.ToFormValues()); using var httpClient = _httpClientFactory.Create(); var result = await httpClient.PostAsync(uri, content, options.TokenValue).ConfigureAwait(false); if (result.IsSuccessStatusCode) { return; } var body = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = body, Statement = uri.ToString() }; //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(body, ctx); //Throw any other error cases result.ThrowOnError(ctx); } catch (Exception exception) { _logger.LogError(exception, "Failed to upsert bucket with name {settings.Name} - {uri}", _redactor.MetaData(settings.Name), _redactor.SystemData(uri)); throw; } }
public async Task FlushBucketAsync(string bucketName, FlushBucketOptions?options = null) { options ??= new FlushBucketOptions(); // get uri and amend path to flush endpoint var builder = new UriBuilder(GetUri(bucketName)); builder.Path = Path.Combine(builder.Path, "controller/doFlush"); var uri = builder.Uri; _logger.LogInformation($"Attempting to flush bucket with name {bucketName} - {uri}", _redactor.MetaData(bucketName), _redactor.SystemData(uri)); try { // try do flush using var httpClient = _httpClientFactory.Create(); var result = await httpClient.PostAsync(uri, null !, options.TokenValue).ConfigureAwait(false); var body = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var ctx = new ManagementErrorContext { HttpStatus = result.StatusCode, Message = body, Statement = uri.ToString() }; if (result.IsSuccessStatusCode) { return; } switch (result.StatusCode) { case HttpStatusCode.NotFound: throw new BucketNotFoundException(bucketName); case HttpStatusCode.BadRequest: { var json = await result.Content.ReadAsStringAsync().ConfigureAwait(false); if (json.IndexOf("Flush is disabled for the bucket", StringComparison.InvariantCultureIgnoreCase) >= 0) { throw new BucketIsNotFlushableException(bucketName); } break; } } //Throw specific exception if a rate limiting exception is thrown. result.ThrowIfRateLimitingError(body, ctx); //Throw any other error cases result.ThrowOnError(ctx); } catch (BucketNotFoundException) { _logger.LogError("Unable to flush bucket with name {bucketName} because it does not exist", _redactor.MetaData(bucketName)); throw; } catch (BucketIsNotFlushableException) { _logger.LogError("Failed to flush bucket with name {bucketName} because it is not flushable", _redactor.MetaData(bucketName)); throw; } catch (Exception exception) { _logger.LogError(exception, "Failed to flush bucket with name {bucketName}", _redactor.MetaData(bucketName)); throw; } }
public static void ThrowIfRateLimitingError(this HttpResponseMessage msg, string body, ManagementErrorContext ctx) { if (msg.StatusCode == (HttpStatusCode)429) { if (body.IndexOf("Limit(s) exceeded [num_concurrent_requests]", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new RateLimitedException(RateLimitedReason.ConcurrentRequestLimitReached, ctx); } if (body.IndexOf("Limit(s) exceeded [ingress]", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new RateLimitedException(RateLimitedReason.NetworkIngressRateLimitReached, ctx); } if (body.IndexOf("Limit(s) exceeded [egress]", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new RateLimitedException(RateLimitedReason.NetworkEgressRateLimitReached, ctx); } //In this case multiple user limits were exceeded if (body.IndexOf("Limit(s) exceeded [", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new RateLimitedException(RateLimitedReason.NetworkEgressRateLimitReached, ctx); } if (body.IndexOf("Maximum number of collections has been reached for scope", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new QuotaLimitedException(QuotaLimitedReason.MaximumNumberOfCollectionsReached, ctx); } } else if (msg.StatusCode == (HttpStatusCode)400 && body.IndexOf("num_fts_indexes", StringComparison.InvariantCultureIgnoreCase) > 0) { throw new QuotaLimitedException(QuotaLimitedReason.MaximumNumberOfIndexesReached, ctx); } }