Files
dpl/app/Services/PaymentHealth/Monitor.php
T

95 lines
7.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Services\PaymentHealth;
use App\Models\Payment;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use RuntimeException;
class Monitor
{
public function __construct(private EpayProbe $probe,private TeleHubReporter $reporter) {}
public function run(): array
{
if(!config('payment_health.enabled',true))return ['status'=>'disabled','channels'=>[]];
$store=new StateStore(config('payment_health.state_path'));
if(!$store->acquire())return ['status'=>'locked','channels'=>[]];
try{
$state=$store->read();$instance=$this->instance();
if(isset($state['instance'])&&$state['instance']!==$instance)throw new RuntimeException('health_state_instance_mismatch');
$state['instance']=$instance;$now=CarbonImmutable::now(config('payment_health.timezone','Asia/Shanghai'));
$day=$now->format('Y-m-d');$slot=$day.'-'.intdiv($now->hour,6);$results=[];
foreach(Payment::orderBy('id')->get()as$p){
if(!$this->probe->supports($p)||in_array($p->id,config('payment_health.excluded_ids',[]),true)){$results[]=['id'=>$p->id,'status'=>'unsupported_or_excluded'];continue;}
$id=(string)$p->uuid;$revision=$this->revision($p);$old=$state['channels'][$id]??[];
$policy=hash('sha256',json_encode(['handoff_v2',config('payment_health.allowed_hosts',[]),(bool)config('payment_health.dynamic_handoffs',true)]));
if(($old['status']??null)==='review_required'&&($old['policy']??null)!==$policy)$old['status']='policy_changed';
if(($old['revision']??null)!==$revision)$old=['slot'=>$old['slot']??null];
$lease=Ownership::lease($p);
$managed=$lease!==null;
$old['managed_disabled']=$managed;
if($managed){$old['managed_disabled']=true;$old['expected_updated_at']=$lease['expected_updated_at'];}
// A toggle or settings edit made outside this monitor releases automatic ownership.
if($managed&&($p->enable||($old['expected_updated_at']??null)!==(string)$p->getRawOriginal('updated_at'))){$managed=false;$old['managed_disabled']=false;}
if(!$p->enable&&!$managed){$old['status']='manual_disabled';$old['revision']=$revision;$state['channels'][$id]=$old;$store->save($state);$results[]=['id'=>$p->id,'status'=>'manual_disabled'];continue;}
if(($old['slot']??null)===$slot||($old['status']??null)==='review_required'){$results[]=['id'=>$p->id,'status'=>'already_checked_or_review'];continue;}
if(($state['budget'][$day]??0)>=(int)config('payment_health.daily_probe_limit',8)){$results[]=['id'=>$p->id,'status'=>'daily_budget_reached'];continue;}
// Persist the claim before any external request. An interrupted run consumes this slot.
$current=$old+['managed_disabled'=>false,'soft_failures'=>0];
unset($current['action']);
$current['slot']=$slot;$current['revision']=$revision;$current['policy']=$policy;$current['phase']='claimed';$current['claimed_at']=$now->toIso8601String();
$state['channels'][$id]=$current;$state['budget']=[$day=>($state['budget'][$day]??0)+1];$store->save($state);
$trade='PH'.gmdate('YmdHis').bin2hex(random_bytes(8));$out=$this->probe->probe($p,$trade);
if(!in_array($out['status']??null,['healthy','hard_failure','soft_failure','indeterminate','review_required'],true))throw new RuntimeException('invalid_probe_result');
$current['phase']='checked';$current['status']=$out['status'];$current['reason']=$out['reason'];$current['checked_at']=$now->toIso8601String();
$current['evidence']=$out;$current['soft_failures']=$out['status']==='soft_failure'?($old['soft_failures']??0)+1:0;
$target=null;$auto=(bool)config('payment_health.auto_toggle',true);
if($auto&&$p->enable&&($out['status']==='hard_failure'||($out['status']==='soft_failure'&&$current['soft_failures']>=config('payment_health.soft_failure_threshold',2))))$target=false;
if($auto&&!$p->enable&&$managed&&$out['status']==='healthy')$target=true;
if($target!==null){
$current['phase']='toggle_pending';$state['channels'][$id]=$current;$store->save($state);
$changed=DB::transaction(function()use($p,$revision,$target){
$fresh=Payment::lockForUpdate()->find($p->id);
if(!$fresh||$this->revision($fresh)!==$revision||$fresh->enable!==$p->enable||$fresh->getRawOriginal('updated_at')!==$p->getRawOriginal('updated_at'))return null;
$fresh->enable=$target;$fresh->save();
if($target)Ownership::clear($fresh);else Ownership::record($fresh);
return $fresh;
});
if($changed){$current['managed_disabled']=!$target;$current['expected_updated_at']=(string)$changed->getRawOriginal('updated_at');$current['phase']='applied';$current['action']=$target?'enabled':'disabled';}
else{$current['status']='manual_override';$current['managed_disabled']=false;$current['phase']='skipped';}
}
if(($old['status']??null)!==$current['status']||$target!==null){
// Healthy first checks are quiet. Emit only useful failures, transitions, and recoveries.
if($current['status']!=='healthy'||!empty($old['status']))$this->event($state,$p,$current,$instance,$now);
}
$state['channels'][$id]=$current;$store->save($state);$results[]=['id'=>$p->id,'status'=>$current['status'],'action'=>$current['action']??null];
}
foreach($state['events']as$key=>$event){
if(in_array($event['delivery']['status']??'', ['sent','failed','uncertain','cancelled'],true))continue;
$delivery=$this->reporter->deliver($event+($event['delivery']??[]));$state['events'][$key]['delivery']=$delivery;$store->save($state);
}
return ['status'=>'complete','channels'=>$results,'notifications'=>array_count_values(array_map(fn($e)=>$e['delivery']['status']??'local_pending',$state['events']))];
}finally{$store->release();}
}
private function instance():string
{
$db=config('database.connections.'.config('database.default').'.database');
return substr(hash('sha256',(string)config('app.url').'|'.(string)$db),0,20);
}
private function revision(Payment $p):string
{
return ChannelIdentity::revision($p);
}
private function event(array &$state,Payment $p,array $c,string $instance,CarbonImmutable $now):void
{
$n=($state['event_sequence']??0)+1;$state['event_sequence']=$n;
$key='xb.payment-health.'.$instance.'.'.$n;
$recovered=$c['status']==='healthy';$label=mb_substr((string)(config('payment_health.site_label')?:admin_setting('app_name','XB')),0,80);
// Channel labels are administrative text. No URLs, signatures, order IDs or user data are sent.
$name=mb_substr(preg_replace('/[\r\n]/u',' ',(string)$p->name),0,80);
$text='【'.$label.' - 支付通道'.($recovered?'恢复':'异常').'】'."\n通道:".$name.'('.$p->id.')'."\n时间:".$now->format('Y-m-d H:i:s T')."\n检测:".$c['reason']."\n处理:".($c['action']??'保持现状,需检查')."\n范围:仅收银可用性,未实际付款";
$state['events'][$key]=['key'=>$key,'bot'=>$recovered?'notification':'error','text'=>$text];
}
}