70 lines
7.3 KiB
C#
70 lines
7.3 KiB
C#
// Explicit operator-only Development acceptance command. Never runs in the normal regression harness.
|
|
using System.Data;
|
|
using System.Diagnostics;
|
|
using System.Text.Json;
|
|
using Dapper;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
|
|
internal static class GeographyLiveRecovery
|
|
{
|
|
public static async Task Run(string[] args)
|
|
{
|
|
if(args.Length!=3 || !int.TryParse(args[1],out var project)||!int.TryParse(args[2],out var location))throw new InvalidOperationException("Use --geography-live-recovery projectId locationId; Development only, one previously empty lookup.");
|
|
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
|
|
foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
|
|
using var process=Process.Start(start)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();
|
|
if(process.ExitCode!=0)throw new InvalidOperationException("Development settings unavailable.");
|
|
var connectionString=environment.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
|
|
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Development only.");
|
|
using var db=new SqlConnection(connectionString);await db.OpenAsync();
|
|
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong effective database.");
|
|
var settingsStart=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
|
|
foreach(var arg in new[]{"-n","cat","/srv/apps/plotdirector-dev/current/appsettings.Development.json"})settingsStart.ArgumentList.Add(arg);
|
|
using var settingsProcess=Process.Start(settingsStart)!;var settingsJson=await settingsProcess.StandardOutput.ReadToEndAsync();await settingsProcess.WaitForExitAsync();
|
|
if(settingsProcess.ExitCode!=0)throw new InvalidOperationException("Development provider settings unavailable.");
|
|
using var settingsStream=new MemoryStream(System.Text.Encoding.UTF8.GetBytes(settingsJson));
|
|
var settings=new ConfigurationBuilder().AddJsonStream(settingsStream).AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();
|
|
if(new Uri(settings["Geography:Endpoint"]!).Host!="nominatim.openstreetmap.org")throw new InvalidOperationException("This acceptance command is restricted to the explicitly selected public Nominatim provider.");
|
|
var services=new ServiceCollection();services.AddLogging();services.Configure<GeocodingOptions>(settings.GetSection("Geography"));
|
|
services.AddHttpClient("Geocoding",client=>client.Timeout=TimeSpan.FromSeconds(25)).RemoveAllLoggers().ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler{AllowAutoRedirect=false});
|
|
services.AddSingleton<IGeocodingProvider,NominatimGeocodingProvider>();
|
|
using var serviceProvider=services.BuildServiceProvider();var provider=serviceProvider.GetRequiredService<IGeocodingProvider>();
|
|
if(!provider.Enabled)throw new InvalidOperationException("Provider disabled or wrong worker host.");
|
|
var repository=new GeographyRepository(new SqlConnectionFactory(settings));
|
|
var rules=new GeographicRules(Path.GetFullPath("PlotLine/Data/Reference/Geography"));var chain=await repository.ChainAsync(location);
|
|
if(chain.Count==0||chain[0].ProjectID!=project||rules.Query(chain) is null)throw new InvalidOperationException("The explicit recovery target must be an eligible location in the selected project.");
|
|
var baseline=await db.ExecuteScalarAsync<int>("SELECT COALESCE((SELECT DailyRequests FROM dbo.GeographicProviderGate WHERE Provider='Geocoding.External'),0)");
|
|
GeographicJob job;
|
|
using(var transaction=db.BeginTransaction())
|
|
{
|
|
var generation=await db.QuerySingleOrDefaultAsync<long?>("SELECT Generation FROM dbo.LocationGeography WITH(UPDLOCK,HOLDLOCK) WHERE LocationID=@location AND Status='Unresolved' AND CandidatesJson='[]' AND Confirmed=0",new{location},transaction);
|
|
if(generation is null)throw new InvalidOperationException("Recovery requires an observed, unconfirmed empty full-context result; refusing to replace newer work.");
|
|
var user=await db.QuerySingleAsync<int>("SELECT MIN(UserID) FROM dbo.ProjectUserAccess WHERE ProjectID=@project AND IsActive=1",new{project},transaction);
|
|
await db.ExecuteAsync("dbo.Geography_Retry",new{ProjectID=project,UserID=user,LocationID=location,Generation=generation.Value},transaction,commandType:CommandType.StoredProcedure);
|
|
// The full query has already returned an empty result. Resume exactly this durable job at its one fallback stage.
|
|
job=await db.QuerySingleAsync<GeographicJob>("UPDATE dbo.LocationGeography SET RelaxedGeneration=Generation,JobState='Processing',Lease=NEWID(),LeaseUntil=DATEADD(minute,2,SYSUTCDATETIME()) OUTPUT inserted.LocationID,inserted.Generation,inserted.Attempts,inserted.Lease,CAST(1 AS bit) RelaxedContext WHERE LocationID=@location",new{location},transaction);
|
|
transaction.Commit();
|
|
}
|
|
await new GeographicProcessor(new HeldJob(repository,job),rules,provider).ProcessOneAsync(default);
|
|
var result=await db.QuerySingleAsync<(string Status,string JobState,int Attempts,string? CandidatesJson)>("SELECT Status,JobState,Attempts,CandidatesJson FROM dbo.LocationGeography WHERE LocationID=@location",new{location});
|
|
var requests=await db.ExecuteScalarAsync<int>("SELECT DailyRequests FROM dbo.GeographicProviderGate WHERE Provider='Geocoding.External'");
|
|
Console.WriteLine($"LIVE Development recovery: location {location}, status {result.Status}, worker state {result.JobState}, failures {result.Attempts}, candidates {JsonSerializer.Deserialize<List<GeographicCandidate>>(result.CandidatesJson??"[]")!.Count}, actual provider reservations {baseline} → {requests}.");
|
|
if(result.Status!="Needs confirmation"||requests-baseline>1)throw new InvalidOperationException("Bounded live recovery did not return confirmation candidates; inspect queue state.");
|
|
}
|
|
sealed class HeldJob(GeographyRepository repository,GeographicJob job):IGeographicQueue
|
|
{
|
|
public Task<GeographicJob?> ClaimAsync(bool enabled)=>Task.FromResult<GeographicJob?>(job);
|
|
public Task<IReadOnlyList<LocationItem>> ChainAsync(int id)=>repository.ChainAsync(id);
|
|
public Task<string?> CacheAsync(string key)=>repository.CacheAsync(key);
|
|
public Task<bool> ReserveAsync(string provider,TimeSpan interval,string key,Guid lease)=>repository.ReserveAsync(provider,interval,key,lease);
|
|
public Task ReleaseAsync(Guid lease,int cooldownSeconds=0)=>repository.ReleaseAsync(lease,cooldownSeconds);
|
|
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0,bool relaxContext=false)
|
|
=>repository.CompleteAsync(job,status,jobState,key,candidates,match,message,failure,delay,relaxContext);
|
|
}
|
|
}
|