umbraco / Umbraco-CMS

Umbraco is a free and open source .NET content management system helping you deliver delightful digital experiences.
https://umbraco.com
MIT License
4.36k stars 2.64k forks source link

Could not obtain an HTTP context when ContentPublishedWebhookEvent fired #16638

Closed cf-marc closed 4 days ago

cf-marc commented 1 week ago

Which Umbraco version are you using? (Please write the exact version, example: 10.1.0)

13.3.2

Bug summary

Hello,

I have developed a Hangfire task that runs daily to import data from an external API. We use integrated webhooks to clear the cache in our frontend application when a node is deleted, moved, published, or unpublished. However, during the execution of the Hangfire import task, an exception occurs when attempting to trigger the webhook.

My current workaround is to suppress all notifications while save and publishing

 using var scope = coreScopeProvider.CreateCoreScope(autoComplete: true);
 {
     using (_ = scope.Notifications.Suppress())
     {
         contentService.SaveAndPublish(jobNode);
     }
 }

Specifics

System.AggregateException: One or more errors occurred. (One or more errors occurred. (Could not obtain an HTTP context))
 ---> System.AggregateException: One or more errors occurred. (Could not obtain an HTTP context)
 ---> System.InvalidOperationException: Could not obtain an HTTP context
   at Umbraco.Cms.Api.Delivery.Services.RequestHeaderHandler.GetHeaderValue(String headerName)
   at Umbraco.Cms.Api.Delivery.Services.RequestPreviewService.IsPreview()
   at Umbraco.Cms.Core.DeliveryApi.ApiContentRouteBuilder.Build(IPublishedContent content, String culture)
   at Umbraco.Cms.Core.DeliveryApi.ApiContentBuilderBase`1.Build(IPublishedContent content)
   at Umbraco.Cms.Core.Webhooks.Events.ContentPublishedWebhookEvent.ConvertEntityToRequestPayload(IContent entity)
   at Umbraco.Cms.Core.Webhooks.WebhookEventContentBase`2.ProcessWebhooks(TNotification notification, IEnumerable`1 webhooks, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Webhooks.WebhookEventBase`1.HandleAsync(TNotification notification, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.INotificationAsyncHandler`1.HandleAsync(IEnumerable`1 notifications, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.EventAggregator.PublishCoreAsync[TNotification](IEnumerable`1 allHandlers, IEnumerable`1 notifications, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.NotificationAsyncHandlerWrapperImpl`1.HandleAsync[TNotification,TNotificationHandler](IEnumerable`1 notifications, CancellationToken cancellationToken, ServiceFactory serviceFactory, Func`4 publish)
   at Umbraco.Cms.Core.Events.EventAggregator.PublishNotificationsAsync[TNotification,TNotificationHandler](IEnumerable`1 notifications, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.WaitAllCore(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.WaitAll(Task[] tasks)
   at Umbraco.Cms.Core.Events.EventAggregator.Publish[TNotification,TNotificationHandler](IEnumerable`1 notifications)
   at Umbraco.Cms.Core.Events.ScopedNotificationPublisher`1.PublishScopedNotifications(IList`1 notifications)
   at Umbraco.Cms.Core.Events.ScopedNotificationPublisher`1.ScopeExit(Boolean completed)
   at Umbraco.Cms.Infrastructure.Scoping.Scope.TryFinally(Action[] actions)
   --- End of inner exception stack trace ---
   at Umbraco.Cms.Infrastructure.Scoping.Scope.TryFinally(Action[] actions)
   at Umbraco.Cms.Infrastructure.Scoping.Scope.Dispose()
   at Umbraco.Cms.Core.Services.ContentService.SaveAndPublish(IContent content, String culture, Int32 userId)`

Steps to reproduce

  1. Install Hangfire
  2. Create a simple task for Hangfire:
public async Task ImportJobs()
{
    using BackgroundScope backgroundScope = new BackgroundScope(serverMessenger);
    using var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext();
    using IServiceScope serviceScope = serviceProvider.CreateScope();
    // Import jobs

    logger.LogInformation("*** starting jobs import");
    variationContextAccessor.VariationContext = new VariationContext("de-CH");
    var root = umbracoContextReference.UmbracoContext.Content.GetAtRoot(true).OfType<Root>().FirstOrDefault();

    if (root == null)
    {
        logger.LogError("*** ImportJobs: Root node not found");
        return;
    }

    var jobContainer = root.Descendant<GlobalJobContainer>();

    if(jobContainer == null)
    {
        logger.LogError("*** ImportJobs: Job container not found");
        return;
    }

    IContent jobNode = contentService.Create("Test 1", jobContainer.Id, GlobalJob.ModelTypeAlias);
    contentService.SaveAndPublish(jobNode);
}
  1. In the umbraco log you will find an warning Failed to process the job '4': an exception occurred. Retry attempt 1 of 10 will be performed in 00:00:37.

Expected result / actual result

The webhook is executed without throwing the exception

github-actions[bot] commented 1 week ago

Hi there @cf-marc!

Firstly, a big thank you for raising this issue. Every piece of feedback we receive helps us to make Umbraco better.

We really appreciate your patience while we wait for our team to have a look at this but we wanted to let you know that we see this and share with you the plan for what comes next.

We wish we could work with everyone directly and assess your issue immediately but we're in the fortunate position of having lots of contributions to work with and only a few humans who are able to do it. We are making progress though and in the meantime, we will keep you in the loop and let you know when we have any questions.

Thanks, from your friendly Umbraco GitHub bot :robot: :slightly_smiling_face:

cf-marc commented 1 week ago

This also seems to happen, when I set a publish at date for scheduling:

System.AggregateException: One or more errors occurred. (One or more errors occurred. (Could not obtain an HTTP context))
 ---> System.AggregateException: One or more errors occurred. (Could not obtain an HTTP context)
 ---> System.InvalidOperationException: Could not obtain an HTTP context
   at Umbraco.Cms.Api.Delivery.Services.RequestHeaderHandler.GetHeaderValue(String headerName)
   at Umbraco.Cms.Api.Delivery.Services.RequestPreviewService.IsPreview()
   at Umbraco.Cms.Core.DeliveryApi.ApiContentRouteBuilder.Build(IPublishedContent content, String culture)
   at Umbraco.Cms.Core.DeliveryApi.ApiContentBuilderBase`1.Build(IPublishedContent content)
   at Umbraco.Cms.Core.Webhooks.Events.ContentPublishedWebhookEvent.ConvertEntityToRequestPayload(IContent entity)
   at Umbraco.Cms.Core.Webhooks.WebhookEventContentBase`2.ProcessWebhooks(TNotification notification, IEnumerable`1 webhooks, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Webhooks.WebhookEventBase`1.HandleAsync(TNotification notification, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.INotificationAsyncHandler`1.HandleAsync(IEnumerable`1 notifications, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.EventAggregator.PublishCoreAsync[TNotification](IEnumerable`1 allHandlers, IEnumerable`1 notifications, CancellationToken cancellationToken)
   at Umbraco.Cms.Core.Events.NotificationAsyncHandlerWrapperImpl`1.HandleAsync[TNotification,TNotificationHandler](IEnumerable`1 notifications, CancellationToken cancellationToken, ServiceFactory serviceFactory, Func`4 publish)
   at Umbraco.Cms.Core.Events.EventAggregator.PublishNotificationsAsync[TNotification,TNotificationHandler](IEnumerable`1 notifications, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.WaitAllCore(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.WaitAll(Task[] tasks)
   at Umbraco.Cms.Core.Events.EventAggregator.Publish[TNotification,TNotificationHandler](IEnumerable`1 notifications)
   at Umbraco.Cms.Core.Events.ScopedNotificationPublisher`1.PublishScopedNotifications(IList`1 notifications)
   at Umbraco.Cms.Core.Events.ScopedNotificationPublisher`1.ScopeExit(Boolean completed)
   at Umbraco.Cms.Infrastructure.Scoping.Scope.TryFinally(Action[] actions)
   --- End of inner exception stack trace ---
   at Umbraco.Cms.Infrastructure.Scoping.Scope.TryFinally(Action[] actions)
   at Umbraco.Cms.Infrastructure.Scoping.Scope.Dispose()
   at Umbraco.Cms.Infrastructure.BackgroundJobs.Jobs.ScheduledPublishingJob.RunJobAsync()
Zeegaan commented 4 days ago

Fixed in https://github.com/umbraco/Umbraco-CMS/pull/16654