feat(worker): expose usage/model-usage hub surface and persist run model
Adds GetUsageSnapshot/GetModelUsage/GetTaskUsage to WorkerHub (backed by a shared UsageSnapshotBuilder), a UsageUpdated broadcast fired after every UsageMonitorService poll cycle, and records the resolved model on each task_runs row so per-model/per-task usage can be reported from history.
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Worker.Config;
|
||||
using ClaudeDo.Worker.Hub;
|
||||
using ClaudeDo.Worker.Usage.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ClaudeDo.Worker.Usage;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Hub-facing usage snapshot DTO from UsageState + IUsageGate + AppSettings
|
||||
/// thresholds. Shared by WorkerHub.GetUsageSnapshot and UsageMonitorService's post-poll
|
||||
/// broadcast so both surfaces agree on staleness/threshold logic.
|
||||
/// </summary>
|
||||
public sealed class UsageSnapshotBuilder
|
||||
{
|
||||
private readonly UsageState _state;
|
||||
private readonly IUsageGate _gate;
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly WorkerConfig _cfg;
|
||||
|
||||
public UsageSnapshotBuilder(
|
||||
UsageState state, IUsageGate gate, IDbContextFactory<ClaudeDoDbContext> dbFactory, WorkerConfig cfg)
|
||||
{
|
||||
_state = state;
|
||||
_gate = gate;
|
||||
_dbFactory = dbFactory;
|
||||
_cfg = cfg;
|
||||
}
|
||||
|
||||
public async Task<UsageSnapshotDto> BuildAsync(CancellationToken ct = default)
|
||||
{
|
||||
var snapshot = _state.Snapshot;
|
||||
var lastError = _state.LastError;
|
||||
|
||||
Data.Models.AppSettingsEntity settings;
|
||||
using (var context = _dbFactory.CreateDbContext())
|
||||
settings = await new AppSettingsRepository(context).GetAsync(ct);
|
||||
|
||||
var decision = await _gate.EvaluateAsync(ct);
|
||||
|
||||
var maxAge = TimeSpan.FromSeconds(_cfg.UsagePollIntervalSeconds * 3);
|
||||
var isStale = snapshot is null || lastError is not null || (DateTime.UtcNow - snapshot.FetchedAtUtc) > maxAge;
|
||||
|
||||
var limits = (snapshot?.Limits ?? Array.Empty<UsageLimitRow>())
|
||||
.Select(l => new UsageLimitDto(l.Kind, l.Group, l.Percent, l.Severity, l.ResetsAt, l.ScopeModelDisplayName, l.IsActive))
|
||||
.ToList();
|
||||
|
||||
return new UsageSnapshotDto(
|
||||
snapshot?.FiveHour?.Utilization,
|
||||
snapshot?.FiveHour?.ResetsAt,
|
||||
snapshot?.SevenDay?.Utilization,
|
||||
snapshot?.SevenDay?.ResetsAt,
|
||||
limits,
|
||||
settings.UsageGateFiveHourPct,
|
||||
settings.UsageGateSevenDayPct,
|
||||
decision.IsBlocked,
|
||||
decision.Reason,
|
||||
snapshot?.FetchedAtUtc,
|
||||
isStale,
|
||||
lastError);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user