fix(agent): observe mDNS UDP receive cancellation (#309)
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 24m57s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m19s
Heimdall Gitea / Build and scan agent image (push) Successful in 11m21s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 15m3s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 2m15s
Heimdall Gitea / CI policy (push) Successful in 1s

## Résumé
Le propriétaire des sockets UDP mDNS annule et observe maintenant les tâches de réception avant de quitter leur portée. Les erreurs socket inattendues restent propagées à la frontière de découverte.

Refs #301

## Validation
- `dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode` : réussi.
- Test de régression ciblé annulation / erreur socket : 1/1 réussi; suite `Heimdall.Agent.Tests` : 440/440 réussis.
- Compose jetable `heimdall-agent-mdns-udp-retry-20261108162648-13721` : restore verrouillé réussi et tests ciblés : 9/9 réussis.
- Nettoyage Compose vérifié : conteneurs, volumes et réseau absents; images construites localement : aucune; image SDK partagée conservée.
- CI du commit `ee865931` : détection de portée réussie; build/tests et CI policy à revérifier après mise à jour de branche.
- L’observation GlitchTip post-déploiement pendant 7 jours reste ouverte; le ticket reste donc référencé par `Refs #301`.

Skill mise à jour : `skills/mdns-camera-discovery/SKILL.md`.

Reviewed-on: #309
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #309.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-08 18:37:45 +01:00
1 parent b3d5ea5add
commit adf8d73476
4 files changed
+86 -39

No files matched your search

+5 -1
View File
@@ -24,8 +24,12 @@ Read `AGENTS.md`, the focused mDNS Gitea issue, `skills/heimdall-dotnet/SKILL.md
- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists.
- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping.
## UDP receive lifetime at shutdown
`MdnsClient` owns each `UdpClient` for one probe/discovery call. When a receive window expires, cancel the receive with a linked token and await its task before leaving the socket scope; this observes the expected cancellation and prevents a pending receive task from surfacing later as `UnobservedTaskException`. Do not swallow unrelated `SocketException` failures: keep them observable (or log a sanitized exception type at the discovery boundary). The focused regression test `ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures` covers expected cancellation and an unexpected socket failure. Run the focused and full `Heimdall.Agent.Tests` suites after changes to this lifecycle.
## Disposable Compose
Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its recursively referenced source projects, plus root build props/targets and `global.json`, into a temporary archive outside the repository. Mount the archive read-only, extract it inside the SDK container with `tar --no-same-owner` into `/tmp` (the container filesystem there is writable), and restore with `--locked-mode`. For mDNS lifecycle changes, run `HomeKitMdnsProbeTests` and the focused receive-cancellation regression test; otherwise run the relevant focused Agent tests. Use a unique Compose project, project-scoped NuGet package volume, and isolated bridge; publish no ports and never use host networking. The container is read-only except for `/tmp`, `/root/.local/share/NuGet` (NuGet HTTP cache), and the project-scoped package volume. Do not mark the bridge `internal`: locked restore may need NuGet network access; the bridge remains isolated from host/production networks. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the archive and Compose file, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN.
This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`.
+5 -1
View File
@@ -10,4 +10,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
</ItemGroup>
</Project>
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.Agent.Tests" />
</ItemGroup>
</Project>
+63 -37
View File
@@ -52,44 +52,46 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
// Try to receive within timeout
var receiveTask = udpClient.ReceiveAsync(ct).AsTask();
var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false);
if (completedTask != receiveTask)
using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
receiveCts.CancelAfter(options.Timeout);
var receiveTask = udpClient.ReceiveAsync(receiveCts.Token).AsTask();
try
{
if (retry < options.MaxRetries)
continue; // retry
break; // timeout, try next service type
}
var result = await receiveTask.ConfigureAwait(false);
var response = MdnsResponse.Parse(result.Buffer);
var result = await receiveTask.ConfigureAwait(false);
var response = MdnsResponse.Parse(result.Buffer);
if (response is not null)
{
// If it's a HomeKit device, parse HomeKit-specific info
if (response.Type == MdnsConstants.TypePtr &&
response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
if (response is not null)
{
// If it's a HomeKit device, parse HomeKit-specific info
if (response.Type == MdnsConstants.TypePtr &&
response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
{
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address,
HomeKitInfo = ParseHomeKitInfo(target, response)
};
}
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address,
HomeKitInfo = ParseHomeKitInfo(target, response)
ResolvedAddress = response.Address
};
}
return new MdnsProbeResult
{
Target = target,
ServiceType = response.Name,
InstanceName = response.PtrName,
HostName = response.Address?.ToString(),
ResolvedAddress = response.Address
};
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
if (retry < options.MaxRetries)
continue; // timeout, retry
break; // timeout, try next service type
}
}
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
@@ -167,17 +169,29 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
{
var receiveTask = udp.ReceiveAsync(ct).AsTask();
var completed = await Task.WhenAny(receiveTask, Task.Delay(options.ListenWindow, ct)).ConfigureAwait(false);
using var receiveCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var remaining = listenUntil - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
break;
receiveCts.CancelAfter(remaining);
var receiveTask = udp.ReceiveAsync(receiveCts.Token).AsTask();
try
{
var result = await receiveTask.ConfigureAwait(false);
var replies = ParsePacket(result.Buffer);
if (completed != receiveTask)
break; // no more replies expected
var result = await receiveTask.ConfigureAwait(false);
var replies = ParsePacket(result.Buffer);
if (replies.Count > 0)
collected.AddRange(replies);
if (replies.Count > 0)
collected.AddRange(replies);
}
catch (SocketException ex)
{
_logger.LogWarning("mDNS multicast receive failed (error type {ErrorType})", ex.GetType().Name);
break;
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
break; // listen window elapsed; receive cancellation is observed here
}
}
// Build devices from collected replies
@@ -201,6 +215,18 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
}
}
internal static async Task ObserveCanceledReceiveAsync(Task<UdpReceiveResult> receiveTask, CancellationToken operationToken)
{
try
{
await receiveTask.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!operationToken.IsCancellationRequested)
{
// The receive was canceled because its individual timeout elapsed.
}
}
// ─── DNS packet parsing (with compression pointers) ──────────────
private sealed record MdnsReply(
@@ -1,5 +1,6 @@
using System.Text;
using System.Net;
using System.Net.Sockets;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Mdns;
@@ -12,6 +13,18 @@ namespace Heimdall.Agent.Tests;
public class HomeKitMdnsProbeTests
{
[Fact]
public async Task ObserveCanceledReceiveAsync_ObservesExpectedCancellationAndPropagatesSocketFailures()
{
var canceledReceive = Task.FromCanceled<UdpReceiveResult>(new CancellationToken(canceled: true));
await Should.NotThrowAsync(() => MdnsClient.ObserveCanceledReceiveAsync(canceledReceive, CancellationToken.None));
var socketFailure = Task.FromException<UdpReceiveResult>(new SocketException((int)SocketError.NetworkDown));
await Should.ThrowAsync<SocketException>(
() => MdnsClient.ObserveCanceledReceiveAsync(socketFailure, CancellationToken.None));
}
[Fact]
public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow()
{