Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions .github/workflows/publish-nuget.yml
Original file line number Diff line number Diff line change
Expand Up @@ -201,17 +201,20 @@ jobs:

# A package must never ship without its tests having run, on every framework it ships for.
# The package targets net9.0 and net10.0. The test project picks its framework from
# UmbracoVersion (16 is net9.0, 17 and 18 are net10.0), so one run per framework: 16.5.1
# for net9.0 and 17.6.1 for net10.0, the same versions ci.yml pins. Each run must produce
# UmbracoVersion (16 is net9.0, 17 and 18 are net10.0), so one run per Umbraco major: 16.5.1
# for net9.0, 17.6.1 and 18.1.0 for net10.0, the same versions ci.yml pins. Each run must produce
# a trx with at least 65 passing tests (the floor ci.yml uses) and a bin folder for the
# framework it claims, so zero discovered tests or a wrong framework fails the publish.
# framework it claims, so zero discovered tests or a wrong framework fails the publish. The
# bin folder and results are deleted before each run, so a folder left by an earlier leg
# cannot satisfy the check.
- name: Test the package on every shipped framework
run: |
for LEG in 16.5.1:net9.0 17.6.1:net10.0; do
for LEG in 16.5.1:net9.0 17.6.1:net10.0 18.1.0:net10.0; do
UMBRACO=${LEG%%:*}
FRAMEWORK=${LEG##*:}
RESULTS="$GITHUB_WORKSPACE/testresults/$FRAMEWORK"
RESULTS="$GITHUB_WORKSPACE/testresults/$UMBRACO"
echo "::group::Umbraco $UMBRACO on $FRAMEWORK"
rm -rf tests/BaryoDev.Umbraco.ReadAloud.Tests/bin "$RESULTS"
dotnet test tests/BaryoDev.Umbraco.ReadAloud.Tests \
--configuration Release \
-p:UmbracoVersion=$UMBRACO \
Expand All @@ -224,7 +227,7 @@ jobs:
echo "::error::Expected $FRAMEWORK test output for Umbraco $UMBRACO" && exit 1
}
scripts/assert-tests-ran.sh "$RESULTS/results.trx" 65 || {
echo "::error::The $FRAMEWORK test run did not meet the floor." && exit 1
echo "::error::The Umbraco $UMBRACO test run did not meet the floor." && exit 1
}
done

Expand Down
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ and [semantic versioning](https://semver.org).

## [Unreleased]

### Added

- Failure backoff. After a synthesis fails, the same text skips the speech service for
`FailureBackoffSeconds` (30). A rejected Azure key backs off every request for
`AuthFailureBackoffSeconds` (300), and a 429 for its Retry-After (capped at 300 seconds) or
`FailureBackoffSeconds`. Both validated at startup, 0 turns them off. New public
`SynthesisRejectedException` and `SynthesisFailureKind` let an engine report these cases.
- Opt-in cache sweep. `CacheMaxAgeDays` (unset by default) deletes cached audio last written
longer ago than that, once a day, in batches. New optional `IAudioCacheSweep`, implemented by
`DiskAudioCache`. `IAudioCache` is unchanged (#5). `CacheMaxAgeDays` is capped at 36500.
- Saving or removing the Azure key in the backoffice clears every failure backoff, so the new key
is tried on the next request.

### Changed

- A cancelled synthesis that is not a shutdown (an engine's HTTP timeout) now counts as a failure
for backoff. A reader closing the tab still records nothing.
- The publish workflow also tests Umbraco 18.1.0, as ci.yml does.

### Fixed

- Text extraction no longer takes quadratic time on a page with many unclosed `<script>` or
Expand Down
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ v1 is configuration only. Every value has a working default.
"DisablePropertyAlias": "readAloudDisabled",
"MaxChars": 8000,
"CachePath": "App_Data/BaryoDev/ReadAloud",
"CacheMaxAgeDays": null,
"FailureBackoffSeconds": 30,
"AuthFailureBackoffSeconds": 300,
"RateLimitPerMinute": 20,
"MaxConcurrentSynthesis": 4,
"Provider": "Browser"
Expand Down Expand Up @@ -298,6 +301,34 @@ whoever asks next. Past the ceiling a request is refused with a 503 and the read
browser's own voice, rather than waiting on a queue with no end. Four is deliberately modest,
because a burst of connections is what gets a service to throttle you.

### Failure backoff

After a synthesis fails, requests for the same text within `FailureBackoffSeconds` (default 30)
skip the speech service and answer the same 503, so the browser voice takes over without another
paid call. When Azure rejects the key (401 or 403), every request skips it for
`AuthFailureBackoffSeconds` (default 300) and one warning is logged. On a 429 the same applies to
every key for the service's Retry-After, capped at 300 seconds, or `FailureBackoffSeconds` when it
sends none. Set a value to 0 to turn that backoff off. A 429 Retry-After is still honoured when
`FailureBackoffSeconds` is 0. Saving or removing the Azure key in the backoffice clears every
backoff at once. Audio already cached is still served.
Failures are remembered in memory only, at most 1000 keys.

A custom engine can report these cases by throwing `SynthesisRejectedException`. The Azure package
does.

### Cleaning up the cache

Cache files are named by a hash of the text, so editing a page makes a new file and leaves the old
one. Files for edited, unpublished and deleted pages stay until swept or until you delete the
folder, which is always safe.

To sweep, set `CacheMaxAgeDays`, for example `30` (1 to 36500). Once a day a background job deletes cached files
last written more than that many days ago, in batches of 500, and the next request for a deleted
entry makes it again. It is off by default and only touches files named like cache entries. It
runs only when the registered `IAudioCache` also implements `IAudioCacheSweep`, which the built-in
disk cache does. The file time is the last write, because the disk cache does not record reads, so
a popular article is regenerated once per window.

## Related

The browser half comes from [`@baryodev/read-aloud`](https://www.npmjs.com/package/@baryodev/read-aloud),
Expand Down
6 changes: 6 additions & 0 deletions src/BaryoDev.Umbraco.ReadAloud.Azure/AzureSpeechAdmin.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using BaryoDev.Umbraco.ReadAloud.Caching;
using BaryoDev.Umbraco.ReadAloud.Engine;
using BaryoDev.Umbraco.ReadAloud.Settings;
using Microsoft.Extensions.Logging;
Expand All @@ -22,6 +23,7 @@ internal sealed class AzureSpeechAdmin : IReadAloudAzureAdmin
private readonly IAzureVoiceClient _voiceClient;
private readonly IAzureVoiceList _voiceList;
private readonly IOptionsMonitor<ReadAloudOptions> _core;
private readonly BackoffResetSignal _backoff;
private readonly ILogger<AzureSpeechAdmin> _logger;

public AzureSpeechAdmin(
Expand All @@ -31,6 +33,7 @@ public AzureSpeechAdmin(
IAzureVoiceClient voiceClient,
IAzureVoiceList voiceList,
IOptionsMonitor<ReadAloudOptions> core,
BackoffResetSignal backoff,
ILogger<AzureSpeechAdmin> logger)
{
_resolver = resolver;
Expand All @@ -39,6 +42,7 @@ public AzureSpeechAdmin(
_voiceClient = voiceClient;
_voiceList = voiceList;
_core = core;
_backoff = backoff;
_logger = logger;
}

Expand Down Expand Up @@ -141,6 +145,7 @@ public AzureSaveModel Save(string? region, string? key, string savedBy)

_store.Save(newRegion, newKey, savedBy);
_voiceList.Evict(newRegion, newKey);
_backoff.Reset();
_logger.LogInformation("The Azure Speech key was saved from the backoffice by {User}.", savedBy);

return new AzureSaveModel(true, "ok", "Saved. Readers get the Azure voice from the next request.");
Expand All @@ -153,6 +158,7 @@ public AzureSaveModel Remove(string removedBy)
var before = _resolver.Current;
_store.Clear();
if (before is not null) _voiceList.Evict(before.Region, before.Key);
_backoff.Reset();
_logger.LogInformation("The Azure Speech key was removed from the backoffice by {User}.", removedBy);

return new AzureSaveModel(true, "ok", "Removed. Readers get the browser voice from the next request.");
Expand Down
11 changes: 9 additions & 2 deletions src/BaryoDev.Umbraco.ReadAloud.Azure/AzureSpeechEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,15 @@ public async Task<SynthesisResult> SynthesizeAsync(

// The error code names the cause (a bad key is AuthenticationFailure, a spent quota
// is TooManyRequests). The free-text details are left out of the message.
throw new InvalidOperationException(
$"Azure Speech refused the synthesis: {details.ErrorCode}.");
var message = $"Azure Speech refused the synthesis: {details.ErrorCode}.";
throw details.ErrorCode switch
{
CancellationErrorCode.AuthenticationFailure or CancellationErrorCode.Forbidden =>
new SynthesisRejectedException(SynthesisFailureKind.Authentication, message),
CancellationErrorCode.TooManyRequests =>
new SynthesisRejectedException(SynthesisFailureKind.RateLimited, message),
_ => new InvalidOperationException(message),
};
}

if (result.Reason != ResultReason.SynthesizingAudioCompleted || result.AudioData.Length == 0)
Expand Down
102 changes: 102 additions & 0 deletions src/BaryoDev.Umbraco.ReadAloud/Caching/AudioCacheSweepService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace BaryoDev.Umbraco.ReadAloud.Caching;

/// <summary>
/// Deletes cached audio older than <c>CacheMaxAgeDays</c>, once a day. Does nothing while that
/// option is unset.
/// </summary>
internal sealed class AudioCacheSweepService : BackgroundService
{
internal const int BatchSize = 500;
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
private static readonly TimeSpan StartupDelay = TimeSpan.FromMinutes(5);
private static readonly TimeSpan BatchPause = TimeSpan.FromSeconds(1);

private readonly IAudioCache _cache;
private readonly IOptionsMonitor<ReadAloudOptions> _options;
private readonly ILogger<AudioCacheSweepService> _logger;
private readonly TimeProvider _time;

public AudioCacheSweepService(
IAudioCache cache,
IOptionsMonitor<ReadAloudOptions> options,
ILogger<AudioCacheSweepService> logger)
: this(cache, options, logger, TimeProvider.System)
{
}

internal AudioCacheSweepService(
IAudioCache cache,
IOptionsMonitor<ReadAloudOptions> options,
ILogger<AudioCacheSweepService> logger,
TimeProvider time)
{
_cache = cache;
_options = options;
_logger = logger;
_time = time;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await Task.Delay(StartupDelay, stoppingToken);

while (!stoppingToken.IsCancellationRequested)
{
try
{
await RunOnceAsync(BatchPause, stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "The read-aloud cache sweep failed. It will try again tomorrow.");
}

await Task.Delay(Interval, stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
}
}

/// <summary>One sweep, in batches. Returns how many files were deleted.</summary>
internal async Task<int> RunOnceAsync(
TimeSpan pauseBetweenBatches, CancellationToken ct, int batchSize = BatchSize)
{
var days = _options.CurrentValue.CacheMaxAgeDays;
if (days is null) return 0;

if (_cache is not IAudioCacheSweep sweep)
{
_logger.LogInformation(
"{Section}:CacheMaxAgeDays is set, but the registered audio cache does not support sweeping.",
ReadAloudOptions.SectionName);
return 0;
}

var cutoff = _time.GetUtcNow().AddDays(-days.Value);
var total = 0;

while (!ct.IsCancellationRequested)
{
var deleted = await sweep.SweepAsync(cutoff, batchSize, ct);
total += deleted;
if (deleted < batchSize) break;

if (pauseBetweenBatches > TimeSpan.Zero) await Task.Delay(pauseBetweenBatches, ct);
}

if (total > 0)
{
_logger.LogInformation("Read-aloud cache sweep deleted {Count} files older than {Days} days.", total, days);
}

return total;
}
}
14 changes: 14 additions & 0 deletions src/BaryoDev.Umbraco.ReadAloud/Caching/BackoffResetSignal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace BaryoDev.Umbraco.ReadAloud.Caching;

/// <summary>
/// Tells the audio source to forget its failure backoff. It has no dependencies, so the Azure
/// admin can raise it without resolving the audio pipeline.
/// </summary>
internal sealed class BackoffResetSignal
{
private int _generation;

public int Generation => Volatile.Read(ref _generation);

public void Reset() => Interlocked.Increment(ref _generation);
}
Loading
Loading