using System.Diagnostics; using System.Globalization; using System.Text.Json; using XFEEDToolBox.Core.Execution; using XFEEDToolBox.Core.Models; using XFEEDToolBox.Core.Navigation; namespace XFEEDToolBox.Core.Session; public interface ITradePauseRecoveryChannel { Task PrepareAsync(CancellationToken token); Task ReadAsync(CancellationToken token); Task RenewAsync(string owner,string runId,ulong entity,CancellationToken token); Task ResumeAsync(string owner,string runId,string requestId,ulong menuSequence,CancellationToken token); Task EndAsync(string owner,string runId); } // JsonWire.U64 on the native side accepts a JSON number, not a string. Keep // the physical entity type explicit all the way through request serialization. public sealed record NativeTradePauseRenewRequest(string Owner,string RunId,ulong EntityId) { public string Op=>"trade.pause.renew"; public int TtlMilliseconds=>750; } /// Purpose-built Pause resume only. Does not open a menu or use the relog action API. public sealed class NativeTradePauseRecoveryChannel(int processId,string gameHash,string packageDirectory):ITradePauseRecoveryChannel { public const string Service="SessionRecovery0514k"; private readonly NavigationPipeClient pipe=new(processId,Service); private long? started; private Task VerifyProcessAsync(CancellationToken token) { token.ThrowIfCancellationRequested();using var process=Process.GetProcessById(processId); if(process.ProcessName!="EliteDangerous64")throw new InvalidDataException("暂停恢复绑定的游戏实例不匹配。"); var at=process.StartTime.ToUniversalTime().Ticks; if(started is {} expected&&at!=expected)throw new InvalidDataException("暂停恢复绑定的游戏实例已经改变。"); started=at;return Task.CompletedTask; } private async Task CallAsync(object request,CancellationToken token) { await VerifyProcessAsync(token).ConfigureAwait(false);var result=await pipe.CallAsync(request,token).ConfigureAwait(false); if(result.GetProperty("schema").GetInt32()!=1||result.GetProperty("name").GetString()!="XFEEDToolBox.SessionRecovery" ||result.GetProperty("service").GetString()!=Service||result.GetProperty("processId").GetInt32()!=processId ||result.GetProperty("gameSha256").GetString()!=gameHash||!result.GetProperty("enabled").GetBoolean() ||!result.TryGetProperty("tradePauseResumeSchema",out var schema)||schema.GetInt32()!=1) throw new NotSupportedException("当前插件尚未提供已验证的跑商暂停恢复,请更新游戏内插件。"); return result; } public async Task PrepareAsync(CancellationToken token) { await new NativeOriginalSessionMenuRecovery(processId,gameHash,packageDirectory,VerifyProcessAsync).PrepareAsync(token).ConfigureAwait(false); await CallAsync(new{op="describe"},token).ConfigureAwait(false); } public Task ReadAsync(CancellationToken token)=>CallAsync(new{op="read"},token); public async Task RenewAsync(string owner,string runId,ulong entity,CancellationToken token) {await CallAsync(new NativeTradePauseRenewRequest(owner,runId,entity),token).ConfigureAwait(false);} public async Task ResumeAsync(string owner,string runId,string requestId,ulong menuSequence,CancellationToken token) {await CallAsync(new{op="trade.pause.resume",owner,runId,requestId,menuSequence,ttlMilliseconds=150},token).ConfigureAwait(false);} public async Task EndAsync(string owner,string runId) { using var stop=new CancellationTokenSource(TimeSpan.FromMilliseconds(400)); try{await CallAsync(new{op="trade.pause.end",owner,runId},stop.Token).ConfigureAwait(false);} catch(Exception error)when(error is IOException or OperationCanceledException or InvalidOperationException or NotSupportedException or InvalidDataException){} } } /// One explicit running authorization. Tests can step it without a timer or game. public sealed class TradePauseRecoverySession(ITradePauseRecoveryChannel channel,Func player,Func isRunning,Func? clock=null) { private readonly string owner=Guid.NewGuid().ToString("N"),runId=Guid.NewGuid().ToString("N"); private bool prepared,armed; private PlayerState? baseline; private string? pending; private DateTimeOffset pendingAt; private int attempts,revoked; public string? LastIssue{get;private set;} public int ConfirmedResumes{get;private set;} private DateTimeOffset Now=>clock?.Invoke()??DateTimeOffset.UtcNow; private static bool Flag(JsonElement value,string name)=>value.TryGetProperty(name,out var item)&&item.ValueKind==JsonValueKind.True; private static string Text(JsonElement value,string name)=>value.TryGetProperty(name,out var item)&&item.ValueKind==JsonValueKind.String?item.GetString()??"":""; private bool Running(CancellationToken token) { if(Volatile.Read(ref revoked)!=0||token.IsCancellationRequested||!isRunning())return false; var current=player(); return current.InGame&¤t.CurrentShipId is not null&¤t.LoadGameAt is not null&¤t.CommanderId.Length>0 &&!NavigationSafety.UnhealthyHull(current)&&!NavigationSafety.HasExternalThreat(current) &&(baseline is null||current.CommanderId==baseline.CommanderId&¤t.CurrentShipId==baseline.CurrentShipId&¤t.LoadGameAt==baseline.LoadGameAt); } private static ulong Identity(JsonElement value,string key)=>value.TryGetProperty(key,out var item)&&item.ValueKind==JsonValueKind.String &&ulong.TryParse(item.GetString(),NumberStyles.None,CultureInfo.InvariantCulture,out var result)?result:0; public async Task StepAsync(CancellationToken token) { if(!Running(token)) { if(armed){armed=false;await channel.EndAsync(owner,runId).ConfigureAwait(false);} if(!isRunning()){baseline=null;pending=null;attempts=0;} return; } baseline??=player(); if(!prepared){await channel.PrepareAsync(token).ConfigureAwait(false);prepared=true;if(!Running(token))return;} var value=await channel.ReadAsync(token).ConfigureAwait(false); if(!Running(token)){await RevokeNativeAsync().ConfigureAwait(false);return;} var state=Text(value,"state");var next=Text(value,"nextState"); if(pending is not null) { var receipt=value.TryGetProperty("tradePauseRecovery",out var result)?result:default; var matching=receipt.ValueKind==JsonValueKind.Object&&Text(receipt,"requestId")==pending; if(state=="InGame"&&next==state) {if(matching&&Flag(receipt,"applied"))ConfirmedResumes++;pending=null;attempts=0;LastIssue=null;} else if(matching&&Flag(receipt,"failed")){pending=null;LastIssue="原始暂停恢复请求已失效,等待新菜单观测。";return;} else {if(Now-pendingAt>TimeSpan.FromSeconds(3))LastIssue="原始暂停恢复尚未确认,未重复提交。";return;} } if(state!=next||state is not("InGame" or "Pause")){await RevokeNativeAsync().ConfigureAwait(false);return;} if(!value.TryGetProperty("tradePauseIdentity",out var identity)||!Flag(identity,"verified"))return; var entity=Identity(identity,"entityId");var observed=identity.GetProperty("observedAtUnixMilliseconds").GetInt64(); var age=Now.ToUnixTimeMilliseconds()-observed; // This is the fresh menu-thread read of current identity/hull, not a // relaxed or reused physics frame. It remains available in Pause. if(entity==0||age is <0 or >200||!identity.TryGetProperty("hullFraction",out var hull)||hull.ValueKind!=JsonValueKind.Number ||!double.IsFinite(hull.GetDouble())||hull.GetDouble() is <=0 or >1)return; if(!Running(token))return; await channel.RenewAsync(owner,runId,entity,token).ConfigureAwait(false);armed=true; if(!Running(token)){await RevokeNativeAsync().ConfigureAwait(false);return;} if(state=="InGame")return; var actions=value.GetProperty("actions").EnumerateArray().Select(row=>new NativeSessionMenuAction(Text(row,"name"),Flag(row,"enabled"))).ToArray(); var observation=new TradePauseResumeObservation{Verified=true,MenuReady=Flag(value,"menuReady"),State=state,NextState=next,Category=Text(value,"categoryName"), Kind=value.GetProperty("kind").GetInt32(),Sequence=value.GetProperty("menuSequence").GetUInt64(), ObservedAtMilliseconds=value.GetProperty("observedAtUnixMilliseconds").GetUInt64(),Actions=actions}; if(attempts>=3||!TradePauseResumePolicy.CanResume(observation,Running(token),(ulong)Now.ToUnixTimeMilliseconds()))return; pending=Guid.NewGuid().ToString("N");pendingAt=Now;attempts++; // No await lies between the final authorization and submitting the // bounded native request. Native dispatch repeats scope/identity/menu // checks, and revocation shares its dispatch barrier. if(!Running(token)){pending=null;await RevokeNativeAsync().ConfigureAwait(false);return;} await channel.ResumeAsync(owner,runId,pending,observation.Sequence,token).ConfigureAwait(false); } private async Task RevokeNativeAsync() {if(armed||pending is not null){armed=false;await channel.EndAsync(owner,runId).ConfigureAwait(false);}} public async Task EndAsync() {Interlocked.Exchange(ref revoked,1);await RevokeNativeAsync().ConfigureAwait(false);} } public sealed class NativeTradePauseRecovery(int processId,string gameHash,Func player,string packageDirectory) { public event Action? Status; public IDisposable EnterRunningMenuRecovery(Func isRunning,CancellationToken token) { var channel=new NativeTradePauseRecoveryChannel(processId,gameHash,packageDirectory); return new RunningLease(new(channel,player,isRunning),token,message=>Status?.Invoke(message)); } private sealed class RunningLease:IDisposable { private readonly TradePauseRecoverySession session;private readonly CancellationTokenSource stop;private readonly CancellationTokenRegistration cancelled; private readonly object lifetime=new();private bool workerFinished; private int disposed; internal RunningLease(TradePauseRecoverySession session,CancellationToken token,Action status) { this.session=session;stop=CancellationTokenSource.CreateLinkedTokenSource(token);cancelled=token.Register(Dispose); _=Task.Run(async()=> { string? lastStatus=null; try { while(!stop.IsCancellationRequested) { try { await session.StepAsync(stop.Token).ConfigureAwait(false); if(session.LastIssue is {} issue&&issue!=lastStatus){lastStatus=issue;status(issue);} else if(session.LastIssue is null)lastStatus=null; } catch(OperationCanceledException)when(stop.IsCancellationRequested){break;} catch(Exception error) {var issue="暂停菜单恢复等待:"+error.Message;if(issue!=lastStatus){lastStatus=issue;status(issue);}} await Task.Delay(250,stop.Token).ConfigureAwait(false); } } catch(OperationCanceledException)when(stop.IsCancellationRequested){} finally { try{await session.EndAsync().ConfigureAwait(false);} finally { // Dispose can race the worker's final cancellation. // Serialize CTS cleanup so a late owner Dispose never // calls Cancel on an already disposed linked source. lock(lifetime){workerFinished=true;cancelled.Unregister();stop.Dispose();} } } }); } public void Dispose() { if(Interlocked.Exchange(ref disposed,1)!=0)return; lock(lifetime){if(!workerFinished)stop.Cancel();cancelled.Unregister();} // Run the revoke off the UI synchronization context. This bounded // barrier prevents an acknowledged stop from leaving queued resume // work authorized on the original menu thread. try{Task.Run(session.EndAsync).Wait(500);}catch(AggregateException){} } } }