From e13d77b6e0107a107f479f19264472cf676f6f24 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:13:08 +0800
Subject: [PATCH 01/10] count listens in memory and write them once a minute
---
.../Controllers/ReadAloudController.cs | 29 +-
.../Listens/IListenStore.cs | 8 +
.../Listens/ListenCounter.cs | 108 +++++
.../Listens/ListenFlushService.cs | 164 +++++++
.../Listens/ListenKey.cs | 8 +
.../Listens/ListenRange.cs | 29 ++
.../Listens/ListenRow.cs | 37 ++
.../Listens/ListenStore.cs | 59 +++
.../Listens/ListensMigrationPlan.cs | 37 ++
.../ReadAloudComposer.cs | 8 +
.../ReadAloudOptions.cs | 25 ++
.../ListenCounterTests.cs | 170 ++++++++
.../ListenCountingTests.cs | 399 ++++++++++++++++++
.../ListenFlushTests.cs | 226 ++++++++++
.../ListenRangeTests.cs | 43 ++
.../ListenSettingTests.cs | 82 ++++
.../ListenStoreTests.cs | 123 ++++++
.../ListenTestSupport.cs | 67 +++
18 files changed, 1619 insertions(+), 3 deletions(-)
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/IListenStore.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenCounter.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenKey.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRange.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRow.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListenStore.cs
create mode 100644 src/BaryoDev.Umbraco.ReadAloud/Listens/ListensMigrationPlan.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCounterTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
create mode 100644 tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenTestSupport.cs
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs b/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
index 07d67af..6039e44 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
@@ -2,6 +2,7 @@
using BaryoDev.Umbraco.ReadAloud.Caching;
using BaryoDev.Umbraco.ReadAloud.Content;
using BaryoDev.Umbraco.ReadAloud.Engine;
+using BaryoDev.Umbraco.ReadAloud.Listens;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Headers;
using Microsoft.AspNetCore.Mvc;
@@ -34,6 +35,7 @@ public class ReadAloudController : Controller
private readonly IPublicAccessService _publicAccess;
private readonly IOptionsMonitor _options;
private readonly ILogger? _logger;
+ private readonly ListenCounter? _listens;
/// Creates the controller.
public ReadAloudController(
@@ -41,13 +43,15 @@ public ReadAloudController(
IPublishedContentQuery content,
IPublicAccessService publicAccess,
IOptionsMonitor options,
- ILogger? logger = null)
+ ILogger? logger = null,
+ ListenCounter? listens = null)
{
_audio = audio;
_content = content;
_publicAccess = publicAccess;
_options = options;
_logger = logger;
+ _listens = listens;
}
/// Returns the audio for a node, synthesizing it on the first request.
@@ -74,9 +78,28 @@ public async Task Get(Guid key, [FromQuery] string? voice, Cancel
if (refusal is not null) return refusal;
var etag = ETagFor(request!, "audio");
- if (NotModified(etag)) return NotModifiedResponse(etag);
+ if (NotModified(etag))
+ {
+ CountListen(key, request!);
+ return NotModifiedResponse(etag);
+ }
+
+ return await SynthesizeAsync(request!, ct, result =>
+ {
+ CountListen(key, request!);
+ return Tagged(etag, File(result.Audio, result.ContentType));
+ });
+ }
+
+ ///
+ /// Counts one play. Called from exactly two places in : the 304 and the 200.
+ /// The voice is the one the request resolved to, never the query value.
+ ///
+ private void CountListen(Guid key, SynthesisRequest request)
+ {
+ if (_listens is null || !ListenRange.CountsAsPlay(Request.Headers.Range)) return;
- return await SynthesizeAsync(request!, ct, result => Tagged(etag, File(result.Audio, result.ContentType)));
+ _listens.Add(key, request.Voice);
}
/// Returns the word timings that drive highlighting, for the same node and voice.
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/IListenStore.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/IListenStore.cs
new file mode 100644
index 0000000..940f480
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/IListenStore.cs
@@ -0,0 +1,8 @@
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+/// Where counts are written. A seam so the flush service can be tested without a database.
+internal interface IListenStore
+{
+ /// Adds to the row for the key, creating it when it is missing.
+ void Add(ListenKey key, int count);
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenCounter.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenCounter.cs
new file mode 100644
index 0000000..d87645c
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenCounter.cs
@@ -0,0 +1,108 @@
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+///
+/// Counts plays in memory per article, voice and UTC day until the flush service writes them.
+///
+///
+/// Holds a count and a key and nothing else, so there is nothing here that could say who listened.
+/// The day is part of the key, so a flush that straddles UTC midnight splits correctly.
+///
+public sealed class ListenCounter
+{
+ /// The most keys held in memory. Past it the oldest day is dropped first.
+ internal const int MaxKeys = 10_000;
+
+ private readonly IOptionsMonitor _options;
+ private readonly TimeProvider _time;
+ private readonly ILogger? _logger;
+ private readonly object _gate = new();
+ private Dictionary _counts = [];
+
+ /// Creates the counter.
+ public ListenCounter(
+ IOptionsMonitor options,
+ TimeProvider time,
+ ILogger? logger = null)
+ {
+ _options = options;
+ _time = time;
+ _logger = logger;
+ }
+
+ /// Counts one play of a node in a voice, today in UTC. Does nothing when counting is off.
+ public void Add(Guid nodeKey, string voice)
+ {
+ if (!_options.CurrentValue.CountListens) return;
+
+ var key = new ListenKey(nodeKey, voice, ListenKey.DayOf(_time.GetUtcNow()));
+
+ lock (_gate)
+ {
+ if (!_counts.ContainsKey(key) && _counts.Count >= MaxKeys) DropOldestDay();
+
+ _counts[key] = _counts.GetValueOrDefault(key) + 1;
+ }
+ }
+
+ /// Takes everything counted so far and starts again from empty.
+ internal Dictionary Drain()
+ {
+ lock (_gate)
+ {
+ var taken = _counts;
+ _counts = [];
+ return taken;
+ }
+ }
+
+ /// Puts drained counts back after a failed write, on top of whatever arrived since.
+ internal void MergeBack(IReadOnlyDictionary counts)
+ {
+ lock (_gate)
+ {
+ foreach (var (key, n) in counts) _counts[key] = _counts.GetValueOrDefault(key) + n;
+
+ while (_counts.Count > MaxKeys)
+ {
+ if (!DropOldestDay()) break;
+ }
+ }
+ }
+
+ /// Forgets everything held. Used when counting is switched off.
+ internal void Clear()
+ {
+ lock (_gate) _counts = [];
+ }
+
+ /// What is held now, for tests.
+ internal IReadOnlyDictionary Snapshot()
+ {
+ lock (_gate) return new Dictionary(_counts);
+ }
+
+ /// Removes every key of the oldest day held. Call with the lock taken.
+ private bool DropOldestDay()
+ {
+ if (_counts.Count == 0) return false;
+
+ var oldest = _counts.Keys.Min(k => k.DayUtc);
+ var dropped = 0;
+ foreach (var key in _counts.Keys.Where(k => k.DayUtc == oldest).ToList())
+ {
+ _counts.Remove(key);
+ dropped++;
+ }
+
+ _logger?.LogWarning(
+ "Read-aloud listen counts reached {Cap} keys in memory. Dropped {Dropped} keys for day {Day}.",
+ MaxKeys,
+ dropped,
+ oldest);
+
+ return true;
+ }
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
new file mode 100644
index 0000000..8dc335c
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
@@ -0,0 +1,164 @@
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using Umbraco.Cms.Core;
+using Umbraco.Cms.Core.Services;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+///
+/// Writes the in-memory counts to the database every minute, and once more at shutdown.
+///
+///
+/// Waits for Umbraco to reach first, so it never writes during an
+/// install or an upgrade. A failed flush puts its counts back in memory and tries again on the next
+/// tick, and logs once per failure streak. A missing table counts as a failure like any other,
+/// which is what a site sees until the migration has run.
+///
+internal sealed class ListenFlushService : BackgroundService
+{
+ internal static readonly TimeSpan FlushInterval = TimeSpan.FromMinutes(1);
+ internal static readonly TimeSpan ReadyPoll = TimeSpan.FromSeconds(1);
+ internal static readonly TimeSpan ShutdownTimeout = TimeSpan.FromSeconds(5);
+
+ private readonly ListenCounter _counter;
+ private readonly IListenStore _store;
+ private readonly Func _ready;
+ private readonly IOptionsMonitor _options;
+ private readonly ILogger _logger;
+ private readonly TimeSpan _interval;
+ private readonly TimeSpan _readyPoll;
+ private readonly TimeSpan _shutdownTimeout;
+ private int _failing;
+
+ public ListenFlushService(
+ ListenCounter counter,
+ IListenStore store,
+ IRuntimeState runtime,
+ IOptionsMonitor options,
+ ILogger logger)
+ : this(counter, store, () => runtime.Level == RuntimeLevel.Run, options, logger,
+ FlushInterval, ReadyPoll, ShutdownTimeout)
+ {
+ }
+
+ internal ListenFlushService(
+ ListenCounter counter,
+ IListenStore store,
+ Func ready,
+ IOptionsMonitor options,
+ ILogger logger,
+ TimeSpan interval,
+ TimeSpan readyPoll,
+ TimeSpan shutdownTimeout)
+ {
+ _counter = counter;
+ _store = store;
+ _ready = ready;
+ _options = options;
+ _logger = logger;
+ _interval = interval;
+ _readyPoll = readyPoll;
+ _shutdownTimeout = shutdownTimeout;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ try
+ {
+ while (!_ready()) await Task.Delay(_readyPoll, stoppingToken);
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ await Task.Delay(_interval, stoppingToken);
+ await Task.Run(() => Flush(), stoppingToken);
+ }
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ }
+ }
+
+ /// Flushes once more on the way out. Never throws, and never waits past the timeout.
+ public override async Task StopAsync(CancellationToken cancellationToken)
+ {
+ try
+ {
+ await base.StopAsync(cancellationToken);
+ }
+ catch (Exception)
+ {
+ }
+
+ try
+ {
+ if (!_ready()) return;
+
+ var written = await Task.Run(() => Flush()).WaitAsync(_shutdownTimeout, cancellationToken);
+ if (!written) DropAtShutdown();
+ }
+ catch (Exception)
+ {
+ DropAtShutdown();
+ }
+ }
+
+ ///
+ /// One flush. Returns false when something could not be written, after putting it back in
+ /// memory. With counting switched off it drops what is held and writes nothing.
+ ///
+ internal bool Flush()
+ {
+ if (!_options.CurrentValue.CountListens)
+ {
+ _counter.Clear();
+ return true;
+ }
+
+ var drained = _counter.Drain();
+ if (drained.Count == 0) return true;
+
+ var written = 0;
+ Exception? failure = null;
+ foreach (var (key, count) in drained)
+ {
+ try
+ {
+ _store.Add(key, count);
+ written++;
+ }
+ catch (Exception ex)
+ {
+ failure = ex;
+ break;
+ }
+ }
+
+ if (failure is null)
+ {
+ Interlocked.Exchange(ref _failing, 0);
+ return true;
+ }
+
+ // Everything after the first failure was never tried, and the failed row may or may not
+ // have been written, so only the rows that were written are left out.
+ _counter.MergeBack(drained.Skip(written).ToDictionary(p => p.Key, p => p.Value));
+
+ if (Interlocked.Exchange(ref _failing, 1) == 0)
+ {
+ _logger.LogWarning(
+ failure,
+ "Read-aloud listen counts could not be written. They are kept in memory and the next flush will retry. "
+ + "If the {Table} table is missing, the package migration has not run.",
+ ListenRow.TableName);
+ }
+
+ return false;
+ }
+
+ private void DropAtShutdown()
+ {
+ _counter.Clear();
+ _logger.LogWarning("Read-aloud listen counts could not be written at shutdown and were dropped.");
+ }
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenKey.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenKey.cs
new file mode 100644
index 0000000..6ac5f1b
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenKey.cs
@@ -0,0 +1,8 @@
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+/// The identity of one counter: article, voice and UTC day.
+internal readonly record struct ListenKey(Guid NodeKey, string Voice, int DayUtc)
+{
+ /// The UTC day as yyyymmdd.
+ internal static int DayOf(DateTimeOffset utc) => utc.Year * 10000 + utc.Month * 100 + utc.Day;
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRange.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRange.cs
new file mode 100644
index 0000000..d6bb786
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRange.cs
@@ -0,0 +1,29 @@
+using Microsoft.Extensions.Primitives;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+///
+/// Which audio requests count as a play, judged by the Range header alone.
+///
+///
+/// The origin answers every range request with the whole recording and a 200, so a browser that
+/// probes with a partial range would otherwise count twice for one press. A request with no range,
+/// or the open range from the start, is the press itself. Everything else is a probe or a seek and
+/// counts nothing. Kept in one place because a real Safari capture may change it.
+///
+internal static class ListenRange
+{
+ private const string Unit = "bytes=";
+
+ /// True when there is no range, or exactly one range that is bytes=0-.
+ internal static bool CountsAsPlay(StringValues range)
+ {
+ if (StringValues.IsNullOrEmpty(range)) return true;
+ if (range.Count != 1) return false;
+
+ var value = range[0]!.Trim();
+ if (!value.StartsWith(Unit, StringComparison.OrdinalIgnoreCase)) return false;
+
+ return value[Unit.Length..].Trim() == "0-";
+ }
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRow.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRow.cs
new file mode 100644
index 0000000..7ba6483
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenRow.cs
@@ -0,0 +1,37 @@
+using NPoco;
+using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+///
+/// One row per article, voice and UTC day. Four columns and nothing else: there is no column
+/// that could say who listened, and adding one is a design change, not a schema tweak.
+///
+[TableName(TableName)]
+[ExplicitColumns]
+public sealed class ListenRow
+{
+ /// The table name.
+ public const string TableName = "baryoReadAloudListens";
+
+ /// The longest voice name the table holds.
+ public const int MaxVoiceLength = 100;
+
+ /// The key of the published node that was read.
+ [Column("NodeKey")]
+ [PrimaryKeyColumn(AutoIncrement = false, Clustered = true, Name = "PK_baryoReadAloudListens", OnColumns = "NodeKey, Voice, DayUtc")]
+ public Guid NodeKey { get; set; }
+
+ /// The voice actually used, after the site's allow-list.
+ [Column("Voice")]
+ [Length(MaxVoiceLength)]
+ public string Voice { get; set; } = string.Empty;
+
+ /// The UTC day as yyyymmdd.
+ [Column("DayUtc")]
+ public int DayUtc { get; set; }
+
+ /// How many plays were served.
+ [Column("Listens")]
+ public int Listens { get; set; }
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenStore.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenStore.cs
new file mode 100644
index 0000000..6472dba
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenStore.cs
@@ -0,0 +1,59 @@
+using System.Data.Common;
+using Umbraco.Cms.Infrastructure.Scoping;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+/// Writes counts to , one statement per row.
+///
+/// An update first, since nearly every write is to a row that exists. When it touches nothing, an
+/// insert in a fresh scope. When the insert throws a , another server won
+/// the race to create the row, so the update runs again in a fresh scope. No provider error codes
+/// are read, because they differ between SQLite and SQL Server.
+///
+internal sealed class ListenStore(IScopeProvider scopes) : IListenStore
+{
+ private const string UpdateSql =
+ "UPDATE baryoReadAloudListens SET Listens = Listens + @0 WHERE NodeKey = @1 AND Voice = @2 AND DayUtc = @3";
+
+ private const string InsertSql =
+ "INSERT INTO baryoReadAloudListens (NodeKey, Voice, DayUtc, Listens) VALUES (@0, @1, @2, @3)";
+
+ /// Runs just before the insert, so a test can make another server win the race.
+ internal Action? BeforeInsert { get; set; }
+
+ public void Add(ListenKey key, int count)
+ {
+ if (Update(key, count)) return;
+
+ try
+ {
+ BeforeInsert?.Invoke(key);
+ Insert(key, count);
+ return;
+ }
+ catch (DbException)
+ {
+ }
+
+ if (!Update(key, count))
+ {
+ throw new InvalidOperationException(
+ "The listens row could not be inserted and was not there to update.");
+ }
+ }
+
+ private bool Update(ListenKey key, int count)
+ {
+ using var scope = scopes.CreateScope();
+ var rows = scope.Database.Execute(UpdateSql, count, key.NodeKey, key.Voice, key.DayUtc);
+ scope.Complete();
+ return rows > 0;
+ }
+
+ private void Insert(ListenKey key, int count)
+ {
+ using var scope = scopes.CreateScope();
+ scope.Database.Execute(InsertSql, key.NodeKey, key.Voice, key.DayUtc, count);
+ scope.Complete();
+ }
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListensMigrationPlan.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListensMigrationPlan.cs
new file mode 100644
index 0000000..78de4e2
--- /dev/null
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListensMigrationPlan.cs
@@ -0,0 +1,37 @@
+using Umbraco.Cms.Core.Packaging;
+using Umbraco.Cms.Infrastructure.Migrations;
+using Umbraco.Cms.Infrastructure.Persistence;
+
+namespace BaryoDev.Umbraco.ReadAloud.Listens;
+
+///
+/// Creates the listens table. Umbraco finds a plan by type scan, so the composer registers nothing
+/// for it. With PackageMigrationsUnattended on, which is the default, it runs at startup.
+///
+public sealed class ListensMigrationPlan() : PackageMigrationPlan("BaryoDev.Umbraco.ReadAloud")
+{
+ ///
+ protected override void DefinePlan()
+ {
+ To("6c1e4b0a-2f7d-4d58-9a13-5e8b7c3f9d24");
+ }
+}
+
+/// Creates , only when it does not exist.
+public sealed class CreateListensTable(IMigrationContext context) : AsyncMigrationBase(context)
+{
+ ///
+ protected override Task MigrateAsync()
+ {
+ if (IsMissing(Database))
+ {
+ Create.Table().Do();
+ }
+
+ return Task.CompletedTask;
+ }
+
+ /// Whether the table has to be created. The guard that makes a second run harmless.
+ internal static bool IsMissing(IUmbracoDatabase database, string tableName = ListenRow.TableName) =>
+ !database.SqlContext.SqlSyntax.DoesTableExist(database, tableName);
+}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/ReadAloudComposer.cs b/src/BaryoDev.Umbraco.ReadAloud/ReadAloudComposer.cs
index 3466ab2..4c5a133 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/ReadAloudComposer.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud/ReadAloudComposer.cs
@@ -1,10 +1,12 @@
using BaryoDev.Umbraco.ReadAloud.Caching;
using BaryoDev.Umbraco.ReadAloud.Engine;
+using BaryoDev.Umbraco.ReadAloud.Listens;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Composing;
@@ -57,6 +59,12 @@ public void Compose(IUmbracoBuilder builder)
sp.GetRequiredService()));
builder.Services.AddHostedService();
+ // Umbraco 17 registers its own TimeProvider, so this is a no-op there and not a conflict.
+ builder.Services.TryAddSingleton(TimeProvider.System);
+ builder.Services.AddSingleton();
+ builder.Services.AddSingleton();
+ builder.Services.AddHostedService();
+
AddRateLimiting(builder);
}
diff --git a/src/BaryoDev.Umbraco.ReadAloud/ReadAloudOptions.cs b/src/BaryoDev.Umbraco.ReadAloud/ReadAloudOptions.cs
index 572a28c..b4c7b2e 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/ReadAloudOptions.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud/ReadAloudOptions.cs
@@ -1,4 +1,5 @@
using BaryoDev.Umbraco.ReadAloud.Engine;
+using BaryoDev.Umbraco.ReadAloud.Listens;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -80,6 +81,15 @@ public class ReadAloudOptions
///
public string KeysPath { get; set; } = "";
+ ///
+ /// Whether server-voiced plays are counted per article, voice and UTC day in the site's own
+ /// database. On by default. Nothing is stored about who listened: the table holds a node key,
+ /// the voice, the day and a count. Read at runtime, so turning it off takes effect without a
+ /// restart: counts held in memory are dropped and nothing more is written, including at shutdown.
+ /// Browser-voice plays are never counted, since the server does not see them.
+ ///
+ public bool CountListens { get; set; } = true;
+
/// Requests per minute per IP, since the endpoint is anonymous.
public int RateLimitPerMinute { get; set; } = 20;
@@ -161,6 +171,11 @@ public ReadAloudOptionsValidation(
_logger = logger;
}
+ private static ValidateOptionsResult TooLong(string setting, string voice) =>
+ ValidateOptionsResult.Fail(
+ $"{ReadAloudOptions.SectionName}:{setting} holds a voice of {voice.Length} characters. "
+ + $"Voice names are at most {ListenRow.MaxVoiceLength} characters, because the listens table stores them.");
+
public ValidateOptionsResult Validate(string? name, ReadAloudOptions options)
{
if (options.MaxChars < 1)
@@ -199,6 +214,16 @@ public ValidateOptionsResult Validate(string? name, ReadAloudOptions options)
+ $"Set it between 0 (off) and {MaxBackoffSeconds}.");
}
+ // The listens table stores the voice in a 100 character column. A longer name would fail
+ // every flush, so it stops the boot here instead.
+ if (options.DefaultVoice is { Length: > ListenRow.MaxVoiceLength })
+ {
+ return TooLong("DefaultVoice", options.DefaultVoice);
+ }
+
+ var tooLong = options.AllowedVoices.FirstOrDefault(v => v is { Length: > ListenRow.MaxVoiceLength });
+ if (tooLong is not null) return TooLong("AllowedVoices", tooLong);
+
// Without case, because this is hand-typed into a configuration file, the same reason the
// controller compares document type aliases without case.
if (string.Equals(options.Provider, ReadAloudOptions.BrowserProvider, StringComparison.OrdinalIgnoreCase))
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCounterTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCounterTests.cs
new file mode 100644
index 0000000..dc02d10
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCounterTests.cs
@@ -0,0 +1,170 @@
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Shouldly;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+public class ListenCounterTests
+{
+ private readonly ListenClock _clock = new();
+ private readonly ListenOptions _options = new();
+ private readonly WarningLog _log = new();
+
+ private ListenCounter Counter() => new(_options, _clock, _log);
+
+ [Fact]
+ public void A_play_is_counted_under_the_node_the_voice_and_the_utc_day_from_the_injected_clock()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+
+ counter.Add(node, "en-GB-SoniaNeural");
+
+ counter.Snapshot().ShouldBe(new Dictionary
+ {
+ [new ListenKey(node, "en-GB-SoniaNeural", ListenClock.Day)] = 1,
+ });
+ }
+
+ [Fact]
+ public void The_day_rolls_over_at_utc_midnight()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+ _clock.Now = new DateTimeOffset(2026, 11, 16, 23, 59, 59, TimeSpan.Zero);
+
+ counter.Add(node, "v");
+ _clock.Advance(TimeSpan.FromSeconds(1));
+ counter.Add(node, "v");
+
+ var held = counter.Snapshot();
+ held[new ListenKey(node, "v", 20261116)].ShouldBe(1);
+ held[new ListenKey(node, "v", 20261117)].ShouldBe(1);
+ }
+
+ [Fact]
+ public void Draining_takes_everything_and_later_adds_start_from_empty()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+ counter.Add(node, "v");
+ counter.Add(node, "v");
+
+ var drained = counter.Drain();
+ counter.Add(node, "v");
+
+ drained.Values.Sum().ShouldBe(2);
+ counter.Snapshot().Values.Sum().ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task Two_parallel_first_adds_for_one_key_end_at_2()
+ {
+ var counter = Counter();
+
+ for (var round = 0; round < 300; round++)
+ {
+ var node = Guid.NewGuid();
+ using var barrier = new Barrier(2);
+ var adds = Enumerable.Range(0, 2)
+ .Select(_ => Task.Run(() =>
+ {
+ barrier.SignalAndWait();
+ counter.Add(node, "v");
+ }))
+ .ToArray();
+ await Task.WhenAll(adds);
+
+ counter.Snapshot()[new ListenKey(node, "v", ListenClock.Day)].ShouldBe(2);
+ }
+ }
+
+ [Fact]
+ public void Turning_the_setting_off_counts_nothing_and_on_again_counts()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+
+ _options.CurrentValue.CountListens = false;
+ counter.Add(node, "v");
+ counter.Snapshot().ShouldBeEmpty();
+
+ _options.CurrentValue.CountListens = true;
+ counter.Add(node, "v");
+ counter.Snapshot().Values.Sum().ShouldBe(1);
+ }
+
+ [Fact]
+ public void Past_the_cap_the_oldest_day_goes_first_with_one_log_line()
+ {
+ var counter = Counter();
+ for (var i = 0; i < ListenCounter.MaxKeys / 2; i++) counter.Add(Guid.NewGuid(), "v");
+ _clock.Advance(TimeSpan.FromDays(1));
+ for (var i = 0; i < ListenCounter.MaxKeys / 2; i++) counter.Add(Guid.NewGuid(), "v");
+ counter.Snapshot().Count.ShouldBe(ListenCounter.MaxKeys);
+ _log.Warnings.ShouldBeEmpty();
+
+ counter.Add(Guid.NewGuid(), "v");
+
+ var held = counter.Snapshot();
+ held.Count.ShouldBe(ListenCounter.MaxKeys / 2 + 1);
+ held.Keys.ShouldAllBe(k => k.DayUtc == 20261117);
+ _log.Warnings.Count.ShouldBe(1);
+ }
+
+ [Fact]
+ public void A_key_already_held_is_counted_at_the_cap_without_dropping_anything()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+ counter.Add(node, "v");
+ for (var i = 1; i < ListenCounter.MaxKeys; i++) counter.Add(Guid.NewGuid(), "v");
+
+ counter.Add(node, "v");
+
+ counter.Snapshot().Count.ShouldBe(ListenCounter.MaxKeys);
+ counter.Snapshot()[new ListenKey(node, "v", ListenClock.Day)].ShouldBe(2);
+ _log.Warnings.ShouldBeEmpty();
+ }
+
+ [Fact]
+ public void Merging_back_adds_on_top_of_what_arrived_since()
+ {
+ var counter = Counter();
+ var node = Guid.NewGuid();
+ counter.Add(node, "v");
+ counter.Add(node, "v");
+ var drained = counter.Drain();
+ counter.Add(node, "v");
+
+ counter.MergeBack(drained);
+
+ counter.Snapshot()[new ListenKey(node, "v", ListenClock.Day)].ShouldBe(3);
+ }
+
+ [Fact]
+ public void Merging_back_past_the_cap_drops_the_oldest_day_first()
+ {
+ var counter = Counter();
+ for (var i = 0; i < 10; i++) counter.Add(Guid.NewGuid(), "v");
+ var oldDay = counter.Drain();
+ _clock.Advance(TimeSpan.FromDays(1));
+ for (var i = 0; i < ListenCounter.MaxKeys; i++) counter.Add(Guid.NewGuid(), "v");
+
+ counter.MergeBack(oldDay);
+
+ counter.Snapshot().Count.ShouldBe(ListenCounter.MaxKeys);
+ counter.Snapshot().Keys.ShouldAllBe(k => k.DayUtc == 20261117);
+ _log.Warnings.Count.ShouldBe(1);
+ }
+
+ [Fact]
+ public void Clearing_forgets_everything_held()
+ {
+ var counter = Counter();
+ counter.Add(Guid.NewGuid(), "v");
+
+ counter.Clear();
+
+ counter.Snapshot().ShouldBeEmpty();
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
new file mode 100644
index 0000000..a790794
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
@@ -0,0 +1,399 @@
+using BaryoDev.Umbraco.ReadAloud.Caching;
+using BaryoDev.Umbraco.ReadAloud.Content;
+using BaryoDev.Umbraco.ReadAloud.Controllers;
+using BaryoDev.Umbraco.ReadAloud.Engine;
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Options;
+using Shouldly;
+using global::Umbraco.Cms.Core;
+using global::Umbraco.Cms.Core.Services;
+using global::Umbraco.Cms.Infrastructure.Scoping;
+using global::Umbraco.Cms.Core.Web;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+///
+/// Drives the controller directly with its own counter and clock, so each test reads exactly what
+/// its own call added. The real pipeline cases at the bottom go through the booted site.
+///
+[Collection(UmbracoCollection.Name)]
+public class ListenCountingTests
+{
+ private readonly UmbracoSiteFixture _site;
+ private readonly ListenClock _clock = new();
+ private readonly ListenOptions _options = new();
+ private readonly ListenCounter _counter;
+
+ public ListenCountingTests(UmbracoSiteFixture site)
+ {
+ _site = site;
+ _counter = new ListenCounter(_options, _clock);
+ }
+
+ private sealed class OkEngine : IReadAloudEngine
+ {
+ public Task SynthesizeAsync(SynthesisRequest request, CancellationToken ct = default) =>
+ Task.FromResult(new SynthesisResult([1, 2, 3], [], "audio/mpeg"));
+ }
+
+ private sealed class ThrowingEngine : IReadAloudEngine
+ {
+ public Task SynthesizeAsync(SynthesisRequest request, CancellationToken ct = default) =>
+ throw new InvalidOperationException("provider down");
+ }
+
+ private sealed class NoCache : IAudioCache
+ {
+ public Task GetAsync(string key, CancellationToken ct = default) =>
+ Task.FromResult(null);
+
+ public Task SetAsync(string key, SynthesisResult result, CancellationToken ct = default) =>
+ Task.CompletedTask;
+ }
+
+ private sealed class Rig(
+ ReadAloudController controller,
+ CoalescingAudioSource audio,
+ HttpContext http,
+ IServiceScope scope,
+ IDisposable context) : IDisposable
+ {
+ public ReadAloudController Controller => controller;
+ public CoalescingAudioSource Audio => audio;
+ public HttpContext Http => http;
+
+ public void Dispose()
+ {
+ context.Dispose();
+ scope.Dispose();
+ }
+ }
+
+ private Rig Build(IReadAloudEngine engine, ReadAloudOptions? configured = null, string? range = null, string? ifNoneMatch = null)
+ {
+ var scope = _site.Services.CreateScope();
+ var services = scope.ServiceProvider;
+ var context = services.GetRequiredService().EnsureUmbracoContext();
+
+ configured ??= new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ var options = new FixedOptions(configured);
+ var audio = new CoalescingAudioSource(engine, new NoCache(), options, NullLogger.Instance);
+
+ var http = new DefaultHttpContext();
+ if (range is not null) http.Request.Headers.Range = range;
+ if (ifNoneMatch is not null) http.Request.Headers.IfNoneMatch = ifNoneMatch;
+
+ var controller = new ReadAloudController(
+ audio,
+ services.GetRequiredService(),
+ services.GetRequiredService(),
+ options,
+ null,
+ _counter)
+ {
+ ControllerContext = new ControllerContext { HttpContext = http },
+ };
+ return new Rig(controller, audio, http, scope, context);
+ }
+
+ private string EtagFor(Rig rig, string html, string voice, ReadAloudOptions options)
+ {
+ var request = new SynthesisRequest
+ {
+ Text = TextExtractor.ToSpeakableText(html, options.MaxChars),
+ Voice = voice,
+ };
+ return $"\"{rig.Audio.KeyFor(request)}-audio-{ReadAloudController.ETagVersion}\"";
+ }
+
+ private int Held(Guid node, string voice) =>
+ _counter.Snapshot().GetValueOrDefault(new ListenKey(node, voice, ListenClock.Day));
+
+ private static string DefaultVoice => new ReadAloudOptions().DefaultVoice;
+
+ [Fact]
+ public async Task A_200_adds_one_for_the_node_the_resolved_voice_and_the_utc_day()
+ {
+ using var rig = Build(new OkEngine());
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBe(new Dictionary
+ {
+ [new ListenKey(_site.PublishedNodeKey, DefaultVoice, ListenClock.Day)] = 1,
+ });
+ }
+
+ [Fact]
+ public async Task A_304_adds_one()
+ {
+ var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ string tag;
+ using (var probe = Build(new OkEngine(), options)) tag = EtagFor(probe, UmbracoSiteFixture.BodyHtml, DefaultVoice, options);
+
+ using var rig = Build(new OkEngine(), options, ifNoneMatch: tag);
+ var result = await rig.Controller.Get(_site.PublishedNodeKey, null, default);
+
+ result.ShouldBeOfType().StatusCode.ShouldBe(304);
+ Held(_site.PublishedNodeKey, DefaultVoice).ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task The_timings_route_adds_nothing()
+ {
+ using var rig = Build(new OkEngine());
+
+ (await rig.Controller.Timings(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task A_refused_page_adds_nothing()
+ {
+ using var rig = Build(new OkEngine());
+
+ foreach (var key in new[]
+ {
+ Guid.NewGuid(), _site.ProtectedNodeKey, _site.DisabledNodeKey, _site.UnpublishedNodeKey,
+ })
+ {
+ (await rig.Controller.Get(key, null, default)).ShouldBeOfType();
+ }
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task A_synthesis_failure_adds_nothing()
+ {
+ using var rig = Build(new ThrowingEngine());
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default))
+ .ShouldBeOfType().StatusCode.ShouldBe(503);
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task Browser_mode_adds_nothing()
+ {
+ var options = new ReadAloudOptions
+ {
+ PropertyAlias = UmbracoSiteFixture.PropertyAlias,
+ Provider = ReadAloudOptions.BrowserProvider,
+ };
+ using var rig = Build(new BrowserVoiceEngine(), options);
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default))
+ .ShouldBeOfType().StatusCode.ShouldBe(503);
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task A_request_cancelled_before_the_audio_is_ready_adds_nothing()
+ {
+ using var rig = Build(new OkEngine());
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, cancelled.Token)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Theory]
+ [InlineData(null, 1)]
+ [InlineData("bytes=0-", 1)]
+ [InlineData("bytes=0-1", 0)]
+ [InlineData("bytes=500-", 0)]
+ [InlineData("bytes=-500", 0)]
+ [InlineData("bytes=0-1,5-6", 0)]
+ [InlineData("bytes=junk", 0)]
+ public async Task Only_a_request_without_a_range_or_with_an_open_range_from_zero_adds_a_listen(
+ string? range,
+ int expected)
+ {
+ using var rig = Build(new OkEngine(), range: range);
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+
+ Held(_site.PublishedNodeKey, DefaultVoice).ShouldBe(expected);
+ }
+
+ [Fact]
+ public async Task A_ranged_304_adds_nothing_like_a_ranged_200()
+ {
+ var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ string tag;
+ using (var probe = Build(new OkEngine(), options)) tag = EtagFor(probe, UmbracoSiteFixture.BodyHtml, DefaultVoice, options);
+
+ using var rig = Build(new OkEngine(), options, range: "bytes=0-1", ifNoneMatch: tag);
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task The_voice_stored_is_the_one_used_and_not_the_one_asked_for()
+ {
+ var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ using var rig = Build(new OkEngine(), options);
+
+ await rig.Controller.Get(_site.PublishedNodeKey, "en-US-NotOnTheList", default);
+
+ Held(_site.PublishedNodeKey, DefaultVoice).ShouldBe(1);
+ Held(_site.PublishedNodeKey, "en-US-NotOnTheList").ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task An_allowed_voice_is_stored_as_that_voice()
+ {
+ var options = new ReadAloudOptions
+ {
+ PropertyAlias = UmbracoSiteFixture.PropertyAlias,
+ AllowedVoices = ["en-GB-RyanNeural"],
+ };
+ using var rig = Build(new OkEngine(), options);
+
+ await rig.Controller.Get(_site.PublishedNodeKey, "en-GB-RyanNeural", default);
+
+ Held(_site.PublishedNodeKey, "en-GB-RyanNeural").ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task A_page_voice_is_stored_as_the_page_voice()
+ {
+ var options = new ReadAloudOptions
+ {
+ PropertyAlias = UmbracoSiteFixture.PropertyAlias,
+ AllowedVoices = [UmbracoSiteFixture.PageVoice],
+ };
+ using var rig = Build(new OkEngine(), options);
+
+ await rig.Controller.Get(_site.OverrideNodeKey, null, default);
+
+ Held(_site.OverrideNodeKey, UmbracoSiteFixture.PageVoice).ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task A_voice_refused_on_an_unpublished_key_writes_nothing()
+ {
+ var options = new ReadAloudOptions
+ {
+ PropertyAlias = UmbracoSiteFixture.PropertyAlias,
+ AllowedVoices = ["en-GB-RyanNeural"],
+ };
+ using var rig = Build(new OkEngine(), options);
+
+ (await rig.Controller.Get(_site.UnpublishedNodeKey, "en-GB-RyanNeural", default))
+ .ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task With_the_setting_off_a_play_adds_nothing()
+ {
+ _options.CurrentValue.CountListens = false;
+ using var rig = Build(new OkEngine());
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task A_controller_built_without_a_counter_still_serves()
+ {
+ using var rig = Build(new OkEngine());
+ var bare = new ReadAloudController(
+ rig.Audio,
+ _site.Services.CreateScope().ServiceProvider.GetRequiredService(),
+ _site.Services.CreateScope().ServiceProvider.GetRequiredService(),
+ new FixedOptions(new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias }))
+ {
+ ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() },
+ };
+
+ (await bare.Get(_site.PublishedNodeKey, null, default)).ShouldBeOfType();
+ }
+
+ [Fact]
+ public async Task A_rate_limited_request_adds_nothing_and_a_served_one_lands_in_the_table()
+ {
+ var counter = _site.Resolve();
+ var caller = System.Net.IPAddress.Parse("203.0.113.77");
+ var path = $"/read-aloud/{_site.NotDisabledNodeKey}";
+ var voice = _site.Resolve>().CurrentValue.DefaultVoice;
+ var key = new ListenKey(_site.NotDisabledNodeKey, voice, ListenKey.DayOf(DateTimeOffset.UtcNow));
+
+ // Discard what other tests in the shared site left held, then count only this caller.
+ FlushDiscard(counter);
+ for (var i = 0; i < UmbracoSiteFixture.RateLimitPerMinute; i++)
+ {
+ await SendAsync(caller, path);
+ }
+
+ var held = counter.Snapshot().GetValueOrDefault(key);
+ var limited = await SendAsync(caller, path);
+
+ limited.Response.StatusCode.ShouldBe(StatusCodes.Status429TooManyRequests);
+ counter.Snapshot().GetValueOrDefault(key).ShouldBe(held);
+ held.ShouldBeGreaterThan(0);
+ }
+
+ [Fact]
+ public async Task One_played_request_goes_from_the_endpoint_through_a_flush_into_the_table()
+ {
+ var counter = _site.Resolve();
+ var flush = _site.Services.GetServices()
+ .OfType().Single();
+ var scopes = _site.Resolve();
+ var voice = _site.Resolve>().CurrentValue.DefaultVoice;
+ var node = _site.EmptyOverrideNodeKey;
+
+ int Stored()
+ {
+ using var scope = scopes.CreateScope();
+ var sum = scope.Database.ExecuteScalar(
+ "SELECT SUM(Listens) FROM baryoReadAloudListens WHERE NodeKey = @0 AND Voice = @1", node, voice);
+ scope.Complete();
+ return sum ?? 0;
+ }
+
+ flush.Flush().ShouldBeTrue();
+ var before = Stored();
+
+ var response = await SendAsync(System.Net.IPAddress.Parse("203.0.113.78"), $"/read-aloud/{node}");
+ response.Response.StatusCode.ShouldBe(StatusCodes.Status200OK);
+ flush.Flush().ShouldBeTrue();
+
+ Stored().ShouldBe(before + 1);
+ counter.Snapshot().ShouldBeEmpty();
+ }
+
+ private static void FlushDiscard(ListenCounter counter) => counter.Clear();
+
+ private Task SendAsync(System.Net.IPAddress caller, string path) =>
+ _site.Server.SendAsync(c =>
+ {
+ c.Request.Method = HttpMethods.Get;
+ c.Request.Path = path;
+ c.Connection.RemoteIpAddress = caller;
+ });
+
+ private sealed class FixedOptions(ReadAloudOptions value) : Microsoft.Extensions.Options.IOptionsMonitor
+ {
+ public ReadAloudOptions CurrentValue { get; } = value;
+
+ public ReadAloudOptions Get(string? name) => CurrentValue;
+
+ public IDisposable? OnChange(Action listener) => null;
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
new file mode 100644
index 0000000..eba3b1d
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
@@ -0,0 +1,226 @@
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Shouldly;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+public class ListenFlushTests
+{
+ private readonly ListenClock _clock = new();
+ private readonly ListenOptions _options = new();
+ private readonly WarningLog _counterLog = new();
+ private readonly WarningLog _log = new();
+ private readonly FakeListenStore _store = new();
+ private readonly ListenCounter _counter;
+ private bool _ready = true;
+
+ public ListenFlushTests() => _counter = new ListenCounter(_options, _clock, _counterLog);
+
+ private ListenFlushService Service(TimeSpan? shutdown = null) =>
+ new(_counter, _store, () => _ready, _options, _log,
+ TimeSpan.FromMilliseconds(20), TimeSpan.FromMilliseconds(10), shutdown ?? TimeSpan.FromSeconds(5));
+
+ private static ListenKey Key(Guid node, string voice = "v") => new(node, voice, ListenClock.Day);
+
+ [Fact]
+ public void Two_flushes_add_up_in_the_store()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+
+ _counter.Add(node, "v");
+ _counter.Add(node, "v");
+ service.Flush().ShouldBeTrue();
+ _counter.Add(node, "v");
+ service.Flush().ShouldBeTrue();
+
+ _store.Rows[Key(node)].ShouldBe(3);
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public void A_count_added_while_a_flush_is_writing_is_written_by_the_next_flush_once()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+ _counter.Add(node, "v");
+ var added = false;
+ _store.OnAdd = () =>
+ {
+ if (added) return;
+ added = true;
+ _counter.Add(node, "v");
+ };
+
+ service.Flush().ShouldBeTrue();
+ _store.Rows[Key(node)].ShouldBe(1);
+ _counter.Snapshot()[Key(node)].ShouldBe(1);
+
+ service.Flush().ShouldBeTrue();
+ _store.Rows[Key(node)].ShouldBe(2);
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public void A_failed_flush_keeps_its_counts_and_the_retry_does_not_write_a_row_twice()
+ {
+ var service = Service();
+ var first = Guid.NewGuid();
+ var second = Guid.NewGuid();
+ var third = Guid.NewGuid();
+ _counter.Add(first, "v");
+ _counter.Add(second, "v");
+ _counter.Add(third, "v");
+ var failing = true;
+ _store.FailWhen = k => failing && k.NodeKey == second;
+
+ service.Flush().ShouldBeFalse();
+ failing = false;
+ service.Flush().ShouldBeTrue();
+
+ foreach (var node in new[] { first, second, third }) _store.Rows[Key(node)].ShouldBe(1);
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public void A_failure_streak_logs_one_warning_and_a_new_streak_logs_another()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+ _counter.Add(node, "v");
+ var failing = true;
+ _store.FailWhen = _ => failing;
+
+ service.Flush().ShouldBeFalse();
+ service.Flush().ShouldBeFalse();
+ service.Flush().ShouldBeFalse();
+ _log.Warnings.Count.ShouldBe(1);
+
+ failing = false;
+ service.Flush().ShouldBeTrue();
+ failing = true;
+ _counter.Add(node, "v");
+ service.Flush().ShouldBeFalse();
+
+ _log.Warnings.Count.ShouldBe(2);
+ }
+
+ [Fact]
+ public void With_the_setting_off_held_counts_are_dropped_and_nothing_is_written()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _options.CurrentValue.CountListens = false;
+
+ service.Flush().ShouldBeTrue();
+
+ _store.Rows.ShouldBeEmpty();
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task Stopping_with_the_setting_off_writes_nothing()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _options.CurrentValue.CountListens = false;
+
+ await service.StopAsync(CancellationToken.None);
+
+ _store.Rows.ShouldBeEmpty();
+ _store.Calls.ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task Stopping_flushes_what_is_held_once()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+ _counter.Add(node, "v");
+ _counter.Add(node, "v");
+
+ await service.StopAsync(CancellationToken.None);
+
+ _store.Rows[Key(node)].ShouldBe(2);
+ _store.Calls.ShouldBe(1);
+ _log.Warnings.ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task Stopping_with_a_failing_store_does_not_throw_and_drops_the_counts_with_one_warning()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _store.FailWhen = _ => true;
+
+ await service.StopAsync(CancellationToken.None);
+
+ _counter.Snapshot().ShouldBeEmpty();
+ // The failed flush itself logs the streak, and the drop logs its own line.
+ _log.Warnings.Count(w => w.Contains("shutdown")).ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task Stopping_with_a_blocked_store_returns_within_the_shutdown_timeout()
+ {
+ using var block = new ManualResetEventSlim(false);
+ var service = Service(TimeSpan.FromMilliseconds(200));
+ _counter.Add(Guid.NewGuid(), "v");
+ _store.Block = block;
+
+ var started = DateTime.UtcNow;
+ await service.StopAsync(CancellationToken.None);
+ var took = DateTime.UtcNow - started;
+ block.Set();
+
+ took.ShouldBeLessThan(TimeSpan.FromSeconds(3));
+ _log.Warnings.ShouldContain(w => w.Contains("shutdown"));
+ }
+
+ [Fact]
+ public async Task Nothing_is_written_until_the_runtime_is_ready()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+ _counter.Add(node, "v");
+ _ready = false;
+
+ await service.StartAsync(CancellationToken.None);
+ await Task.Delay(300);
+ _store.Calls.ShouldBe(0);
+
+ _ready = true;
+ var deadline = DateTime.UtcNow.AddSeconds(10);
+ while (_store.Calls == 0 && DateTime.UtcNow < deadline) await Task.Delay(20);
+ await service.StopAsync(CancellationToken.None);
+
+ _store.Rows[Key(node)].ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task Stopping_before_the_runtime_is_ready_writes_nothing_and_does_not_throw()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _ready = false;
+
+ await service.StopAsync(CancellationToken.None);
+
+ _store.Calls.ShouldBe(0);
+ }
+
+ [Fact]
+ public void A_play_either_side_of_utc_midnight_is_two_rows()
+ {
+ var service = Service();
+ var node = Guid.NewGuid();
+ _clock.Now = new DateTimeOffset(2026, 11, 16, 23, 59, 59, TimeSpan.Zero);
+ _counter.Add(node, "v");
+ _clock.Advance(TimeSpan.FromSeconds(1));
+ _counter.Add(node, "v");
+
+ service.Flush();
+
+ _store.Rows[new ListenKey(node, "v", 20261116)].ShouldBe(1);
+ _store.Rows[new ListenKey(node, "v", 20261117)].ShouldBe(1);
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
new file mode 100644
index 0000000..84d2cd9
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
@@ -0,0 +1,43 @@
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.Extensions.Primitives;
+using Shouldly;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+public class ListenRangeTests
+{
+ [Fact]
+ public void No_range_header_counts()
+ {
+ ListenRange.CountsAsPlay(StringValues.Empty).ShouldBeTrue();
+ }
+
+ [Theory]
+ [InlineData("bytes=0-")]
+ [InlineData("BYTES=0-")]
+ [InlineData(" bytes=0- ")]
+ public void The_open_range_from_the_start_counts(string header)
+ {
+ ListenRange.CountsAsPlay(header).ShouldBeTrue();
+ }
+
+ [Theory]
+ [InlineData("bytes=0-1")]
+ [InlineData("bytes=500-")]
+ [InlineData("bytes=-500")]
+ [InlineData("bytes=0-1,5-6")]
+ [InlineData("bytes=0-,5-6")]
+ [InlineData("bytes=junk")]
+ [InlineData("junk")]
+ [InlineData("items=0-")]
+ public void Any_other_range_counts_nothing(string header)
+ {
+ ListenRange.CountsAsPlay(header).ShouldBeFalse();
+ }
+
+ [Fact]
+ public void Two_range_headers_count_nothing()
+ {
+ ListenRange.CountsAsPlay(new StringValues(["bytes=0-", "bytes=0-"])).ShouldBeFalse();
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
new file mode 100644
index 0000000..96eaa11
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
@@ -0,0 +1,82 @@
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging.Abstractions;
+using Shouldly;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+public class ListenSettingTests
+{
+ private static ReadAloudOptionsValidation Validation() =>
+ new([], NullLogger.Instance);
+
+ [Fact]
+ public void Counting_is_on_by_default()
+ {
+ new ReadAloudOptions().CountListens.ShouldBeTrue();
+ }
+
+ [Fact]
+ public void A_default_voice_of_100_characters_passes_and_101_fails()
+ {
+ Validation().Validate(null, new ReadAloudOptions { DefaultVoice = new string('a', 100) }).Succeeded.ShouldBeTrue();
+ Validation().Validate(null, new ReadAloudOptions { DefaultVoice = new string('a', 101) }).Failed.ShouldBeTrue();
+ }
+
+ [Fact]
+ public void An_allowed_voice_of_100_characters_passes_and_101_fails()
+ {
+ Validation().Validate(null, new ReadAloudOptions { AllowedVoices = [new string('a', 100)] }).Succeeded.ShouldBeTrue();
+ Validation().Validate(null, new ReadAloudOptions { AllowedVoices = [new string('a', 101)] }).Failed.ShouldBeTrue();
+ }
+
+ [Fact]
+ public void The_voice_length_limit_applies_in_browser_mode_too()
+ {
+ var options = new ReadAloudOptions
+ {
+ Provider = ReadAloudOptions.BrowserProvider,
+ AllowedVoices = [new string('a', 101)],
+ };
+
+ Validation().Validate(null, options).Failed.ShouldBeTrue();
+ }
+
+ [Fact]
+ public void The_composer_registers_the_counter_and_the_flush_service()
+ {
+ var provider = ReadAloudComposerTests_Provider();
+
+ provider.GetRequiredService().ShouldNotBeNull();
+ provider.GetServices().OfType().Count().ShouldBe(1);
+ }
+
+ [Fact]
+ public void The_composer_keeps_a_time_provider_the_site_registered_first()
+ {
+ var mine = new ListenClock();
+ var provider = ReadAloudComposerTests_Provider(mine);
+
+ provider.GetRequiredService().ShouldBeSameAs(mine);
+ }
+
+ [Fact]
+ public void The_composer_registers_the_system_time_provider_when_the_site_has_none()
+ {
+ ReadAloudComposerTests_Provider().GetRequiredService().ShouldBeSameAs(TimeProvider.System);
+ }
+
+ private static ServiceProvider ReadAloudComposerTests_Provider(TimeProvider? first = null)
+ {
+ var services = new ServiceCollection();
+ services.AddLogging();
+ services.AddSingleton(new ReadAloudComposerTests.StubEnvironment());
+ if (first is not null) services.AddSingleton(first);
+
+ var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build();
+ new ReadAloudComposer().Compose(new ReadAloudComposerTests.StubUmbracoBuilder(services, configuration));
+ return services.BuildServiceProvider();
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
new file mode 100644
index 0000000..24d51a4
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
@@ -0,0 +1,123 @@
+using System.Data.Common;
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Shouldly;
+using Umbraco.Cms.Infrastructure.Scoping;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+[Collection(UmbracoCollection.Name)]
+public class ListenStoreTests
+{
+ private readonly UmbracoSiteFixture _site;
+
+ public ListenStoreTests(UmbracoSiteFixture site) => _site = site;
+
+ private ListenStore Store() => new(_site.Services.GetRequiredService());
+
+ private int Listens(ListenKey key)
+ {
+ using var scope = _site.Services.GetRequiredService().CreateScope();
+ var rows = scope.Database.Fetch(
+ "SELECT Listens FROM baryoReadAloudListens WHERE NodeKey = @0 AND Voice = @1 AND DayUtc = @2",
+ key.NodeKey, key.Voice, key.DayUtc);
+ scope.Complete();
+ return rows.Count == 0 ? 0 : rows[0];
+ }
+
+ private static ListenKey NewKey() => new(Guid.NewGuid(), "en-GB-SoniaNeural", ListenClock.Day);
+
+ [Fact]
+ public void Two_adds_for_one_key_end_as_one_row_holding_the_sum()
+ {
+ var store = Store();
+ var key = NewKey();
+
+ store.Add(key, 3);
+ store.Add(key, 4);
+
+ Listens(key).ShouldBe(7);
+ }
+
+ [Fact]
+ public void Another_server_inserting_first_is_met_with_an_update_not_a_failure()
+ {
+ var store = Store();
+ var key = NewKey();
+ store.BeforeInsert = k => new ListenStore(_site.Services.GetRequiredService())
+ .Add(k, 5);
+
+ store.Add(key, 2);
+
+ Listens(key).ShouldBe(7);
+ }
+
+ [Fact]
+ public void An_insert_that_fails_and_leaves_no_row_to_update_throws()
+ {
+ var store = Store();
+ var key = NewKey();
+ store.BeforeInsert = _ => throw new TestDbException();
+
+ Should.Throw(() => store.Add(key, 1));
+
+ Listens(key).ShouldBe(0);
+ }
+
+ [Fact]
+ public void The_table_has_four_columns_and_a_three_column_primary_key_that_refuses_a_duplicate()
+ {
+ using (var scope = _site.Services.GetRequiredService().CreateScope())
+ {
+ var columns = scope.Database.Fetch("SELECT name AS Name, pk AS Pk FROM pragma_table_info('baryoReadAloudListens')");
+ scope.Complete();
+
+ columns.Select(c => c.Name).OrderBy(n => n).ShouldBe(["DayUtc", "Listens", "NodeKey", "Voice"]);
+ columns.Count(c => c.Pk > 0).ShouldBe(3);
+ columns.Single(c => c.Name == "Listens").Pk.ShouldBe(0);
+ }
+
+ var key = NewKey();
+ Store().Add(key, 1);
+ using var dupe = _site.Services.GetRequiredService().CreateScope();
+ Should.Throw(() => dupe.Database.Execute(
+ "INSERT INTO baryoReadAloudListens (NodeKey, Voice, DayUtc, Listens) VALUES (@0, @1, @2, 1)",
+ key.NodeKey, key.Voice, key.DayUtc));
+ }
+
+ [Fact]
+ public void The_migration_guard_sees_the_real_table_and_a_missing_one()
+ {
+ using var scope = _site.Services.GetRequiredService().CreateScope();
+
+ CreateListensTable.IsMissing(scope.Database).ShouldBeFalse();
+ CreateListensTable.IsMissing(scope.Database, "baryoReadAloudNoSuchTable").ShouldBeTrue();
+ scope.Complete();
+ }
+
+ [Fact]
+ public void The_migration_plan_is_named_for_the_package_and_ends_at_the_table_step()
+ {
+ var plan = new ListensMigrationPlan();
+
+ plan.Name.ShouldBe("BaryoDev.Umbraco.ReadAloud");
+ plan.FinalState.ShouldNotBeNullOrEmpty();
+ }
+
+ [Fact]
+ public void The_flush_service_is_registered_as_a_hosted_service_in_the_booted_site()
+ {
+ _site.Services.GetServices().OfType().Count().ShouldBe(1);
+ }
+
+ private sealed class ColumnInfo
+ {
+ public string Name { get; set; } = "";
+ public int Pk { get; set; }
+ }
+
+ private sealed class TestDbException : DbException
+ {
+ }
+}
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenTestSupport.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenTestSupport.cs
new file mode 100644
index 0000000..ce921ff
--- /dev/null
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenTestSupport.cs
@@ -0,0 +1,67 @@
+using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace BaryoDev.Umbraco.ReadAloud.Tests;
+
+/// A clock a test can move. Starts at noon UTC on 16 November 2026.
+internal sealed class ListenClock : TimeProvider
+{
+ public DateTimeOffset Now = new(2026, 11, 16, 12, 0, 0, TimeSpan.Zero);
+
+ public const int Day = 20261116;
+
+ public override DateTimeOffset GetUtcNow() => Now;
+
+ public void Advance(TimeSpan by) => Now += by;
+}
+
+/// Options a test can change after the monitor is handed out.
+internal sealed class ListenOptions : IOptionsMonitor
+{
+ public ReadAloudOptions CurrentValue { get; } = new() { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+
+ public ReadAloudOptions Get(string? name) => CurrentValue;
+
+ public IDisposable? OnChange(Action listener) => null;
+}
+
+/// Keeps the warnings a component logs.
+internal sealed class WarningLog : ILogger
+{
+ public List Warnings { get; } = [];
+
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func formatter)
+ {
+ if (logLevel == LogLevel.Warning) lock (Warnings) Warnings.Add(formatter(state, exception));
+ }
+}
+
+/// A store that adds into a dictionary, and fails or blocks when a test says so.
+internal sealed class FakeListenStore : IListenStore
+{
+ public Dictionary Rows { get; } = [];
+ public int Calls;
+ public Func? FailWhen;
+ public Action? OnAdd;
+ public ManualResetEventSlim? Block;
+
+ public void Add(ListenKey key, int count)
+ {
+ Block?.Wait();
+ OnAdd?.Invoke();
+ if (FailWhen?.Invoke(key) == true) throw new InvalidOperationException("no such table: baryoReadAloudListens");
+
+ lock (Rows) Rows[key] = Rows.GetValueOrDefault(key) + count;
+ Interlocked.Increment(ref Calls);
+ }
+}
From 780e63a74938631b385d99e8b55f4b5f100f04a3 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:13:09 +0800
Subject: [PATCH 02/10] document listen counts and the new table
---
.github/ISSUE_TEMPLATE/feature_request.yml | 2 +-
CHANGELOG.md | 13 ++++
CONTRIBUTING.md | 8 +--
README.md | 60 +++++++++++++++++--
SECURITY.md | 3 +-
.../AzureCredentialStore.cs | 2 +-
.../BaryoDev.Umbraco.ReadAloud.csproj | 2 +-
tests/TestSite/DemoArticle.cs | 8 +--
tests/TestSite/Views/readAloudArticle.cshtml | 4 +-
umbraco-marketplace.json | 2 +-
10 files changed, 85 insertions(+), 19 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index d77f411..91c018f 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -9,7 +9,7 @@ body:
over a hosted service, so a feature breaking one is usually the wrong feature even when
it is useful.
- **Nothing about a listener is stored.** No table, no IP, no identity.
+ **Nothing that says who listened is stored.** Counts per page, voice and day, and no IP or identity.
**Nothing leaves the server** except the synthesis call itself.
**No build step** for the site owner.
**The engine stays behind an interface**, so a provider can be swapped by config.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c9b34ec..540761d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,19 @@
Notable changes to `BaryoDev.Umbraco.ReadAloud`. Follows [Keep a Changelog](https://keepachangelog.com)
and [semantic versioning](https://semver.org).
+## [Unreleased]
+
+### Added
+
+- Listen counts (#2). A play adds one to a count for the page, the voice used and the UTC day,
+ kept in memory and written once a minute and at shutdown. Stored: node key, voice, day, count.
+ Nothing that says who listened. A request with a `Range` header counts only when it is
+ `bytes=0-`. `CountListens` (default `true`) turns it off at runtime.
+- **The update creates one table, `baryoReadAloudListens`, on every install, including sites that
+ use the browser voice.** It is created by a package migration at startup. A site with
+ `PackageMigrationsUnattended` set to false must run the migration from the backoffice.
+- `DefaultVoice` and `AllowedVoices` entries longer than 100 characters are refused at startup.
+
## [0.4.0] - 2026-11-16
### Added
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3c1f569..058bca6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,10 +27,10 @@ in your environment, and excluded from CI. Run it deliberately when you change t
These are the reasons to choose this over a hosted service, so a change breaking one is usually
the wrong change even when it is convenient.
-**Nothing about a listener is ever stored.** No table, no migration, no IP, no user agent, no
-identity. The only persisted state is derived audio on disk and, in the Azure package, a Speech
-key an admin saves: encrypted in the Umbraco database, with its Data Protection key ring on disk.
-Neither says anything about a listener. If a change would let this package answer "who listened",
+**Nothing that says who listened is ever stored.** No IP, no user agent, no identity, no cookie. The
+persisted state is derived audio on disk, one table of listen counts (node key, voice, UTC day and a
+count, nothing else) and, in the Azure package, a Speech key an admin saves: encrypted in the Umbraco
+database, with its Data Protection key ring on disk. None of them says anything about a listener. If a change would let this package answer "who listened",
it needs a different design.
**Nothing leaves the server except the synthesis call.** No analytics, no telemetry, no third
diff --git a/README.md b/README.md
index 34bd359..f6ccc12 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
Add "listen to this article" to an Umbraco site. By default the reader's browser speaks the text
with its own built-in voice. For natural neural voices with word highlighting, add the Azure
-package. Audio from the server is cached on your own server, and nothing about a listener is ever
-stored.
+package. Audio from the server is cached on your own server. The only thing kept about listening is
+a count per page, voice and day, and nothing that says who listened.
For Umbraco 16, 17 and 18, on .NET 9 and .NET 10.
@@ -61,8 +61,9 @@ No build step: the file above is a plain ES module, committed as-is in the packa
## What it does not do
-- **Store anything about a listener.** No table, no migration, no IP, no user agent, no identity.
- The only thing written anywhere is derived audio you can delete at any time
+- **Store anything about a listener.** No IP, no user agent, no identity, no cookie. The only things
+ written are derived audio you can delete at any time and a table of listen counts (see
+ [Listen counts](#listen-counts))
- **Call any third party except the speech service itself.** No analytics, no telemetry
- **Require a build step.** No npm, no bundler
@@ -85,6 +86,7 @@ v1 is configuration only. Every value has a working default.
"CacheMaxAgeDays": null,
"FailureBackoffSeconds": 30,
"AuthFailureBackoffSeconds": 300,
+ "CountListens": true,
"RateLimitPerMinute": 20,
"MaxConcurrentSynthesis": 4,
"Provider": "Browser"
@@ -268,6 +270,56 @@ native binaries. Keeping it out of the core means sites on the browser voice do
Failures: the route answers 503 and the browser falls back to
`speechSynthesis`. The audio is `audio-24khz-48kbitrate-mono-mp3`, the same format the browser client already plays.
+### Listen counts
+
+`CountListens` (default `true`) counts plays. It can be switched off at runtime; held counts are then
+dropped and nothing more is written.
+
+**What is counted.** One count each time the audio route answers a play with a 200 or a 304. The
+timings route, refusals, 404s, failures and browser-voice mode count nothing. A request with a
+`Range` header counts only when it is `bytes=0-`, so a seek or a probe does not add a play.
+
+**What is stored.** One table, `baryoReadAloudListens`, with four columns: the node key, the voice
+actually used, the UTC day as `yyyymmdd`, and the count. No IP, no user agent, no identity, no
+cookie, no time of day. Nothing in it says who listened.
+
+**What this does not see.**
+
+- A CDN or proxy that answers for the origin hides those plays. The count is plays that reached
+ the server.
+- Your web server's request log still records every request, with whatever it logs. This package
+ does not control that.
+- A crash or a hard stop loses up to a minute of counts. They are held in memory and written once a
+ minute and again at shutdown. A shutdown waits at most five seconds.
+- Rows for a node that is later deleted stay. Nothing removes them.
+
+**Read the counts.**
+
+```sql
+SELECT NodeKey, Voice, SUM(Listens) AS Listens
+FROM baryoReadAloudListens
+GROUP BY NodeKey, Voice
+ORDER BY Listens DESC;
+```
+
+**Prune old days.** There is no retention setting. Delete what you do not want (`20260101` is a
+day, as a number):
+
+```sql
+DELETE FROM baryoReadAloudListens WHERE DayUtc < 20260101;
+```
+
+**The table is created by a package migration**, on every install including sites that use the
+browser voice. Umbraco runs it at startup when `Umbraco:CMS:Unattended:PackageMigrationsUnattended`
+is true, which is the default. If you set it to false, the table is not created until you run the package migration yourself
+(for example by setting it to true for one start). Until it does, counts stay in memory, the flush
+logs one warning per failure streak, and nothing else breaks. Voices longer than 100 characters in
+`DefaultVoice` or `AllowedVoices` are refused at startup because the column holds 100.
+
+**Remove it.** Set `CountListens` to `false`, uninstall the package, then `DROP TABLE
+baryoReadAloudListens`. Umbraco keeps the migration state for the plan `BaryoDev.Umbraco.ReadAloud` in
+`umbracoKeyValue`. Remove that row too if you reinstall and want the migration to run again.
+
### RateLimitPerMinute and what "per IP" means
The limit is a fixed one-minute window per source IP **as the server sees it**, which is the
diff --git a/SECURITY.md b/SECURITY.md
index fec06bc..c108e79 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -35,7 +35,8 @@ A node key is not a secret: it is in the page markup by design, so neither route
key being hard to guess. If you find a way to make either one answer for a node the site would not
serve to an anonymous visitor, that is a security bug.
-**Nothing about a listener is stored.** No table, no migration, no IP, no user agent, no identity.
+**Nothing that says who listened is stored.** The only listener-related data is a table of counts per
+node, voice and UTC day. No IP, no user agent, no identity, no cookie.
If you find a way to make this package answer "who listened", that is a security bug in this
project's terms even if nothing leaves the server.
diff --git a/src/BaryoDev.Umbraco.ReadAloud.Azure/AzureCredentialStore.cs b/src/BaryoDev.Umbraco.ReadAloud.Azure/AzureCredentialStore.cs
index 9eeade6..03c6794 100644
--- a/src/BaryoDev.Umbraco.ReadAloud.Azure/AzureCredentialStore.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud.Azure/AzureCredentialStore.cs
@@ -13,7 +13,7 @@ internal interface ICredentialRecords
void Write(string value);
}
-/// Umbraco's key-value table, so the package adds no tables of its own.
+/// Umbraco's key-value table, so the Azure package adds no tables of its own.
internal sealed class KeyValueCredentialRecords(IKeyValueService keyValues) : ICredentialRecords
{
internal const string Key = "BaryoDev.ReadAloud.AzureSpeech";
diff --git a/src/BaryoDev.Umbraco.ReadAloud/BaryoDev.Umbraco.ReadAloud.csproj b/src/BaryoDev.Umbraco.ReadAloud/BaryoDev.Umbraco.ReadAloud.csproj
index 93e8b8b..bfe809e 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/BaryoDev.Umbraco.ReadAloud.csproj
+++ b/src/BaryoDev.Umbraco.ReadAloud/BaryoDev.Umbraco.ReadAloud.csproj
@@ -11,7 +11,7 @@
- Add "listen to this article" to an Umbraco site. By default the reader's browser speaks with its built-in voice. Add the Azure package for neural voices with word highlighting, cached on your own server. Nothing about a listener is stored.
+ Add "listen to this article" to an Umbraco site. By default the reader's browser speaks with its built-in voice. Add the Azure package for neural voices with word highlighting, cached on your own server. Listens are counted per page, voice and day, and nothing that says who listened is stored.
MIT
README.md
icon.png
diff --git a/tests/TestSite/DemoArticle.cs b/tests/TestSite/DemoArticle.cs
index 1a9ed8d..962dc59 100644
--- a/tests/TestSite/DemoArticle.cs
+++ b/tests/TestSite/DemoArticle.cs
@@ -14,8 +14,8 @@ public static class DemoArticle
/// The published value of the article's body property.
public const string BodyHtml = """
By default the words you are hearing are spoken by your own browser, using the voice it
- ships with. The server that sent you this page synthesizes nothing, and nothing about the
- fact that you pressed Listen was recorded anywhere.
+ ships with. The server that sent you this page synthesizes nothing, and nothing about
+ you was recorded when you pressed Listen, beyond one added to a count for this page.
A site can switch on a neural voice by installing the Azure package and pasting in a key
for its own Azure Speech resource. The server then sends the article text to that service,
@@ -45,8 +45,8 @@ does not accept text.
the next request. Delete the cache folder at any time and the only cost is that the next
listener waits a few seconds.
- There is no listener table. No address, no user agent, no identity, and no count of how
- many times this article has been played. The requesting address is held in memory for up to
+
There is no listener table. No address, no user agent, no identity. There is a count of
+ how many times this article has been played, by voice and by day. The requesting address is held in memory for up to
one minute as a rate limiting bucket and then forgotten. That is a decision rather than an
oversight. A read aloud button is an accessibility feature, and somebody who needs one
should not have to pay for it with a record of having needed it.
diff --git a/tests/TestSite/Views/readAloudArticle.cshtml b/tests/TestSite/Views/readAloudArticle.cshtml
index c6b4b20..c30648a 100644
--- a/tests/TestSite/Views/readAloudArticle.cshtml
+++ b/tests/TestSite/Views/readAloudArticle.cshtml
@@ -130,8 +130,8 @@
- A stock Umbraco with this one package installed and nothing else. Nothing about you
- is stored: no listen count, no address, no identity.
+ A stock Umbraco with this one package installed and nothing else. Nothing that says who
+ you are is stored: no address, no identity. A play adds one to a count for this page.
diff --git a/umbraco-marketplace.json b/umbraco-marketplace.json
index 185a07b..7d636a9 100644
--- a/umbraco-marketplace.json
+++ b/umbraco-marketplace.json
@@ -2,7 +2,7 @@
"$schema": "https://marketplace.umbraco.com/umbraco-marketplace-schema.json",
"PackageType": "Package",
"Category": "Developer Tools",
- "Description": "Add \"listen to this article\" to any page with a single element. By default the reader's browser speaks the text with its own built-in voice and your server synthesizes nothing. For server-made neural voices with real word timings, install the separate BaryoDev.Umbraco.ReadAloud.Azure package and set Provider to Azure with your own Speech resource; the core package reads no credentials. If server audio fails, the client falls back to the browser's speech synthesis, so a page always has a voice. Audio is cached on your own server, word highlighting follows real timings from the engine rather than estimates, and nothing about a listener is ever stored. No table, no migration, no IP, no user agent. Free and MIT licensed, with no build step and no third-party dashboard.",
+ "Description": "Add \"listen to this article\" to any page with a single element. By default the reader's browser speaks the text with its own built-in voice and your server synthesizes nothing. For server-made neural voices with real word timings, install the separate BaryoDev.Umbraco.ReadAloud.Azure package and set Provider to Azure with your own Speech resource; the core package reads no credentials. If server audio fails, the client falls back to the browser's speech synthesis, so a page always has a voice. Audio is cached on your own server, word highlighting follows real timings from the engine rather than estimates, and listens are counted per page, voice and day with nothing that says who listened. No IP, no user agent. The package adds one small table. Free and MIT licensed, with no build step and no third-party dashboard.",
"AuthorDetails": {
"Name": "BaryoDev",
"Description": "Small open source .NET and JavaScript packages.",
From 9320072098779ca0ff7ffcfb44c93c8d3d15897f Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:25:14 +0800
Subject: [PATCH 03/10] list the flush service in the composer test instead of
resolving it
---
.../ListenSettingTests.cs | 16 +++++++++++-----
1 file changed, 11 insertions(+), 5 deletions(-)
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
index 96eaa11..d15bede 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenSettingTests.cs
@@ -47,10 +47,13 @@ public void The_voice_length_limit_applies_in_browser_mode_too()
[Fact]
public void The_composer_registers_the_counter_and_the_flush_service()
{
- var provider = ReadAloudComposerTests_Provider();
+ var services = ReadAloudComposerTests_Services();
- provider.GetRequiredService().ShouldNotBeNull();
- provider.GetServices().OfType().Count().ShouldBe(1);
+ // Listed, not resolved. The flush service needs Umbraco's scope provider and runtime state,
+ // which a bare container does not have. The real boot resolves it in the endpoint tests.
+ services.BuildServiceProvider().GetRequiredService().ShouldNotBeNull();
+ services.Count(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ListenFlushService))
+ .ShouldBe(1);
}
[Fact]
@@ -68,7 +71,10 @@ public void The_composer_registers_the_system_time_provider_when_the_site_has_no
ReadAloudComposerTests_Provider().GetRequiredService().ShouldBeSameAs(TimeProvider.System);
}
- private static ServiceProvider ReadAloudComposerTests_Provider(TimeProvider? first = null)
+ private static ServiceProvider ReadAloudComposerTests_Provider(TimeProvider? first = null) =>
+ ReadAloudComposerTests_Services(first).BuildServiceProvider();
+
+ private static ServiceCollection ReadAloudComposerTests_Services(TimeProvider? first = null)
{
var services = new ServiceCollection();
services.AddLogging();
@@ -77,6 +83,6 @@ private static ServiceProvider ReadAloudComposerTests_Provider(TimeProvider? fir
var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build();
new ReadAloudComposer().Compose(new ReadAloudComposerTests.StubUmbracoBuilder(services, configuration));
- return services.BuildServiceProvider();
+ return services;
}
}
From d14493c247c347d676efa2b188d3100a99e3d95a Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:28:34 +0800
Subject: [PATCH 04/10] run the test site without generated models and note the
models mode check
---
CHANGELOG.md | 3 +++
README.md | 4 ++++
tests/TestSite/appsettings.json | 3 +++
3 files changed, 10 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 540761d..73f30af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,9 @@ and [semantic versioning](https://semver.org).
- **The update creates one table, `baryoReadAloudListens`, on every install, including sites that
use the browser voice.** It is created by a package migration at startup. A site with
`PackageMigrationsUnattended` set to false must run the migration from the backoffice.
+- On Umbraco 17 and 18, a site with `ModelsBuilder:ModelsMode` set to `InMemoryAuto` needs the
+ `Umbraco.Cms.DevelopmentMode.Backoffice` package. Without it, the start that runs this package's
+ migration fails, until restart. This is Umbraco's own check, and any package migration triggers it.
- `DefaultVoice` and `AllowedVoices` entries longer than 100 characters are refused at startup.
## [0.4.0] - 2026-11-16
diff --git a/README.md b/README.md
index f6ccc12..0c9b1cb 100644
--- a/README.md
+++ b/README.md
@@ -316,6 +316,10 @@ is true, which is the default. If you set it to false, the table is not created
logs one warning per failure streak, and nothing else breaks. Voices longer than 100 characters in
`DefaultVoice` or `AllowedVoices` are refused at startup because the column holds 100.
+**On Umbraco 17 and 18, a site with `Umbraco:CMS:ModelsBuilder:ModelsMode` set to `InMemoryAuto` needs the
+`Umbraco.Cms.DevelopmentMode.Backoffice` package.** Without it, the start that runs this package's
+migration fails, until restart. This is Umbraco's own check, and any package migration triggers it.
+
**Remove it.** Set `CountListens` to `false`, uninstall the package, then `DROP TABLE
baryoReadAloudListens`. Umbraco keeps the migration state for the plan `BaryoDev.Umbraco.ReadAloud` in
`umbracoKeyValue`. Remove that row too if you reinstall and want the migration to run again.
diff --git a/tests/TestSite/appsettings.json b/tests/TestSite/appsettings.json
index 86639d1..21d11db 100644
--- a/tests/TestSite/appsettings.json
+++ b/tests/TestSite/appsettings.json
@@ -25,6 +25,9 @@
"UnattendedUserEmail": "test@example.com",
"UnattendedUserPassword": "LocalOnly-ChangeMe-1234!"
},
+ "ModelsBuilder": {
+ "ModelsMode": "Nothing"
+ },
"Security": {
"AllowConcurrentLogins": false
},
From 0cd95a7f327db6f48c3aa12836c66addf09ef3f3 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:29:30 +0800
Subject: [PATCH 05/10] say the next start works after the models mode check
---
CHANGELOG.md | 2 +-
README.md | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 73f30af..d8e6979 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ and [semantic versioning](https://semver.org).
`PackageMigrationsUnattended` set to false must run the migration from the backoffice.
- On Umbraco 17 and 18, a site with `ModelsBuilder:ModelsMode` set to `InMemoryAuto` needs the
`Umbraco.Cms.DevelopmentMode.Backoffice` package. Without it, the start that runs this package's
- migration fails, until restart. This is Umbraco's own check, and any package migration triggers it.
+ migration fails. The next start works. This is Umbraco's own check, and any package migration triggers it.
- `DefaultVoice` and `AllowedVoices` entries longer than 100 characters are refused at startup.
## [0.4.0] - 2026-11-16
diff --git a/README.md b/README.md
index 0c9b1cb..e10ffdc 100644
--- a/README.md
+++ b/README.md
@@ -318,7 +318,7 @@ logs one warning per failure streak, and nothing else breaks. Voices longer than
**On Umbraco 17 and 18, a site with `Umbraco:CMS:ModelsBuilder:ModelsMode` set to `InMemoryAuto` needs the
`Umbraco.Cms.DevelopmentMode.Backoffice` package.** Without it, the start that runs this package's
-migration fails, until restart. This is Umbraco's own check, and any package migration triggers it.
+migration fails. The next start works. This is Umbraco's own check, and any package migration triggers it.
**Remove it.** Set `CountListens` to `false`, uninstall the package, then `DROP TABLE
baryoReadAloudListens`. Umbraco keeps the migration state for the plan `BaryoDev.Umbraco.ReadAloud` in
From 33aab943fe35b3bbe601a80f269f8278e5129739 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:47:11 +0800
Subject: [PATCH 06/10] count no listen for a cancelled request, fail a stalled
test boot in 90 seconds
---
.../Controllers/ReadAloudController.cs | 7 +++
.../ListenCountingTests.cs | 45 +++++++++++++++++--
.../UmbracoSiteFixture.cs | 15 ++++++-
3 files changed, 62 insertions(+), 5 deletions(-)
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs b/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
index 6039e44..afd6fde 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud/Controllers/ReadAloudController.cs
@@ -80,12 +80,19 @@ public async Task Get(Guid key, [FromQuery] string? voice, Cancel
var etag = ETagFor(request!, "audio");
if (NotModified(etag))
{
+ // A request nobody is waiting for is not a listen.
+ if (ct.IsCancellationRequested) return new EmptyResult();
+
CountListen(key, request!);
return NotModifiedResponse(etag);
}
return await SynthesizeAsync(request!, ct, result =>
{
+ // A cache hit or a synthesis that finished first still returns a result to a caller
+ // that has gone, so the token is checked here, before anything is counted.
+ ct.ThrowIfCancellationRequested();
+
CountListen(key, request!);
return Tagged(etag, File(result.Audio, result.ContentType));
});
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
index a790794..0cc4949 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
@@ -55,6 +55,15 @@ public Task SetAsync(string key, SynthesisResult result, CancellationToken ct =
Task.CompletedTask;
}
+ private sealed class HitCache : IAudioCache
+ {
+ public Task GetAsync(string key, CancellationToken ct = default) =>
+ Task.FromResult(new SynthesisResult([1, 2, 3], [], "audio/mpeg"));
+
+ public Task SetAsync(string key, SynthesisResult result, CancellationToken ct = default) =>
+ Task.CompletedTask;
+ }
+
private sealed class Rig(
ReadAloudController controller,
CoalescingAudioSource audio,
@@ -73,7 +82,7 @@ public void Dispose()
}
}
- private Rig Build(IReadAloudEngine engine, ReadAloudOptions? configured = null, string? range = null, string? ifNoneMatch = null)
+ private Rig Build(IReadAloudEngine engine, ReadAloudOptions? configured = null, string? range = null, string? ifNoneMatch = null, IAudioCache? cache = null)
{
var scope = _site.Services.CreateScope();
var services = scope.ServiceProvider;
@@ -81,7 +90,7 @@ private Rig Build(IReadAloudEngine engine, ReadAloudOptions? configured = null,
configured ??= new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
var options = new FixedOptions(configured);
- var audio = new CoalescingAudioSource(engine, new NoCache(), options, NullLogger.Instance);
+ var audio = new CoalescingAudioSource(engine, cache ?? new NoCache(), options, NullLogger.Instance);
var http = new DefaultHttpContext();
if (range is not null) http.Request.Headers.Range = range;
@@ -196,8 +205,10 @@ public async Task Browser_mode_adds_nothing()
}
[Fact]
- public async Task A_request_cancelled_before_the_audio_is_ready_adds_nothing()
+ public async Task A_cancelled_request_adds_nothing_when_the_audio_is_already_done()
{
+ // The engine finishes at once and the cache is empty, so the result is ready before the
+ // caller's token is looked at. Nothing here depends on what an earlier test cached.
using var rig = Build(new OkEngine());
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
@@ -207,6 +218,34 @@ public async Task A_request_cancelled_before_the_audio_is_ready_adds_nothing()
_counter.Snapshot().ShouldBeEmpty();
}
+ [Fact]
+ public async Task A_cancelled_request_adds_nothing_on_a_cache_hit()
+ {
+ using var rig = Build(new ThrowingEngine(), cache: new HitCache());
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, cancelled.Token)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
+ [Fact]
+ public async Task A_cancelled_request_adds_nothing_on_a_304()
+ {
+ var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ string tag;
+ using (var probe = Build(new OkEngine(), options)) tag = EtagFor(probe, UmbracoSiteFixture.BodyHtml, DefaultVoice, options);
+
+ using var rig = Build(new OkEngine(), options, ifNoneMatch: tag);
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+
+ (await rig.Controller.Get(_site.PublishedNodeKey, null, cancelled.Token)).ShouldBeOfType();
+
+ _counter.Snapshot().ShouldBeEmpty();
+ }
+
[Theory]
[InlineData(null, 1)]
[InlineData("bytes=0-", 1)]
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
index 6324d06..227da78 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
@@ -173,8 +173,19 @@ public async Task InitializeAsync()
// Force the host to build and the unattended install to finish before anything asks
// Umbraco for a service. The status does not matter: the site has no template, so the
// front end is entitled to answer this with a 404.
- using var response = await Client.GetAsync("/");
- _ = response.StatusCode;
+ // A stalled boot (the database cache rebuild once never finished on 17.6.1) must fail in
+ // a minute with a reason, not leave the test host silent until the hang timeout.
+ using var boot = new CancellationTokenSource(TimeSpan.FromSeconds(90));
+ try
+ {
+ using var response = await Client.GetAsync("/", boot.Token);
+ _ = response.StatusCode;
+ }
+ catch (OperationCanceledException) when (boot.IsCancellationRequested)
+ {
+ throw new TimeoutException(
+ "Umbraco did not finish booting within 90 seconds. See tests/TestSite/umbraco/Logs for the last boot step.");
+ }
await PublishNodesAsync();
From a4be98cea0e7e6d4786cafef19291f48005ec4e5 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 17:06:15 +0800
Subject: [PATCH 07/10] wait for Umbraco to finish booting before the first
request in the test site
---
.../UmbracoSiteFixture.cs | 20 +++++++++++++------
1 file changed, 14 insertions(+), 6 deletions(-)
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
index 227da78..6f4fd59 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/UmbracoSiteFixture.cs
@@ -170,21 +170,29 @@ public async Task InitializeAsync()
{
Client = CreateClient();
- // Force the host to build and the unattended install to finish before anything asks
- // Umbraco for a service. The status does not matter: the site has no template, so the
- // front end is entitled to answer this with a 404.
- // A stalled boot (the database cache rebuild once never finished on 17.6.1) must fail in
- // a minute with a reason, not leave the test host silent until the hang timeout.
+ // The package migration makes Umbraco boot through the unattended upgrade path, on a
+ // background service, after the host has started. On 17.6.1 a request sent into that
+ // window stalled the database cache rebuild for good. So nothing is sent until the
+ // runtime says Run (or a boot failure, which the tests then report as the 500s they get).
+ // A stalled boot fails in 90 seconds with a reason, not after the 9 minute hang timeout.
using var boot = new CancellationTokenSource(TimeSpan.FromSeconds(90));
try
{
+ var runtime = Services.GetRequiredService();
+ while (runtime.Level != RuntimeLevel.Run && runtime.Level != RuntimeLevel.BootFailed)
+ {
+ await Task.Delay(100, boot.Token);
+ }
+
+ // The status does not matter: the site has no template, so the front end is entitled
+ // to answer this with a 404.
using var response = await Client.GetAsync("/", boot.Token);
_ = response.StatusCode;
}
catch (OperationCanceledException) when (boot.IsCancellationRequested)
{
throw new TimeoutException(
- "Umbraco did not finish booting within 90 seconds. See tests/TestSite/umbraco/Logs for the last boot step.");
+ "Umbraco did not reach the Run level within 90 seconds. See tests/TestSite/umbraco/Logs for the last boot step.");
}
await PublishNodesAsync();
From 171f1f6b66d53ec6deab577ab476262a21ae3ff9 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 17:30:28 +0800
Subject: [PATCH 08/10] send the asked voice in the query too in the stored
voice test
---
tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
index 0cc4949..d787e9a 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
@@ -283,6 +283,8 @@ public async Task The_voice_stored_is_the_one_used_and_not_the_one_asked_for()
{
var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
using var rig = Build(new OkEngine(), options);
+ // A real request carries the asked voice in the query and model binding copies it into the parameter.
+ rig.Http.Request.QueryString = new QueryString("?voice=en-US-NotOnTheList");
await rig.Controller.Get(_site.PublishedNodeKey, "en-US-NotOnTheList", default);
From e008778ef07dd65f5951c9b44d6f2a583d6f9f62 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 17:46:47 +0800
Subject: [PATCH 09/10] keep the listen flush running on a bad options reload
and fix its warnings
---
CHANGELOG.md | 5 +-
README.md | 8 +-
.../Listens/ListenFlushService.cs | 24 ++++--
.../ListenCountingTests.cs | 31 ++++++++
.../ListenFlushTests.cs | 78 ++++++++++++++++++-
.../ListenRangeTests.cs | 4 +
.../ListenStoreTests.cs | 35 +++++++++
7 files changed, 175 insertions(+), 10 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d8e6979..fde7464 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,7 +10,10 @@ and [semantic versioning](https://semver.org).
- Listen counts (#2). A play adds one to a count for the page, the voice used and the UTC day,
kept in memory and written once a minute and at shutdown. Stored: node key, voice, day, count.
Nothing that says who listened. A request with a `Range` header counts only when it is
- `bytes=0-`. `CountListens` (default `true`) turns it off at runtime.
+ `bytes=0-`. `CountListens` (default `true`) turns it off at runtime. After the update a site
+ counts plays unless `CountListens` is false.
+- The `ReadAloudController` constructor gained a trailing optional parameter. A class compiled
+ against 0.4.0 that derives from it or calls its constructor must be rebuilt.
- **The update creates one table, `baryoReadAloudListens`, on every install, including sites that
use the browser voice.** It is created by a package migration at startup. A site with
`PackageMigrationsUnattended` set to false must run the migration from the backoffice.
diff --git a/README.md b/README.md
index e10ffdc..7125351 100644
--- a/README.md
+++ b/README.md
@@ -272,12 +272,15 @@ Failures: the route answers 503 and the browser falls back to
### Listen counts
-`CountListens` (default `true`) counts plays. It can be switched off at runtime; held counts are then
+`CountListens` (default `true`) counts plays. After the update a site counts plays unless
+`CountListens` is false. It can be switched off at runtime; held counts are then
dropped and nothing more is written.
**What is counted.** One count each time the audio route answers a play with a 200 or a 304. The
timings route, refusals, 404s, failures and browser-voice mode count nothing. A request with a
`Range` header counts only when it is `bytes=0-`, so a seek or a probe does not add a play.
+A count is a request, not a person. Bots and link previews that fetch the audio are counted. A play
+is counted when the 200 or 304 is returned, not when it is delivered or heard.
**What is stored.** One table, `baryoReadAloudListens`, with four columns: the node key, the voice
actually used, the UTC day as `yyyymmdd`, and the count. No IP, no user agent, no identity, no
@@ -313,7 +316,8 @@ DELETE FROM baryoReadAloudListens WHERE DayUtc < 20260101;
browser voice. Umbraco runs it at startup when `Umbraco:CMS:Unattended:PackageMigrationsUnattended`
is true, which is the default. If you set it to false, the table is not created until you run the package migration yourself
(for example by setting it to true for one start). Until it does, counts stay in memory, the flush
-logs one warning per failure streak, and nothing else breaks. Voices longer than 100 characters in
+logs one warning per failure streak, and nothing else breaks. Umbraco itself logs the database
+error for each failed statement, next to the package's one warning per streak. Voices longer than 100 characters in
`DefaultVoice` or `AllowedVoices` are refused at startup because the column holds 100.
**On Umbraco 17 and 18, a site with `Umbraco:CMS:ModelsBuilder:ModelsMode` set to `InMemoryAuto` needs the
diff --git a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
index 8dc335c..dc16b1c 100644
--- a/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
+++ b/src/BaryoDev.Umbraco.ReadAloud/Listens/ListenFlushService.cs
@@ -71,7 +71,15 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(_interval, stoppingToken);
- await Task.Run(() => Flush(), stoppingToken);
+ try
+ {
+ await Task.Run(() => Flush(), stoppingToken);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ // Reading the options can throw after a bad reload. Keep the loop and the held counts.
+ _logger.LogWarning(ex, "Read-aloud listen counts could not be flushed. The next flush will retry.");
+ }
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
@@ -94,7 +102,7 @@ public override async Task StopAsync(CancellationToken cancellationToken)
{
if (!_ready()) return;
- var written = await Task.Run(() => Flush()).WaitAsync(_shutdownTimeout, cancellationToken);
+ var written = await Task.Run(() => Flush(atShutdown: true)).WaitAsync(_shutdownTimeout, cancellationToken);
if (!written) DropAtShutdown();
}
catch (Exception)
@@ -107,16 +115,21 @@ public override async Task StopAsync(CancellationToken cancellationToken)
/// One flush. Returns false when something could not be written, after putting it back in
/// memory. With counting switched off it drops what is held and writes nothing.
///
- internal bool Flush()
+ internal bool Flush(bool atShutdown = false)
{
if (!_options.CurrentValue.CountListens)
{
_counter.Clear();
+ Interlocked.Exchange(ref _failing, 0); // counting is off, so the streak ends
return true;
}
var drained = _counter.Drain();
- if (drained.Count == 0) return true;
+ if (drained.Count == 0)
+ {
+ Interlocked.Exchange(ref _failing, 0);
+ return true;
+ }
var written = 0;
Exception? failure = null;
@@ -144,7 +157,8 @@ internal bool Flush()
// have been written, so only the rows that were written are left out.
_counter.MergeBack(drained.Skip(written).ToDictionary(p => p.Key, p => p.Value));
- if (Interlocked.Exchange(ref _failing, 1) == 0)
+ // At shutdown the caller logs the one drop line, so the streak line stays out.
+ if (Interlocked.Exchange(ref _failing, 1) == 0 && !atShutdown)
{
_logger.LogWarning(
failure,
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
index d787e9a..445ac79 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenCountingTests.cs
@@ -292,6 +292,37 @@ public async Task The_voice_stored_is_the_one_used_and_not_the_one_asked_for()
Held(_site.PublishedNodeKey, "en-US-NotOnTheList").ShouldBe(0);
}
+ [Fact]
+ public async Task An_empty_voice_is_stored_as_the_default_voice()
+ {
+ var options = new ReadAloudOptions { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ using var rig = Build(new OkEngine(), options);
+ rig.Http.Request.QueryString = new QueryString("?voice=");
+
+ await rig.Controller.Get(_site.PublishedNodeKey, "", default);
+
+ Held(_site.PublishedNodeKey, DefaultVoice).ShouldBe(1);
+ Held(_site.PublishedNodeKey, "").ShouldBe(0);
+ }
+
+ [Fact]
+ public async Task A_case_variant_of_an_allowed_voice_is_stored_as_the_default_voice()
+ {
+ var options = new ReadAloudOptions
+ {
+ PropertyAlias = UmbracoSiteFixture.PropertyAlias,
+ AllowedVoices = ["en-GB-RyanNeural"],
+ };
+ using var rig = Build(new OkEngine(), options);
+ rig.Http.Request.QueryString = new QueryString("?voice=EN-GB-RYANNEURAL");
+
+ await rig.Controller.Get(_site.PublishedNodeKey, "EN-GB-RYANNEURAL", default);
+
+ Held(_site.PublishedNodeKey, DefaultVoice).ShouldBe(1);
+ Held(_site.PublishedNodeKey, "EN-GB-RYANNEURAL").ShouldBe(0);
+ Held(_site.PublishedNodeKey, "en-GB-RyanNeural").ShouldBe(0);
+ }
+
[Fact]
public async Task An_allowed_voice_is_stored_as_that_voice()
{
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
index eba3b1d..52fdca2 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenFlushTests.cs
@@ -1,4 +1,5 @@
using BaryoDev.Umbraco.ReadAloud.Listens;
+using Microsoft.Extensions.Options;
using Shouldly;
namespace BaryoDev.Umbraco.ReadAloud.Tests;
@@ -155,8 +156,81 @@ public async Task Stopping_with_a_failing_store_does_not_throw_and_drops_the_cou
await service.StopAsync(CancellationToken.None);
_counter.Snapshot().ShouldBeEmpty();
- // The failed flush itself logs the streak, and the drop logs its own line.
- _log.Warnings.Count(w => w.Contains("shutdown")).ShouldBe(1);
+ _log.Warnings.Count.ShouldBe(1);
+ _log.Warnings[0].ShouldContain("shutdown");
+ }
+
+ [Fact]
+ public void A_new_streak_after_the_setting_was_switched_off_logs_again()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _store.FailWhen = _ => true;
+ service.Flush().ShouldBeFalse();
+
+ _options.CurrentValue.CountListens = false;
+ service.Flush().ShouldBeTrue();
+ _options.CurrentValue.CountListens = true;
+ _counter.Add(Guid.NewGuid(), "v");
+ service.Flush().ShouldBeFalse();
+
+ _log.Warnings.Count.ShouldBe(2);
+ }
+
+ [Fact]
+ public void A_new_streak_after_an_empty_flush_logs_again()
+ {
+ var service = Service();
+ _counter.Add(Guid.NewGuid(), "v");
+ _store.FailWhen = _ => true;
+ service.Flush().ShouldBeFalse();
+
+ _counter.Clear();
+ service.Flush().ShouldBeTrue();
+ _counter.Add(Guid.NewGuid(), "v");
+ service.Flush().ShouldBeFalse();
+
+ _log.Warnings.Count.ShouldBe(2);
+ }
+
+ [Fact]
+ public async Task A_flush_that_cannot_read_the_options_logs_a_warning_keeps_running_and_writes_later()
+ {
+ var options = new ThrowingOptions { Throwing = true };
+ var service = new ListenFlushService(
+ _counter, _store, () => _ready, options, _log,
+ TimeSpan.FromMilliseconds(20), TimeSpan.FromMilliseconds(10), TimeSpan.FromSeconds(5));
+ var node = Guid.NewGuid();
+ _counter.Add(node, "v");
+
+ await service.StartAsync(CancellationToken.None);
+ var deadline = DateTime.UtcNow.AddSeconds(10);
+ while (_log.Warnings.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(20);
+
+ _log.Warnings.Count.ShouldBeGreaterThanOrEqualTo(2);
+ service.ExecuteTask!.IsFaulted.ShouldBeFalse();
+ service.ExecuteTask.IsCompleted.ShouldBeFalse();
+ _store.Calls.ShouldBe(0);
+
+ options.Throwing = false;
+ deadline = DateTime.UtcNow.AddSeconds(10);
+ while (_store.Calls == 0 && DateTime.UtcNow < deadline) await Task.Delay(20);
+ await service.StopAsync(CancellationToken.None);
+
+ _store.Rows[Key(node)].ShouldBe(1);
+ }
+
+ private sealed class ThrowingOptions : IOptionsMonitor
+ {
+ private readonly ReadAloudOptions _value = new() { PropertyAlias = UmbracoSiteFixture.PropertyAlias };
+ public volatile bool Throwing;
+
+ public ReadAloudOptions CurrentValue =>
+ Throwing ? throw new OptionsValidationException("", typeof(ReadAloudOptions), ["bad reload"]) : _value;
+
+ public ReadAloudOptions Get(string? name) => CurrentValue;
+
+ public IDisposable? OnChange(Action listener) => null;
}
[Fact]
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
index 84d2cd9..3daf59b 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenRangeTests.cs
@@ -16,6 +16,8 @@ public void No_range_header_counts()
[InlineData("bytes=0-")]
[InlineData("BYTES=0-")]
[InlineData(" bytes=0- ")]
+ [InlineData("bytes= 0-")]
+ [InlineData("")]
public void The_open_range_from_the_start_counts(string header)
{
ListenRange.CountsAsPlay(header).ShouldBeTrue();
@@ -23,6 +25,8 @@ public void The_open_range_from_the_start_counts(string header)
[Theory]
[InlineData("bytes=0-1")]
+ [InlineData("bytes=0-0")]
+ [InlineData("bytes=0-100")]
[InlineData("bytes=500-")]
[InlineData("bytes=-500")]
[InlineData("bytes=0-1,5-6")]
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
index 24d51a4..c3b5cb9 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/ListenStoreTests.cs
@@ -40,6 +40,41 @@ public void Two_adds_for_one_key_end_as_one_row_holding_the_sum()
Listens(key).ShouldBe(7);
}
+ [Fact]
+ public void Two_voices_on_one_day_and_one_voice_on_two_days_are_separate_rows()
+ {
+ var store = Store();
+ var node = Guid.NewGuid();
+ var sonia = new ListenKey(node, "en-GB-SoniaNeural", ListenClock.Day);
+ var ryan = new ListenKey(node, "en-GB-RyanNeural", ListenClock.Day);
+ var nextDay = new ListenKey(node, "en-GB-SoniaNeural", ListenClock.Day + 1);
+
+ store.Add(sonia, 1);
+ store.Add(ryan, 2);
+ store.Add(nextDay, 4);
+ store.Add(sonia, 8);
+
+ Listens(sonia).ShouldBe(9);
+ Listens(ryan).ShouldBe(2);
+ Listens(nextDay).ShouldBe(4);
+ }
+
+ [Fact]
+ public void A_non_ascii_voice_round_trips_unchanged()
+ {
+ var store = Store();
+ var key = new ListenKey(Guid.NewGuid(), "zh-CN-\u6653\u6653Neural", ListenClock.Day);
+
+ store.Add(key, 2);
+ store.Add(key, 3);
+
+ Listens(key).ShouldBe(5);
+ using var scope = _site.Services.GetRequiredService().CreateScope();
+ scope.Database.Fetch("SELECT Voice FROM baryoReadAloudListens WHERE NodeKey = @0", key.NodeKey)
+ .ShouldBe([key.Voice]);
+ scope.Complete();
+ }
+
[Fact]
public void Another_server_inserting_first_is_met_with_an_update_not_a_failure()
{
From 20443f2014db821ab7531cad79df5a507b781800 Mon Sep 17 00:00:00 2001
From: Arnel Robles <3198856+arnelirobles@users.noreply.github.com>
Date: Wed, 25 Nov 2026 19:25:10 +0800
Subject: [PATCH 10/10] allow the listen table's two schema consts in the
public const test
---
.../BaryoDev.Umbraco.ReadAloud.Tests/PublicConstantTests.cs | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/tests/BaryoDev.Umbraco.ReadAloud.Tests/PublicConstantTests.cs b/tests/BaryoDev.Umbraco.ReadAloud.Tests/PublicConstantTests.cs
index 8d04c40..451bf74 100644
--- a/tests/BaryoDev.Umbraco.ReadAloud.Tests/PublicConstantTests.cs
+++ b/tests/BaryoDev.Umbraco.ReadAloud.Tests/PublicConstantTests.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using BaryoDev.Umbraco.ReadAloud.Engine;
+using BaryoDev.Umbraco.ReadAloud.Listens;
using Shouldly;
using Xunit;
@@ -64,12 +65,16 @@ public void No_other_public_const_is_added_without_a_decision()
{
// PolicyName is an attribute argument. The SynthesisFailureKind members are enum members,
// which are consts by nature: new in 0.4.0 and only ever appended, never renumbered.
+ // ListenRow's two are attribute arguments on the row ([TableName] and [Length]) and part
+ // of the table's schema, so changing either needs a migration whether or not it is const.
var allowed = new[]
{
nameof(ReadAloudRateLimiting.PolicyName),
nameof(SynthesisFailureKind.Other),
nameof(SynthesisFailureKind.Authentication),
nameof(SynthesisFailureKind.RateLimited),
+ nameof(ListenRow.TableName),
+ nameof(ListenRow.MaxVoiceLength),
};
var consts = typeof(ReadAloudOptions).Assembly