using XFEEDToolBox.Core.Data; using XFEEDToolBox.Core.Models; namespace XFEEDToolBox.Core.Session; public sealed record ShipProtectionProgress(bool EmergencyActive,bool TestingBlocked,string Message); /// Shared production/test protection. Damage processing never waits for the UI dispatcher. public sealed class ShipProtectionMonitor(IGameSessionDriver driver,Func player,Action stopAutomation,bool automaticExit=true):IAsyncDisposable { private readonly object gate=new(); private readonly ShieldRestartGuard guard=new(); private readonly InterdictionExitGuard interdiction=new(); private ShipProtectionTrigger? lastTrigger; private GameSessionTarget? replacement; private readonly CancellationTokenSource lifetime=new(); private GameSessionTarget? target; private bool enabled; private Task? emergency; private NativeFlightTestProtection? nativeProtection; private readonly SemaphoreSlim nativeGate=new(1,1); public GameSessionTarget? BoundTarget{get{lock(gate)return target;}} public ShipProtectionTrigger? LastTrigger{get{lock(gate)return lastTrigger;}} public GameSessionTarget? RestartTarget{get{lock(gate)return replacement;}} public bool ExitOnInterdiction{get;init;}=true; public bool ContinuousHealthReady=>nativeProtection?.Fresh==true; public bool AutomaticExitEnabled=>automaticExit; public Func? ExpectedInputFreeJumpLoading{get;set;} public Action? PauseAutomationForMonitoring{get;set;} public Action? NativeProtectionDiagnostics{get;set;} public event Action? Progress; public event Action? Reentry; public bool TestingBlocked{get{lock(gate)return guard.TestingBlocked;}} public bool EmergencyActive{get{lock(gate)return emergency is {IsCompleted:false};}} public Task Completion{get{lock(gate)return emergency??Task.CompletedTask;}} public async Task EnableAsync(CancellationToken token=default) { var next=await driver.FindTargetAsync(token); EnableTarget(next); } internal void EnableTarget(GameSessionTarget next) { lock(gate) { if(lifetime.IsCancellationRequested)return; target=next;enabled=true;lastTrigger=null;replacement=null;interdiction.Reset(DateTimeOffset.UtcNow);guard.SetEnabled(true,DateTimeOffset.UtcNow);guard.Prime(player(),next); } if(TestingBlocked)StopAutomation(); Report(false,TestingBlocked?"飞船当前受损或船体已失效 · 自动操作已暂停":automaticExit?"保护监测中 · 被拦截立即大退;受损后破盾或低血量大退":"人工观察模式 · 异常只停自动输入,不退出游戏"); } public async Task AttachNativeAsync(string gameHash,CancellationToken token=default,bool exitForFailedHandoff=true) { await nativeGate.WaitAsync(token); try { RequireHealthyShip();var expected=BoundTarget??throw new InvalidOperationException("飞船保护尚未绑定游戏实例。"); if(nativeProtection is {Stopped:false})return; if(nativeProtection is {} previous){nativeProtection=null;await previous.DisposeAsync();} nativeProtection=await NativeFlightTestProtection.ArmAsync(expected.ProcessId,gameHash,driver,player,StopAutomation,token,this,automaticExit,exitForFailedHandoff, expectedInputFreeJumpLoading:ExpectedInputFreeJumpLoading,pauseAutomation:PauseAutomationForMonitoring,diagnostics:NativeProtectionDiagnostics); Report(false,"连续保护中 · 被拦截立即大退;受损后破盾或低血量立即大退"); } finally{nativeGate.Release();} } public void RequireHealthyShip(bool requireContinuous=false) { if(Navigation.NavigationSafety.UnhealthyHull(player())) throw new InvalidOperationException("船体已失效,无法继续自动操作。"); if(TestingBlocked)throw new Navigation.FlightTelemetryUnavailableException("正在等待受损停止后的连续稳定观测,暂不发送驾驶输入。"); if(requireContinuous&&!ContinuousHealthReady)throw new Navigation.FlightTelemetryUnavailableException("正在恢复连续船体与护盾监测,暂不发送驾驶输入。"); } public void Observe(ObservedJournalEvent observed,PlayerState state) { if(ObserveInterdiction(state,DateTimeOffset.UtcNow,observed))return; GameSessionTarget? restart=null;ShipProtectionTrigger? trigger=null;bool blocked; lock(gate) { if(!enabled||target is null||emergency is {IsCompleted:false})return; if(guard.Observe(observed,state,target)){restart=target;trigger=lastTrigger=guard.LastTrigger;} blocked=guard.TestingBlocked; if(restart is not null) { StopAutomation(); if(automaticExit)emergency=Task.Run(()=>ProtectAsync(restart,trigger)); } } if(blocked)StopAutomation(); } public void Observe(ShipHealthSample sample,DateTimeOffset now) { GameSessionTarget? restart=null;ShipProtectionTrigger? trigger=null;bool blocked; lock(gate) { if(!enabled||target is null||emergency is {IsCompleted:false})return; if(guard.ObserveHealth(sample,player(),target,now)){restart=target;trigger=lastTrigger=guard.LastTrigger;} blocked=guard.TestingBlocked; if(restart is not null){StopAutomation();if(automaticExit)emergency=Task.Run(()=>ProtectAsync(restart,trigger));} } if(blocked)StopAutomation(); } public bool ObserveInterdiction(PlayerState state,DateTimeOffset now,ObservedJournalEvent? observed=null) { lock(gate) { if(!enabled||target is null||!automaticExit||!ExitOnInterdiction||emergency is {IsCompleted:false})return false; if(!(observed is null?interdiction.ObserveStatus(state,target,now):interdiction.ObserveJournal(observed,state,target,now)))return false; var expected=target;var trigger=new ShipProtectionTrigger(ShipProtectionReason.Interdicted,null,now);lastTrigger=trigger; // The exit starts independently of worker cancellation, UI dispatch, // health reads, escape-vector alignment and launcher validation. emergency=Task.Run(()=>ProtectAsync(expected,trigger)); } StopAutomation();return true; } private async Task ProtectAsync(GameSessionTarget expected,ShipProtectionTrigger? trigger) { Report(true,(trigger?.Message??"飞船受损")+" · 正在大退"); try { var sessions=new GameSessionController(driver,()=>false); sessions.Reentry+=entry=> { if(entry.Stage==SessionReentryStage.ProcessReady)lock(gate)replacement=entry.Target; if(Reentry is not {} handlers)return; foreach(Action handler in handlers.GetInvocationList()) try{handler(entry);}catch{ /* A notification failure cannot affect emergency protection. */ } }; await sessions.EmergencyRestartAsync(expected,lifetime.Token); lock(gate){target=null;} Report(false,TestingBlocked?"已大退重启 · 等待新的稳定健康观测后重试":trigger?.Reason==ShipProtectionReason.Interdicted?"拦截已大退保护 · 等待原模式恢复并继续原货物":"已大退重启 · 等待新会话;初始无盾不触发"); } catch(OperationCanceledException)when(lifetime.IsCancellationRequested){Report(false,"已取消后续重启等待");} catch(Exception error){Report(false,"飞船保护停止 · "+error.Message);} } private void StopAutomation(){try{stopAutomation();}catch{ /* A worker failure must not prevent the emergency exit. */ }} private void Report(bool active,string message) { var progress=new ShipProtectionProgress(active,TestingBlocked,message); if(Progress is not {} handlers)return; foreach(Action handler in handlers.GetInvocationList()) try{handler(progress);}catch{ /* A failed UI subscriber cannot delay ship protection. */ } } public async ValueTask DisposeAsync() { Task? pending; lock(gate){enabled=false;guard.SetEnabled(false,DateTimeOffset.UtcNow);pending=emergency;lifetime.Cancel();} await nativeGate.WaitAsync(); try{if(nativeProtection is {} native){nativeProtection=null;await native.DisposeAsync();}} finally{nativeGate.Release();} if(pending is not null)await pending; lifetime.Dispose(); } }