Merge branch 'main' into fix/214-hangfire-startup-lock
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 27m42s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s

This commit is contained in:
arnaud.dartois committed 2026-11-07 10:59:58 +01:00
commit 1e32d585f5
14 files changed
+397 -25

No files matched your search

+1
View File
@@ -11,6 +11,7 @@
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md).
+21
View File
@@ -0,0 +1,21 @@
---
name: agent-heartbeat-timeout
description: Diagnose and validate Central heartbeat timeouts without terminating the Heimdall Agent background service.
---
# Agent heartbeat timeout
`AgentRegistrationService` sends periodic Central heartbeats through the named `Central` `HttpClient`, whose timeout is configured in `src/Heimdall.Agent/Program.cs`. An `HttpClient.Timeout` surfaces as `OperationCanceledException`/`TaskCanceledException`, even though the host's `stoppingToken` is not canceled. `SendHeartbeatAsync` must log this as a transient timeout and return to the loop. Preserve cancellation when `stoppingToken.IsCancellationRequested` so host shutdown remains cooperative.
## Change and test
- Keep the timeout handling local to `SendHeartbeatAsync`; registration cancellation and shutdown semantics have different retry behavior.
- Catch `OperationCanceledException` only under `!stoppingToken.IsCancellationRequested`, log it as a timeout, and allow the next loop iteration to retry. The existing general exception handler continues to cover other transient failures.
- In `tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs`, use an asynchronous HTTP handler that waits on the request cancellation token. Give its `HttpClient` a short timeout, then assert that a second heartbeat arrives. This verifies both the timeout source and continued service operation without waiting 10 seconds.
- Run `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter FullyQualifiedName~Heartbeat_HttpTimeout_DoesNotStopService_AndNextHeartbeatSucceeds`, then the full Agent test project.
## Disposable Compose acceptance
Run `bash skills/agent-heartbeat-timeout/acceptance.sh` from the repository root. The recipe builds the Agent image from `docker/Dockerfile.agent` in this checkout and a small local fake Central image. The fake Central delays the first heartbeat for 12 seconds (longer than the Agent's configured 10-second `Central` client timeout), then accepts later heartbeats. Acceptance requires the Agent health endpoint to respond after the timeout and the fake Central to observe a subsequent heartbeat. The script uses a random Compose project, random site token, Compose-managed isolated volume/network, dynamically assigned loopback Agent port, and unique local image tags. Its `EXIT` trap tears down only that project, verifies its containers/volumes/networks are gone, removes and verifies absence of both exact image tags, and removes temporary files. It retains shared SDK/runtime/base images.
This synthetic recipe proves local retry behavior only. It does not validate a production runner, Central instance, or post-deployment GlitchTip telemetry; record that follow-up on Gitea issue #248.
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \n')"
project="heimdall-heartbeat-${suffix}"
central_image="heimdall-heartbeat-mock:${suffix}"
agent_image="heimdall-agent:heartbeat-${suffix}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
compose_file="$temp_dir/compose.yml"
env_file="$temp_dir/acceptance.env"
local_image_tags=("$agent_image" "$central_image")
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
down --volumes --remove-orphans || cleanup_failed=1
containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then
printf 'Project resource cleanup failed: containers=%s volumes=%s networks=%s\n' \
"${containers:-<none>}" "${volumes:-<none>}" "${networks:-<none>}" >&2
cleanup_failed=1
else
printf 'Verified no containers, volumes, or networks remain for %s\n' "$project"
fi
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Recipe image still exists: %s\n' "$tag" >&2
cleanup_failed=1
else
printf 'Verified recipe image absent: %s\n' "$tag"
fi
done
rm -rf -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable recipe cleanup failed for project %s\n' "$project" >&2
status=1
fi
exit "$status"
}
trap cleanup EXIT
site_token=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
cat >"$env_file" <<EOF
ACCEPTANCE_PROJECT=$project
ACCEPTANCE_AGENT_IMAGE=$agent_image
ACCEPTANCE_CENTRAL_IMAGE=$central_image
ACCEPTANCE_SITE_TOKEN=$site_token
EOF
mkdir -p "$temp_dir/mock-central"
cat >"$temp_dir/mock-central/Dockerfile" <<'EOF'
FROM python:3.13-alpine
WORKDIR /app
COPY mock_central.py .
CMD ["python", "-u", "/app/mock_central.py"]
EOF
cat >"$temp_dir/mock-central/mock_central.py" <<'PY'
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
heartbeat_count = 0
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
self.send_response(200)
self.end_headers()
elif self.path == "/counts":
payload = json.dumps({"heartbeats": heartbeat_count}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
else:
self.send_error(404)
def do_POST(self):
global heartbeat_count
length = int(self.headers.get("Content-Length", "0"))
self.rfile.read(length)
if self.path == "/api/agents/register":
payload = json.dumps({
"agentId": "a583ec73-665f-4628-93e3-fcfe746a0e02",
"apiKey": "synthetic-acceptance-key",
"apiKeyPrefix": "synthetic",
}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
elif self.path.endswith("/heartbeat"):
heartbeat_count += 1
if heartbeat_count == 1:
time.sleep(12)
self.send_response(200)
self.end_headers()
else:
self.send_error(404)
def log_message(self, *_args):
pass
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
PY
cat >"$compose_file" <<'YAML'
services:
fake-central:
image: ${ACCEPTANCE_CENTRAL_IMAGE}
build:
context: ./mock-central
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz')"]
interval: 1s
timeout: 2s
retries: 20
agent:
image: ${ACCEPTANCE_AGENT_IMAGE}
build:
context: ${ACCEPTANCE_REPO_ROOT}
dockerfile: docker/Dockerfile.agent
environment:
ASPNETCORE_URLS: http://127.0.0.1:8081
Agent__CentralUrl: http://fake-central:8080
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${ACCEPTANCE_SITE_TOKEN}
Agent__AgentName: heartbeat-acceptance
Agent__HeartbeatIntervalSeconds: "5"
Agent__PublicIpResolverUrl: ""
Agent__StateDirectory: /var/lib/heimdall
volumes:
- agent_state:/var/lib/heimdall
ports:
- "127.0.0.1::8081"
depends_on:
fake-central:
condition: service_healthy
volumes:
agent_state:
YAML
printf 'ACCEPTANCE_REPO_ROOT=%s\n' "$repo_root" >>"$env_file"
printf 'Disposable project: %s\n' "$project"
printf 'Locally built image tags: %s %s\n' "$agent_image" "$central_image"
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" up -d --build
deadline=$((SECONDS + 45))
while (( SECONDS < deadline )); do
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
exec -T agent wget -q --spider http://127.0.0.1:8081/healthz >/dev/null 2>&1; then
break
fi
sleep 1
done
if (( SECONDS >= deadline )); then
printf 'Agent health endpoint did not become available\n' >&2
exit 1
fi
deadline=$((SECONDS + 35))
while (( SECONDS < deadline )); do
counts=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
exec -T fake-central python -c \
'import json,urllib.request; print(json.load(urllib.request.urlopen("http://127.0.0.1:8080/counts"))["heartbeats"])')
if [[ "$counts" =~ ^[0-9]+$ ]] && (( counts >= 2 )); then
printf 'Acceptance passed: Agent remained healthy and fake Central observed %s heartbeats, including a retry after its first delayed response.\n' "$counts"
exit 0
fi
sleep 1
done
printf 'Acceptance failed: fake Central did not observe a heartbeat retry (last count: %s)\n' "${counts:-unknown}" >&2
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs --no-color agent | tail -80 >&2 || true
exit 1
+2
View File
@@ -28,6 +28,8 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore
```
For `NetworkCameraScanner` TCP probes, bound connects with a linked cancellation token and await the connect task on both success and timeout. Do not race a live `TcpClient.ConnectAsync` against `Task.Delay` and return while the connect task is still running: closing the client can surface a later socket cancellation as an unobserved task exception. Keep a focused test proving the timeout cancels and observes the pending connect, and that caller cancellation still propagates.
For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon.
This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`.
+2
View File
@@ -7,6 +7,8 @@ description: Maintain Central server installation, Compose refresh, and Docker i
Use this skill when changing the Linux or Windows Central installer, its generated Compose, or Central container update behavior.
For installer, Compose, image, and documentation work that can proceed independently, use [parallel development with Orca](../parallel-development/SKILL.md). Keep shared deployment contracts and the final isolated acceptance run coordinated and integrated before recording evidence.
## Central and release endpoints
- The Central address embedded in generated Agent installation commands must come from the browser's exposed `NavigationManager.BaseUri`; do not store a deployment hostname in a Razor page or installer template. Preserve the path base and trim only its trailing slash.
@@ -7,6 +7,8 @@ description: Build and acceptance-test Heimdall changes in a disposable Docker C
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
When implementation or acceptance preparation has independent branches, use [parallel development with Orca](../parallel-development/SKILL.md) to assign bounded work. Keep the final Compose run, cleanup verification, and acceptance evidence under one coordinator so the combined change is validated as a whole.
Track the change and its acceptance evidence in a Gitea issue; follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md). Put the project name, exact local image tags and cleanup verification in the issue or linked PR, and close the ticket only after the recipe and other required gates pass.
## Safety and isolation
+2
View File
@@ -7,6 +7,8 @@ description: Implement or review database persistence in Heimdall with Entity Fr
Use this skill whenever changing how application or Agent data is read or written.
For work spanning multiple persistence concerns, use [parallel development with Orca](../parallel-development/SKILL.md). Keep each `DbContext` operation isolated; assign migration/model ownership clearly and serialize edits that touch the same entity configuration or migration chain.
- Use EF Core LINQ and entity configurations for CRUD. Prefer projections, bounded result sets, asynchronous APIs, and `CancellationToken`; use `AsNoTracking` for read-only entity queries.
- Create a short-lived `DbContext` per operation. Hosted services and concurrent workers should use `IDbContextFactory<TContext>` and dispose each context; never share a context across parallel work.
- Evolve schemas through reviewed EF Core migrations. Preserve deployed data and test upgrades from every supported on-disk schema, including Agent-local SQLite outboxes.
+2
View File
@@ -7,6 +7,8 @@ description: Create, maintain, link, and close Heimdall project tickets in Gitea
Gitea issues are the source of truth for planned work, acceptance evidence, operational follow-up, and completion. Do not use a repository markdown checklist as a parallel backlog.
For implementation work that has independent tasks, use [parallel development with Orca](../parallel-development/SKILL.md). Keep Gitea as the work-status source: create linked issues for independently deliverable outcomes, while Orca Runs/Tasks coordinate the execution and dependencies.
## Before implementation
1. Read `AGENTS.md` and the focused skill(s) for the affected area.
+2
View File
@@ -7,6 +7,8 @@ description: Implement or review Heimdall .NET 10 application, EF Core persisten
Read `AGENTS.md`, the relevant Gitea issue, and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) first. Trace a feature through `Domain` → `Application` → `Infrastructure` → `Web` or `Agent` before editing; update only the layers that own the behavior.
For multi-layer work, use [parallel development with Orca](../parallel-development/SKILL.md) to dispatch non-overlapping layer tasks early, sequence shared contract decisions, and integrate the result before running combined verification.
For persistence changes, inspect the entity configuration and latest migration, then verify PostgreSQL translation and transactions with focused integration tests. Keep migrations compatible with existing rows, record the data backfill or rollback requirement, and avoid client-side filtering on access-controlled queries.
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
+45
View File
@@ -0,0 +1,45 @@
---
name: parallel-development
description: Plan and coordinate parallel Heimdall implementation work with Orca workers while preserving architecture, issue tracking, and acceptance evidence.
---
# Parallel development with Orca
Use this workflow for a Heimdall change that can be split into independent investigations or implementation tasks. Read `AGENTS.md`, the focused Gitea issue, the relevant domain skills, and the installed Orca `orchestration` guide first. The Orca CLI guide is also required when creating or managing worktrees. The version-matched instructions come from `orca-ide skills get orchestration` and `orca-ide skills get orca-cli`; follow the resolved executable specified by those guides.
## Find parallel work early
1. Map the requested outcome to the Heimdall boundaries: `Domain`, `Application`, `Infrastructure`, `Web`, and `Agent`. Also identify tests, migrations, documentation, and disposable acceptance work.
2. List concrete work packages with a single owner, bounded files or components, required inputs, and an observable deliverable. Mark each dependency explicitly.
3. Start every ready, independent investigation or implementation promptly. Keep sequential work (shared contract decisions, migration ordering, integration, final acceptance, ticket update, and PR) with the coordinator unless it is itself safely isolated.
4. Split independent, user-visible deliverables into linked Gitea issues before dispatch, following `gitea-ticket-workflow`. Keep one issue for coordinated subtasks that do not ship independently.
Choose the Orca coordination shape that matches the dependency graph:
- For a small set of independent tasks with clear, separate outputs, use the version-matched `worker-start --spec` workflow. Give workers precise scope and tell them to report evidence and blockers.
- For dependent tasks or several waves of work, create an Orca Run and Tasks with explicit dependencies, then start all Tasks reported ready. Recheck readiness after each worker report and start newly unblocked work without waiting for unrelated branches.
- Use a shared current worktree only when workers cannot conflict in files. If edits overlap or cannot be partitioned confidently, assign separate Orca worktrees and integrate their changes deliberately. Do not start concurrent workers that edit the same files.
- Do not parallelize a decision that needs one owner, duplicate the same task across workers, or turn a straightforward isolated change into coordination overhead.
## Heimdall task contracts
Every worker brief must include the user outcome, issue number, exact component/file ownership, architectural constraints, dependencies, acceptance evidence, and what to return. Ask for a concise report with files changed, commands/evidence, remaining risks, and any files or decisions needed from the coordinator. Do not provide credentials, production data, RTSP URLs, raw tokens, or real customer information in a worker prompt.
Workers must preserve these boundaries:
- Domain stays independent of infrastructure; use cases and interfaces belong in Application; adapters and EF Core persistence belong in Infrastructure; HTTP/UI composition belongs in Web; camera/runtime behavior belongs in Agent.
- EF Core and PostgreSQL requirements remain in force. Do not share a `DbContext` across concurrent work. Schema changes include reviewed migrations and relational verification.
- Each worker edits only its assigned scope. When shared contracts must change, have one owner define the contract first, then unblock dependent tasks in the Orca DAG.
- Each independent implementation still follows its focused skill and records results against the Gitea issue. Delegation does not waive authorization, security, CI runner, secret, or review rules.
## Integrate and validate once
1. Coordinate through Orca messages and worker reports, not by polling or steering worker terminals. Follow the version-matched guide's wake, recovery, and completion rules; do not treat silence as proof of completion.
2. Review each returned diff against its assigned scope and the issue criteria. Resolve overlapping changes in the coordinator's integration step; do not accept a report as proof without inspecting the relevant change/evidence.
3. Run shared builds, tests, persistence checks, and disposable Compose acceptance after integrating dependent changes. Avoid making every worker rerun the same full suite; ask each worker for focused evidence, then run the smallest combined checks once at integration.
4. Keep required project-specific acceptance intact. Behavior and deployment changes still use `compose-disposable-recipe`; account bootstrap and Central update changes use their additional focused recipes. Never claim external runner, registry, camera, or storage evidence from a worker's local mock.
5. Update the issue with completed criteria and actual evidence, create/update the PR with `Closes #N` only when every criterion is complete (otherwise `Refs #N`), and record unresolved external validation separately.
## Completion record
The issue or PR should make the coordination auditable without duplicating a long-lived backlog: note the Orca work packages at a high level, which were integrated, the combined checks actually run, and any tasks or acceptance gates still open. Close or settle worker Tasks only when their evidence is received; a reported failure remains open work.
@@ -246,6 +246,11 @@ public class AgentRegistrationService : BackgroundService
_buffer.Count);
}
}
catch (OperationCanceledException ex) when (!stoppingToken.IsCancellationRequested)
{
// HttpClient.Timeout cancels only this request; keep the hosted service alive.
_logger.LogWarning(ex, "Heartbeat timed out (will retry)");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Heartbeat error (will retry)");
@@ -614,17 +614,39 @@ public NetworkCameraScanner(
var tasks = CameraPorts.Select(async port =>
{
using var client = new TcpClient();
var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
if (completed == connectTask && client.Connected)
if (await ConnectWithTimeoutAsync(
token => client.ConnectAsync(IPAddress.Parse(ip), port, token), PortTimeout, ct)
.ConfigureAwait(false))
open.Add(port);
client.Close();
});
await Task.WhenAll(tasks).ConfigureAwait(false);
return [.. open.Order()];
}
internal static async Task<bool> ConnectWithTimeoutAsync(
Func<CancellationToken, ValueTask> connectAsync,
TimeSpan timeout,
CancellationToken cancellationToken)
{
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
try
{
await connectAsync(timeoutSource.Token).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return false;
}
catch (SocketException)
{
return false;
}
}
private async Task<HttpProbe?> ProbeHttpAsync(string ip, int port, CancellationToken ct)
{
try
@@ -1104,9 +1126,9 @@ public NetworkCameraScanner(
{
var uri = new Uri(url);
using var client = new TcpClient();
var connectTask = client.ConnectAsync(uri.Host, uri.Port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
if (!await ConnectWithTimeoutAsync(
token => client.ConnectAsync(uri.Host, uri.Port, token), RtspTimeout, ct)
.ConfigureAwait(false))
return false;
var options = $"OPTIONS rtsp://{uri.Host}:{uri.Port}/ RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: HeimdallAgent/1.0\r\n\r\n";
@@ -1188,11 +1210,10 @@ public NetworkCameraScanner(
var password = credentials.Length > 1 ? Uri.UnescapeDataString(credentials[1]) : "";
using var client = new TcpClient();
var connectTask = client.ConnectAsync(host, port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
if (!await ConnectWithTimeoutAsync(
token => client.ConnectAsync(host, port, token), DvripTimeout, ct)
.ConfigureAwait(false))
return false;
await connectTask.ConfigureAwait(false);
var stream = client.GetStream();
@@ -1315,11 +1336,10 @@ public NetworkCameraScanner(
var port = uri.IsDefaultPort ? 1935 : uri.Port;
using var client = new TcpClient();
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
if (!await ConnectWithTimeoutAsync(
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
.ConfigureAwait(false))
return false;
await connectTask.ConfigureAwait(false);
var stream = client.GetStream();
@@ -1370,11 +1390,10 @@ public NetworkCameraScanner(
var path = string.IsNullOrEmpty(uri.AbsolutePath) ? "/bubble/live?ch=0&stream=0" : uri.PathAndQuery;
using var client = new TcpClient();
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
if (!await ConnectWithTimeoutAsync(
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
.ConfigureAwait(false))
return false;
await connectTask.ConfigureAwait(false);
var stream = client.GetStream();
@@ -1431,11 +1450,10 @@ public NetworkCameraScanner(
var port = uri.IsDefaultPort ? 8080 : uri.Port;
using var client = new TcpClient();
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
if (!await ConnectWithTimeoutAsync(
token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct)
.ConfigureAwait(false))
return false;
await connectTask.ConfigureAwait(false);
var stream = client.GetStream();
var request = $"GET /accessories HTTP/1.1\r\nHost: {uri.Host}\r\n\r\n";
@@ -254,6 +254,36 @@ public class AgentRegistrationServiceTests : IDisposable
authorization.ShouldBeNull();
}
[Fact]
public async Task Heartbeat_HttpTimeout_DoesNotStopService_AndNextHeartbeatSucceeds()
{
var heartbeatCount = 0;
var handler = new AsyncMockHttpMessageHandler(async (request, cancellationToken) =>
{
if (request.RequestUri?.ToString().Contains("/heartbeat") == true &&
Interlocked.Increment(ref heartbeatCount) == 1)
{
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
}
return request.RequestUri?.ToString().Contains("/register") == true
? CreateRegistrationResponse()
: new HttpResponseMessage(HttpStatusCode.OK);
});
var factory = CreateHttpClientFactory(handler, TimeSpan.FromMilliseconds(100));
var service = CreateService(factory);
await service.StartAsync(CancellationToken.None);
var deadline = DateTime.UtcNow.AddSeconds(8);
while (DateTime.UtcNow < deadline && Volatile.Read(ref heartbeatCount) < 2)
await Task.Delay(50);
await service.StopAsync(CancellationToken.None);
heartbeatCount.ShouldBeGreaterThanOrEqualTo(2);
}
public void Dispose()
{
_tmp.Dispose();
@@ -284,9 +314,14 @@ public class AgentRegistrationServiceTests : IDisposable
}
private static IHttpClientFactory CreateHttpClientFactory(
MockHttpMessageHandler handler)
HttpMessageHandler handler,
TimeSpan? timeout = null)
{
var client = new HttpClient(handler) { BaseAddress = new Uri("http://heimdall.test") };
var client = new HttpClient(handler)
{
BaseAddress = new Uri("http://heimdall.test"),
Timeout = timeout ?? TimeSpan.FromSeconds(100)
};
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("Central").Returns(client);
factory.CreateClient("IpResolver").Returns(client);
@@ -330,3 +365,14 @@ public class MockHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage
return Task.FromResult(handler(request));
}
}
public sealed class AsyncMockHttpMessageHandler(
Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
: HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
return handler(request, cancellationToken);
}
}
@@ -42,4 +42,40 @@ public class NetworkCameraScannerTests
var scanner = new NetworkCameraScanner(logger, loggerFactory);
scanner.ShouldNotBeNull();
}
[Fact]
public async Task ConnectWithTimeoutAsync_CancelsAndObservesTimedOutConnect()
{
var connectCancellationObserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var connected = await NetworkCameraScanner.ConnectWithTimeoutAsync(async cancellationToken =>
{
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
}
catch (OperationCanceledException)
{
connectCancellationObserved.TrySetResult();
throw;
}
}, TimeSpan.FromMilliseconds(25), CancellationToken.None);
connected.ShouldBeFalse();
await connectCancellationObserved.Task.WaitAsync(TimeSpan.FromSeconds(1));
}
[Fact]
public async Task ConnectWithTimeoutAsync_PropagatesCallerCancellation()
{
using var cancellation = new CancellationTokenSource();
var connecting = NetworkCameraScanner.ConnectWithTimeoutAsync(
token => new ValueTask(Task.Delay(Timeout.InfiniteTimeSpan, token)),
TimeSpan.FromSeconds(5),
cancellation.Token);
await cancellation.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(async () => await connecting);
}
}