Files
Heimdall/src/Heimdall.Web/Controllers/AgentsController.cs
T

111 lines
4.9 KiB
C#
Raw Normal View History

using Heimdall.Application.Agents.Commands.RegisterAgent;
using Heimdall.Application.Agents.Commands.Heartbeat;
using Heimdall.Application.Agents.Queries.GetAgent;
using Heimdall.Application.Agents.Queries.GetAgentsBySite;
using Heimdall.Application.Agents.Queries.GetAllAgents;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/agents")]
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly IMediator _mediator;
public AgentsController(IMediator mediator) => _mediator = mediator;
/// <summary>Register an agent using a site registration token.</summary>
[AllowAnonymous]
[HttpPost("register")]
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Register(
[FromBody] RegisterAgentRequest request, CancellationToken ct)
{
// Extract API key from header (may be empty for registration)
var apiKey = Request.Headers.Authorization.FirstOrDefault()
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
var command = new RegisterAgentCommand(request.Token, request.Hostname, request.Version, request.PublicIp);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Send heartbeat from agent (API Key auth).</summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpPost("{id:guid}/heartbeat")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Heartbeat(
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
{
GpuAcceleration? gpuType = request.GpuType is not null && Enum.TryParse<GpuAcceleration>(request.GpuType, true, out var parsed) ? parsed : null;
var command = new HeartbeatCommand(
id,
request.PublicIp,
request.HasGpu,
request.CpuCores,
(int?)request.MemoryMb,
gpuType,
request.IsOffline,
request.CpuUsagePercent,
request.MemoryUsageBytes,
request.DiskUsagePercent,
request.UptimeSeconds);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get agent details (JWT auth).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _mediator.Send(new GetAgentQuery(id), ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List agents for a site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _mediator.Send(new GetAgentsBySiteQuery(siteId, page, pageSize), ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>List all agents across all sites.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListAll(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _mediator.Send(new GetAllAgentsQuery(page, pageSize), ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}