Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ConcurrencyException with Sitemaps when saving two content items at once (Lombiq Technologies: GOV-33) #15777

Merged
merged 10 commits into from
Apr 17, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,11 @@ public ContentTypesSitemapUpdateHandler(ISitemapUpdateHandler sitemapUpdateHandl
_sitemapUpdateHandler = sitemapUpdateHandler;
}

public override Task PublishedAsync(PublishContentContext context)
{
var updateContext = new SitemapUpdateContext
{
UpdateObject = context.ContentItem,
};
public override Task PublishedAsync(PublishContentContext context) => UpdateSitemapAsync(context);

return _sitemapUpdateHandler.UpdateSitemapAsync(updateContext);
}
public override Task UnpublishedAsync(PublishContentContext context) => UpdateSitemapAsync(context);

public override Task UnpublishedAsync(PublishContentContext context)
private Task UpdateSitemapAsync(ContentContextBase context)
{
var updateContext = new SitemapUpdateContext
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.Locking.Distributed;

namespace OrchardCore.Sitemaps.Handlers
{
public class DefaultSitemapUpdateHandler : ISitemapUpdateHandler
{
private readonly IEnumerable<ISitemapTypeUpdateHandler> _sitemapTypeUpdateHandlers;
private readonly IDistributedLock _distributedLock;

public DefaultSitemapUpdateHandler(IEnumerable<ISitemapTypeUpdateHandler> sitemapTypeUpdateHandlers)
public DefaultSitemapUpdateHandler(
IEnumerable<ISitemapTypeUpdateHandler> sitemapTypeUpdateHandlers,
IDistributedLock distributedLock)
{
_sitemapTypeUpdateHandlers = sitemapTypeUpdateHandlers;
_distributedLock = distributedLock;
}

public async Task UpdateSitemapAsync(SitemapUpdateContext context)
{
foreach (var sitemapTypeUpdateHandler in _sitemapTypeUpdateHandlers)
// Doing the update in a synchronized way makes sure that two simultaneous content item updates don't cause
// a ConcurrencyException due to the same sitemap document being updated.

var timeout = TimeSpan.FromMilliseconds(20_000);
(var locker, var locked) = await _distributedLock.TryAcquireLockAsync("SITEMAPS_UPDATE_LOCK", timeout, timeout);

if (!locked)
{
throw new TimeoutException($"Couldn't acquire a lock to update the sitemap within {timeout.Seconds} seconds.");
}

using (locker)
{
await sitemapTypeUpdateHandler.UpdateSitemapAsync(context);
foreach (var sitemapTypeUpdateHandler in _sitemapTypeUpdateHandlers)
{
await sitemapTypeUpdateHandler.UpdateSitemapAsync(context);
}
}
}
}
Expand Down