Skip to content

Commit 3cf0b63

Browse files
kennygutierrezkennygutierrez-centuryclaudevaldisiljuconoks
authored
Page the "Register content move redirects" job so it survives large tables (6.x backport of #188) (#193)
* Page the move-redirects job so it survives large tables The "Register content move redirects" job loaded the entire NotFoundHandler.ContentUrlHistory table in one unbounded query (GetAllMoved -> .ToList()). On large tables that SELECT exceeds the SqlClient command timeout, and SqlDataExecutor.ExecuteQuery swallowed the exception then returned ds.Tables[0] on an empty DataSet, surfacing a misleading "Cannot find table 0" instead of the real timeout. - SqlDataExecutor: apply a configurable CommandTimeout and rethrow query failures instead of masking them as "Cannot find table 0". - NotFoundHandlerOptions.CommandTimeout (default 30s). - IContentUrlHistoryLoader/SqlContentUrlHistoryRepository: add a paged GetAllMoved(skip, take) using OFFSET/FETCH over the moved keys, and make the parameterless overload stream pages so the unbounded query is gone. - RegisterMovedContentRedirectsJob: process the table page-by-page, tunable via OptimizelyNotFoundHandlerOptions.MovedContentBatchSize (default 1000). - Tests for repository paging and job batching; README updated. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Address review: clamp batch size, keep interface source-compatible, changelog Review feedback on PR #188 (thanks @ivanmarkovic1402): - RegisterMovedContentRedirectsJob: clamp MovedContentBatchSize to >= 1. A misconfigured 0/negative would page with "FETCH NEXT 0 ROWS ONLY" (invalid SQL) and, now that ExecuteQuery rethrows, fail the whole job. - IContentUrlHistoryLoader.GetAllMoved(skip, take) is now a default interface implementation (pages in-memory over GetAllMoved()), so the addition no longer breaks third-party implementers. Data-backed stores (SqlContentUrlHistoryRepository) still override it with the OFFSET/FETCH query. - CHANGELOG: document the new options (CommandTimeout, MovedContentBatchSize), the paged GetAllMoved, and the ExecuteQuery rethrow behavior change. - Tests: guard test for the batch-size clamp and an exact-multiple-of-batch case (one trailing empty fetch, then stop). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Harden paged query and command timeout against bad inputs - SqlContentUrlHistoryRepository.GetAllMoved(skip, take): short-circuit to empty when take <= 0 (FETCH NEXT 0/negative ROWS is invalid SQL) and clamp a negative skip, so a direct caller can't push invalid SQL to the database. - SqlDataExecutor: clamp a negative CommandTimeout to 0; SqlCommand.CommandTimeout otherwise throws and would break every query. Documented 0 = no timeout. - Tests: cover the non-positive take guard; drop an xUnit2013 warning. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Update CHANGELOG for version 6.1.0 release Documented the addition of new options for handling content moves and command timeouts in version 6.1.0. --------- Co-authored-by: Kenny Gutierrez <Kenny.Gutierrez@centurycommunities.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: valdis iljuconoks <valdis.iljuconoks@outlook.com>
1 parent 5de9220 commit 3cf0b63

10 files changed

Lines changed: 333 additions & 29 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## [6.1.0]
6+
7+
### Added
8+
9+
- `OptimizelyNotFoundHandlerOptions.MovedContentBatchSize` (default 1000) and `NotFoundHandlerOptions.CommandTimeout` so the "Register content move redirects" job pages through large `NotFoundHandler.ContentUrlHistory` tables instead of loading every row in one unbounded query that exceeded the command timeout.
10+
- `IContentUrlHistoryLoader.GetAllMoved(int skip, int take)` for paged access to moved content. Ships as a default interface implementation (pages in-memory over `GetAllMoved()`), so existing implementers keep compiling.
11+
12+
### Changed
13+
14+
- `SqlDataExecutor.ExecuteQuery` now propagates SQL exceptions (e.g. command timeouts) instead of swallowing them and returning an empty result, which previously surfaced as a misleading "Cannot find table 0" error.
15+
516
## [1.1.0]
617

718
- Refctoring

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ If the `bufferSize` is set to `0`, the `threshold` value will be ignored, and ev
152152

153153
**LogWithHostname**: Set to `true` to include hostname in the log. Useful in a multisite environment with several hostnames/domains. Default is `false`
154154

155+
**CommandTimeout**: Command timeout, in seconds, applied to SQL queries issued by the NotFound handler. Raise it past the SqlClient default of 30 if you have very large NotFound handler tables. Default is 30
156+
155157
**ActiveStatusCodes**: A integerlist with the status codes that NotFoundHandler will be active on. (Ex. ```options.ActiveStatusCodes = new int[] { StatusCodes.Status404NotFound, StatusCodes.Status410Gone };```)
156158

157159
### Specifying ignored resources
@@ -320,7 +322,13 @@ An Optimizely scheduled job was added - <code>[Geta NotFoundHandler] Suggestions
320322

321323
Additionally, there are two optimizely scheduled jobs responsible for:
322324
- *[Geta NotFoundHandler] Index content URLs* - as mentioned before, this job indexes URLs of content. Usually, it is required to run this job only once. All new content is automatically indexed. But if for some reason content publish events are not firing when creating new content (for example, during the import), then you should set this job to run frequently.
323-
- *[Geta NotFoundHandler] Register content move redirects* - this job creates redirects based on registered moved content. Normally, this job is not required at all, but there might be situations when content move is registered but redirect creation is not completed. This could happen during deployments. In this case, you can manually run this job or schedule it to run time to time to fix such issues.
325+
- *[Geta NotFoundHandler] Register content move redirects* - this job creates redirects based on registered moved content. Normally, this job is not required at all, but there might be situations when content move is registered but redirect creation is not completed. This could happen during deployments. In this case, you can manually run this job or schedule it to run time to time to fix such issues. The job processes the `NotFoundHandler.ContentUrlHistory` table page-by-page so it scales to large tables. You can tune the page size via `MovedContentBatchSize` (default 1000):
326+
```
327+
services.AddOptimizelyNotFoundHandler(o =>
328+
{
329+
o.MovedContentBatchSize = 1000;
330+
});
331+
```
324332

325333

326334
# Troubleshooting

‎src/Geta.NotFoundHandler.Optimizely/Core/AutomaticRedirects/IContentUrlHistoryLoader.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,29 @@
22
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
33

44
using System.Collections.Generic;
5+
using System.Linq;
56

67
namespace Geta.NotFoundHandler.Optimizely.Core.AutomaticRedirects
78
{
89
public interface IContentUrlHistoryLoader
910
{
1011
bool IsRegistered(ContentUrlHistory entity);
1112
IEnumerable<(string contentKey, IReadOnlyCollection<ContentUrlHistory> histories)> GetAllMoved();
13+
14+
/// <summary>
15+
/// Returns a single page of moved content (keys with more than one URL-history entry),
16+
/// ordered by content key. Lets callers stream large tables instead of loading every row
17+
/// in one unbounded query.
18+
/// </summary>
19+
/// <param name="skip">Number of moved content keys to skip.</param>
20+
/// <param name="take">Maximum number of moved content keys to return.</param>
21+
/// <remarks>
22+
/// Default implementation pages in-memory over <see cref="GetAllMoved()"/> so existing
23+
/// implementers keep compiling; data-backed stores should override it with a server-side paged query.
24+
/// </remarks>
25+
IEnumerable<(string contentKey, IReadOnlyCollection<ContentUrlHistory> histories)> GetAllMoved(int skip, int take)
26+
=> GetAllMoved().Skip(skip).Take(take);
27+
1228
IReadOnlyCollection<ContentUrlHistory> GetMoved(string contentKey);
1329
}
1430
}

‎src/Geta.NotFoundHandler.Optimizely/Core/AutomaticRedirects/RegisterMovedContentRedirectsJob.cs‎

Lines changed: 44 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
using EPiServer.PlugIn;
77
using EPiServer.Scheduler;
88
using Geta.NotFoundHandler.Optimizely.Infrastructure;
9+
using Geta.NotFoundHandler.Optimizely.Infrastructure.Configuration;
10+
using Microsoft.Extensions.Options;
911

1012
namespace Geta.NotFoundHandler.Optimizely.Core.AutomaticRedirects
1113
{
@@ -17,60 +19,78 @@ public class RegisterMovedContentRedirectsJob : ScheduledJobBase
1719
private readonly IContentUrlHistoryLoader _contentUrlHistoryLoader;
1820
private readonly JobStatusLogger _jobStatusLogger;
1921
private readonly IAutomaticRedirectsService _automaticRedirectsService;
22+
private readonly int _batchSize;
2023
private bool _stopped;
2124

2225
public RegisterMovedContentRedirectsJob(
2326
IAutomaticRedirectsService automaticRedirectsService,
24-
IContentUrlHistoryLoader contentUrlHistoryLoader)
27+
IContentUrlHistoryLoader contentUrlHistoryLoader,
28+
IOptions<OptimizelyNotFoundHandlerOptions> options)
2529
{
2630
_automaticRedirectsService = automaticRedirectsService;
2731
_contentUrlHistoryLoader = contentUrlHistoryLoader;
32+
// Clamp to >= 1: a misconfigured 0/negative would page with FETCH NEXT 0 ROWS (invalid SQL) and fail the job.
33+
_batchSize = Math.Max(1, options.Value.MovedContentBatchSize);
2834
_jobStatusLogger = new JobStatusLogger(OnStatusChanged);
2935

3036
IsStoppable = true;
3137
}
3238

3339
public override string Execute()
3440
{
35-
var movedContent = _contentUrlHistoryLoader.GetAllMoved().ToList();
36-
var totalCount = movedContent.Count;
3741
var successCount = 0;
3842
var failedCount = 0;
3943
var currentCount = 0;
44+
var skip = 0;
4045

41-
_jobStatusLogger.LogWithStatus($"In total will process moved content: {totalCount}");
46+
_jobStatusLogger.LogWithStatus($"Processing moved content in batches of {_batchSize}");
4247

43-
foreach (var content in movedContent)
48+
// Page through the moved content rather than materialising the whole table up front.
49+
// CreateRedirects only touches the redirects store, not ContentUrlHistory, so the moved
50+
// set is stable for the duration of the run and skip-based paging never skips a key.
51+
while (true)
4452
{
45-
if (_stopped)
53+
var batch = _contentUrlHistoryLoader.GetAllMoved(skip, _batchSize).ToList();
54+
55+
foreach (var content in batch)
4656
{
47-
_jobStatusLogger.Log(
48-
$"Job was stopped, successful content handled before stopped: {successCount} out of total {totalCount} content");
49-
return _jobStatusLogger.ToString();
50-
}
57+
if (_stopped)
58+
{
59+
_jobStatusLogger.Log(
60+
$"Job was stopped, successful content handled before stopped: {successCount} out of {currentCount} processed");
61+
return _jobStatusLogger.ToString();
62+
}
5163

52-
currentCount++;
64+
currentCount++;
5365

54-
try
55-
{
56-
_automaticRedirectsService.CreateRedirects(content.histories);
57-
successCount++;
58-
}
59-
catch (Exception ex)
60-
{
61-
_jobStatusLogger.Log($"Processing [{content.contentKey}] failed, exception: {ex}");
62-
failedCount++;
66+
try
67+
{
68+
_automaticRedirectsService.CreateRedirects(content.histories);
69+
successCount++;
70+
}
71+
catch (Exception ex)
72+
{
73+
_jobStatusLogger.Log($"Processing [{content.contentKey}] failed, exception: {ex}");
74+
failedCount++;
75+
}
76+
77+
if (currentCount % 500 == 0)
78+
{
79+
_jobStatusLogger.Status(
80+
$"Processed {currentCount}, of whom successful {successCount}; failed: {failedCount}");
81+
}
6382
}
6483

65-
if (currentCount % 500 == 0)
84+
if (batch.Count < _batchSize)
6685
{
67-
_jobStatusLogger.Status(
68-
$"Processed {currentCount} of whom successful {successCount} out of total {totalCount} content; failed: {failedCount}");
86+
break;
6987
}
88+
89+
skip += _batchSize;
7090
}
7191

7292
_jobStatusLogger.Log(
73-
$"Processed {currentCount} of whom successful {successCount} out of total {totalCount} content; failed: {failedCount}");
93+
$"Processed {currentCount}, of whom successful {successCount}; failed: {failedCount}");
7494

7595
return _jobStatusLogger.ToString();
7696
}

‎src/Geta.NotFoundHandler.Optimizely/Data/SqlContentUrlHistoryRepository.cs‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public class SqlContentUrlHistoryRepository : IRepository<ContentUrlHistory>, IC
1818
{
1919
private const string ContentUrlHistoryTable = "[dbo].[NotFoundHandler.ContentUrlHistory]";
2020
private const string AllFields = "Id, ContentKey, Urls, CreatedUtc, md5_ContentKey";
21+
private const int DefaultPageSize = 1000;
2122
private readonly IDataExecutor _dataExecutor;
2223

2324
public SqlContentUrlHistoryRepository(IDataExecutor dataExecutor)
@@ -69,17 +70,56 @@ public bool IsRegistered(ContentUrlHistory entity)
6970

7071
public IEnumerable<(string contentKey, IReadOnlyCollection<ContentUrlHistory> histories)> GetAllMoved()
7172
{
73+
// Stream the table one page at a time rather than issuing a single unbounded query that
74+
// grows with the table and can exceed the command timeout on large sites.
75+
var skip = 0;
76+
while (true)
77+
{
78+
var page = GetAllMoved(skip, DefaultPageSize).ToList();
79+
80+
foreach (var moved in page)
81+
{
82+
yield return moved;
83+
}
84+
85+
if (page.Count < DefaultPageSize)
86+
{
87+
yield break;
88+
}
89+
90+
skip += DefaultPageSize;
91+
}
92+
}
93+
94+
public IEnumerable<(string contentKey, IReadOnlyCollection<ContentUrlHistory> histories)> GetAllMoved(int skip, int take)
95+
{
96+
// Guard the inputs: "FETCH NEXT 0 ROWS ONLY" (or a negative count) is invalid SQL, and a
97+
// negative offset would fail too, so a bad caller shouldn't reach the database.
98+
if (take <= 0)
99+
{
100+
return Enumerable.Empty<(string, IReadOnlyCollection<ContentUrlHistory>)>();
101+
}
102+
103+
skip = Math.Max(0, skip);
104+
105+
// Page over the moved content keys (md5_ContentKey is the hash of ContentKey, so each key
106+
// maps to a single group and is never split across pages) and return their histories.
72107
var sqlCommand = $@"SELECT h.Id, h.ContentKey, h.Urls, h.CreatedUtc, h.md5_ContentKey
73108
FROM {ContentUrlHistoryTable} h
74-
INNER JOIN
109+
INNER JOIN
75110
(SELECT ContentKey, md5_ContentKey
76111
FROM {ContentUrlHistoryTable}
77112
GROUP BY ContentKey, md5_ContentKey
78-
HAVING COUNT(*) > 1) k
113+
HAVING COUNT(*) > 1
114+
ORDER BY ContentKey, md5_ContentKey
115+
OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY) k
79116
ON h.ContentKey = k.ContentKey AND h.md5_ContentKey = k.md5_ContentKey
80117
ORDER BY h.ContentKey, h.CreatedUtc DESC";
81118

82-
var dataTable = _dataExecutor.ExecuteQuery(sqlCommand);
119+
var dataTable = _dataExecutor.ExecuteQuery(
120+
sqlCommand,
121+
_dataExecutor.CreateIntParameter("skip", skip),
122+
_dataExecutor.CreateIntParameter("take", take));
83123

84124
var histories = ToContentUrlHistory(dataTable);
85125

‎src/Geta.NotFoundHandler.Optimizely/Infrastructure/Configuration/OptimizelyNotFoundHandlerOptions.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ public class OptimizelyNotFoundHandlerOptions
1616
public bool AutomaticRedirectsEnabled { get; set; }
1717
public RedirectType AutomaticRedirectType { get; set; } = RedirectType.Temporary;
1818

19+
/// <summary>
20+
/// Number of moved content keys the "Register content move redirects" job loads per page.
21+
/// The job processes the table page-by-page so it scales to large NotFoundHandler tables.
22+
/// </summary>
23+
public int MovedContentBatchSize { get; set; } = 1000;
24+
1925
private readonly List<Type> _contentKeyProviders = new();
2026
public IEnumerable<Type> ContentKeyProviders => _contentKeyProviders;
2127

‎src/Geta.NotFoundHandler/Data/SqlDataExecutor.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,15 @@ public class SqlDataExecutor : IDataExecutor
1616
{
1717
private readonly ILogger<SqlDataExecutor> _logger;
1818
private readonly string _connectionString;
19+
private readonly int _commandTimeout;
1920

2021
public SqlDataExecutor(
2122
IOptions<NotFoundHandlerOptions> options,
2223
ILogger<SqlDataExecutor> logger)
2324
{
2425
_connectionString = options.Value.ConnectionString;
26+
// SqlCommand.CommandTimeout throws on a negative value; clamp so a misconfiguration can't break every query. (0 = no timeout.)
27+
_commandTimeout = Math.Max(0, options.Value.CommandTimeout);
2528
_logger = logger;
2629
}
2730

@@ -42,6 +45,12 @@ public DataTable ExecuteQuery(string sqlCommand, params IDbDataParameter[] param
4245
_logger.LogError(ex,
4346
"An error occurred in the ExecuteSQL method with the following sql: {SqlCommand}",
4447
sqlCommand);
48+
49+
// Previously the exception was swallowed here and execution fell through to
50+
// 'return ds.Tables[0]'. On a failed Fill the DataSet has no tables, so that line
51+
// threw IndexOutOfRangeException ("Cannot find table 0"), masking the real cause
52+
// (e.g. a command timeout). Rethrow so callers see the actual failure.
53+
throw;
4554
}
4655

4756
return ds.Tables[0];
@@ -199,10 +208,11 @@ private static SqlParameter CreateReturnParameter()
199208
return parameter;
200209
}
201210

202-
private static SqlCommand CreateCommand(SqlConnection connection, string sqlCommand, params IDbDataParameter[] parameters)
211+
private SqlCommand CreateCommand(SqlConnection connection, string sqlCommand, params IDbDataParameter[] parameters)
203212
{
204213
var command = connection.CreateCommand();
205214
command.CommandText = sqlCommand;
215+
command.CommandTimeout = _commandTimeout;
206216

207217
if (parameters != null)
208218
{

‎src/Geta.NotFoundHandler/Infrastructure/Configuration/NotFoundHandlerOptions.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ public class NotFoundHandlerOptions
1717

1818
public int BufferSize { get; set; } = 30;
1919
public int ThreshHold { get; set; } = 5;
20+
21+
/// <summary>
22+
/// Command timeout, in seconds, applied to SQL queries issued by <see cref="Data.SqlDataExecutor"/>.
23+
/// Exposed so sites with large NotFoundHandler tables can raise it past the SqlClient default of 30s.
24+
/// Set to 0 for no timeout; negative values are treated as 0.
25+
/// </summary>
26+
public int CommandTimeout { get; set; } = 30;
2027
public SuggestionsCleanupOptions SuggestionsCleanupOptions { get; set; } = new();
2128
public bool UseInternalScheduler { get; set; }
2229
public string InternalSchedulerCronInterval { get; set; } = "0 0 * * *";

0 commit comments

Comments
 (0)