예제 #1
0
        public async Task <PurgeResponse> PurgeAsync(IEnumerable <IPublishedContent> content)
        {
            var config = _configService.GetConfig();

            var publishedContent = content as IPublishedContent[] ?? content.ToArray();

            var contentTypeIds = publishedContent.Select(c => c.ContentType.Id).ToHashSet().ToArray();
            var contentTypes   = _contentTypeService.GetAll(contentTypeIds).ToDictionary(c => c.Id, c => c);

            var filteredContent =
                publishedContent.Where(c => config.ContentFilter.AllowedContent(contentTypes[c.ContentType.Id]));

            using (var context = _umbracoContextFactory.EnsureUmbracoContext())
            {
                var urls = from contentItem in filteredContent
                           from culture in contentItem.Cultures
                           select context.UmbracoContext.UrlProvider.GetUrl(contentItem, UrlMode.Absolute, culture.Key);

                if (!urls.Any())
                {
                    return(new PurgeResponse(
                               result: PurgeResult.NothingPurged,
                               failedUrls: null,
                               failMessages: null,
                               exception: null));
                }

                var request = new PurgeRequest(urls);

                return(await PurgeAsync(request));
            }
        }
예제 #2
0
        public async Task PurgeByUrlAsync_GivenInvalidResponse_ThenReturnException(HttpStatusCode responseStatusCode)
        {
            var mockProvider = new MockProvider();

            var mockUrlsBatch = Enumerable.Range(1, 30).Select(i => "mock-url-" + i);

            MockHttpRequest(mockProvider, "https://api.cloudflare.com/client/v4/zones/mock-zone-id/purge_cache", HttpMethod.Post,
                            (PurgeFilesCacheRequest r) => r.Files.Count() == 30,
                            responseStatusCode, "--invalid-response--");

            var request = new PurgeRequest(mockUrlsBatch);

            using (var instance = mockProvider.GetInstance())
            {
                var result = await instance.PurgeByUrlAsync(request);

                Assert.AreEqual(PurgeResult.Fail, result.Result);
                Assert.IsFalse(result.FailMessages.Any());
                Assert.AreEqual(mockUrlsBatch, result.FailedUrls[CdnType.CloudFlare]);
                Assert.IsNotNull(result.Exception);
                Assert.AreEqual(1, result.Exception.InnerExceptions.Count);
            }

            mockProvider.HttpMessageHandlerMock
            .Protected().Verify <Task <HttpResponseMessage> >("SendAsync",
                                                              Times.Once(),
                                                              ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()
                                                              );
        }
예제 #3
0
        public async Task <PurgeResponse> PurgeByUrlAsync(PurgeRequest request)
        {
            var config = _configService.GetConfig();

            var apiRequest = new PurgeFilesCacheRequest(request.Urls);

            var uri = new Uri($"{Endpoint}/zones/{config.CloudFlare.ZoneId}/purge_cache");

            try
            {
                var result = await FetchAsync <CloudFlareResponse <PurgeCacheResult>, PurgeFilesCacheRequest>(uri, HttpMethod.Post, apiRequest);

                return(new PurgeResponse(
                           result: result.Success?PurgeResult.Success: PurgeResult.Fail,
                           cdnType: CdnType.CloudFlare,
                           failedUrls: null,              // TODO
                           failMessages: (result.Messages ?? Array.Empty <string>()).Union(result.Errors?.Select(e => e.Message) ?? Array.Empty <string>()),
                           exception: null));
            }
            catch (Exception ex)
            {
                return(new PurgeResponse(
                           result: PurgeResult.Fail,
                           cdnType: CdnType.CloudFlare,
                           failedUrls: request.Urls,
                           failMessages: null,
                           exception: new AggregateException(ex)));
            }
        }
예제 #4
0
        public virtual async Task <PurgeResponse> PurgeAsync(PurgeRequest request, CancellationToken cancellationToken = default)
        {
            var httpRequest = PurgeHttpRequestFactory.Create(request);

            using (var res = await SendAsync(httpRequest, cancellationToken).ForAwait())
            {
                return(await PurgeResponseFactory.CreateAsync(res).ForAwait());
            }
        }
예제 #5
0
        public virtual HttpRequest Create(PurgeRequest request)
        {
            Ensure.Any.IsNotNull(request, nameof(request));

            var data = new PurgeData(request.SeqsById);

            return(new HttpRequest(HttpMethod.Post, GenerateRelativeUrl(request))
                   .SetRequestTypeHeader(request.GetType())
                   .SetJsonContent(Serializer.ToJson(data)));
        }
예제 #6
0
        public async Task <PurgeResponse> PurgeAsync(PurgeRequest request)
        {
            var maxRequestSize = _cdnApis.Min(c => c.MaxBatchSize);

            var batches = request.Urls.Batch(maxRequestSize, c => new PurgeRequest(c));

            var purgeTasks = _cdnApis.Where(c => c.IsEnabled())
                             .SelectMany(cdn => batches.Select(cdn.PurgeByUrlAsync));

            var results = await Task.WhenAll(purgeTasks);

            return(PurgeResponse.Aggregate(results));
        }
예제 #7
0
        public void Flow_tests()
        {
            var post1 = SUT.PostAsync(ClientTestData.Artists.Artist1Json);
            var post2 = SUT.PostAsync(ClientTestData.Artists.Artist2Json);

            post1.Result.Should().BeSuccessfulPost(ClientTestData.Artists.Artist1Id);
            post2.Result.Should().BeSuccessfulPost(ClientTestData.Artists.Artist2Id);

            var get1 = SUT.GetAsync(post1.Result.Id);
            var get2 = SUT.GetAsync(post2.Result.Id);

            get1.Result.Should().BeSuccessfulGet(post1.Result.Id, post1.Result.Rev);
            get2.Result.Should().BeSuccessfulGet(post2.Result.Id, post2.Result.Rev);

            var kv1 = DbClient.Serializer.Deserialize <IDictionary <string, dynamic> >(get1.Result.Content);

            kv1["year"] = 2000;
            var docUpd1 = DbClient.Serializer.Serialize(kv1);
            var put1    = SUT.PutAsync(get1.Result.Id, docUpd1);

            var kv2 = DbClient.Serializer.Deserialize <IDictionary <string, dynamic> >(get2.Result.Content);

            kv2["year"] = 2001;
            var docUpd2 = DbClient.Serializer.Serialize(kv2);
            var put2    = SUT.PutAsync(get2.Result.Id, docUpd2);

            put1.Result.Should().BeSuccessfulPut(get1.Result.Id);
            put2.Result.Should().BeSuccessfulPut(get2.Result.Id);

            var delete1 = SUT.DeleteAsync(put1.Result.Id, put1.Result.Rev);
            var delete2 = SUT.DeleteAsync(put2.Result.Id, put2.Result.Rev);

            delete1.Result.Should().BeSuccessfulDelete(put1.Result.Id);
            delete2.Result.Should().BeSuccessfulDelete(put2.Result.Id);

            var purgeReq = new PurgeRequest()
                           .Include(delete1.Result.Id, delete1.Result.Rev)
                           .Include(delete2.Result.Id, delete2.Result.Rev);

            SUT.PurgeAsync(purgeReq).Result.Should().BeSuccessfulPurge(purgeReq.SeqsById);
        }
예제 #8
0
        public async Task PurgeByUrlAsync_GivenSuccess_ThenExpectedResult()
        {
            var mockProvider = new MockProvider();

            MockHttpRequest(mockProvider, "https://api.cloudflare.com/client/v4/zones/mock-zone-id/purge_cache", HttpMethod.Post,
                            (PurgeFilesCacheRequest r) => r.Files.Count() == 2,
                            HttpStatusCode.OK, "{ 'success': true }");

            var request = new PurgeRequest(new[] { "mock-url-1", "mock-url-2" });

            using (var instance = mockProvider.GetInstance())
            {
                var result = await instance.PurgeByUrlAsync(request);

                Assert.AreEqual(PurgeResult.Success, result.Result);
                Assert.IsEmpty(result.FailMessages);
                Assert.IsEmpty(result.FailedUrls);
                Assert.IsNull(result.Exception);
            }

            mockProvider.HttpMessageHandlerMock.VerifyAll();
        }
예제 #9
0
        /// <summary>
        /// Sends the purge request to edge cast for the media path passed in.
        /// </summary>
        /// <param name="mediaPath"></param>
        private bool SubmitPurgeRequest(string mediaPath)
        {
            bool bReturn = true;

            Log.LogMessage("Purging [{0}]", mediaPath);
            var client = new RestClient(RestUri);

            var request = new RestRequest("/edge/purge", Method.PUT)
            {
                RequestFormat = DataFormat.Json
            };

            request.AddHeader("Authorization", string.Format("TOK:{0}", RestApiToken));
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");

            var purge = new PurgeRequest()
            {
                MediaPath = string.Format("{0}/{1}", BaseMediaPath, mediaPath)
            };

            Log.LogMessage(purge.MediaPath);
            request.AddBody(purge);

            var response = client.Execute <PurgeResponse>(request);

            if (response.ResponseStatus != ResponseStatus.Completed)
            {
                Log.LogError("Error: " + response.ErrorMessage);
                Log.LogMessage("Content: " + response.Content);
                bReturn = false;
            }
            else
            {
                PurgeRequestIdList.Add(response.Data.Id);
            }

            return(bReturn);
        }
예제 #10
0
 protected virtual string GenerateRelativeUrl(PurgeRequest request)
 {
     return("/_purge");
 }