fix(agent): keep heartbeat timeouts transient #277

Merged
arnaud.dartois merged 1 commits from fix/248-heartbeat-timeout into main 2026-11-07 10:24:32 +01:00
4 changed files with 262 additions and 2 deletions

No files matched your search

+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
@@ -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)");
@@ -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);
}
}