This commit is contained in:
1 parent
539859d250
commit
0f47236c08
34 files changed
+889
-64
No files matched your search
@@ -0,0 +1,147 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/updates")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public class UpdatesController : ControllerBase
|
||||
{
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<UpdatesController> _logger;
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
};
|
||||
|
||||
private static readonly object _cacheLock = new();
|
||||
private static LatestReleaseCache? _cache;
|
||||
private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(1);
|
||||
private const string ForgejoApiUrl =
|
||||
"https://forgejo.tordais.cc/api/v1/repos/nonobis/Heimdall/releases/latest";
|
||||
|
||||
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> logger)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("latest")]
|
||||
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetLatestRelease(CancellationToken ct)
|
||||
{
|
||||
var cached = GetCached();
|
||||
if (cached is not null && !IsStale(cached))
|
||||
return Ok(cached.Response);
|
||||
if (cached is not null && IsStale(cached))
|
||||
{
|
||||
_ = RefreshCacheAsync(ct);
|
||||
return Ok(cached.Response);
|
||||
}
|
||||
var result = await FetchLatestReleaseAsync(ct);
|
||||
if (result is null)
|
||||
return StatusCode(502, new { error = "Failed to fetch release info" });
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("agents/{id:guid}/update")]
|
||||
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> TriggerAgentUpdate(Guid id, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Update triggered for agent {AgentId}", id);
|
||||
var cached = GetCached();
|
||||
if (cached is not null && !IsStale(cached))
|
||||
return Ok(cached.Response);
|
||||
var result = await FetchLatestReleaseAsync(ct);
|
||||
if (result is null)
|
||||
return StatusCode(502, new { error = "Failed to fetch release info" });
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = _httpClientFactory.CreateClient("Central");
|
||||
client.Timeout = TimeSpan.FromSeconds(15);
|
||||
var response = await client.GetAsync(ForgejoApiUrl, ct);
|
||||
if (!response.IsSuccessStatusCode) { _logger.LogWarning("Forgejo returned {Code}", response.StatusCode); return null; }
|
||||
var release = await response.Content.ReadFromJsonAsync<ForgejoRelease>(Json, ct);
|
||||
if (release is null) return null;
|
||||
var assets = new Dictionary<string, PlatformAsset>();
|
||||
foreach (var asset in release.Assets ?? [])
|
||||
{
|
||||
var platform = DetectPlatform(asset.Name);
|
||||
if (platform is null) continue;
|
||||
assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = ExtractSha256(asset.Digest), Size = asset.Size };
|
||||
}
|
||||
var result = new LatestReleaseResponse { Version = release.TagName, ReleaseNotes = release.Body, PublishedAt = release.PublishedAt, Assets = assets };
|
||||
lock (_cacheLock) { _cache = new LatestReleaseCache(result, DateTime.UtcNow); }
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; }
|
||||
}
|
||||
|
||||
private async Task RefreshCacheAsync(CancellationToken ct) { try { await FetchLatestReleaseAsync(ct); } catch { } }
|
||||
private static LatestReleaseCache? GetCached() { lock (_cacheLock) return _cache; }
|
||||
private static bool IsStale(LatestReleaseCache c) => DateTime.UtcNow - c.Timestamp > CacheDuration;
|
||||
|
||||
private static string? DetectPlatform(string? name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return null;
|
||||
var l = name.ToLowerInvariant();
|
||||
if (l.Contains("linux-x64")) return "linux-x64";
|
||||
if (l.Contains("linux-arm64")) return "linux-arm64";
|
||||
if (l.Contains("linux-arm")) return "linux-arm";
|
||||
if (l.Contains("win-x64") || l.Contains("windows-x64")) return "win-x64";
|
||||
if (l.Contains("osx-x64") || l.Contains("macos-x64")) return "osx-x64";
|
||||
if (l.Contains("osx-arm64") || l.Contains("macos-arm64")) return "osx-arm64";
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ExtractSha256(string? digest)
|
||||
{
|
||||
if (string.IsNullOrEmpty(digest)) return null;
|
||||
const string pfx = "sha256:";
|
||||
return digest.StartsWith(pfx, StringComparison.OrdinalIgnoreCase) ? digest[pfx.Length..] : null;
|
||||
}
|
||||
|
||||
public class LatestReleaseResponse
|
||||
{
|
||||
[JsonPropertyName("version")] public string Version { get; set; } = string.Empty;
|
||||
[JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; }
|
||||
[JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; }
|
||||
[JsonPropertyName("assets")] public Dictionary<string, PlatformAsset> Assets { get; set; } = [];
|
||||
}
|
||||
public class PlatformAsset
|
||||
{
|
||||
[JsonPropertyName("url")] public string Url { get; set; } = string.Empty;
|
||||
[JsonPropertyName("sha256")] public string? Sha256 { get; set; }
|
||||
[JsonPropertyName("size")] public long Size { get; set; }
|
||||
}
|
||||
private sealed class ForgejoRelease
|
||||
{
|
||||
[JsonPropertyName("tag_name")] public string TagName { get; set; } = string.Empty;
|
||||
[JsonPropertyName("body")] public string? Body { get; set; }
|
||||
[JsonPropertyName("published_at")] public DateTime? PublishedAt { get; set; }
|
||||
[JsonPropertyName("assets")] public List<ForgejoAsset>? Assets { get; set; }
|
||||
}
|
||||
private sealed class ForgejoAsset
|
||||
{
|
||||
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
|
||||
[JsonPropertyName("browser_download_url")] public string BrowserDownloadUrl { get; set; } = string.Empty;
|
||||
[JsonPropertyName("digest")] public string? Digest { get; set; }
|
||||
[JsonPropertyName("size")] public long Size { get; set; }
|
||||
}
|
||||
private sealed record LatestReleaseCache(LatestReleaseResponse Response, DateTime Timestamp);
|
||||
}
|
||||
Reference in new issue
Block a user