fix(session): confirm routed delivery and keep playback state with the owner

This commit is contained in:
2026-09-26 14:45:40 +10:00
parent 086fdb8257
commit 611bcf2c4a
17 changed files with 1068 additions and 216 deletions
@@ -73,6 +73,7 @@ namespace Emby.Server.Implementations.Session
private readonly ConcurrentDictionary<string, long> _connectionEpochs = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, long> _lastDirectoryPublish = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, bool> _directoryOwned = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _activeLiveStreamSessions
= new(StringComparer.OrdinalIgnoreCase);
@@ -80,6 +81,7 @@ namespace Emby.Server.Implementations.Session
private Timer _idleTimer;
private Timer _inactiveTimer;
private Timer _directoryTimer;
private int _refreshingDirectory;
private DtoOptions _itemInfoDtoOptions;
private bool _disposed;
@@ -364,6 +366,20 @@ namespace Emby.Server.Implementations.Session
}
}
// A playback transition changes what every instance's session list shows, so it is not left to
// the throttle.
private Task PublishToDirectoryNowAsync(SessionInfo session)
{
if (!_directoryEnabled || string.IsNullOrEmpty(session.Id))
{
return Task.CompletedTask;
}
_lastDirectoryPublish[session.Id] = Environment.TickCount64;
return PublishToDirectoryAsync(session);
}
private async Task PublishToDirectoryAsync(SessionInfo session)
{
if (!_directoryEnabled || string.IsNullOrEmpty(session.Id))
@@ -373,16 +389,16 @@ namespace Emby.Server.Implementations.Session
try
{
var connectedUtcTicks = GetConnectionEpoch(session);
var connectionEpoch = await GetConnectionEpochAsync(session).ConfigureAwait(false);
await _sessionDirectory.PublishAsync(
_directoryOwned[session.Id] = await _sessionDirectory.PublishAsync(
new SessionDirectoryEntry
{
OwnerPod = _podMessageBus.PodId,
HoldsConnection = connectedUtcTicks > 0,
HoldsConnection = connectionEpoch > 0,
Session = ToSessionInfoDto(session)
},
connectedUtcTicks).ConfigureAwait(false);
connectionEpoch).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -391,8 +407,10 @@ namespace Emby.Server.Implementations.Session
}
// Ownership follows the connection, not the last request served: an instance without a live
// controller claims with epoch zero, which never displaces an instance that has one.
private long GetConnectionEpoch(SessionInfo session)
// controller claims with epoch zero, which never displaces an entry another instance holds. The
// epoch is handed out by the shared store, so the epochs of two instances are ordered by one
// clock rather than by whichever machine's wall clock wrote them.
private async Task<long> GetConnectionEpochAsync(SessionInfo session)
{
if (!session.SessionControllers.Any(i => i.IsSessionActive))
{
@@ -400,13 +418,21 @@ namespace Emby.Server.Implementations.Session
return 0;
}
return _connectionEpochs.GetOrAdd(session.Id, _ => DateTime.UtcNow.Ticks);
if (_connectionEpochs.TryGetValue(session.Id, out var epoch))
{
return epoch;
}
var allocated = await _sessionDirectory.AllocateConnectionEpochAsync(session.Id).ConfigureAwait(false);
return _connectionEpochs.GetOrAdd(session.Id, allocated);
}
private async ValueTask RemoveFromDirectoryAsync(SessionInfo session)
{
_connectionEpochs.TryRemove(session.Id, out _);
_lastDirectoryPublish.TryRemove(session.Id, out _);
_directoryOwned.TryRemove(session.Id, out _);
if (!_directoryEnabled || string.IsNullOrEmpty(session.Id))
{
@@ -416,19 +442,37 @@ namespace Emby.Server.Implementations.Session
await _sessionDirectory.RemoveAsync(session.Id, _podMessageBus.PodId).ConfigureAwait(false);
}
private async void RefreshSessionDirectory(object state)
private void RefreshSessionDirectory(object state)
{
if (Interlocked.CompareExchange(ref _refreshingDirectory, 1, 0) == 0)
{
_ = RefreshSessionDirectoryAsync();
}
}
// Only the entries this instance can hold are refreshed: republishing a copy of a session another
// instance owns just has the claim refused.
private async Task RefreshSessionDirectoryAsync()
{
try
{
foreach (var session in _activeConnections.Values)
{
await PublishToDirectoryAsync(session).ConfigureAwait(false);
if (session.SessionControllers.Any(i => i.IsSessionActive)
|| (_directoryOwned.TryGetValue(session.Id, out var owned) && owned))
{
await PublishToDirectoryAsync(session).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Error refreshing the session directory.");
}
finally
{
Interlocked.Exchange(ref _refreshingDirectory, 0);
}
}
private async Task<IReadOnlyList<SessionDirectoryEntry>> GetRemoteEntriesAsync(CancellationToken cancellationToken)
@@ -479,34 +523,38 @@ namespace Emby.Server.Implementations.Session
Capabilities = dto.Capabilities?.ToClientCapabilities()
};
if (entry.HoldsConnection)
{
session.AddController(new RemoteSessionController(_podMessageBus, _logger, entry.OwnerPod, dto.Id, dto.SupportsMediaControl));
}
session.AddController(new RemoteSessionController(_podMessageBus, _logger, entry.OwnerPod, dto.Id, dto.SupportsMediaControl));
return session;
}
private Task OnPodMessage(PodMessage message)
// What is returned here becomes the sender's answer, so a message this instance could not carry
// out is reported as undelivered instead of being counted by the sender as having arrived.
private Task<bool> OnPodMessage(PodMessage message)
{
switch (message.Kind)
{
case RoutedSessionMessage.Kind:
return OnRoutedSessionMessage(message);
case RoutedAdditionalUserChange.Kind:
OnRoutedAdditionalUserChange(message);
return Task.CompletedTask;
return Task.FromResult(OnRoutedAdditionalUserChange(message));
case RoutedNowViewingItem.Kind:
return Task.FromResult(OnRoutedNowViewingItem(message));
case RoutedPlaybackReport.StartKind:
case RoutedPlaybackReport.ProgressKind:
case RoutedPlaybackReport.StoppedKind:
return OnRoutedPlaybackReport(message);
default:
return Task.CompletedTask;
return Task.FromResult(false);
}
}
private async Task OnRoutedSessionMessage(PodMessage message)
private async Task<bool> OnRoutedSessionMessage(PodMessage message)
{
var routed = JsonSerializer.Deserialize<RoutedSessionMessage>(message.Payload, JsonDefaults.Options);
if (routed is null)
{
return;
return false;
}
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, routed.SessionId, StringComparison.Ordinal));
@@ -518,7 +566,7 @@ namespace Emby.Server.Implementations.Session
"A {MessageType} message for session {Session} was routed to this instance, which no longer holds its connection.",
routed.MessageType,
routed.SessionId);
return;
return false;
}
using var data = JsonDocument.Parse(routed.Data);
@@ -526,9 +574,11 @@ namespace Emby.Server.Implementations.Session
{
await controller.SendMessage(routed.MessageType, routed.MessageId, data.RootElement, CancellationToken.None).ConfigureAwait(false);
}
return true;
}
private void OnRoutedAdditionalUserChange(PodMessage message)
private bool OnRoutedAdditionalUserChange(PodMessage message)
{
var routed = JsonSerializer.Deserialize<RoutedAdditionalUserChange>(message.Payload, JsonDefaults.Options);
var session = routed is null
@@ -537,7 +587,7 @@ namespace Emby.Server.Implementations.Session
if (session is null)
{
return;
return false;
}
if (routed.Add)
@@ -548,6 +598,95 @@ namespace Emby.Server.Implementations.Session
{
DetachAdditionalUser(session, routed.UserId);
}
QueueDirectoryPublish(session);
return true;
}
private bool OnRoutedNowViewingItem(PodMessage message)
{
var routed = JsonSerializer.Deserialize<RoutedNowViewingItem>(message.Payload, JsonDefaults.Options);
var session = routed is null
? null
: Sessions.FirstOrDefault(i => string.Equals(i.Id, routed.SessionId, StringComparison.Ordinal));
if (session is null)
{
return false;
}
SetNowViewingItem(session, routed.ItemId);
return true;
}
private async Task<bool> OnRoutedPlaybackReport(PodMessage message)
{
try
{
switch (message.Kind)
{
case RoutedPlaybackReport.StartKind:
await OnPlaybackStartCore(Deserialize<PlaybackStartInfo>(message)).ConfigureAwait(false);
return true;
case RoutedPlaybackReport.ProgressKind:
return await OnPlaybackProgressCore(Deserialize<PlaybackProgressInfo>(message), false).ConfigureAwait(false);
default:
await OnPlaybackStoppedCore(Deserialize<PlaybackStopInfo>(message)).ConfigureAwait(false);
return true;
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "A {Kind} report routed to this instance could not be applied.", message.Kind);
return false;
}
}
private static T Deserialize<T>(PodMessage message)
=> JsonSerializer.Deserialize<T>(message.Payload, JsonDefaults.Options);
// A sessionId-addressed mutation belongs to the instance whose copy of the session everyone else
// is shown. An undeliverable route falls back to handling it here, which is what a deployment
// without a directory does anyway.
private async Task<bool> TryRouteToOwnerAsync(string sessionId, string kind, object payload, CancellationToken cancellationToken)
{
if (!_directoryEnabled || string.IsNullOrEmpty(sessionId))
{
return false;
}
try
{
var entry = await _sessionDirectory.GetAsync(sessionId, cancellationToken).ConfigureAwait(false);
if (entry is null || string.Equals(entry.OwnerPod, _podMessageBus.PodId, StringComparison.Ordinal))
{
return false;
}
var routed = await _podMessageBus.RequestAsync(
entry.OwnerPod,
new PodMessage
{
Kind = kind,
Payload = JsonSerializer.Serialize(payload, JsonDefaults.Options)
},
cancellationToken).ConfigureAwait(false);
if (!routed)
{
_logger.LogWarning("Instance {OwnerPod} did not apply the {Kind} report for session {Session}; it is applied here instead.", entry.OwnerPod, kind, sessionId);
}
return routed;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Could not reach the owner of session {Session}; the {Kind} report is applied here instead.", sessionId, kind);
return false;
}
}
/// <inheritdoc />
@@ -1014,6 +1153,16 @@ namespace Emby.Server.Implementations.Session
ArgumentNullException.ThrowIfNull(info);
if (await TryRouteToOwnerAsync(info.SessionId, RoutedPlaybackReport.StartKind, info, CancellationToken.None).ConfigureAwait(false))
{
return;
}
await OnPlaybackStartCore(info).ConfigureAwait(false);
}
private async Task OnPlaybackStartCore(PlaybackStartInfo info)
{
var session = GetSession(info.SessionId);
var libraryItem = info.ItemId.IsEmpty()
@@ -1080,6 +1229,8 @@ namespace Emby.Server.Implementations.Session
_logger);
StartCheckTimers();
await PublishToDirectoryNowAsync(session).ConfigureAwait(false);
}
/// <summary>
@@ -1146,10 +1297,23 @@ namespace Emby.Server.Implementations.Session
ArgumentNullException.ThrowIfNull(info);
// An automated report is generated from the copy of the session this instance already holds,
// so it is never the one that belongs somewhere else.
if (!isAutomated
&& await TryRouteToOwnerAsync(info.SessionId, RoutedPlaybackReport.ProgressKind, info, CancellationToken.None).ConfigureAwait(false))
{
return;
}
await OnPlaybackProgressCore(info, isAutomated).ConfigureAwait(false);
}
private async Task<bool> OnPlaybackProgressCore(PlaybackProgressInfo info, bool isAutomated)
{
var session = GetSession(info.SessionId, false);
if (session is null)
{
return;
return false;
}
var libraryItem = info.ItemId.IsEmpty()
@@ -1206,6 +1370,10 @@ namespace Emby.Server.Implementations.Session
}
StartCheckTimers();
QueueDirectoryPublish(session);
return true;
}
private void OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info)
@@ -1302,6 +1470,16 @@ namespace Emby.Server.Implementations.Session
ArgumentNullException.ThrowIfNull(info);
if (await TryRouteToOwnerAsync(info.SessionId, RoutedPlaybackReport.StoppedKind, info, CancellationToken.None).ConfigureAwait(false))
{
return;
}
await OnPlaybackStoppedCore(info).ConfigureAwait(false);
}
private async Task OnPlaybackStoppedCore(PlaybackStopInfo info)
{
var session = GetSession(info.SessionId);
session.StopAutomaticProgress();
@@ -1406,6 +1584,8 @@ namespace Emby.Server.Implementations.Session
await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false);
EventHelper.QueueEventIfNotNull(PlaybackStopped, this, eventArgs, _logger);
await PublishToDirectoryNowAsync(session).ConfigureAwait(false);
}
private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed)
@@ -1465,8 +1645,11 @@ namespace Emby.Server.Implementations.Session
return session;
}
// A local SessionInfo without a live controller is a copy left behind by a request this instance
// happened to serve, not the connection: prefer the owner named by the directory over it.
// Resolves the session a message has to be written to. A local SessionInfo without a live
// controller is a copy left behind by a request this instance happened to serve, not the
// connection, so it is never the answer: either the owner named by the directory can take the
// message or nothing can, and the caller is told so rather than handed a copy that silently
// swallows it. A directory that cannot be read raises rather than reading as "no such session".
private async Task<SessionInfo> GetSessionToRemoteControl(string sessionId)
{
var local = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
@@ -1476,15 +1659,21 @@ namespace Emby.Server.Implementations.Session
return local;
}
var session = await GetRemoteSession(sessionId).ConfigureAwait(false) ?? local;
return await GetRemoteSession(sessionId).ConfigureAwait(false)
?? throw new ResourceNotFoundException(
string.Format(CultureInfo.InvariantCulture, "No instance holds a connection to session {0}.", sessionId));
}
if (session is null)
{
throw new ResourceNotFoundException(
// Resolves a session to authorize against or to change server-side state on. Nothing is written to
// a connection here, so a copy without one still answers the question.
private async Task<SessionInfo> GetSessionForControl(string sessionId)
{
var local = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
return local
?? await GetRemoteSession(sessionId).ConfigureAwait(false)
?? throw new ResourceNotFoundException(
string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId));
}
return session;
}
/// <inheritdoc />
@@ -1553,7 +1742,7 @@ namespace Emby.Server.Implementations.Session
if (!string.IsNullOrEmpty(controllingSessionId))
{
var controllingSession = await GetSessionToRemoteControl(controllingSessionId).ConfigureAwait(false);
var controllingSession = await GetSessionForControl(controllingSessionId).ConfigureAwait(false);
AssertCanControl(session, controllingSession);
}
@@ -1562,7 +1751,14 @@ namespace Emby.Server.Implementations.Session
private static async Task SendMessageToSession<T>(SessionInfo session, SessionMessageType name, T data, CancellationToken cancellationToken)
{
var controllers = session.SessionControllers;
var controllers = session.SessionControllers.Where(i => i.IsSessionActive).ToList();
if (controllers.Count == 0)
{
throw new ResourceNotFoundException(
string.Format(CultureInfo.InvariantCulture, "No instance holds a connection to session {0}.", session.Id));
}
var messageId = Guid.NewGuid();
foreach (var controller in controllers)
@@ -1664,7 +1860,7 @@ namespace Emby.Server.Implementations.Session
if (!string.IsNullOrEmpty(controllingSessionId))
{
var controllingSession = await GetSessionToRemoteControl(controllingSessionId).ConfigureAwait(false);
var controllingSession = await GetSessionForControl(controllingSessionId).ConfigureAwait(false);
AssertCanControl(session, controllingSession);
if (!controllingSession.UserId.IsEmpty())
{
@@ -1682,10 +1878,10 @@ namespace Emby.Server.Implementations.Session
// SyncPlay group membership is instance-local, so a session listed by another instance is not
// reachable from here. It is skipped rather than reported as missing.
var session = GetSession(sessionId, false);
var session = GetConnectedSession(sessionId);
if (session is null)
{
_logger.LogDebug("SyncPlay command for session {Session} dropped; it is not held by this instance.", sessionId);
_logger.LogDebug("SyncPlay command for session {Session} dropped; this instance does not hold its connection.", sessionId);
return;
}
@@ -1697,16 +1893,25 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
var session = GetSession(sessionId, false);
var session = GetConnectedSession(sessionId);
if (session is null)
{
_logger.LogDebug("SyncPlay group update for session {Session} dropped; it is not held by this instance.", sessionId);
_logger.LogDebug("SyncPlay group update for session {Session} dropped; this instance does not hold its connection.", sessionId);
return;
}
await SendMessageToSession(session, SessionMessageType.SyncPlayGroupUpdate, command, cancellationToken).ConfigureAwait(false);
}
// Both instances keep a copy of a session whose requests they have served, so holding a copy is
// not holding the connection.
private SessionInfo GetConnectedSession(string sessionId)
{
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
return session?.SessionControllers.Any(i => i.IsSessionActive) == true ? session : null;
}
private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user)
{
var item = _libraryManager.GetItemById(id);
@@ -1799,7 +2004,7 @@ namespace Emby.Server.Implementations.Session
if (!string.IsNullOrEmpty(controllingSessionId))
{
var controllingSession = await GetSessionToRemoteControl(controllingSessionId).ConfigureAwait(false);
var controllingSession = await GetSessionForControl(controllingSessionId).ConfigureAwait(false);
AssertCanControl(session, controllingSession);
if (!controllingSession.UserId.IsEmpty())
{
@@ -1883,11 +2088,11 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
var session = await GetSessionToRemoteControl(sessionId).ConfigureAwait(false);
var session = await GetSessionForControl(sessionId).ConfigureAwait(false);
if (!string.IsNullOrEmpty(controllingSessionId))
{
var controllingSession = await GetSessionToRemoteControl(controllingSessionId).ConfigureAwait(false);
var controllingSession = await GetSessionForControl(controllingSessionId).ConfigureAwait(false);
AssertCanControl(session, controllingSession);
AssertCanAttachUser(controllingSession, userId);
}
@@ -1900,13 +2105,14 @@ namespace Emby.Server.Implementations.Session
var user = _userManager.GetUserById(userId)
?? throw new ArgumentException("The requested user does not exist.");
await RouteAdditionalUserChange(sessionId, userId, true).ConfigureAwait(false);
var local = GetSession(sessionId, false);
if (local is not null)
{
AttachAdditionalUser(local, userId, user.Username);
QueueDirectoryPublish(local);
}
await RouteAdditionalUserChange(sessionId, userId, true).ConfigureAwait(false);
}
/// <summary>
@@ -1922,11 +2128,11 @@ namespace Emby.Server.Implementations.Session
{
CheckDisposed();
var session = await GetSessionToRemoteControl(sessionId).ConfigureAwait(false);
var session = await GetSessionForControl(sessionId).ConfigureAwait(false);
if (!string.IsNullOrEmpty(controllingSessionId))
{
AssertCanControl(session, await GetSessionToRemoteControl(controllingSessionId).ConfigureAwait(false));
AssertCanControl(session, await GetSessionForControl(controllingSessionId).ConfigureAwait(false));
}
if (session.UserId.Equals(userId))
@@ -1934,13 +2140,14 @@ namespace Emby.Server.Implementations.Session
throw new ArgumentException("The requested user is already the primary user of the session.");
}
await RouteAdditionalUserChange(sessionId, userId, false).ConfigureAwait(false);
var local = GetSession(sessionId, false);
if (local is not null)
{
DetachAdditionalUser(local, userId);
QueueDirectoryPublish(local);
}
await RouteAdditionalUserChange(sessionId, userId, false).ConfigureAwait(false);
}
private static void AttachAdditionalUser(SessionInfo session, Guid userId, string userName)
@@ -1987,7 +2194,7 @@ namespace Emby.Server.Implementations.Session
Add = add
};
var delivered = await _podMessageBus.PublishAsync(
var delivered = await _podMessageBus.RequestAsync(
entry.OwnerPod,
new PodMessage
{
@@ -1995,9 +2202,10 @@ namespace Emby.Server.Implementations.Session
Payload = JsonSerializer.Serialize(payload, JsonDefaults.Options)
}).ConfigureAwait(false);
if (delivered == 0)
if (!delivered)
{
_logger.LogWarning("Instance {OwnerPod} holds session {Session} but is not listening; the additional user change was not applied there.", entry.OwnerPod, sessionId);
throw new ResourceNotFoundException(
string.Format(CultureInfo.InvariantCulture, "The instance holding session {0} did not apply the change.", sessionId));
}
}
@@ -2297,19 +2505,36 @@ namespace Emby.Server.Implementations.Session
}
/// <inheritdoc />
public void ReportNowViewingItem(string controllingSessionId, string sessionId, string itemId)
public async Task ReportNowViewingItem(string controllingSessionId, string sessionId, string itemId)
{
ArgumentException.ThrowIfNullOrEmpty(itemId);
var item = _libraryManager.GetItemById(new Guid(itemId));
var session = GetSession(sessionId);
var session = await GetSessionForControl(sessionId).ConfigureAwait(false);
if (!string.IsNullOrEmpty(controllingSessionId))
{
AssertCanControl(session, GetSession(controllingSessionId));
AssertCanControl(session, await GetSessionForControl(controllingSessionId).ConfigureAwait(false));
}
session.NowViewingItem = GetItemInfo(item, null);
var payload = new RoutedNowViewingItem { SessionId = sessionId, ItemId = itemId };
if (await TryRouteToOwnerAsync(sessionId, RoutedNowViewingItem.Kind, payload, CancellationToken.None).ConfigureAwait(false))
{
return;
}
var local = GetSession(sessionId, false);
if (local is not null)
{
SetNowViewingItem(local, itemId);
}
}
private void SetNowViewingItem(SessionInfo session, string itemId)
{
session.NowViewingItem = GetItemInfo(_libraryManager.GetItemById(new Guid(itemId)), null);
QueueDirectoryPublish(session);
}
/// <inheritdoc />