PlotDirector/PlotLine/Services/GeographicWorker.cs

105 lines
5.8 KiB
C#

using System.Text.Json;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services;
public sealed class GeographicWorker(IServiceScopeFactory scopes, ILogger<GeographicWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer=new PeriodicTimer(TimeSpan.FromSeconds(30));
do
{
try
{
using var scope=scopes.CreateScope();
var processor=scope.ServiceProvider.GetRequiredService<GeographicProcessor>();
// Bounded batches also classify ineligible roots without sending any external requests.
for(var i=0;i<20 && !stoppingToken.IsCancellationRequested;i++)
if(!await processor.ProcessOneAsync(stoppingToken)) break;
}
catch(OperationCanceledException) when(stoppingToken.IsCancellationRequested) { return; }
catch(Exception ex)
{
// Log codes only: provider exceptions may include private queries or credentials.
logger.LogWarning("Geographic queue cycle failed ({ErrorType}); retrying next cycle.",ex.GetType().Name);
}
} while(await timer.WaitForNextTickAsync(stoppingToken));
}
}
public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRules rules,IGeocodingProvider provider,ILogger<GeographicProcessor>? logger=null)
{
public async Task<bool> ProcessOneAsync(CancellationToken cancellationToken)
{
var job=await repository.ClaimAsync(provider.Enabled);
if(job is null) return false;
logger?.LogInformation("Geographical job {LocationID} generation {Generation} claimed at attempt {Attempt}.",job.LocationID,job.Generation,job.Attempts+1);
var cooldown=0;
try
{
var chain=await repository.ChainAsync(job.LocationID);
var query=rules.Query(chain);
if(query is null)
{
await repository.CompleteAsync(job,"Not eligible","Done",message:"Use geographical types beneath a recognised country or qualified region.");
return true;
}
query=query with {RelaxedContext=job.RelaxedContext};
var key=GeographicRules.CacheKey(query,provider.Name);
var cached=await repository.CacheAsync(key);
IReadOnlyList<GeographicCandidate> candidates;
if(cached is not null) candidates=JsonSerializer.Deserialize<List<GeographicCandidate>>(cached) ?? [];
else
{
if(!provider.Enabled)
{
await repository.CompleteAsync(job,"Pending","Waiting configuration",message:"External geographical lookup is disabled until a provider is configured.");
return true;
}
if(!await repository.ReserveAsync("Geocoding.External",provider.MinimumInterval,key,job.Lease))
{
await repository.CompleteAsync(job,"Pending","Queued",delay:Math.Max(1,(int)Math.Ceiling(provider.MinimumInterval.TotalSeconds)));
return false;
}
using var timeout=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
candidates=await provider.SearchAsync(query,timeout.Token);
}
candidates=GeographicRules.Candidates(query,candidates);
logger?.LogInformation("Geographical job {LocationID} generation {Generation}: {Count} candidates; cache hit {CacheHit}.",job.LocationID,job.Generation,candidates.Count,cached is not null);
var json=JsonSerializer.Serialize(candidates);
if(candidates.Count==0 && query.Ancestors.Length>1 && !query.RelaxedContext)
{
await repository.CompleteAsync(job,"Pending","Queued",key,json,message:"Full hierarchy context had no match; a country-scoped lookup is queued for confirmation.",delay:Math.Max(15,(int)provider.MinimumInterval.TotalSeconds),relaxContext:true);
return true;
}
// Provider adapters must establish uniqueness independently of their result limit/ranking.
var resolved=candidates.Count==1 && candidates[0].UniqueWithinContext;
await repository.CompleteAsync(job,candidates.Count==0?"Unresolved":resolved?"Resolved":"Needs confirmation","Done",key,json,
resolved?JsonSerializer.Serialize(candidates[0]):null,
candidates.Count==0?"No reliable geographical match.":resolved?"Unique geographical match":"Choose a geographical match.");
}
catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested)
{
// The lease expires durably; a subsequent worker recovers it.
throw;
}
catch(Exception ex)
{
if(ex is GeocodingHttpException http)
cooldown=http.StatusCode is 403 or 429 ? Math.Clamp((int)(http.RetryAfter?.TotalSeconds ?? 3600),900,86400) : 60;
logger?.LogWarning("Geographical job {LocationID} generation {Generation} failed ({ErrorType}, HTTP {Status}); cooldown {CooldownSeconds}s.",job.LocationID,job.Generation,ex.GetType().Name,(ex as GeocodingHttpException)?.StatusCode,cooldown);
var exhausted=job.Attempts>=3;
await repository.CompleteAsync(job,exhausted?"Unresolved":"Pending",exhausted?"Done":"Queued",
message:exhausted?"Provider lookup failed after four attempts. You can retry later.":"Provider temporarily unavailable.",
failure:true,delay:(int)Math.Pow(2,job.Attempts)*60);
}
finally
{
await repository.ReleaseAsync(job.Lease,cooldown);
}
return true;
}
}